Skip to content

Instantly share code, notes, and snippets.

@0xqd
Forked from doublenns/run_shell_cmd.py
Created May 22, 2018 07:28
Show Gist options
  • Save 0xqd/25af3424c8858e30156125073eb531d8 to your computer and use it in GitHub Desktop.
Save 0xqd/25af3424c8858e30156125073eb531d8 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" 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