Python:具有不同工作目录的子进程 [英] Python: subprocess with different working directory
问题描述
我在这个目录下有一个 python 脚本:
I have a python script that is under this directory:
work/project/test/a.py
在 a.py
中,我使用 subprocess.POPEN
从另一个目录启动进程,
Inside a.py
, I use subprocess.POPEN
to launch the process from another directory,
work/to_launch/file1.pl, file2.py, file3.py, ...
Python 代码:
subprocess.POPEN("usr/bin/perl ../to_launch/file1.pl")
在工作/项目/下,我输入以下内容
and under work/project/, I type the following
[user@machine project]python test/a.py,
错误file2.py,'没有那个文件或目录'"
error "file2.py, 'No such file or directory'"
如何添加work/to_launch/
,以便可以找到这些依赖文件file2.py
?
How can I add work/to_launch/
, so that these dependent files file2.py
can be found?
推荐答案
您的代码不起作用,因为相对路径是相对于您的当前位置(test/a.py
).
Your code does not work, because the relative path is seen relatively to your current location (one level above the test/a.py
).
在 sys.path[0]
中,您有当前正在运行的脚本的路径.
In sys.path[0]
you have the path of your currently running script.
使用 os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch)
和 relPathToLaunch = '../to_launch/file1.pl'
获取 file1.pl
的绝对路径并使用它运行 perl
.
Use os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch)
with relPathToLaunch = '../to_launch/file1.pl'
to get the absolute path to your file1.pl
and run perl
with it.
编辑:如果您想从其目录启动 file1.pl 然后返回,只需记住您当前的工作目录,然后切换回来:
EDIT: if you want to launch file1.pl from its directory and then return back, just remember your current working directory and then switch back:
origWD = os.getcwd() # remember our original working directory
os.chdir(os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch))
subprocess.POPEN("usr/bin/perl ./file1.pl")
[...]
os.chdir(origWD) # get back to our original working directory
这篇关于Python:具有不同工作目录的子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!