Skip to content

Instantly share code, notes, and snippets.

@cgobat
Created September 2, 2022 17:44
Show Gist options
  • Save cgobat/d6688143af6a6e996c30b341f7f17f24 to your computer and use it in GitHub Desktop.
Save cgobat/d6688143af6a6e996c30b341f7f17f24 to your computer and use it in GitHub Desktop.
Python subprocess quick reference guide

Python subprocess quick reference guide

Some methods for running shell commands from within Python, depending on what the expected behavior and desired output are.


Popen

class subprocess.Popen(args, bufsize=- 1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=- 1, encoding=None, errors=None, text=None, pipesize=- 1)

Master class instantiated by the following functions.

run

func subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None, **other_popen_kwargs)

General-purpose function for running commands. Return value is a CompletedProcess with attributes depending on the function's arguments.

call

func subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

Runs the command, then returns simply the returncode.

check_call

func subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs)

Same as call, but raises an error if returncode != 0.

check_output

func subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)

Runs command, returns output, raises an error if returncode != 0.

getoutput

func subprocess.getoutput(cmd)

Return output (stdout and stderr) alone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment