子进程命令的控制环境

controlling environment for subprocess command

我正在尝试使用

从特定的绝对路径启动脚本
from subprocess import check_output

如果我运行:

# myscript.py
check_command=['pwd']
ret=check_output(check_command,shell=True)
print(ret)
path_set_command=['cd MYABSPATH']
ret=check_output(path_set_command,shell=True)
ret=check_output(check_command,shell=True)
print(ret)

它打印两次 myscript.py 所在的文件夹。 因此,我知道 shell 中的环境变量在每次调用 check_output.

时都会重新创建

如何用check_ouput设置命令的路径? 我试图让我的命令为

ret=check_output(['cd MYABSPATH; ./otherscript.py'] ,shell=True)

但是,如果我将参数传递给 otherscript.py(将它们作为额外项附加到包含命令的列表中),它们将不会被正确转发。

那么我如何 运行 otherscript.py in MYABSPATH with foo bar arguments?

在启动脚本之前使用 os module 更改目录。然后你应该能够访问你的脚本

import os
from subprocess import check_output

os.chdir('MYABSPATH')
ret = check_output(path_set_command, shell=True)
print(ret)

你可以使用 cwd:

foo = check_output("pwd", cwd="/MYABSPATH", shell=True)