Python:使用不同工作目录的subprocess

19 投票
3 回答
44672 浏览
提问于 2025-04-16 04:25

我有一个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了?

3 个回答

1

你可以使用这段代码来设置当前的目录:

import os
os.chdir("/path/to/your/files")
3

使用相对于脚本的路径,而不是当前工作目录

os.path.join(os.path.dirname(__file__), '../../to_launch/file1.pl)

另外,你可以看看我对这个问题的回答:Python: 如何获取姐妹目录中的文件路径?

18

你的代码不工作,是因为相对路径是相对于你当前的位置来看待的(也就是在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所在的目录启动它,然后再返回,记得保存你当前的工作目录,然后再切换回来:

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

撰写回答