Run consecutive Shell commands in Python-Subprocess

﹥>﹥吖頭↗ 提交于 2021-02-08 08:23:20

问题


These are some dependant commands i am trying to run. My expectation was it will change current folder to abc & list files.

Also after setting z=88, it will print z.

import subprocess
cmd_list = []
cmd_list.append("cd ./abc")
cmd_list.append("ls")
cmd_list.append("export z=88")
cmd_list.append("echo $z")

my_env = os.environ.copy()
for cmd in cmd_list:
    sp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env, shell=True,text=True)

But unable to get any output for ls and echo $z


回答1:


You can't do this with multiple calls to subprocess.Popen(). Each call creates a new child process, and changes they make to their environment do not propagate back to the Python process.

You can do it by concatenating all the commands into a single command line to be run by bash -c.

cmd = 'cd abc; ls; export z=88; echo $z'
subprocess.Popen(['bash', '-c', cmd], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=my_env,text=True)

There's also no point in exporting z, since you're not running any child processes of the shell that use the environment variable. Just assign an ordinary shell variable with z=88.



来源:https://stackoverflow.com/questions/61177465/run-consecutive-shell-commands-in-python-subprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!