欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python可以直接打印中午吗_Python print不能立即打印的解决方式

发布时间:2025/3/20 python 91 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python可以直接打印中午吗_Python print不能立即打印的解决方式 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1、问题描述

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

1

2def hello():

print("hello world!")

2、原因

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

3、解决方法

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

1

2

3

4import sys

def hello():

print("hello world!")

sys.stdout.flush()

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

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

1

2def hello():

print("hello world!", flush=True)

参考官方手册

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

需求目标

执行Python程序的时候在控制台输出内容的时候只显示一行,然后自动刷新内容,像这样:Downloading File FooFile.txt [47%]

而不是这样:

1

2

3DownloadingFile FooFile.txt [47%]

DownloadingFile FooFile.txt [48%]

DownloadingFile FooFile.txt [49%]

实现环境

Python 3.x

实现代码

1

2

3

4import time

for iin 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

9import sys

import time

for iin range(1000):

percent= 1.0 * i/ 1000 * 100

sys.stdout.write("\r nihao: %d / %d" %(percent,100))

sys.stdout.flush()

time.sleep(0.1)

总结

以上是生活随笔为你收集整理的python可以直接打印中午吗_Python print不能立即打印的解决方式的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。