在Python中,你可以使用多种方法来打印进度条。以下是一些示例代码,你可以根据自己的需求进行调整:
使用 `sys` 库
```python
import sys
import time
def print_progress_bar(iteration, total, prefix='', suffix='', length=50, fill=''):
percent = '{:.1f}%'.format(100 * (iteration / float(total)))
filled_length = int(length * iteration // total)
bar = fill * filled_length + '-' * (length - filled_length)
sys.stdout.write('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix))
sys.stdout.flush()
示例:打印一个进度条
total = 100
for i in range(total + 1):
print_progress_bar(i, total, prefix='Progress:', suffix='Complete', length=50)
time.sleep(0.1)
使用 `tqdm` 库
`tqdm` 是一个流行的Python库,用于显示进度条、剩余时间、速度等信息。
```python
from tqdm import tqdm
import time
num = 10
with tqdm(total=num, desc="Count", unit="it") as pbar:
for i in range(num):
time.sleep(1) 1秒延时
pbar.update(1) 进度条更新
pbar.close() 关闭资源
使用 `time` 和 `sys` 库
```python
import sys
import time
def progress(percent, width=50):
if percent >= 100:
percent = 100
show_str = '[%-50s] %d%%' % (width, int(width * percent / 100) * '')
print('\r%s %d%%' % (show_str, percent), end='')
示例:下载进度条
recv_size = 0
total_size =
while recv_size < total_size:
time.sleep(0.01) 下载了1024个字节的数据
recv_size += 1024 recv_size=2048
progress(recv_size / total_size) 打印进度条
使用 `time` 和 `print`
```python
import time
for i in range(1, 101):
print('\r', end='')
print('进度: {}%'.format(i), end='')
sys.stdout.flush()
time.sleep(0.05)
print('\n')
以上代码展示了如何使用 `sys` 库、`tqdm` 库以及纯 `time` 和 `print` 函数来打印进度条。你可以选择最适合你需求的方法。