Skip to content

Instantly share code, notes, and snippets.

@hartwork
Created January 31, 2015 21:08
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hartwork/c0ea8b2278ca18e3f099 to your computer and use it in GitHub Desktop.
Capture another program's std{in,out,err} (Python)
#! /usr/bin/env python
#
# stddump - A command line tool to capture std{in,out,err}
#
# Copyright (C) 2011 Sebastian Pipping <sebastian@pipping.org>
# Licensed under GPL v3 or later
#
# 2011-03-01 14:30 UTC+1
import subprocess
import sys
import os
try:
command = os.environ['STDDUMP_COMMAND']
except:
print "stddump: Variable STDDUMP_COMMAND need be set, cannot continue"
sys.exit(1)
args = [command, ] + sys.argv[1:]
stdin_grabber = subprocess.Popen(["tee", "stdin"],
stdout=subprocess.PIPE)
monitee = subprocess.Popen(args,
stdin=stdin_grabber.stdout,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout_grabber = subprocess.Popen(["tee", "stdout"],
stdin=monitee.stdout)
stderr_grabber = subprocess.Popen(["tee", "stderr"],
stdin=monitee.stderr,
stdout=sys.stderr)
monitee.wait()
stdin_grabber.terminate()
sys.exit(monitee.returncode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment