问题
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