如何使用distutils编译简单的python嵌入式程序

时间:2013-10-12 09:48:54

标签: python visual-c++ compilation

这是我的代码:

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"])

当我运行它时,python_launcher.exe出现,但是,当我尝试运行它时,我得不到有效的win32应用程序错误。

我可以使用visaul c ++ 2008编译相同的代码并且它可以工作,但我想为此使用distutils,因为我希望它为编译器找出配置选项。

调试

我试图在WinDebug中打开已创建的可执行文件,但我无法打开,因为这发生了: enter image description here

土耳其语部分称它不是有效的Win32应用程序。

1 个答案:

答案 0 :(得分:0)

您的代码有两处修改才能使其正常工作:

  1. 使用link_executable输出独立的可执行文件(compile.link()没用,改为使用子函数。)

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

    此时您应该收到以下错误消息:

    X:\dev\null>python_launcher.exe 
    ImportError: No module named site
    
  2. 那是因为你没有输入PYTHONPATH和PYTHONHOME变量env。在你的main.c:

    1. VARENV:

      putenv("PYTHONPATH=C:/Python27/Lib");
      putenv("PYTHONHOME=C:/Python27");
      
    2. 它应该与这些修复程序一起使用(在Windows XP x86,Python 2.7,VSExpress 2008上测试)

      整个代码:

      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"])