Use the subprocess
module in the standard librarysubprocess.run
:
import subprocess
# for simple commands
subprocess.run(["ls", "-l"])
# for complex commands, with many args, use string + `shell=True`:
cmd_str = "ls -l /tmp | awk '{print $3,$9}' | grep root"
subprocess.run(cmd_str, shell=True)
The advantage of subprocess.run
overAnother common way is os.system
is thatbut you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also subprocess.run
is generally more flexible (you can get the stdout
, stderr
, the "real" status code, better error handling, it is not prone to problems due to spaces in folders in the path to the executable, etc...).
Even the the documentationdocumentation for os.system
recommends using subprocess
instead:.
The
subprocess
module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in thesubprocess
documentation for some helpful recipes.
On Python 3.4 and earlier, use subprocess.call
instead of .run
:
subprocess.call(["ls", "-l"])