Last active
June 9, 2022 03:07
-
-
Save jdgregson/a9f8c248bc4897268088fff00c891e05 to your computer and use it in GitHub Desktop.
Run system commands in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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