Guest User

Untitled

a guest
Jan 18th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import subprocess
  4.  
  5.  
  6. def run_shell_cmd(cmd, *shell):
  7. # Might want to use a "try" or call.check in case Command fails
  8. if "shell" in shell.lower():
  9. process = subprocess.Popen(cmd,
  10. stdout=subprocess.PIPE, shell=True)
  11. else:
  12. process = subprocess.Popen(cmd.split(),
  13. stdout=subprocess.PIPE)
  14. output = process.communicate()[0]
  15. rc = process.returncode
  16. return output, rc
  17.  
  18.  
  19. # Examples
  20. output, returncode = (run_shell_cmd("echo hello"))
  21. # output = (run_shell_cmd("echo hello")[0])
  22. # Output will include the newline in it unless stripped.
  23. # Output is also a byte object in Python3 as opposed to a string
  24. # returncode = (run_shell_cmd("echo hello")[1])
  25.  
  26. print("The output of the 1st shell command is: " + output.decode("utf-8").rstrip())
  27. print("The return code of the 1st shell command is:", returncode)
  28. print()
  29.  
  30. output = run_shell_cmd("echo pipes{junk} and special characters | awk -F '{[^}]*}' '{print $1 $2}'", "shell")[0]
  31. print("Using subprocess' shell=True works with", output.decode("utf-8").rstrip())
Add Comment
Please, Sign In to add comment