打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python print不能立即打印的解决方式
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.python.org/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
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
python3的print()函数的用法图文讲解
Python 标准输出 sys.stdout 重定向
python3 出现print输出的中文乱码问题解决
Python基本输出函数print()用法小结
tushare连接mysql问题
你真的懂print('Hello World!')?我不信
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服