Is it possible to implement python without a standard library?

Is it possible to embed python without a standard library?

I am working with cmake build for python 2.7.6 and I have a basic built-in script run like

#include <stdio.h> #include <Python.h> int main(int argc, char *argv[]) { /* Setup */ Py_SetProgramName(argv[0]); Py_Initialize(); /* Run the 'main' module */ int rtn = Py_Main(argc, _argv); Py_Finalize(); return rtn; } 

.. but when I run it, I get:

 ImportError: No module named site 

If I set up the correct $ PYTHONHOME, it works fine; but that’s not what I'm trying to do. I am trying to embed a copy of python in a standalone application without a standard library.

I appreciate its use, but for this particular embedded environment, I want something more like lua (but with python syntax obviously) where only specific libraries provided by the parent application are available.

This has the added bonus of not having to worry about distributing (or creating) a standard library with all its cross dynamic libraries.

Is this possible like everyone else? Or am I inevitably about to stumble over missing fundamental blocks of the language, such as sys.path, import, {}, [] or the like, which are part of the standard library?

If possible, how would you do it?

+7
python python-embedding
Jan 06 '14 at 2:02 on
source share
2 answers

The simple answer is yes, you can.

 int main(int argc, char *argv[]) { /* Setup */ Py_NoSiteFlag = 1; // <--- This Py_SetProgramName(argv[0]); Py_Initialize(); /* Run the 'main' module */ int rtn = Py_Main(argc, argv); Py_Finalize(); return rtn; } 

As far as I can tell, nothing will break, and you can continue to use everything (including the ability to import modules ~) completely fine. If you try to import something from the standard library, which is not included in the package, you will receive:

 >>> import os; Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named os 

I will leave a copy of the code here for anyone interested;

https://github.com/shadowmint/cmake-python-embed-nostdlib

+11
Jan 07 '14 at 8:53
source share

AFAIK, you cannot. Without a standard library, Python will not even start, as it tries to find os.py (in 3.x; string.py in 2.x). At startup, it imports several modules, in particular site.py. You need at least pythonxy.dll and possibly the contents of the lib folder as well as extension modules, i.e. the contents of the DLL folder.

You can send it with the pythonXX.zip file (where XX is the version number, for example 27 or 33), which should be an encrypted copy of the standard library. You can rob the library of materials that you do not need; there are various tools that statically put dependencies (see modulefinder ).

I think that’s why Lua is more popular as a built-in scripting language.

+1
Jan 6
source share



All Articles