How to compile a simple python built-in program using distutils

Here is my code:

from distutils.msvc9compiler import MSVCCompiler target_python_file = "main.py" ccode = """#include <Python.h> int main(int argc, char *argv[]) { PyObject* PyFileObject; putenv("PYTHONPATH=lib"); putenv("PYTHONHOME=."); Py_SetProgramName(argv[0]); Py_Initialize(); PyFileObject = PyFile_FromString("%s", "r"); PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "%s", 1); Py_Finalize(); return 0; } """ % (target_python_file, target_python_file) with open("main.c","w") as main: main.write(ccode) compiler = MSVCCompiler() compiler.compile(["main.c"],include_dirs=["C:/Python27/include"]) compiler.link("",["main.obj"],"python_launcher.exe",libraries=["python27"], library_dirs=["C:/Python27/libs"]) 

When I run this, python_launcher.exe appears, however, when I try to start it, I get an invalid win32 application error.

I can compile the same code using visul C ++ 2008 and it works, but I want to use distutils for this because I want it to define configuration options for the compiler.

Debug

I tried to open the created executable in WinDebug, but I could not open it because it happened: enter image description here

The Turkish side claims that this is not a valid Win32 application.

+6
source share
1 answer

There are two modifications to your code:

  • Use link_executable to output a standalone executable (compile.link () is useless, use subfunctions).

     compiler.link_executable( ["main.obj"], #object "launch" , # strip the .exe extension, it will be added libraries=["python27"], library_dirs=["C:/Python27/libs"] ) 

    At this point, you should get this error message:

     X:\dev\null>python_launcher.exe ImportError: No module named site 

This is because you did not enter the variable PYTHONPATH and PYTHONHOME env. in your main.c:

  • VARENV:

     putenv("PYTHONPATH=C:/Python27/Lib"); putenv("PYTHONHOME=C:/Python27"); 

It should work with these fixes (tested on Windows XP x86, Python 2.7, VSExpress 2008)

All code:

 from distutils.msvc9compiler import MSVCCompiler target_python_file = "main.py" ccode = """#include <Python.h> int main(int argc, char *argv[]) { PyObject* PyFileObject; putenv("PYTHONPATH=C:/Python27/Lib"); putenv("PYTHONHOME=C:/Python27"); Py_SetProgramName(argv[0]); Py_Initialize(); PyFileObject = PyFile_FromString("%s", "r"); PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "%s", 1); Py_Finalize(); return 0; } """ % (target_python_file, target_python_file) with open("main.c","w") as main: main.write(ccode) compiler = MSVCCompiler() compiler.compile(["main.c"],include_dirs=["C:/Python27/include"]) compiler.link_executable(["main.obj"],"launch", libraries=["python27"], library_dirs=["C:/Python27/libs"]) 
0
source

Source: https://habr.com/ru/post/955834/


All Articles