关于print()、sys.stdout、sys.stderr的一些理解

【参考】:【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!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值