Python Py_Initialize 运行需要哪些文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39539089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What files are required for Py_Initialize to run?
提问by Matt McC
I am working on a simple piece of code that runs a Python function from a C/C++ application. In order to do this I set the PYTHONPATH and run initialize as follows:
我正在编写一段从 C/C++ 应用程序运行 Python 函数的简单代码。为了做到这一点,我设置了 PYTHONPATH 并按如下方式运行初始化:
Py_SetPythonHome("../Python27");
Py_InitializeEx(0);
Then I import my module and run my function. It works great.
然后我导入我的模块并运行我的函数。它工作得很好。
I am now attempting to build an installer for my colleagues to run my code. I want to minimize the number of files I need to include in this installer, for obvious reasons.
我现在正在尝试为我的同事构建一个安装程序来运行我的代码。出于显而易见的原因,我想尽量减少需要包含在此安装程序中的文件数量。
Googling around the subject tells me that I should be able to include the files "Python27.lib" and "Python27.dll", then zip the "DLLs" and "Lib" folders and include them. However, when I attempt this, Py_Initialize fails.
谷歌搜索这个主题告诉我,我应该能够包含文件“Python27.lib”和“Python27.dll”,然后压缩“DLL”和“Lib”文件夹并包含它们。但是,当我尝试这样做时, Py_Initialize 失败了。
A quick examination of what is causing this failure shows that Py_Initialize appears to depend upon a number of .pyc files in the Lib folder including (but not limited to warnings.pyc, _abcoll.pyc, _future_.pycand the contents of the "encodings" folder.
快速检查导致此失败的原因表明 Py_Initialize 似乎依赖于 Lib 文件夹中的许多 .pyc 文件,包括(但不限于warnings.pyc、_abcoll.pyc、_future_.pyc和“编码”的内容“ 文件夹。
I cannot understand why this would be. Any advice?
我不明白为什么会这样。有什么建议吗?
采纳答案by CristiFati
At the beginning, I wanted to say that there's no module required (at least no non-builtinone) for Py_InitializeEx, so the only requirement was python27.dll(btw: python27.libis notrequired, unless your colleagues want to link something against it - but that wouldn't be very easy w/o Python's Includedir). I had this code (BTW: I am using Python 2.7.10that I built using VStudio 10(2010)):
在开始的时候,我想说的话,有没有需要的模块(至少没有非内置之一)Py_InitializeEx,所以是唯一的要求python27.dll(顺便说一句:python27.lib是不是必须的,除非你的同事要链接的东西反对它 - 但如果没有Python的Include目录,那不会很容易)。我有这个代码(顺便说一句:我使用的是我使用VStudio 10( 2010)构建的Python 2.7.10):
#include <stdio.h>
#include <conio.h>
#include <Python.h>
int main() {
int i = 0;
char *pyCode =
"s = \"abc\"\n"
"print s, 1234";
Py_InitializeEx(0);
i = PyRun_SimpleString(pyCode);
Py_Finalize();
printf("PyRun_SimpleString returned: %d\nPress a key to exit...\n", i);
_getch();
return 0;
}
It built fine, it ran OK from VStudio, and from the command line (after copying the .dllin its folder). But then I copied the .exeand .dllto another computer and when running, bang!!!
它构建良好,从VStudio和命令行运行正常(在其文件夹中复制.dll之后)。但是后来我将.exe和.dll复制到另一台计算机,运行时,砰!!!
ImportError: No module named site
ImportError: No module named site
Considering that:
考虑到:
- I have no PYTHON*env vars set in neither of the consoles on the 2 machines where I ran the .exe(with different results)
- On both machines the Pythoninstallation is on the same path (I previously (years ago) modified it on the machine that doesn't work)
- 我在运行.exe的两台机器上的两个控制台中都没有设置PYTHON*env vars (结果不同)
- 在两台机器上,Python安装在同一路径上(我以前(几年前)在无法工作的机器上修改了它)
I don't know why it doesn't behave the same (one thing that I haven't check is that there might be some registry key on the machine that works?).
我不知道为什么它的行为不一样(我没有检查的一件事是机器上可能有一些可以工作的注册表项?)。
Note: siteis a (.py(c)) module located under %PYTHON_INSTALL_DIR%\Lib.
注意:站点是位于%PYTHON_INSTALL_DIR%\Lib下的(.py(c))模块。
Then, I browsed Python's source code and I came across this (file: pythonrun.c, line: 269, function Py_InitializeExor pythonrun.c:269: Py_InitializeEx- this is how I'm going to refer a point in the source code):
然后,我浏览了Python的源代码,发现了这个(文件:pythonrun.c,行:269,函数Py_InitializeEx或pythonrun.c:269:Py_InitializeEx- 这就是我将如何引用源代码中的一个点代码):
if (!Py_NoSiteFlag)
initsite(); /* Module site */
while in pythonrun.c:727: initsite:
在pythonrun.c:727: initsite 中:
m = PyImport_ImportModule("site");
which is pretty obvious (Py_NoSiteFlagis 0).
这很明显(Py_NoSiteFlag为 0)。
Then I noticed that Py_NoSiteFlagis declared as extern __declspec(dllexport)
([MS.Docs]: Using extern to Specify Linkage, [MS.Docs]: dllexport, dllimport), so I modified my code to:
然后我注意到Py_NoSiteFlag被声明为extern __declspec(dllexport)
( [MS.Docs]: Using extern to Specify Linkage, [MS.Docs]: dllexport, dllimport),所以我将代码修改为:
#include <stdio.h>
#include <conio.h>
#include <Python.h>
extern __declspec(dllimport) int Py_NoSiteFlag;
int main() {
int i = 0;
char *pyCode =
"s = \"abc\"\n"
"print s, 1234";
Py_NoSiteFlag = 1;
Py_InitializeEx(0);
i = PyRun_SimpleString(pyCode);
Py_Finalize();
printf("PyRun_SimpleString returned: %d\nPress a key to exit...\n", i);
_getch();
return 0;
}
and it works! Yay!
它有效!好极了!
So, at this point only the .dllis required in order to run a piece of code. But I imagine that your code is "a little bit" more complex than that (it has imports ([Python 2.Docs]: The import statement). To solve the importproblem, you can use this nice module: [Python 2.Docs]: modulefinder - Find modules used by a script(part of Python 2.7's standard modules). To make use of it:
因此,此时只需要.dll即可运行一段代码。但我想你的代码比那“有点”复杂(它有imports([Python 2.Docs]:导入语句)。要解决导入问题,你可以使用这个不错的模块:[Python 2 .Docs]: modulefinder - 查找脚本使用的模块(Python 2.7标准模块的一部分)。要使用它:
- Save the code that you execute from Cin a .pyfile
- Run modulefinderagainst it
- 将您从C执行的代码保存在.py文件中
- 针对它运行modulefinder
Here's an example for my code (pyCodecontents in my Cprogram, saved in a file).
这是我的代码示例(我的C程序中的pyCode内容,保存在文件中)。
code.py:
代码.py:
s = "abc"
print s, 1234
Running:
跑步:
%PYTHON_INSTALL_DIR%\python -m modulefinder code.py
%PYTHON_INSTALL_DIR%\python -m modulefinder code.py
yields:
产量:
Name File ---- ---- m __main__ code.py
Name File ---- ---- m __main__ code.py
But, if I add an import os
(which is a pretty common module) statement in the file, the above command yields:
但是,如果我import os
在文件中添加一个(这是一个非常常见的模块)语句,上面的命令会产生:
Name File ---- ---- m StringIO %PYTHON_INSTALL_DIR%\lib\StringIO.py m UserDict %PYTHON_INSTALL_DIR%\lib\UserDict.py m __builtin__ m __future__ %PYTHON_INSTALL_DIR%\lib\__future__.py m __main__ a.py m _abcoll %PYTHON_INSTALL_DIR%\lib\_abcoll.py m _codecs m _collections m _functools m _hashlib %PYTHON_INSTALL_DIR%\DLLs\_hashlib.pyd m _heapq m _io m _locale m _random m _sre m _struct m _subprocess m _threading_local %PYTHON_INSTALL_DIR%\lib\_threading_local.py m _warnings m _weakref m _weakrefset %PYTHON_INSTALL_DIR%\lib\_weakrefset.py m abc %PYTHON_INSTALL_DIR%\lib\abc.py m array m atexit %PYTHON_INSTALL_DIR%\lib\atexit.py m bdb %PYTHON_INSTALL_DIR%\lib\bdb.py m binascii m cPickle m cStringIO m cmd %PYTHON_INSTALL_DIR%\lib\cmd.py m codecs %PYTHON_INSTALL_DIR%\lib\codecs.py m collections %PYTHON_INSTALL_DIR%\lib\collections.py m copy %PYTHON_INSTALL_DIR%\lib\copy.py m copy_reg %PYTHON_INSTALL_DIR%\lib\copy_reg.py m difflib %PYTHON_INSTALL_DIR%\lib\difflib.py m dis %PYTHON_INSTALL_DIR%\lib\dis.py m doctest %PYTHON_INSTALL_DIR%\lib\doctest.py m dummy_thread %PYTHON_INSTALL_DIR%\lib\dummy_thread.py P encodings %PYTHON_INSTALL_DIR%\lib\encodings\__init__.py m encodings.aliases %PYTHON_INSTALL_DIR%\lib\encodings\aliases.py m errno m exceptions m fnmatch %PYTHON_INSTALL_DIR%\lib\fnmatch.py m functools %PYTHON_INSTALL_DIR%\lib\functools.py m gc m genericpath %PYTHON_INSTALL_DIR%\lib\genericpath.py m getopt %PYTHON_INSTALL_DIR%\lib\getopt.py m gettext %PYTHON_INSTALL_DIR%\lib\gettext.py m hashlib %PYTHON_INSTALL_DIR%\lib\hashlib.py m heapq %PYTHON_INSTALL_DIR%\lib\heapq.py m imp m inspect %PYTHON_INSTALL_DIR%\lib\inspect.py m io %PYTHON_INSTALL_DIR%\lib\io.py m itertools m keyword %PYTHON_INSTALL_DIR%\lib\keyword.py m linecache %PYTHON_INSTALL_DIR%\lib\linecache.py m locale %PYTHON_INSTALL_DIR%\lib\locale.py P logging %PYTHON_INSTALL_DIR%\lib\logging\__init__.py m marshal m math m msvcrt m nt m ntpath %PYTHON_INSTALL_DIR%\lib\ntpath.py m opcode %PYTHON_INSTALL_DIR%\lib\opcode.py m operator m optparse %PYTHON_INSTALL_DIR%\lib\optparse.py m os %PYTHON_INSTALL_DIR%\lib\os.py m os2emxpath %PYTHON_INSTALL_DIR%\lib\os2emxpath.py m pdb %PYTHON_INSTALL_DIR%\lib\pdb.py m pickle %PYTHON_INSTALL_DIR%\lib\pickle.py m posixpath %PYTHON_INSTALL_DIR%\lib\posixpath.py m pprint %PYTHON_INSTALL_DIR%\lib\pprint.py m random %PYTHON_INSTALL_DIR%\lib\random.py m re %PYTHON_INSTALL_DIR%\lib\re.py m repr %PYTHON_INSTALL_DIR%\lib\repr.py m select %PYTHON_INSTALL_DIR%\DLLs\select.pyd m shlex %PYTHON_INSTALL_DIR%\lib\shlex.py m signal m sre_compile %PYTHON_INSTALL_DIR%\lib\sre_compile.py m sre_constants %PYTHON_INSTALL_DIR%\lib\sre_constants.py m sre_parse %PYTHON_INSTALL_DIR%\lib\sre_parse.py m stat %PYTHON_INSTALL_DIR%\lib\stat.py m string %PYTHON_INSTALL_DIR%\lib\string.py m strop m struct %PYTHON_INSTALL_DIR%\lib\struct.py m subprocess %PYTHON_INSTALL_DIR%\lib\subprocess.py m sys m tempfile %PYTHON_INSTALL_DIR%\lib\tempfile.py m textwrap %PYTHON_INSTALL_DIR%\lib\textwrap.py m thread m threading %PYTHON_INSTALL_DIR%\lib\threading.py m time m token %PYTHON_INSTALL_DIR%\lib\token.py m tokenize %PYTHON_INSTALL_DIR%\lib\tokenize.py m traceback %PYTHON_INSTALL_DIR%\lib\traceback.py m types %PYTHON_INSTALL_DIR%\lib\types.py P unittest %PYTHON_INSTALL_DIR%\lib\unittest\__init__.py m unittest.case %PYTHON_INSTALL_DIR%\lib\unittest\case.py m unittest.loader %PYTHON_INSTALL_DIR%\lib\unittest\loader.py m unittest.main %PYTHON_INSTALL_DIR%\lib\unittest\main.py m unittest.result %PYTHON_INSTALL_DIR%\lib\unittest\result.py m unittest.runner %PYTHON_INSTALL_DIR%\lib\unittest\runner.py m unittest.signals %PYTHON_INSTALL_DIR%\lib\unittest\signals.py m unittest.suite %PYTHON_INSTALL_DIR%\lib\unittest\suite.py m unittest.util %PYTHON_INSTALL_DIR%\lib\unittest\util.py m warnings %PYTHON_INSTALL_DIR%\lib\warnings.py m weakref %PYTHON_INSTALL_DIR%\lib\weakref.py Missing modules: ? _emx_link imported from os ? ce imported from os ? fcntl imported from subprocess, tempfile ? org.python.core imported from copy, pickle ? os.path imported from os, shlex ? os2 imported from os ? posix imported from os ? pwd imported from posixpath ? readline imported from cmd, pdb ? riscos imported from os ? riscosenviron imported from os ? riscospath imported from os
Name File ---- ---- m StringIO %PYTHON_INSTALL_DIR%\lib\StringIO.py m UserDict %PYTHON_INSTALL_DIR%\lib\UserDict.py m __builtin__ m __future__ %PYTHON_INSTALL_DIR%\lib\__future__.py m __main__ a.py m _abcoll %PYTHON_INSTALL_DIR%\lib\_abcoll.py m _codecs m _collections m _functools m _hashlib %PYTHON_INSTALL_DIR%\DLLs\_hashlib.pyd m _heapq m _io m _locale m _random m _sre m _struct m _subprocess m _threading_local %PYTHON_INSTALL_DIR%\lib\_threading_local.py m _warnings m _weakref m _weakrefset %PYTHON_INSTALL_DIR%\lib\_weakrefset.py m abc %PYTHON_INSTALL_DIR%\lib\abc.py m array m atexit %PYTHON_INSTALL_DIR%\lib\atexit.py m bdb %PYTHON_INSTALL_DIR%\lib\bdb.py m binascii m cPickle m cStringIO m cmd %PYTHON_INSTALL_DIR%\lib\cmd.py m codecs %PYTHON_INSTALL_DIR%\lib\codecs.py m collections %PYTHON_INSTALL_DIR%\lib\collections.py m copy %PYTHON_INSTALL_DIR%\lib\copy.py m copy_reg %PYTHON_INSTALL_DIR%\lib\copy_reg.py m difflib %PYTHON_INSTALL_DIR%\lib\difflib.py m dis %PYTHON_INSTALL_DIR%\lib\dis.py m doctest %PYTHON_INSTALL_DIR%\lib\doctest.py m dummy_thread %PYTHON_INSTALL_DIR%\lib\dummy_thread.py P encodings %PYTHON_INSTALL_DIR%\lib\encodings\__init__.py m encodings.aliases %PYTHON_INSTALL_DIR%\lib\encodings\aliases.py m errno m exceptions m fnmatch %PYTHON_INSTALL_DIR%\lib\fnmatch.py m functools %PYTHON_INSTALL_DIR%\lib\functools.py m gc m genericpath %PYTHON_INSTALL_DIR%\lib\genericpath.py m getopt %PYTHON_INSTALL_DIR%\lib\getopt.py m gettext %PYTHON_INSTALL_DIR%\lib\gettext.py m hashlib %PYTHON_INSTALL_DIR%\lib\hashlib.py m heapq %PYTHON_INSTALL_DIR%\lib\heapq.py m imp m inspect %PYTHON_INSTALL_DIR%\lib\inspect.py m io %PYTHON_INSTALL_DIR%\lib\io.py m itertools m keyword %PYTHON_INSTALL_DIR%\lib\keyword.py m linecache %PYTHON_INSTALL_DIR%\lib\linecache.py m locale %PYTHON_INSTALL_DIR%\lib\locale.py P logging %PYTHON_INSTALL_DIR%\lib\logging\__init__.py m marshal m math m msvcrt m nt m ntpath %PYTHON_INSTALL_DIR%\lib\ntpath.py m opcode %PYTHON_INSTALL_DIR%\lib\opcode.py m operator m optparse %PYTHON_INSTALL_DIR%\lib\optparse.py m os %PYTHON_INSTALL_DIR%\lib\os.py m os2emxpath %PYTHON_INSTALL_DIR%\lib\os2emxpath.py m pdb %PYTHON_INSTALL_DIR%\lib\pdb.py m pickle %PYTHON_INSTALL_DIR%\lib\pickle.py m posixpath %PYTHON_INSTALL_DIR%\lib\posixpath.py m pprint %PYTHON_INSTALL_DIR%\lib\pprint.py m random %PYTHON_INSTALL_DIR%\lib\random.py m re %PYTHON_INSTALL_DIR%\lib\re.py m repr %PYTHON_INSTALL_DIR%\lib\repr.py m select %PYTHON_INSTALL_DIR%\DLLs\select.pyd m shlex %PYTHON_INSTALL_DIR%\lib\shlex.py m signal m sre_compile %PYTHON_INSTALL_DIR%\lib\sre_compile.py m sre_constants %PYTHON_INSTALL_DIR%\lib\sre_constants.py m sre_parse %PYTHON_INSTALL_DIR%\lib\sre_parse.py m stat %PYTHON_INSTALL_DIR%\lib\stat.py m string %PYTHON_INSTALL_DIR%\lib\string.py m strop m struct %PYTHON_INSTALL_DIR%\lib\struct.py m subprocess %PYTHON_INSTALL_DIR%\lib\subprocess.py m sys m tempfile %PYTHON_INSTALL_DIR%\lib\tempfile.py m textwrap %PYTHON_INSTALL_DIR%\lib\textwrap.py m thread m threading %PYTHON_INSTALL_DIR%\lib\threading.py m time m token %PYTHON_INSTALL_DIR%\lib\token.py m tokenize %PYTHON_INSTALL_DIR%\lib\tokenize.py m traceback %PYTHON_INSTALL_DIR%\lib\traceback.py m types %PYTHON_INSTALL_DIR%\lib\types.py P unittest %PYTHON_INSTALL_DIR%\lib\unittest\__init__.py m unittest.case %PYTHON_INSTALL_DIR%\lib\unittest\case.py m unittest.loader %PYTHON_INSTALL_DIR%\lib\unittest\loader.py m unittest.main %PYTHON_INSTALL_DIR%\lib\unittest\main.py m unittest.result %PYTHON_INSTALL_DIR%\lib\unittest\result.py m unittest.runner %PYTHON_INSTALL_DIR%\lib\unittest\runner.py m unittest.signals %PYTHON_INSTALL_DIR%\lib\unittest\signals.py m unittest.suite %PYTHON_INSTALL_DIR%\lib\unittest\suite.py m unittest.util %PYTHON_INSTALL_DIR%\lib\unittest\util.py m warnings %PYTHON_INSTALL_DIR%\lib\warnings.py m weakref %PYTHON_INSTALL_DIR%\lib\weakref.py Missing modules: ? _emx_link imported from os ? ce imported from os ? fcntl imported from subprocess, tempfile ? org.python.core imported from copy, pickle ? os.path imported from os, shlex ? os2 imported from os ? posix imported from os ? pwd imported from posixpath ? readline imported from cmd, pdb ? riscos imported from os ? riscosenviron imported from os ? riscospath imported from os
As you can see, there is an awfully lot of modules (I modified the output a little bit, instead of the actual path I placed the %PYTHON_INSTALL_DIR%env var). In order for the Pythoncode to work, you'll have to include all of those modules/packages in the installer.
如您所见,有非常多的模块(我稍微修改了输出,而不是我放置%PYTHON_INSTALL_DIR% 环境变量的实际路径)。为了让Python代码正常工作,您必须在安装程序中包含所有这些模块/包。
Notesabout modulefinder's output (that I've noticed while playing with it):
关于modulefinder输出的注意事项(我在使用它时注意到):
- It searches for modules recursively, so here is the whole module dependency tree
- It searches for importstatements located in functions (so, not only the ones at module level)
- It doesn'tsearch for dynamic imports (e.g. [Python 2.Docs]: __import__(name[, globals[, locals[, fromlist[, level]]]]))
- 它递归地搜索模块,所以这里是整个模块依赖树
- 它搜索位于函数中的导入语句(因此,不仅是模块级别的语句)
- 它不搜索动态imports(例如[Python 2.Docs]: __import__( name[, globals[, locals[, fromlist[, level]]]]))
So, looking at the modules that are required by os, I'm not sure that taking out the siteimport from Cmakes much of a difference.
因此,查看os所需的模块,我不确定从C 中取出站点导入会产生很大的不同。
IMPORTANT NOTE: To make sure your .exeworks on any computer, you might consider including VStudio C Runtime Libraryor VCRTLib(msvcr##(#).dll: [MS.Docs]: Run-Time Library Reference) (where #s are placeholders for digits - representing VStudioversion) in your installer.
重要说明:为了确保您的.exe可以在任何计算机上运行,您可以考虑包含VStudio C 运行时库或VCRTLib(msvcr##(#).dll: [MS.Docs]: 运行时库参考)(其中#s是安装程序中的数字占位符 - 代表VStudio版本)。