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

标签 python subprocess working-directory

<分区>

我在这个目录下有一个 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

关于Python:具有不同工作目录的子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3762468/

相关文章:

python - 列表与特定总和的组合

python - 在 python Docker 容器中安装 pip 包

c++ - 使用某个程序打开文件会更改该程序的工作目录吗?

c - 为以 exec 启动的进程设置自定义工作目录

Linux进程如何将数据从父进程传递给子进程

Mercurial:将补丁应用到工作目录

python - IPython Notebook session 中的多个目录和/或子目录?

python - Pandas:检查两个数据帧是否匹配值,然后根据标签填充一行

python - 在Python中将密码发送到sftp子进程

Python subprocess communicate() yields None,当需要数字列表时