本文将会介绍3个Python第三方模块的使用方法,它们分别是tqdm
, pyyaml
和traceback
模块,各自的用途描述以下:python
tqdm
: 能够显示循环的进度条;pyyaml
:Python操做YAML文件的库;tracebak
:详细追踪错误信息的库。下面将会给出这3个模块的简单介绍和使用。json
tqdm是Python中能够显示循环的进度条模块,tqdm()能够直接包裹iterable的对象。若是咱们须要显示程序处理的进度条时,咱们能够使用该模块。
下面将给出几个简单使用tqdm的例子。
例子1:直接使用进度条,示例程序以下:调试
# -*- coding: utf-8 -*- import time from tqdm import tqdm for i in tqdm(range(100)): time.sleep(0.01)
输出结果以下:code
100%|██████████| 100/100 [00:01<00:00, 91.52it/s]
例子2:在处理进度条的同时,输出额外的处理信息,示例程序以下:orm
# -*- coding: utf-8 -*- import time from tqdm import tqdm pbar = tqdm(["a", "b", "c", "d"]) for char in pbar: pbar.set_description("Processing %s" % char) time.sleep(1)
输出以下:对象
Processing d: 100%|██████████| 4/4 [00:04<00:00, 1.00s/it]
例子3:人工控制进度条的进度,示例代码以下(为了演示效果,进度条没有100%):接口
# -*- coding: utf-8 -*- import time from tqdm import tqdm with tqdm(total=100) as pbar: for i in range(5): time.sleep(0.5) pbar.update(10)
输出以下:ip
50%|█████ | 50/100 [00:02<00:02, 19.89it/s]
更多的内容请参考tqdm
模块的官网:https://pypi.org/project/tqdm/ 。utf-8
&emsop;YAML
是数据序列化格式,便于人的阅读和交互,与JSON
相似,经常使用于配置文件。pyyaml
是Python用于操做YAML
文件的模块,支持常见的读写操做。
例子1:YAML文件写入,示例代码以下:unicode
# -*- coding: utf-8 -*- import yaml json_data = {'name': 'Alice', 'age': 1956, 'job': ['Doctor', 'Driver', 'Worker'] } # 输出 y = yaml.dump(json_data, default_flow_style=False).encode('utf-8').decode('unicode_escape') print(y) # 写入到YAML文件 with open('./alice.yaml', 'w') as f: y = yaml.dump(json_data, f)
输出结果以下(同时也会生成alice.yaml文件,内容一致):
age: 1956 job: - Doctor - Driver - Worker name: Alice
例子2:读取YAML文件,示例代码以下:
# -*- coding: utf-8 -*- import yaml with open("./alice.yaml", 'r', encoding='utf-8') as ymlfile: cfg = yaml.safe_load(ymlfile) print(cfg)
输出结果以下:
{'age': 1956, 'job': ['Doctor', 'Driver', 'Worker'], 'name': 'Alice'}
YAML
文件的输出有其自身的规范,总结以下:
一、大小写敏感 二、使用缩进表示层级关系 三、缩进时不容许使用Tab键,只容许使用空格。 四、缩进的空格数目不重要,只要相同层级的元素左侧对齐便可 五、# 表示注释,从这个字符一直到行尾,都会被解析器忽略,这个和python的注释同样 六、列表里的项用"-"来表明,字典里的键值对用":"分隔
更多关于pyyaml
的内容,能够参考网址:https://pyyaml.org/wiki/PyYAMLDocumentation 。
traceback
模块提供了一个标准接口,用于提取,格式化和打印Python程序的堆栈跟踪。它在打印堆栈跟踪时彻底模仿了Python解释器的行为。简单来讲,这个模块能够详细跟踪错误的信息,并能格式化输出,这在程序调试时会颇有用。
用try...except...
机制,咱们能够捕捉到错误,但不会有详细的错误信息,好比下面的程序:
# -*- coding: utf-8 -*- try: result = '1' + 2 print(result) except Exception as err: print(err)
程序的输出以下:
must be str, not int
该输出只告诉咱们错误的内容,可是没有告诉咱们错在哪里,详细的信息是什么,这样的处理方式在项目中广泛存在的话,那么项目的开发简直就是个灾难。
那么,换成traceback会有什么变化呢?
# -*- coding: utf-8 -*- import traceback try: result = '1' + 2 print(result) except Exception as err: print(traceback.format_exc())
输出结果以下:
Traceback (most recent call last): File "/Users/Jclian91/PycharmProjects/demo/delete.py", line 7, in <module> result = '1' + 2 TypeError: must be str, not int
该输出告诉咱们程序的第7行出错,以及具体的错误信息,这对程序的开发颇有帮助。
本次分享较为简单,但愿能对读者有用。 本次分享到此结束,感谢你们阅读~