写一段进度条代码
时间: 2023-07-10 20:25:50 浏览: 36
以下是一个简单的进度条代码,使用Python的time和sys模块:
```
import time
import sys
def update_progress(progress):
"""
This function creates a progress bar that updates with each iteration of your loop.
"""
bar_length = 20 # length of progress bar
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = "Error: progress input must be an integer or float\r\n"
if progress < 0:
progress = 0
status = "Halt...\r\n"
if progress >= 1:
progress = 1
status = "Done...\r\n"
block = int(round(bar_length*progress))
text = "\rProgress: [{0}] {1}% {2}".format( "#"*block + "-"*(bar_length-block), round(progress*100, 2), status)
sys.stdout.write(text)
sys.stdout.flush()
# Sample Usage
for i in range(101):
time.sleep(0.1)
update_progress(i/100.0)
```
这段代码会打印出一个进度条,长度为20个字符,随着迭代次数的增加而更新。在每个迭代中,您只需调用`update_progress()`函数并将当前进度传递给它即可。