Python:具有不同工作目录的子进程

2024-04-27 03:05:58 发布

您现在位置: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,'No such file or directory'”

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


Tags: topytest目录project脚本进程launch
3条回答

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

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

另见我对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,然后返回,只需记住当前工作目录,然后切换回:

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

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

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

相关问题 更多 >