问题描述
我正在尝试使用 python 子进程来执行脚本,这让我很感兴趣能够导入我的项目.在另一个进程中运行时,我只有典型的模块,而在执行导入时没有我的项目的模块.如何导入我的模块?
I am trying to use a python subprocess to execute a script, which interests me to be able to do an import of my project. When running in another process, I only have the typical modules, and not those of my project when doing an import. How can I get my modules imported?
示例:
first_script.py
import subprocess
from my_project.any_module import any_module
def __init__(self):
subprocess.call(['python', 'path/to/exec/second_script.py'])
second_script.py
from my_project.any_module import any_module
def __init__(self):
print any_module.argument
在第一个脚本中,import any_module 有效,在第二个脚本中无效.
In the first script, import any_module works, in the second it does not.
有什么想法吗?谢谢.
推荐答案
my_project
模块需要在你的 PYTHONPATH 中,这样 Python 才能找到它.PYTHONPATH 包含您当前的工作目录,这就是为什么当您运行它时它在您的第一个脚本中工作的原因.但是当你调用一个子进程时,cwd 是不同的.因此,您需要将 my_project
的路径添加到 PYTHONPATH,并使用 subprocess.call()
的 env
参数显式指定 PYTHONPATH.
The my_project
module needs to be in your PYTHONPATH so Python can find it. PYTHONPATH includes your current working directory, which is why it works in your first script when you run it. But when you invoke a subprocess, the cwd is different. So you need to add the path to my_project
to PYTHONPATH and specify PYTHONPATH explicitly with the env
argument to subprocess.call()
.
然而,以这种方式运行 Python 代码很尴尬.除非您有阻止这种情况的特定要求,否则我建议使用 multiprocessing 包而是在单独的进程中运行 Python 代码.
However, running Python code this way is awkward. Unless you have specific requirements that prevent this, I would suggest using the multiprocessing package instead to run Python code in a separate process.
这篇关于Python子进程我无法导入其他模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!