How do I execute a program or call a system command?
For Python versions 3.5 and above, leverage subprocess.run()
of the subprocess
module to execute system commands.
Take echo
for instance:
The output can be captured using capture_output=True
:
In Python <3.5, use subprocess.call()
as a substitute for run
:
Mastering Process Control: subprocess.Popen
For complex subprocess interactions, real-time control of the process I/O, the mighty subprocess.Popen
comes to rescue! Ideal when your process requires timely outputs or inputs.
An example of subprocess.Popen
usage:
Ensure to "clean your room" — terminate your subprocesses properly to avoid ghost processes.👻
Safety First: Sanitize inputs
While playing with subprocesses, you should be like a goalkeeper— keeping the injections attacks at bay. Always remember to sanitize user inputs, especially if your command uses any user-generated data.
Check out sanitized inputs in action:
Redirect, Detach, Repeat: Advanced subprocess control
Subprocesses may need to detach or redirect errors for specific functionalities. subprocess.Popen
offers multiple options, such as stderr
and creation flags like DETACHED_PROCESS
and CREATE_NEW_CONSOLE
on Windows.
Redirecting errors — keep calm and redirect:
Creating a detached process on Windows — a little "me time":
Remember, just as every superhero has a unique power, every operating system has its own behavior. So, if you're targeting multiple platforms, make sure your script runs consistently across all of them.
Emulating subprocesses and cross-platform consistency
Subprocesses can be naughty and behave differently across OS environments. Know their nuances for termination and streaming I/O on varying platforms. For more control, you can use subprocess.Popen
to emulate the os.system()
behavior in complex cases without setting stdout
and stderr
.
File handling, FreeBSD style:
To ensure your script remains consistent across different OSes, brace it with thorough testing and conditional logic:
For faster and more secure alternative execution methods, consider the os.exec*
and os.spawn*
families, where the called command isn't wrapped in a shell.
Was this article helpful?