
【原文】
需求
:打印一颗 ”*” 休息1s
代码如下:
#!/usr/bin/python
#coding=utf-8
'''
暂停1s输出
''' import time def printStar(n):
for i in range(n):
print " * ",
time.sleep(1) if __name__ == '__main__':
printStar(10)
输出结果(等待10s后一次性输出):
[root@miner_k test]# python sleep.py
* * * * * * * * * *
分析原因:
在运行代码时,打印10个"*"
没有占满缓存区,所以等到程序结束时,才会一次性输出。
缓冲区的刷新方式:
1.flush()刷新缓存区
2.缓冲区满时,自动刷新
3.文件关闭或者是程序结束自动刷新。
正确代码:
#!/usr/bin/python
#coding=utf-8
'''
暂停1s输出
''' import time
import sys def printStar(n):
for i in range(n):
print " * ",
sys.stdout.flush()
time.sleep(1) if __name__ == '__main__':
printStar(10)
另外,在https://blog.csdn.net/qq_16234613/article/details/79532050 中也有相关描述:
【实际测试】
Python 3 应该不存在此前置刷新缓冲区 现象。
#!/usr/bin/python
#coding=utf-8 #暂停1s输出 import time def printStar(n):
for i in range(n):
print("*"),
time.sleep(1) if __name__ == '__main__':
printStar(60)
对于Python3环境,将代码作小的修改后,实际打印的效果为:
每个1s打印一次 *
可通过 计时程序执行时间:
#!/usr/bin/python
#coding=utf-8 #暂停1s输出 import time def printStar(n):
for i in range(n):
print("*"),
time.sleep(1)
start = time.clock()
print("Timing from now on.") #从现在开始计时
if __name__ == '__main__': printStar(60) end = time.clock()
t=end-start
print("Rumtime is :",t,"s")
————————(我是分割线)————————
参考:
1. https://blog.csdn.net/miner_k/article/details/76946045
2. https://blog.csdn.net/qq_16234613/article/details/79532050
备注:
初次编辑时间:2019年9月22日17:21:47
环境:Windows 7 / Python 3.7.2