python中stdout输出不缓存的设置方法
时间:2023-03-08 10:23:15
考虑以下python程序:
#!/usr/bin/env python
import sys
sys.stdout.write("stdout1 ")
sys.stderr.write("stderr1 ")
sys.stdout.write("stdout2 ")
sys.stderr.write("stderr2 ")
其中的sys.stdout.write也可以换成print。
运行这程序,你觉得会输出什么?试验一下,就会发现,其实输出并不是
stdout1 stderr1 stdout2 stderr2
而是:
stderr1 stderr2 stdout1 stdout2
究其原因,是因为缓存:虽然stderr和stdout默认都是指向屏幕的,但是stderr是无缓存的,程序往stderr输出一个字符,就会在屏幕上显示一个;而stdout是有缓存的,只有遇到换行或者积累到一定的大小,才会显示出来。这就是为什么上面的会显示两个stderr的原因了。
然而,有时候,你可能还是希望stdout的行为和stderr一样,能不能实现呢?当然是可以的,而且对于python,实现起来还特别方便,以下是两个方法:
python -u stderr_stdout.py
PYTHONUNBUFFERED=1 python stderr_stdout.py
第一种方法是给python指定 -u 参数,第二种方法是在python运行时,指定 PYTHONUNBUFFERED 环境变量,这两种方法其实是等效的。
当然,也可以在程序的第一行指定 #!/usr/bin/python -u 然后程序加可执行权限来运行,或者把 export PYTHONUNBUFFERED=1 写到 .bashrc 里去。
附:stackoverflow上也有同学遇到类似问题,可以参考一下
地址:http://stackoverflow.com/questions/107705/python-output-buffering
被采纳的代码:
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
import sys
sys.stdout = Unbuffered(sys.stdout)
print 'Hello'
标签:python,stdout
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
OpenCV哈里斯(Harris)角点检测的实现
2022-10-07 01:41:26
![](https://img.aspxhome.com/file/2023/6/134916_0s.png)
在python中使用xlrd获取合并单元格的方法
2023-09-09 17:00:43
python3爬虫之设计签名小程序
2021-09-16 00:26:46
![](https://img.aspxhome.com/file/2023/7/113167_0s.png)
mysql8重置root用户密码的完整步骤
2024-01-13 16:04:45
Django+boostrap 美化admin后台的操作
2022-02-26 16:16:21
![](https://img.aspxhome.com/file/2023/3/71503_0s.jpg)
python SQLAlchemy的Mapping与Declarative详解
2022-12-04 02:48:37
MySQL学习(七):Innodb存储引擎索引的实现原理详解
2024-01-25 05:53:02
![](https://img.aspxhome.com/file/2023/8/121248_0s.png)
MySQL中无过滤条件的count详解
2024-01-22 13:06:20
Python warning警告出现的原因及忽略方法
2021-10-16 10:59:02
tensorflow: variable的值与variable.read_value()的值区别详解
2023-01-02 22:29:40
![](https://img.aspxhome.com/file/2023/5/85035_0s.jpg)
python绘制圆柱体的方法
2022-07-31 02:00:31
![](https://img.aspxhome.com/file/2023/6/96946_0s.jpg)
使用Python实现图像标记点的坐标输出功能
2022-10-31 16:15:06
![](https://img.aspxhome.com/file/2023/9/68839_0s.jpg)
python实现无边框进度条的实例代码
2023-07-23 05:22:59
![](https://img.aspxhome.com/file/2023/5/81815_0s.png)
非常详细的SQL--JOIN之完全用法
2024-01-17 11:59:19
使用SQL Server 2008远程链接时SQL数据库不成功的解决方法
2024-01-29 09:15:46
![](https://img.aspxhome.com/file/2023/2/99992_0s.gif)
python numpy中对ndarry按照index增删改查
2022-01-20 22:32:25
详解Python爬虫的基本写法
2022-12-26 07:49:45
python+opencv实现论文插图局部放大并拼接效果
2023-12-07 17:29:12
![](https://img.aspxhome.com/file/2023/2/92442_0s.png)
Python+matplotlib实现绘制等高线图示例详解
2022-09-18 05:44:11
![](https://img.aspxhome.com/file/2023/2/112022_0s.jpg)
Javascript DOM 编程实例讲解--仿LightBox效果提示框
2008-05-01 13:25:00
![](https://img.aspxhome.com/file/UploadPic/up/2008050116095611.gif)