Best practices for using subprocess?
Why is subprocess so hated?
How to use subprocess popen Python - Stack Overflow
Limitations of `subprocess`?
Videos
A pattern I keep coming across is wanting to use a Linux tool or some executable in a Python script. The easiest way to run arbitrary executables is obviously to use the Subprocess module, but for some reason this just feels hacky to me.
What are best practices for using the Subprocess module properly? When is it NOT advised? Is it actually as hacky as I feel it is?
Ultimately my goal is to get the functionality of executables that have presumably already been built, tested, and in some cases may have much better performance than if it were written in Python, without reinventing the wheel altogether.
I need to use subprocess to run programs like rclone. I've seen a lot of people hate on subprocess. know one of the things is to be careful about using the shell=True argument. Apart from that anything I should be worried about? Or any suggestions for a better way for a python script to run other command line programs?
subprocess.Popen takes a list of arguments:
from subprocess import Popen, PIPE
process = Popen(['swfdump', '/tmp/filename.swf', '-d'], stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
There's even a section of the documentation devoted to helping users migrate from os.popen to subprocess.
In the recent Python version, subprocess has a big change. It offers a brand-new class Popen to handle os.popen1|2|3|4.
The new subprocess.Popen()
import subprocess
subprocess.Popen('ls -la', shell=True)
Its arguments:
subprocess.Popen(args,
bufsize=0,
executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=False,
shell=False,
cwd=None, env=None,
universal_newlines=False,
startupinfo=None,
creationflags=0)
Simply put, the new Popen includes all the features which were split into 4 separate old popen.
The old popen:
Method Arguments
popen stdout
popen2 stdin, stdout
popen3 stdin, stdout, stderr
popen4 stdin, stdout and stderr
You could get more information in Stack Abuse - Robert Robinson. Thank him for his devotion.
» pip install subprocess.run