Skip to content

Instantly share code, notes, and snippets.

@zanerobinson
Created September 21, 2018 21:27
Show Gist options
  • Save zanerobinson/9ab894a7118a83fa0212a5e7697727d0 to your computer and use it in GitHub Desktop.
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
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