【参考】:【Python】关于print()、sys.stdout、sys.stderr的一些理解 - 牡蛎君 - 博客园 (cnblogs.com)
其中file = sys.stdout的意思是,print函数会将内容打印输出到标准输出流(即 sys.stdout),当然也可以自定义输出流:
with open('test.log', 'a') as f: print('hello world!', file=f) # 内容输出到了test.log文件中,终端不会打印任何内容
也可以输出到错误输出流sys.stderr:
import sys print('hello world!', file=sys.stderr) # 》》hello world!
其实print函数的默认输出等价于sys.stdout.write(),只是print会自动换行,而stdout需要手动添加转义符"\n"
import sys print('hello world!') # 》》hello world! sys.stdout.write('hello world!\n') # 》》hello world!