Python subprocess: Running External Commands Safely
The subprocess module runs external commands from Python. Here is how I use it without shell injection risks and deadlocks. The subprocess module lets Python run external commands. shell scripts, system utilities, other programs. It replaced the older os.system and os.popen functions, which are limited and insecure. I use subprocess for build scripts, git automation, and calling tools that lack Python bindings. The module is powerful but has pitfalls around security, deadlocks, and output handling that I learned to work with. run: The Modern Interface The run function, added in Python 3.5, is the recommended interface for most use cases. It runs a command, waits for it to complete, and returns a CompletedProcess object with the return code, stdout, and stderr. import subprocess result = subprocess.run( ['git', 'status'], capture_output=True, text=True, ) print(result.returncode) # 0 for success print(result.stdout) # command output print(result.stderr) # error output Passing the command as a list of strings is the safe way. Each element is a separate argument, so there is no shell interpretation. The text=True parameter decodes output as text (UTF-8 by default) instead of returning bytes. The capture_output=True parameter captures both stdout and stderr.…