在Windows上使用MS编译器构建Python模块
我正在尝试构建一个示例,这个示例是Python源代码包里的,路径在PC\example_nt。
我把example.c和setup.py复制到了一个目录C:\mymod。
当我运行 C:\Python27\python.exe setup.py install
时,出现了一个错误……
错误:无法找到 vcvarsall.bat
我在distutils里查了一下,发现它是想找微软Visual Studio的9版本,但我只有8版本。显然,它之所以要找9版本,是因为C:\Python27下的Python是用9版本编译的。
我修改了setup.py,把以下内容放在了最上面。
from distutils import msvc9compiler
msvc9compiler.VERSION = 8.0
这样做之后,我成功编译了,并得到了以下结果……
C:\mymod>C:\Python27\python.exe setup.py install
running install
running build
running build_ext
building 'example' extension
creating build
creating build\temp.win32-2.7
creating build\temp.win32-2.7\Release
C:\Program Files\Microsoft Visual Studio 8\VC\BIN\cl.exe /c /nologo /Ox /MD /W3
/GS- /DNDEBUG -IC:\Python27\include -IC:\Python27\PC /Tcexample.c /Fobuild\temp.
win32-2.7\Release\example.obj
example.c
creating build\lib.win32-2.7
C:\Program Files\Microsoft Visual Studio 8\VC\BIN\link.exe /DLL /nologo /INCREME
NTAL:NO /LIBPATH:C:\Python27\libs /LIBPATH:C:\Python27\PCbuild /EXPORT:initexamp
le build\temp.win32-2.7\Release\example.obj /OUT:build\lib.win32-2.7\example.pyd
/IMPLIB:build\temp.win32-2.7\Release\example.lib /MANIFESTFILE:build\temp.win32
-2.7\Release\example.pyd.manifest
Creating library build\temp.win32-2.7\Release\example.lib and object build\te
mp.win32-2.7\Release\example.exp
C:\Program Files\Microsoft Visual Studio 8\VC\BIN\mt.exe -nologo -manifest build
\temp.win32-2.7\Release\example.pyd.manifest -outputresource:build\lib.win32-2.7
\example.pyd;2
running install_lib
copying build\lib.win32-2.7\example.pyd -> C:\Python27\Lib\site-packages
running install_egg_info
Removing C:\Python27\Lib\site-packages\example-1.0-py2.7.egg-info
Writing C:\Python27\Lib\site-packages\example-1.0-py2.7.egg-info
现在,当我运行C:\Python27\python.exe并尝试 import example
时,出现了以下内容……
ImportError: DLL load failed: The specified module could not be found.
我是不是做错了什么?VS8是否不支持创建Python 2.7模块?我该怎么办?
最终,我需要为某个Windows C库构建绑定,这样我就可以用Python来扩展一些专有程序,而不是用C。我必须使用VS8来创建C扩展。那么这让我处于什么境地呢?
请给我一些建议。
谢谢,
~Eric
1 个回答
1
一般来说,你需要用和Python相同版本的Visual Studio(VS)来构建Python模块。你有几个选择:
- 使用Python2.6,我觉得这是VS8(或者更早的版本,我确定在2.5和2.6之间有变化)。
- 使用VS9。我猜你不能这样做,因为你正在使用的专有库是用VS8构建的。这和Python遇到的问题是一样的。
- 使用ctypes来创建你的绑定。这可能会很困难,而且很容易导致程序崩溃。
- 用VS8从源代码构建Python2.7。如果你因为某种原因不能使用Python2.6,那么这可能是最好的选择。
如果可行的话,我建议选择第一个选项。