Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an application which embeds and runs Python code without local Python installation?

Hello fellow software developers.

I want to distribute a C program which is scriptable by embedding the Python interpreter.
The C program uses Py_Initialize, PyImport_Import and so on to accomplish Python embedding.

I'm looking for a solution where I distribute only the following components:

  • my program executable and its libraries
  • the Python library (dll/so)
  • a ZIP-file containing all necessary Python modules and libraries.

How can I accomplish this? Is there a step-by-step recipe for that?

The solution should be suitable for both Windows and Linux.

Thanks in advance.

like image 407
Robert Avatar asked Mar 22 '10 17:03

Robert


3 Answers

Have you looked at Python's official documentation : Embedding Python into another application?

There's also this really nice PDF by IBM : Embed Python scripting in C application.

You should be able to do what you want using those two resources.

like image 138
Laurent Parenteau Avatar answered Nov 13 '22 17:11

Laurent Parenteau


I simply tested my executable on a computer which hasn't Python installed and it worked.

When you link Python to your executable (no matter if dynamically or statically) your executable already gains basic Python language functionality (operators, methods, basic structures like string, list, tuple, dict, etc.) WITHOUT any other dependancy.

Then I let Python's setup.py compile a Python source distribution via python setup.py sdist --format=zip which gave me a ZIP file I named pylib-2.6.4.zip.

My further steps were:

char pycmd[1000]; // temporary buffer for forged Python script lines
...
Py_NoSiteFlag=1;
Py_SetProgramName(argv[0]);
Py_SetPythonHome(directoryWhereMyOwnPythonScriptsReside);
Py_InitializeEx(0);

// forge Python command to set the lookup path
// add the zipped Python distribution library to the search path as well
snprintf(
    pycmd,
    sizeof(pycmd),
    "import sys; sys.path = ['%s/pylib-2.6.4.zip','%s']",
    applicationDirectory,
    directoryWhereMyOwnPythonScriptsReside
);

// ... and execute
PyRun_SimpleString(pycmd);

// now all succeeding Python import calls should be able to
// find the other modules, especially those in the zipped library

...
like image 31
Robert Avatar answered Nov 13 '22 18:11

Robert


Did you take a look at Portable Python ? No need to install anything. Just copy the included files to use the interpreter.

Edit : This is a Windows only solution.

like image 31
Pierre-Jean Coudert Avatar answered Nov 13 '22 17:11

Pierre-Jean Coudert