17

我在此目录下有一个 python 脚本:

work/project/test/a.py

在里面a.py,我用来subprocess.POPEN从另一个目录启动进程,

work/to_launch/file1.pl, file2.py, file3.py, ...

蟒蛇代码:

subprocess.POPEN("usr/bin/perl ../to_launch/file1.pl") 

在工作/项目/下,我输入以下内容

[user@machine project]python test/a.py,

错误“file2.py,'没有这样的文件或目录'”

如何添加work/to_launch/,以便file2.py可以找到这些依赖文件?

4

3 回答 3

16

您的代码不起作用,因为相对路径相对于您当前的位置(在 上一级test/a.py)可见。

sys.path[0]你有你当前正在运行的脚本的路径。

使用os.path.join(os.path.abspath(sys.path[0]), relPathToLaunch)withrelPathToLaunch = '../to_launch/file1.pl'获取您的绝对路径file1.plperl使用它运行。

编辑:如果您想从其目录启动 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
于 2010-09-21T16:48:47.320 回答
3

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

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

另请参阅我对Python 的回答:获取姐妹目录中文件的路径?

于 2010-09-21T17:42:01.640 回答
0

您可以使用此代码来设置当前目录:

import os
os.chdir("/path/to/your/files")
于 2010-09-21T16:57:31.470 回答