Python sys.stdout
当我们在 Python 中打印对象调用 print(obj) 时候,事实上是调用了 sys.stdout.write(obj+'\n')
print 将你需要的内容打印到了控制台,然后追加了一个换行符
print 会调用 sys.stdout 的 write 方法
以下两行在事实上等价:
sys.stdout.write('hello'+'\n') print('hello')
举例
import sys temp = sys.stdout f = open('test.txt','w') print('heyyy') sys.stdout = f print('hello') sys.stdout = temp print('恢复') f.close()
第一个print函数会显示在屏幕上
第二个print函数 会将内容打印到test.txt文件中
第三个print函数 又会将内容打印到屏幕上