The Python Oracle

How do I execute multiple shell commands with a single python subprocess call?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 How Do I Execute Multiple Shell Commands With A Single Python Subprocess Call?
00:26 Accepted Answer Score 8
01:02 Thank you

--

Full question
https://stackoverflow.com/questions/3972...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #subprocess

#avk47



ACCEPTED ANSWER

Score 8


Use semicolon to chain them if they're independent.

For example, (Python 3)

>>> import subprocess
>>> result = subprocess.run('echo Hello ; echo World', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
>>> result
CompletedProcess(args='echo Hello ; echo World', returncode=0, stdout=b'Hello\nWorld\n')

But technically that's not a pure Python solution, because of shell=True. The arg processing is actually done by shell. (You may think of it as of executing /bin/sh -c "$your_arguments")

If you want a somewhat more pure solution, you'll have to use shell=False and loop over your several commands. As far as I know, there is no way to start multiple subprocesses directly with subprocess module.