繁体   English   中英

为什么以下python代码不打印到文件

[英]Why the following python code does not print to file

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

问题是: print等同于sys.stdout.write()

因此,当您from sys import stdout执行操作时, print不会使用变量stdout

但是,当你这样做

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM