Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to embed python without the standard library?

Is it possible to embed python without the standard library?

I'm working with a cmake build for python 2.7.6 and I've got a basic embedded script running, like so:

#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 setup a correct $PYTHONHOME, it works fine; but that's not what I'm trying to do. I'm trying to embed a copy of python in a stand alone application without the standard library.

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

This has the added bonus of not caring about distributing (or building) the standard library with all it's cross linked dynamic libraries.

Is this possible as all? Or am I inevitably going to stumble into missing fundamental blocks of the language like sys.path, import, {}, [] or similar that are part of the standard library?

If it is possible, how would you go about doing it?

like image 483
Doug Avatar asked Jan 06 '14 14:01

Doug


1 Answers

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 breaks and you can continue to use everything (including the ability to import modules~) perfectly fine. If you try to import anything from the standard library that isn't bundled, you'll get:

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

I'll leave a copy of the code up here for anyone who's interested;

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

like image 194
Doug Avatar answered Oct 13 '22 00:10

Doug