Skip to content

Instantly share code, notes, and snippets.

@doublenns
Last active November 21, 2019 19:43
Show Gist options
  • Save doublenns/ff63a62c7ef84a68db13b7212b68c959 to your computer and use it in GitHub Desktop.
Save doublenns/ff63a62c7ef84a68db13b7212b68c959 to your computer and use it in GitHub Desktop.
Quick, dirty function to call shell commands from Python
#!/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