为什么下面的Python代码没有将内容打印到文件?

7
from sys import stdout
stdout = open('file', 'w')
print 'test'
stdout.close()

创建了文件,但是里面什么也没有。
我不得不使用
import sys
sys.stdout = open('file', 'w')
print 'test'
sys.stdout.close()

但是from ... import...不会自动使名称可用吗?为什么我仍然需要使用sys.stdout而不是stdout


1
只是想澄清一下,您这里是在问两个问题吗?为什么您的文件没有包含任何内容或者为什么您必须使用sys.stdout而不是stdout? - TerryA
1
在第二种方法中,你需要使用 import sys - ATOzTOA
1
这是一篇非常有趣的帖子,重点介绍了 sys.stdout 的作用。然而,我认为你会从 logging 模块 中受益匪浅。 - inspectorG4dget
1个回答

8
问题是这样的:print 相当于 sys.stdout.write()
因此,当你执行 from sys import stdout 时,变量 stdout 不会被 print 使用。
但是当你执行
import sys
print 'test'

这段代码实际上是写入到sys.stdout,该对象指向您打开的file文件。

分析

from sys import stdout
stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the terminal
stdout.close()

import sys
sys.stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the file
sys.stdout.close()

结论

这个方法可行...

from sys import stdout
stdout = open('file', 'w')
stdout.write('test')
stdout.close()

这是另一个问题,但是如果他真的想要覆盖“stdout”以将某些内容写入文件,则需要考虑。 - Markus Unterwaditzer
@MarkusUnterwaditzer说得好... 如果他想让大型程序中的所有“print”语句都写入日志文件,这就变得相关了... - ATOzTOA

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接