我正在使用作为脚本环境嵌入到应用程序 (x64) 中的 Python 3.1.4。 到目前为止,我遇到了很多嵌入式 python 的限制。不知道是正常现象还是应用程序的程序员屏蔽了一些功能。
例如下面的代码不工作:
from multiprocessing import Process
def f(name):
print('hello', name)
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
# --> error in forking.py: 'module' object has no attribute 'argv'
# print(sys.argv) gives the same error
sys.executable
返回应用程序的路径。
我也试过这个:
multiprocessing.forking.set_executable('C:\Python31\python.exe')
multiprocessing.set_executable('C:\Python31\python.exe')
没有成功。
有没有可能的解决方法?我不太可能有能力让应用程序的开发人员更改他们的代码中的某些内容。
谢谢
编辑
我通过添加以下内容让它工作:
sys.argv = ['c:/pathToScript/scipt.py']
我也需要这一行:
multiprocessing.set_executable('C:/Python31/python.exe')
否则应用程序的另一个实例将打开而不是运行代码。
我剩下的唯一问题是我不能使用控制应用程序本身的方法(例如:create_project()、add_report(),..)。我的主要目标是能够调用多个方法而无需等待第一个方法完成。但我认为这是不可能的。
最佳答案
默认情况下,sys.argv
在嵌入式代码中不可用:
Embedding Python
The basic initialization function is Py_Initialize(). This initializes the table of loaded modules, and creates the fundamental modules builtins, __main__, and sys. It also initializes the module search path (sys.path).
Py_Initialize() does not set the “script argument list” (sys.argv). If this variable is needed by Python code that will be executed later, it must be set explicitly with a call to PySys_SetArgvEx(argc, argv, updatepath) after the call to Py_Initialize()
在 Windows 上,multiprocessing
必须从头开始生成新进程。它使用命令行开关--multiprocessing-fork
来区分子进程,同时也将原始的argv
从父进程传递给子进程。
在创建子进程之前分配 sys.argv = ['c:/pathToScript/scipt.py']
,就像您发现的那样,
似乎是一个很好的解决方法。
第二个相关文档是 multiprocessing.set_executable()
的文档:
Sets the path of the Python interpreter to use when starting a child process. (By default
sys.executable
is used). Embedders will probably need to do some thing like
set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))
before they can create child processes. (Windows only)
关于python - 嵌入式 python : multiprocessing not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15636266/