我有一个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,'No such file or directory'”
如何添加work/to_launch/
,以便找到这些依赖文件file2.py
?
使用与脚本相关的路径,而不是当前工作目录
另见我对Python: get path to file in sister directory?的回答
代码无法工作,因为相对路径相对于当前位置可见(高于
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,然后返回,只需记住当前工作目录,然后切换回:
可以使用此代码设置当前目录:
相关问题 更多 >
编程相关推荐