【发布时间】:2011-05-04 17:01:33
【问题描述】:
我有一堆print 调用需要写入文件而不是stdout。 (我根本不需要stdout。)
我正在考虑三种方法。它们中的任何一个有什么优势(包括性能)吗?
完全重定向,我看到here:
import sys
saveout = sys.stdout
fsock = open('out.log', 'w')
sys.stdout = fsock
print(x)
# and many more print calls
# later if I ever need it:
# sys.stdout = saveout
# fsock.close()
在每个打印语句中重定向:
fsock = open('out.log', 'w')
print(x, file = fsock)
# and many more print calls
写函数:
fsock = open('out.log', 'w')
fsock.write(str(x))
# and many more write calls
【问题讨论】:
-
如果您使用的是 py3k,请阅读 diveintopython3
-
忘了补充说我不久前问了一个相关问题。 stackoverflow.com/questions/4090652/…
标签: python file redirect python-3.x stdout