
艺术字、进度条
更新: 2025/2/24 字数: 0 字 时长: 0 分钟
pyfiglet艺术字
pyfiglet是一个专门用来生成艺术字的第三方库,但只支持英文。
安装pyfiglet
首先,我们来安装 pyfiglet 库:
pip install pyfiglet
支持的字体
我们先看看都支持哪些字体吧:
python
from pyfiglet import FigletFont
print(FigletFont().getFonts())
生成艺术字
使用pyfiglet生成艺术字体:
python
from pyfiglet import Figlet
# 指定slant字体(默认standard),width宽度200(默认80)
f = Figlet(font="slant", width=200)
# 指定转换的内容"handsome"
print(f.renderText("handsome"))
"""
输出:
__ __
/ /_ ____ _____ ____/ /________ ____ ___ ___
/ __ \/ __ `/ __ \/ __ / ___/ __ \/ __ `__ \/ _ \
/ / / / /_/ / / / / /_/ (__ ) /_/ / / / / / / __/
/_/ /_/\__,_/_/ /_/\__,_/____/\____/_/ /_/ /_/\___/
"""
tqdm进度条
安装tqdm
**tqdm是一个显示进度条的第三方包。**安装命令如下:
pip install tqdm
生成进度条
使用tqdm会在输出有一个进度条的展示。代码如下:
python
import time
from tqdm import tqdm
# a为一个整型值
a = 100
# b为一个可迭代对象
b = range(a)
# 按位置传参会出错,所以关键字传参。iterable为可迭代对象,total为显示进度条的迭代次数。
c = tqdm(iterable=b, total=a)
for i in c:
# 每迭代一次程序阻塞0.1秒
time.sleep(0.1)
结合多线程
python
import time
import random
from tqdm import tqdm
from concurrent.futures import ThreadPoolExecutor, as_completed
# 读取数据
def read_data():
for file in ['a.txt', 'b.txt', 'c.txt']:
# 线程执行列表
to_do = []
# 20个线程的执行对象
executor = ThreadPoolExecutor(max_workers=20)
# 每个文件读取100行,添加到执行列表
for row in range(100):
data = f'{file}_{row}'
future = executor.submit(push_data, data)
to_do.append(future)
# 显示进度条
for _ in tqdm(iterable=as_completed(to_do), total=len(to_do)):
pass
# 等待当前所有子线程执行完
executor.shutdown()
# 输出返回结果,统计失败次数(0的个数)
error_count = [res.result() for res in as_completed(to_do)].count(0)
print(f'{file} fail times {error_count}!')
# 推送数据
def push_data(data):
random_sleep = random.randint(1, 3)
time.sleep(random_sleep)
# 如果推送时间等于3秒,则判断为失败返回0,反之返回1。
return 0 if random_sleep == 3 else data
if __name__ == '__main__':
read_data()
'''
输出:
100%|██████████| 100/100 [00:12<00:00, 8.32it/s]
a.txt fail times 32!
100%|██████████| 100/100 [00:11<00:00, 9.04it/s]
b.txt fail times 29!
100%|██████████| 100/100 [00:12<00:00, 8.30it/s]
c.txt fail times 38!
'''