如何选择 ProcessPoolExecutor 进程的 python 解释器?
How to choose the python interpreter of a ProcessPoolExecutor process?
我正在制作一个程序,运行s 在 ProcessPoolExecutor 中处理,returns 完成后结果。我想要 运行 的脚本使用了非常古老的库,所以我不想将它们包含在主脚本中。相反,我有另一个虚拟环境设置为 运行 子进程。
我正在使用 ProcessPoolExecutor 生成作业。当 运行 执行这些作业时,如何选择要使用的 python 解释器?
我看到 ProcessPoolExecutor 有一个 initargs
参数,但是当我将它包含在我的代码中时:
with concurrent.futures.ProcessPoolExecutor(
initargs=('PYTHONHOME', r'C:\Users\Tom.Mclean\Anaconda3\envs\weatherrouting_v1')) as pool:
return await loop.run_in_executor(pool, fn, *args)
它刚刚崩溃了。
编辑:
with concurrent.futures.ProcessPoolExecutor() as pool:
pool._mp_context.set_executable(r'C:\Users\Tom.Mclean\Anaconda3\envs\weatherrouting_v2\python.exe')
return await loop.run_in_executor(pool, fn, *args)
为池提供一个 multiprocessing
具有显式可执行文件的上下文。
import multiprocessing
import concurrent.futures
if __name__ == "__main__":
context = multiprocessing.get_context('spawn')
context.set_executable(...) # <<< set worker executable
with concurrent.futures.ProcessPoolExecutor(mp_context=context) as pool:
...
请注意,concurrent.futures
根据父进程的 concurrent.futures
库初始化工作进程。这意味着可执行文件必须能够解析 运行 父进程 ' 版本中的库。
结果,这可以例如与使用相同 Python 版本的不同 venv 一起使用。它不能用于 运行 明显较旧的 Python 版本,例如 Python 3.9 的父进程和 Python 3.7 的工作进程。
我正在制作一个程序,运行s 在 ProcessPoolExecutor 中处理,returns 完成后结果。我想要 运行 的脚本使用了非常古老的库,所以我不想将它们包含在主脚本中。相反,我有另一个虚拟环境设置为 运行 子进程。
我正在使用 ProcessPoolExecutor 生成作业。当 运行 执行这些作业时,如何选择要使用的 python 解释器?
我看到 ProcessPoolExecutor 有一个 initargs
参数,但是当我将它包含在我的代码中时:
with concurrent.futures.ProcessPoolExecutor(
initargs=('PYTHONHOME', r'C:\Users\Tom.Mclean\Anaconda3\envs\weatherrouting_v1')) as pool:
return await loop.run_in_executor(pool, fn, *args)
它刚刚崩溃了。
编辑:
with concurrent.futures.ProcessPoolExecutor() as pool:
pool._mp_context.set_executable(r'C:\Users\Tom.Mclean\Anaconda3\envs\weatherrouting_v2\python.exe')
return await loop.run_in_executor(pool, fn, *args)
为池提供一个 multiprocessing
具有显式可执行文件的上下文。
import multiprocessing
import concurrent.futures
if __name__ == "__main__":
context = multiprocessing.get_context('spawn')
context.set_executable(...) # <<< set worker executable
with concurrent.futures.ProcessPoolExecutor(mp_context=context) as pool:
...
请注意,concurrent.futures
根据父进程的 concurrent.futures
库初始化工作进程。这意味着可执行文件必须能够解析 运行 父进程 ' 版本中的库。
结果,这可以例如与使用相同 Python 版本的不同 venv 一起使用。它不能用于 运行 明显较旧的 Python 版本,例如 Python 3.9 的父进程和 Python 3.7 的工作进程。