4

我正在开发一个简单的(?)嵌入式 Python 项目。我有一个自定义包,它已通过“setup.py install”安装到站点包中,例如:

在 C:\Python27\Lib\site-packages\:

mypackage\
    __init__.py
    subpackage\
        __init__.py
        subpackage.py
    .... 
    mymodule.py

只是做了一些简单的嵌入调用,我得到的一些行为与我在运行 Python 的 cmd 窗口中得到的行为不匹配。具体来说:

PyRun_SimpleString("import mypackage") //Success (return == 0)
PyRun_SimpleString("from mypackage import subpackage") //Success
PyRun_SimpleString("from mypackage import mymodule") //Fail (return == -1)

...而所有这些在 cmd 窗口中都可以正常工作(没有 ImportError,我可以在例如dir(mymodule)

我知道由此产生的解释器与Py_Initialize()您在 cmd 窗口中获得的解释器略有不同,特别是 sys.path ...在阅读了一些其他答案后,我尝试将 '' 作为第一个元素插入 sys .path: PyRun_SimpleString("import sys\nsys.path.insert(0,'')")在导入失败之前,但没有运气,仍然返回-1。还尝试将 sys.path 附加到“C:\Python27\Lib\site-packages\mypackage”,但导入“mymodule”(mymodule.py)仍然没有运气。

基于 SO 和其他网站上的其他示例,我在导入时尝试了一些变体,例如

__import__('mypackage',globals(), locals(), fromlist=['mymodule'])
__import__('mypackage.mymodule',globals(), locals(), fromlist=['mymodule'])

也尝试过PyImport_ImportModuleEx,与 PyRun_SimpleString 一样,它适用于除“from mypackage import mymodule”之外的所有内容。

此外:此方案在 MacOS/Python 2.7 下运行良好。它只是在Windows下失败了。

Any ideas where this could be going off the rails?

UPDATE: some additional information: 'subpackage.py' imports an extension library (let's call it 'utilites.pyd'). I'm able to import other ".py" modules that do not import this.

4

1 回答 1

0

Taking the rare opportunity to answer my own question...

Once I narrowed the problem down to modules that were importing the utilities.pyd extension, I did some digging around with the Dependency Walker tool and discovered that there was an error loading MSVCR90.DLL (file not found). In the old days, you could just drop that DLL into your application's path and it would usually work.

But nowadays (Vista and after), it's a bit more involved. After reading this interesting blog post about an older MSVCR DLL, I figured I would try updating the <dependency> section of the manifest of my .pyd file to point to the same MSVCR90.DLL as Python27.DLL which resides in the \Windows\WinSxS (side-by-side) folder.

After that, it worked like a charm. Now I just need to figure out how to automatically include the dependency section during python setup.py mypackage, but that's another question :-)

于 2012-04-18T20:56:12.443 回答