Running system commands
In some cases, especially when writing system tools, there might be work that you need to offload to another command. For example, if you have to decompress a file, in many cases, it might make sense to offload the work to gunzip
/zip
commands instead or trying to reproduce the same behavior in Python.
While there are many ways in Python to handle this work, they all have subtle differences that might make the life of any developer hard, so it's good to have a generally working solution that tackles the most common issues.
How to do it...
Perform the following steps:
- Combining the
subprocess
andshlex
modules allows us to build a solution that is reliable in most cases:
import shlex import subprocess def run(command): try: result = subprocess.check_output(shlex.split(command), stderr=subprocess.STDOUT) return 0, result except subprocess.CalledProcessError as e: return e.returncode, e.output
- It's easy...