Python学习 Python,这 22 个包怎能不掌握?( 五 )


Setuptools 是用来创建 Python 包的工具 。
这个项目的文档很糟糕 。 文档并没有描述它的功能 , 还包含死链接 。 真正的好文档在这里:https://packaging.python.org/ , 以及这篇文章中关于怎样创建 Python 包的教程:https://packaging.python.org/tutorials/packaging-projects/ 。
17. awscli
第3、7、17和22名互相关联 , 所以请参见第3名的介绍 。
18. pytz
3.94亿次下载
类似于第5名的 dateutils , 该库可以帮助你操作日期和时间 。 处理时区很麻烦 。 幸运的是 , 这个包可以让时区处理变得很容易 。
关于时间 , 我的经验是:在内部永远使用UTC , 只有在需要产生供人阅读的输出时才转换成本地时间 。
下面是 pytz 的例子:
from datetime import datetimefrom pytz import timezoneamsterdam = timezone('Europe/Amsterdam')ams_time = amsterdam.localize(datetime(2002, 10, 27, 6, 0, 0))print(ams_time)# 2002-10-27 06:00:00+01:00# It will also know when it's Summer Time# in Amsterdam (similar to Daylight Savings Time):ams_time = amsterdam.localize(datetime(2002, 6, 27, 6, 0, 0))print(ams_time)# 2002-06-27 06:00:00+02:00 更多文档和例子可以参见 PyPI 页面 。
19. Futures
3.89亿次下载
从 Python 3.2 开始 , python 开始提供 concurrent.futures 模块 , 可以帮你执行异步操作 。 futures 包是该库的反向移植 , 所以它是用于 Python 2 的 。 当前的 Python 3 版本不需要该包 , 因为 Python 3 本身就提供了该功能 。
前面我说过 , 从2020年1月1日起官方已经停止支持 Python 2 。 我希望明年再做这个列表的时候 , 不再看到这个包排进前22名 。
下面是 futures 包的基本用法:
from concurrent.futures import ThreadPoolExecutorfrom time import sleepdef return_after_5_secs(message):sleep(5)return messagepool = ThreadPoolExecutor(3)future = pool.submit(return_after_5_secs,("Hello world"))print(future.done)# Falsesleep(5)print(future.done)# Trueprint(future.result)# Hello World 可见 , 我们可以创建一个线程池 , 然后提交一个函数 , 让某个线程执行 。 同时 , 你的程序会继续在主线程上运行 。 这是实现并行执行的一种很容易的方式 。
20. Colorama
3.70亿次下载
你可以使用 Colorama 在终端上添加颜色:
Python学习 Python,这 22 个包怎能不掌握?
本文插图
下面的示例演示了实现这个功能有多么容易:
from colorama import Fore, Back, Styleprint(Fore.RED + 'some red text')print(Back.GREEN + 'and with a green background')print(Style.DIM + 'and in dim text')print(Style.RESET_ALL)print('back to normal now')21. Simplejson
3.41亿次下载
Python 自带的 json 模块有什么问题导致了这个包有如此高的排名?没有任何问题!实际上 ,Python 的 json 就是 simplejson 。 但 simplejson 有一些优点:

  • 能在更多 Python 版本上运行
  • 更新频率高于 Python
  • 一部分代码是用C编写的 , 运行得非常快
有时候你会看到脚本中这样写:
try:import simplejson as jsonexcept ImportError:import json 不过 , 除非确实需要一些标准库中没有的功能 , 我依然会使用 json 。 SImplejson 可能比 json快很多 , 因为它的一部分是用C实现的 。 但是除非你要处理几千个 JSON 文件 , 否则这点速度提升并不明显 。 此外还可以看看 UltraJSON , 这是个几乎完全用C编写的包 , 应该速度更快 。


推荐阅读