python进度条使用和生成二维码

一、进度条

1、利用time模块实现

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()

在这里插入图片描述
⑤自定义进度条显示信息
通过set_descriptionset_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))

在这里插入图片描述
⑧pandas中使用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]

二、二维码

1、安装依赖包

pip install qrcode

2、简单示例

import qrcode

# 二维码内容
url = "https://movie.douban.com/"
# 生成二维码
img = qrcode.make(data=url)
# 直接显示二维码
img.show()
# 保存二维码为文件
img.save("示例图片.jpg")

生成的二维码如下:
在这里插入图片描述
3、设置二维码的颜色等样式

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()

生成一个 blue 的二维码:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_37886429/article/details/109284355
今日推荐