Advertisement
Guest User

Untitled

a guest
Apr 21st, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # No dependencies needed.
  3. # G.Berthiaume 2019
  4. import pathlib
  5. import subprocess
  6. import shlex
  7. from typing import Tuple # mypy
  8.  
  9. def execute_command(cmd: str, cwd: pathlib.Path = pathlib.Path(".")) -> Tuple[str, str]:
  10. """ Execute a child program in a new process and pipe the output out.
  11. Args:
  12. cmd: The command to execute. eg. `git status`
  13. cwd: Where to start the child program. The default is in the same directory
  14. as this python script.
  15.  
  16. Returns:
  17. A tuple of two strings: The standard output and the standard error
  18. of the child program.
  19. If there's no stdout, stdout will be an empty string.
  20. If there's no stderr, stderr will be an empty string.
  21. """
  22. PIPE = subprocess.PIPE
  23. process = subprocess.Popen(
  24. shlex.split(cmd), stdout=PIPE, stderr=PIPE, cwd=str(cwd.resolve())
  25. )
  26. stdout_raw, stderr_raw = process.communicate()
  27. stdout, stderr = stdout_raw.decode("utf-8"), stderr_raw.decode("utf-8")
  28. return stdout, stderr
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement