Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/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())
Add Comment
Please, Sign In to add comment