Python:具有不同工作目录的子进程
我有一个位于此目录下的 python 脚本:
work/project/test/a.py
在 a.py
内,我使用 subprocess.POPEN
从另一个目录启动进程,
work/to_launch/file1.pl, file2.py, file3.py, ...
Python 代码:
subprocess.POPEN("usr/bin/perl ../to_launch/file1.pl")
在 work/ 下project/ 时,我输入以下
[user@machine project]python test/a.py,
错误“file2.py,'没有这样的文件或目录'”
如何添加 work/to_launch/
,以便这些依赖文件 file2.py 可以找到吗?
I have a python script that is under this directory:
work/project/test/a.py
Inside a.py
, I use subprocess.POPEN
to launch the process from another directory,
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'"
How can I add work/to_launch/
, so that these dependent files file2.py
can be found?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码不起作用,因为相对路径是相对于您当前位置的(
test/a.py
上一级)。在
sys.path[0]
中,您拥有当前运行脚本的路径。将 os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch) 与 relPathToLaunch = '../to_launch/file1.pl' 结合使用获取
file1.pl
的绝对路径并使用它运行perl
。编辑:如果您想从其目录启动 file1.pl 然后返回,只需记住您当前的工作目录,然后切换回来:
Your code does not work, because the relative path is seen relatively to your current location (one level above the
test/a.py
).In
sys.path[0]
you have the path of your currently running script.Use
os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch)
withrelPathToLaunch = '../to_launch/file1.pl'
to get the absolute path to yourfile1.pl
and runperl
with it.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:
使用相对于脚本的路径,而不是当前工作目录
另请参阅我对 Python:获取姐妹目录中文件的路径?
Use paths relative to the script, not the current working directory
See also my answer to Python: get path to file in sister directory?
您可以使用此代码来设置当前目录:
You could use this code to set the current directory: