1.プログレスバー
1.タイムモジュールで実現
import time
for i in range(0, 101, 2):
time.sleep(0.3)
num = i // 2
if i == 100:
process = "\r[%3s%% ]: |%-50s|\n" % (i, '#' * num)
else:
process = "\r[%3s%% ]: |%-50s|" % (i, '#' * num)
print(process, end='', flush=True)
2.tqdmモジュールを使用して
①インストールを実現
pip install tqdm
②反復オブジェクト処理
from tqdm import tqdm,trange
import time
#for i in tqdm(range(100)):
for i in trange(100):
time.sleep(0.1)
pass
③処理済みデータの観察tqdmが提供するset_description
方法により、処理済みデータをリアルタイムで表示できます。
from tqdm import tqdm
import time
pbar = tqdm(["a","b","c","d"])
for c in pbar:
time.sleep(1)
pbar.set_description("Processing %s"%c)
④処理の進行状況を手動で設定する方法
により、update
各進行状況バーの更新の進行状況を制御できます。
from tqdm import tqdm
import time
#total参数设置进度条的总长度
with tqdm(total=100) as pbar:
for i in range(100):
time.sleep(0.05)
#每次更新进度条的长度
pbar.update(1)
を使用with
することに加えて、上記の効果を達成するために別の方法を使用することもできます
from tqdm import tqdm
import time
#total参数设置进度条的总长度
pbar = tqdm(total=100)
for i in range(100):
time.sleep(0.05)
#每次更新进度条的长度
pbar.update(1)
#关闭占用的资源
pbar.close()
プログレスバーの表示情報⑤Customizeプログレスバーの表示情報を設定する
ことにより、set_description
およびset_postfix
方法を
from tqdm import trange
from random import random,randint
import time
with trange(100) as t:
for i in t:
#设置进度条左边显示的信息
t.set_description("GEN %i"%i)
#设置进度条右边显示的信息
t.set_postfix(loss=random(),gen=randint(1,999),str="h",lst=[1,2])
time.sleep(0.1)
from tqdm import tqdm
import time
with tqdm(total=10,bar_format="{postfix[0]}{postfix[1][value]:>9.3g}",
postfix=["Batch",dict(value=0)]) as t:
for i in range(10):
time.sleep(0.05)
t.postfix[1]["value"] = i / 2
t.update()
⑥多層サイクルプログレスバー
from tqdm import tqdm
import time
for i in tqdm(range(20), ascii=True,desc="1st loop"):
for j in tqdm(range(10), ascii=True,desc="2nd loop"):
time.sleep(0.01)
✓
マルチプロセスプログレスバーマルチプロセスを使用してタスクを処理する場合、tqdmを介して各プロセスタスクの処理ステータスをリアルタイムで表示できます。
from time import sleep
from tqdm import trange, tqdm
from multiprocessing import Pool, freeze_support, RLock
L = list(range(9))
def progresser(n):
interval = 0.001 / (n + 2)
total = 5000
text = "#{}, est. {:<04.2}s".format(n, interval * total)
for i in trange(total, desc=text, position=n,ascii=True):
sleep(interval)
if __name__ == '__main__':
freeze_support() # for Windows support
p = Pool(len(L),
# again, for Windows support
initializer=tqdm.set_lock, initargs=(RLock(),))
p.map(progresser, L)
print("\n" * (len(L) - 2))
⑧パンダでtqdmを使用する
import pandas as pd
import numpy as np
from tqdm import tqdm
df = pd.DataFrame(np.random.randint(0, 100, (100000, 6)))
tqdm.pandas(desc="my bar!")
df.progress_apply(lambda x: x**2)
⑨プログレスバーを再帰的に使用する
from tqdm import tqdm
import os.path
def find_files_recursively(path, show_progress=True):
files = []
# total=1 assumes `path` is a file
t = tqdm(total=1, unit="file", disable=not show_progress)
if not os.path.exists(path):
raise IOError("Cannot find:" + path)
def append_found_file(f):
files.append(f)
t.update()
def list_found_dir(path):
"""returns os.listdir(path) assuming os.path.isdir(path)"""
try:
listing = os.listdir(path)
except:
return []
# subtract 1 since a "file" we found was actually this directory
t.total += len(listing) - 1
# fancy way to give info without forcing a refresh
t.set_postfix(dir=path[-10:], refresh=False)
t.update(0) # may trigger a refresh
return listing
def recursively_search(path):
if os.path.isdir(path):
for f in list_found_dir(path):
recursively_search(os.path.join(path, f))
else:
append_found_file(path)
recursively_search(path)
t.set_postfix(dir=path)
t.close()
return files
find_files_recursively("E:/")
注:tqdmを使用して進行状況バーを表示する場合、コードが存在すると、print
複数行の進行状況バーが出力される可能性があります。現時点print语句改为tqdm.write
では、コードは次のとおりです。
for i in tqdm(range(10),ascii=True):
tqdm.write("come on")
time.sleep(0.1)
3.Linuxコマンド表示プログレスバー①tqdmは使用しないでください
$ time find . -name '*.java' -type f -exec cat \{} \; | wc -l
263866
real 0m3.562s
user 0m1.399s
sys 0m2.351s
②tqdmを使用する
##安装
git地址:https://github.com/tqdm/tqdm
pip install tqdm
$ time find . -name '*.java' -type f -exec cat \{} \; | tqdm | wc -l
263866it [00:02, 103691.49it/s]
263866
real 0m2.653s
user 0m1.734s
sys 0m1.280s
③tqdmのパラメータを指定してプログレスバーを制御する
$$ find . -name '*.java' -type f -exec cat \{} \; | tqdm --unit loc --unit_scale --total 263866 >> /dev/null
100%|███████████████████████████████| 264k/264k [00:02<00:00, 112kloc/s]
###Backing up a large directory
$ tar -zcf - ~/ | tqdm --bytes --total `du -sb ./ | cut -f1` > backup.tgz
85%|██████████████████▋ | 321M/379M [00:10<00:01, 32.3MB/s]
2.QRコード
1.依存関係をインストールします
pip install qrcode
2.簡単な例
import qrcode
# 二维码内容
url = "https://movie.douban.com/"
# 生成二维码
img = qrcode.make(data=url)
# 直接显示二维码
img.show()
# 保存二维码为文件
img.save("示例图片.jpg")
生成されるQRコードは次のとおりです。3。QRコード
の色とその他のスタイルを設定します。
import qrcode
# 实例化二维码生成类
qr = qrcode.QRCode(border=2)
# 设置二维码数据
url = "https://movie.douban.com/"
qr.add_data(data=url)
# 启用二维码颜色设置
qr.make(fit=True)
img = qr.make_image(fill_color="blue", back_color="white")
# 显示二维码
img.show()
青いQRコードを生成します。