Skip to content

Instantly share code, notes, and snippets.

@jdgregson
Last active June 9, 2022 03:07
Show Gist options
  • Save jdgregson/a9f8c248bc4897268088fff00c891e05 to your computer and use it in GitHub Desktop.
Save jdgregson/a9f8c248bc4897268088fff00c891e05 to your computer and use it in GitHub Desktop.
Run system commands in Python
"""
NOTE: This requires Python 3.9+ simply due to the use of "tuple" as a type hint.
If you remove type hints this works back to at least 3.4, and likely older.
"""
import subprocess
import sys
def syscmd(cmd: str) -> tuple[int, bytes]:
"""
Runs a command on the system, waits for the process to exit, and then returns
a tuple containing the return code and the text output of the command. This is
meant as a "no fuss" solution to subprocesses in Python. It works on Windows
and Linux. It returns all output, error messages, and return codes without
throwing exceptions if the command fails or is not found.
Usage (Windows):
>>> syscmd("cd C:/")
(0, b'')
>>> syscmd("cd /nonexistent")
(1, b'The system cannot find the path specified.')
>>> syscmd("nonexistent") #doctest: +ELLIPSIS
(1, b"'nonexistent' is not recognized as an internal or ...")
"""
p = subprocess.Popen(
cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, close_fds=(not sys.platform == "win32"))
p.wait()
output = p.stdout.read()
if len(output) > 1:
output = output.strip()
return p.returncode, output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment