Created
September 21, 2018 21:27
-
-
Save zanerobinson/9ab894a7118a83fa0212a5e7697727d0 to your computer and use it in GitHub Desktop.
[run bash command](use subprocess to pip stderr and stdout) #subprocess #Popen #stdout #stderr #bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def run_command(cmd_to_run): | |
""" | |
Wrapper around subprocess that pipes the stderr and stdout from `cmd_to_run` | |
to temporary files. Using the temporary files gets around subprocess.PIPE's | |
issues with handling large buffers. | |
Note: this command will block the python process until `cmd_to_run` has completed. | |
Returns a tuple, containing the stderr and stdout as strings. | |
""" | |
with tempfile.TemporaryFile() as stdout_file, tempfile.TemporaryFile() as stderr_file: | |
# Run the command | |
popen = subprocess.Popen(cmd_to_run, stdout=stdout_file, stderr=stderr_file) | |
popen.wait() | |
stderr_file.seek(0) | |
stdout_file.seek(0) | |
stderr = stderr_file.read() | |
stdout = stdout_file.read() | |
return stderr, stdout |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment