python - 嵌入式 python : multiprocessing not working

标签 python multiprocessing

我正在使用作为脚本环境嵌入到应用程序 (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/

相关文章:

python - N阶差分和N阶差分

python - 使用python将 "string-like"列表转换为int

python - 是否可以以编程方式(而不是从命令行)运行 manim?

python - 在 Python 脚本中将 freeze_support() 放在哪里?

python - 使每个进程都可以访问全局变量

python - Pyramid 全局对象跨线程共享

javascript - 如何让这个 websocket 示例与 Flask 一起工作?

python - 在池多处理中写入文件 (Python 2.7)

python - 为什么 Pandas 中的多重处理比简单计算慢?

具有不同功能的python多处理