With Standard Library
With the standard library
The UseUse the subprocess module (Python 3):
import subprocess
subprocess.run(['ls', '-l'])
It is the recommended standard way. However, more complicated tasks (pipes, output, input, etc.) can be tedious to construct and write.
Note on Python version: If you are still using Python 2, subprocess.call works in a similar way.
ProTip: shlex.split can help you to parse the command for run
, call
, and other subprocess
functions in case you don't want (or you can't!) provide them in form of lists:
import shlex
import subprocess
subprocess.run(shlex.split('ls -l'))
With External Dependencies
With external dependencies
If you do not mind external dependencies, use plumbum:
from plumbum.cmd import ifconfig
print(ifconfig['wlan0']())
It is the best subprocess
wrapper. It's cross-platform, i.e. it works on both Windows and Unix-like systems. Install by pip install plumbum
.
Another popular library is sh:
from sh import ifconfig
print(ifconfig('wlan0'))
However, sh
dropped Windows support, so it's not as awesome as it used to be. Install by pip install sh
.