教你用Python脚本使用进度条

简介: 教你用Python脚本使用进度条

教你用Python脚本使用进度条

安装

github地址:https://github.com/tqdm/tqdm

想要安装tqdm也是非常简单的,通过pip或conda就可以安装,而且不需要安装其他的依赖库

pip安装

1

pip install tqdm

conda安装

1

conda install -c conda-forge tqdm

迭代对象处理

对于可以迭代的对象都可以使用下面这种方式,来实现可视化进度,非常方便

1

2

3

4

5

6

fromtqdm importtqdm

importtime

 

fori intqdm(range(100)):

  time.sleep(0.1)

  pass

在使用tqdm的时候,可以将tqdm(range(100))替换为trange(100)代码如下

1

2

3

4

5

6

fromtqdm importtqdm,trange

importtime

 

fori intrange(100):

  time.sleep(0.1)

  pass

观察处理的数据

通过tqdm提供的set_description方法可以实时查看每次处理的数据

1

2

3

4

5

6

7

fromtqdm importtqdm

importtime

 

pbar =tqdm(["a","b","c","d"])

forc inpbar:

  time.sleep(1)

  pbar.set_description("Processing %s"%c)

手动设置处理的进度

通过update方法可以控制每次进度条更新的进度

1

2

3

4

5

6

7

8

9

fromtqdm importtqdm

importtime

 

#total参数设置进度条的总长度

with tqdm(total=100) as pbar:

  fori inrange(100):

    time.sleep(0.05)

    #每次更新进度条的长度

    pbar.update(1)

除了使用with之外,还可以使用另外一种方法实现上面的效果

1

2

3

4

5

6

7

8

9

10

11

fromtqdm importtqdm

importtime

 

#total参数设置进度条的总长度

pbar =tqdm(total=100)

fori inrange(100):

  time.sleep(0.05)

  #每次更新进度条的长度

  pbar.update(1)

#关闭占用的资源

pbar.close()

linux命令展示进度条

不使用tqdm

1

2

3

4

5

6

$ timefind. -name '*.py'-typef -execcat\{} \; | wc-l

857365

 

real  0m3.458s

user  0m0.274s

sys   0m3.325s

使用tqdm


1

2

3

4

5

6

7

$ timefind. -name '*.py'-typef -execcat\{} \; | tqdm | wc-l

857366it [00:03, 246471.31it/s]

857365

 

real  0m3.585s

user  0m0.862s

sys   0m3.358s

指定tqdm的参数控制进度条

1

2

3

$ find. -name '*.py'-typef -execcat\{} \; |

  tqdm --unit loc --unit_scale --total 857366 >> /dev/null

100%|███████████████████████████████████| 857K/857K[00:04<00:00, 246Kloc/s]

1

2

3

$ 7z a -bd -r backup.7z docs/ | grepCompressing |

  tqdm --total $(finddocs/ -typef | wc-l) --unit files >> backup.log

100%|███████████████████████████████▉| 8014/8014[01:37<00:00, 82.29files/s]

自定义进度条显示信息

通过set_descriptionset_postfix方法设置进度条显示信息

1

2

3

4

5

6

7

8

9

10

11

fromtqdm importtrange

fromrandom importrandom,randint

importtime

 

with trange(100) as t:

  fori int:

    #设置进度条左边显示的信息

    t.set_description("GEN %i"%i)

    #设置进度条右边显示的信息

    t.set_postfix(loss=random(),gen=randint(1,999),str="h",lst=[1,2])

    time.sleep(0.1)

1

2

3

4

5

6

7

8

9

fromtqdm importtqdm

importtime

 

with tqdm(total=10,bar_format="{postfix[0]}{postfix[1][value]:>9.3g}",

     postfix=["Batch",dict(value=0)]) as t:

  fori inrange(10):

    time.sleep(0.05)

    t.postfix[1]["value"] =i /2

    t.update()

多层循环进度条

通过tqdm也可以很简单的实现嵌套循环进度条的展示

1

2

3

4

5

6

fromtqdm importtqdm

importtime

 

fori intqdm(range(20), ascii=True,desc="1st loop"):

  forj intqdm(range(10), ascii=True,desc="2nd loop"):

    time.sleep(0.01)

pycharm中执行以上代码的时候,会出现进度条位置错乱,目前官方并没有给出好的解决方案,这是由于pycharm不支持某些字符导致的,不过可以将上面的代码保存为脚本然后在命令行中执行,效果如下

多进程进度条

在使用多进程处理任务的时候,通过tqdm可以实时查看每一个进程任务的处理情况

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

fromtime importsleep

fromtqdm importtrange, tqdm

frommultiprocessing importPool, freeze_support, RLock

 

L =list(range(9))

 

defprogresser(n):

  interval =0.001/(n +2)

  total =5000

  text ="#{}, est. {:<04.2}s".format(n, interval *total)

  fori intrange(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

1

2

3

4

5

6

7

8

9

importpandas as pd

importnumpy as np

fromtqdm importtqdm

 

df =pd.DataFrame(np.random.randint(0, 100, (100000, 6)))

 

 

tqdm.pandas(desc="my bar!")

df.progress_apply(lambdax: x**2)

递归使用进度条

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

fromtqdm importtqdm

importos.path

 

deffind_files_recursively(path, show_progress=True):

  files =[]

  # total=1 assumes `path` is a file

  t =tqdm(total=1, unit="file", disable=notshow_progress)

  ifnotos.path.exists(path):

    raiseIOError("Cannot find:"+path)

 

  defappend_found_file(f):

    files.append(f)

    t.update()

 

  deflist_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

    returnlisting

 

  defrecursively_search(path):

    ifos.path.isdir(path):

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

  returnfiles

 

find_files_recursively("E:/")

注意

在使用tqdm显示进度条的时候,如果代码中存在print可能会导致输出多行进度条,此时可以将print语句改为tqdm.write,代码如下

1

2

3

fori intqdm(range(10),ascii=True):

  tqdm.write("come on")

  time.sleep(0.1)

目录
相关文章
|
4月前
|
安全 网络安全 文件存储
思科设备巡检命令Python脚本大集合
【10月更文挑战第18天】
145 1
思科设备巡检命令Python脚本大集合
|
2月前
|
Python
自动化微信朋友圈:Python脚本实现自动发布动态
本文介绍如何使用Python脚本自动化发布微信朋友圈动态,节省手动输入的时间。主要依赖`pyautogui`、`time`、`pyperclip`等库,通过模拟鼠标和键盘操作实现自动发布。代码涵盖打开微信、定位朋友圈、准备输入框、模拟打字等功能。虽然该方法能提高效率,但需注意可能违反微信使用条款,存在风险。定期更新脚本以适应微信界面变化也很重要。
213 61
|
3月前
|
数据采集 监控 数据挖掘
Python自动化脚本:高效办公新助手###
本文将带你走进Python自动化脚本的奇妙世界,探索其在提升办公效率中的强大潜力。随着信息技术的飞速发展,重复性工作逐渐被自动化工具取代。Python作为一门简洁而强大的编程语言,凭借其丰富的库支持和易学易用的特点,成为编写自动化脚本的首选。无论是数据处理、文件管理还是网页爬虫,Python都能游刃有余地完成任务,极大地减轻了人工操作的负担。接下来,让我们一起领略Python自动化脚本的魅力,开启高效办公的新篇章。 ###
|
25天前
|
安全 Linux 网络安全
利用Python脚本自动备份网络设备配置
通过本文的介绍,我们了解了如何利用Python脚本自动备份网络设备配置。该脚本使用 `paramiko`库通过SSH连接到设备,获取并保存配置文件。通过定时任务调度,可以实现定期自动备份,确保网络设备配置的安全和可用。希望这些内容能够帮助你在实际工作中实现网络设备的自动化备份。
51 14
|
2月前
|
数据采集 存储 监控
21个Python脚本自动执行日常任务(2)
21个Python脚本自动执行日常任务(2)
129 7
21个Python脚本自动执行日常任务(2)
|
3月前
|
关系型数据库 MySQL 数据库连接
python脚本:连接数据库,检查直播流是否可用
【10月更文挑战第13天】本脚本使用 `mysql-connector-python` 连接MySQL数据库,检查 `live_streams` 表中每个直播流URL的可用性。通过 `requests` 库发送HTTP请求,输出每个URL的检查结果。需安装 `mysql-connector-python` 和 `requests` 库,并配置数据库连接参数。
147 68
|
2月前
|
数据挖掘 vr&ar C++
让UE自动运行Python脚本:实现与实例解析
本文介绍如何配置Unreal Engine(UE)以自动运行Python脚本,提高开发效率。通过安装Python、配置UE环境及使用第三方插件,实现Python与UE的集成。结合蓝图和C++示例,展示自动化任务处理、关卡生成及数据分析等应用场景。
178 5
|
2月前
|
Android开发 开发者 Python
通过标签清理微信好友:Python自动化脚本解析
微信已成为日常生活中的重要社交工具,但随着使用时间增长,好友列表可能变得臃肿。本文介绍了一个基于 Python 的自动化脚本,利用 `uiautomator2` 库,通过模拟用户操作实现根据标签批量清理微信好友的功能。脚本包括环境准备、类定义、方法实现等部分,详细解析了如何通过标签筛选并删除好友,适合需要批量管理微信好友的用户。
108 7
|
3月前
|
监控 数据挖掘 数据安全/隐私保护
Python脚本:自动化下载视频的日志记录
Python脚本:自动化下载视频的日志记录
|
3月前
|
运维 监控 网络安全
自动化运维的崛起:如何利用Python脚本简化日常任务
【10月更文挑战第43天】在数字化时代的浪潮中,运维工作已从繁琐的手工操作转变为高效的自动化流程。本文将引导您了解如何运用Python编写脚本,以实现日常运维任务的自动化,从而提升工作效率和准确性。我们将通过一个实际案例,展示如何使用Python来自动部署应用、监控服务器状态并生成报告。文章不仅适合运维新手入门,也能为有经验的运维工程师提供新的视角和灵感。

热门文章

最新文章

推荐镜像

更多