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

Qia*_* Li 7 python

from sys import stdout
stdout = open('file', 'w')
print 'test'
stdout.close()
Run Code Online (Sandbox Code Playgroud)

确实创建了文件,但它什么都没包含.

我不得不使用

import sys
sys.stdout = open('file', 'w')
print 'test'
sys.stdout.close()
Run Code Online (Sandbox Code Playgroud)

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

ATO*_*TOA 8

问题是:print相当于sys.stdout.write().

所以当你这样做时from sys import stdout,变量stdout将不会被使用print.

但是,当你这样做

import sys
print 'test'
Run Code Online (Sandbox Code Playgroud)

它实际写到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()
Run Code Online (Sandbox Code Playgroud)
import sys
sys.stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the file
sys.stdout.close()
Run Code Online (Sandbox Code Playgroud)

结论

这有效......

from sys import stdout
stdout = open('file', 'w')
stdout.write('test')
stdout.close()
Run Code Online (Sandbox Code Playgroud)