简体   繁体   English

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

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

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

does create the file, but it contains nothing. 确实创建了文件,但它什么都没包含。

I had to use 我不得不使用

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

But wouldn't the from ... import... automatically make the name available? 但是不会from ... import...自动使名称可用? Why do I still have to use sys.stdout instead of stdout ? 为什么我仍然需要使用sys.stdout而不是stdout

The problem is this: print is equivalent to sys.stdout.write() . 问题是: print等同于sys.stdout.write()

So when you do from sys import stdout , the variable stdout won't be used by print . 因此,当您from sys import stdout执行操作时, print不会使用变量stdout

But when you do 但是,当你这样做

import sys
print 'test'

it actually writes to sys.stdout which is pointing to the file you opened. 它实际上写入sys.stdout ,它指向您打开的file

Analysis 分析

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

Conclusion 结论

This works... 这有效......

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