由于你很习惯从代码中生成外部进程,因此可以使用tee它本身。我不知道有什么Unix系统调用可以完全做到这tee一点。
# Note this version was written circa Python 2.6, see below for# an updated 3.3+-compatible version.import subprocess, os, sys# Unbuffer output (this ensures the output is in the correct order)sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)tee = subprocess.Popen(["tee", "log.txt"], stdin=subprocess.PIPE)os.dup2(tee.stdin.fileno(), sys.stdout.fileno())os.dup2(tee.stdin.fileno(), sys.stderr.fileno())print "nstdout"print >>sys.stderr, "stderr"os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})os.execve("/bin/ls", ["/bin/ls"], os.environ)你还可以
tee使用多处理程序包进行仿真(如果使用的是Python 2.5或更早版本,则可以使用处理程序)。
更新资料
这是与Python 3.3+兼容的版本:
import subprocess, os, systee = subprocess.Popen(["tee", "log.txt"], stdin=subprocess.PIPE)# Cause tee's stdin to get a copy of our stdin/stdout (as well as that# of any child processes we spawn)os.dup2(tee.stdin.fileno(), sys.stdout.fileno())os.dup2(tee.stdin.fileno(), sys.stderr.fileno())# The flush flag is needed to guarantee these lines are written before# the two spawned /bin/ls processes emit any outputprint("nstdout", flush=True)print("stderr", file=sys.stderr, flush=True)# These child processes' stdin/stdout are os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})os.execve("/bin/ls", ["/bin/ls"], os.environ)


