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 run it, I get not a valid win32 application error.
I can compile same code using visaul c++ 2008 and it works, but I want to utilize distutils for this, because I want it to figure out configuration options for compiler.
I tried to open created executable in WinDebug, but I couldn't open, because this happened:
Turkish part says it is not a valid Win32 application.
There are two modifications to your code to make it work :
Use link_executable to output a standalone executable (the compile.link() is useless, use the subfunctions instead).
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
That's because you didn't entered the PYTHONPATH and PYTHONHOME variable env. in your main.c :
VARENV :
putenv("PYTHONPATH=C:/Python27/Lib"); putenv("PYTHONHOME=C:/Python27");
It should work with those fixes (tested on Windows XP x86, Python 2.7, VSExpress 2008)
The whole 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"])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.