If I run echo a; echo b
in bash the result will be that both commands are run. However if I use subprocess then the first command is run, printing out the whole of the rest of the line.
The code below echos a; echo b
instead of a b
, how do I get it to run both commands?
JavaScript
x
8
1
import subprocess, shlex
2
def subprocess_cmd(command):
3
process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
4
proc_stdout = process.communicate()[0].strip()
5
print proc_stdout
6
7
subprocess_cmd("echo a; echo b")
8
Advertisement
Answer
You have to use shell=True in subprocess and no shlex.split:
JavaScript
1
11
11
1
import subprocess
2
3
command = "echo a; echo b"
4
5
ret = subprocess.run(command, capture_output=True, shell=True)
6
7
# before Python 3.7:
8
# ret = subprocess.run(command, stdout=subprocess.PIPE, shell=True)
9
10
print(ret.stdout.decode())
11
returns:
JavaScript
1
3
1
a
2
b
3