Last active
August 30, 2024 08:37
-
-
Save doublenns/ff63a62c7ef84a68db13b7212b68c959 to your computer and use it in GitHub Desktop.
Quick, dirty function to call shell commands from Python
This file contains 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
#!/usr/bin/env python3 | |
import subprocess | |
def run_shell_cmd(cmd, *shell): | |
# Might want to use a "try" or call.check in case Command fails | |
if "shell" or "sh" in shell.lower(): | |
process = subprocess.Popen(cmd, | |
stdout=subprocess.PIPE, shell=True) | |
else: | |
process = subprocess.Popen(cmd.split(), | |
stdout=subprocess.PIPE) | |
output = process.communicate()[0] | |
rc = process.returncode | |
return output, rc | |
# Examples | |
output, returncode = (run_shell_cmd("echo hello")) | |
# output = (run_shell_cmd("echo hello")[0]) | |
# Output will include the newline in it unless stripped. | |
# Output is also a byte object in Python3 as opposed to a string | |
# returncode = (run_shell_cmd("echo hello")[1]) | |
print("The output of the 1st shell command is: " + output.decode("utf-8").rstrip()) | |
print("The return code of the 1st shell command is:", returncode) | |
print() | |
output = run_shell_cmd("echo pipes{junk} and special characters | awk -F '{[^}]*}' '{print $1 $2}'", "shell")[0] | |
print("Using subprocess' shell=True works with", output.decode("utf-8").rstrip()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment