栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python-如何将sys.stdout复制到日志文件?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python-如何将sys.stdout复制到日志文件?

由于你很习惯从代码中生成外部进程,因此可以使用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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/456368.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号