Python:具有不同工作目录的子进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3762468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: subprocess with different working directory
提问by pepero
I have a python script that is under this directory:
我在这个目录下有一个 python 脚本:
work/project/test/a.py
Inside a.py, I use subprocess.POPENto launch the process from another directory,
在里面a.py,我用来subprocess.POPEN从另一个目录启动进程,
work/to_launch/file1.pl, file2.py, file3.py, ...
Python Code:
蟒蛇代码:
subprocess.POPEN("usr/bin/perl ../to_launch/file1.pl")
and under work/project/, I type the following
在工作/项目/下,我输入以下内容
[user@machine project]python test/a.py,
error "file2.py, 'No such file or directory'"
错误“file2.py,'没有这样的文件或目录'”
How can I add work/to_launch/, so that these dependent files file2.pycan be found?
如何添加work/to_launch/,以便file2.py可以找到这些依赖文件?
回答by eumiro
Your code does not work, because the relative path is seen relatively to your current location (one level above the test/a.py).
您的代码不起作用,因为相对路径是相对于您的当前位置(在 上的一级test/a.py)。
In sys.path[0]you have the path of your currently running script.
在sys.path[0]你有你的当前运行的脚本的路径。
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.pland run perlwith it.
使用os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch)withrelPathToLaunch = '../to_launch/file1.pl'获取你的绝对路径file1.pl并运行perl它。
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:
编辑:如果您想从其目录启动 file1.pl 然后返回,只需记住您当前的工作目录,然后切换回:
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
回答by anijhaw
You could use this code to set the current directory:
您可以使用此代码设置当前目录:
import os
os.chdir("/path/to/your/files")
回答by Adam Byrtek
Use paths relative to the script, not the current working directory
使用相对于脚本的路径,而不是当前工作目录
os.path.join(os.path.dirname(__file__), '../../to_launch/file1.pl)
See also my answer to Python: get path to file in sister directory?
另请参阅我对Python 的回答:获取姊妹目录中的文件路径?

