分享

Python print不能立即打印的解决方式

 rongq2007 2020-08-06

1、问题描述

在Python中使用print打印hello world时,终端不显示

1
2
def hello():
 print("hello world!")

2、原因

因为标准输入输出stdin/stdout有缓冲区,所以使用print不能立即打印出来,作为刚接触Python的菜鸟,迷瞪了半天

3、解决方法

1)刷新缓冲区,python中是sys.stdout.flush()

1
2
3
4
import sys
def hello():
 print("hello world!")
 sys.stdout.flush()

2)python3中支持print支持参数flush

原型:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

1
2
def hello():
 print("hello world!", flush=True)

参考官方手册

https://docs./zh-cn/3/library/functions.html#print

Python控制台输出时刷新当前行内容而不是输出新行的实现

需求目标

执行Python程序的时候在控制台输出内容的时候只显示一行,然后自动刷新内容,像这样:

Downloading File FooFile.txt [47%]

而不是这样:

1
2
3
Downloading File FooFile.txt [47%]
Downloading File FooFile.txt [48%]
Downloading File FooFile.txt [49%]

实现环境

Python 3.x

实现代码

1
2
3
4
import time
for i in range(10):
 time.sleep(0.2)
 print ("\r Loading... ".format(i)+str(i), end="")

这里主要用到了Python 3.x里面print函数增加的功能,使用\r可以刷新当前行输出,2.x里面没有测试,理论上不可以这样操作

拓展知识:

python 覆盖输出/单行输出方式

有时候看输出进度时,会分别输出进度,也就是输出一长串数字,如果能够覆盖之前的输出视觉效果会更好。

1
2
3
4
5
6
7
8
9
import sys
import time
 
for i in range(1000):
 percent = 1.0 * i / 1000 * 100
 sys.stdout.write("\r nihao: %d / %d" %(percent, 100))
 sys.stdout.flush()
 
 time.sleep(0.1)

https://blog.csdn.net/lpwmm/article/details/82926099

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多