file io - Python `tee` stdout of child process -
is there way in python equivalent of unix command line tee
? i'm doing typical fork/exec pattern, , i'd stdout child appear in both log file , on stdout of parent simultaneously without requiring buffering.
in python code instance, stdout of child ends in log file, not in stdout of parent.
pid = os.fork() logfile = open(path,"w") if pid == 0: os.dup2(logfile.fileno(),1) os.execv(cmd)
edit: not wish use subprocess module. i'm doing complicated stuff child process requires me call fork
manually.
here have working solution without using subprocess
module. although, use tee process while still using exec*
functions suite custom subprocess (just use stdin=subprocess.pipe
, duplicate descriptor stdout).
import os, time, sys pr, pw = os.pipe() pid = os.fork() if pid == 0: os.close(pw) os.dup2(pr, sys.stdin.fileno()) os.close(pr) os.execv('/usr/bin/tee', ['tee', 'log.txt']) else: os.close(pr) os.dup2(pw, sys.stdout.fileno()) os.close(pw) pid2 = os.fork() if pid2 == 0: # replace custom process call os.execv('/usr/bin/yes', ['yes']) else: try: while true: time.sleep(1) except keyboardinterrupt: pass
note tee
command, internally, same thing ben suggested in answer: reading input , looping on output file descriptors while writing them. may more efficient because of optimized implementation , because it's written in c, have overhead of different pipes (don't know sure solution more efficient, in opinion, reassigning custom file-like object stdout
more elegant solution).
some more resources:
Comments
Post a Comment