-
-
Save klaernie/738fd618b3a37eca8c58090cb90ca424 to your computer and use it in GitHub Desktop.
bidirectional tee
This file contains 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
#!/usr/bin/python | |
import sys | |
import subprocess | |
import threading | |
import signal | |
import logging | |
if len(sys.argv) < 3: | |
sys.stderr.write("Usage: {0} output_file command [arg [arg] ...]\n"\ | |
.format(sys.argv[0])) | |
sys.exit(1) | |
name = sys.argv[0] | |
filename = sys.argv[1] | |
command = sys.argv[2:] | |
logging.basicConfig( | |
format='%(asctime)s %(message)s', | |
level=logging.INFO, | |
datefmt='%Y-%m-%d %H:%M:%S', | |
filename=filename, | |
) | |
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, | |
stderr=subprocess.PIPE, bufsize=1) | |
logging.info("{0} -- started {1}".format(p.pid, repr(command))) | |
def t(pfrom, pto, name): | |
while True: | |
line = pfrom.readline() | |
if not line: | |
break | |
pto.write(line) | |
pto.flush() | |
logging.info(str(p.pid) + " " + name + " " + line.rstrip('\n')) | |
if pto == p.stdin: | |
pto.close() | |
def s(*args): | |
logging.info("{0} -- SIGINT".format(p.pid)) | |
p.send_signal(signal.SIGINT) | |
signal.signal(signal.SIGINT, s) | |
thr_in = threading.Thread(target=t, args=(sys.stdin, p.stdin, ">>")) | |
thr_out = threading.Thread(target=t, args=(p.stdout, sys.stdout, "<<")) | |
thr_err = threading.Thread(target=t, args=(p.stderr, sys.stderr, "!!")) | |
thr_in.daemon = True | |
thr_in.start() | |
thr_out.start() | |
thr_err.start() | |
r = p.wait() | |
thr_out.join() | |
thr_err.join() | |
logging.info("{0} -- exited: {1}".format(p.pid, r)) | |
sys.exit(r) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment