Running Bash commands in Python - Stack Overflow
Some summary:
- Use
subprocess.run() - Be aware of the following argument possibilities with
subprocess.run():check=True— Raises an error should the process failsstdout=subprocess.PIPEandstderr=subprocess.PIPEto capture outputs from processuniversal_newlines=True(ortext=Truein Python 3.7) — Ensures thatstdoutandstderrare encoded as unicode instead of byte stringsshell=True- Pass a single string to your shell
- Able to take advantage of shell features like redirection, wildcard expansions, etc
shell=False- (Default) Supply arguments as a list. Augment
shlex.splitto return appropriate list from a string. - More lightweight, reduces hidden complexities and minimizes chance of bugs and security problems
- Limitations of not using shell can be handled directly via Python
- (Default) Supply arguments as a list. Augment
env={‘foo’: ‘bar’}— Exposes environmental variablefoowith value”bar”to subprocessexecutable:/bin/bash— Specify which executable should execute this process