[英]What's the best way to handle output redirection?
我希望我的程序默认为stdout,但可以选择将其写入文件。 我应该创建自己的打印功能并调用该测试来确定是否存在输出文件,还是有更好的方法? 这对我来说似乎效率很低,但是我能想到的每种方式都会对每个打印调用进行额外的if测试。 我知道至少从长远来看,这实际上从长远来看并不重要,但我只是在尝试学习良好的习惯。
只需使用打印将标准输出。 如果用户要将输出重定向到文件,则可以执行以下操作:
python foo.py > output.txt
写入文件对象,然后在程序启动时将该对象指向sys.stdout或用户指定的文件。
Mark Byers的答案更像是Unix,其中大多数命令行工具仅使用stdin和stdout,并让用户根据自己的意愿进行重定向。
不,您不需要创建单独的打印功能。 在Python 2.6中,您具有以下语法:
# suppose f is an open file
print >> f, "hello"
# now sys.stdout is file too
print >> sys.stdout, "hello"
在Python 3.x中:
print("hello", file=f)
# or
print("hello", file=sys.stdout)
因此,您实际上不必区分文件和标准输出。 他们是一样的。
一个玩具示例,它以您想要的方式输出“ hello”:
#!/usr/bin/env python3
import sys
def produce_output(fobj):
print("hello", file=fobj)
# this can also be
# fobj.write("hello\n")
if __name__=="__main__":
if len(sys.argv) > 2:
print("Too many arguments", file=sys.stderr)
exit(1)
f = open(argv[1], "a") if len(argv)==2 else sys.stdout
produce_output(f)
请注意,打印过程是抽象的,它适用于stdout还是文件。
我建议您使用日志记录模块和logging.handlers ...流,输出文件等。
如果您使用子流程模块,则根据您从命令行获取的选项,您可以将stdout选项用于打开的文件对象。 这样,您可以从程序中重定向到文件。
import subprocess
with open('somefile','w') as f:
proc = subprocess.Popen(['myprog'],stdout=f,stderr=subprocess.PIPE)
out,err = proc.communicate()
print 'output redirected to somefile'
我的反应是将其输出到一个临时文件,然后将其转储到stdio,或将其移动到他们要求的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.