我在这个目录下有一个 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
?
您的代码不起作用,因为相对路径是相对于您当前位置(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