python3_标准库汇总, 简单使用

目录:


subprocess

使用shell执行子进程:

from subprocess import Popen, PIPE
p = Popen('echo hello', shell=True, stdout=PIPE)
code = p.wait(timeout=-1)     # 默认timeout=-1, 阻塞直到进程结束,返回结果,如果超时,抛出异常
out = p.stdout.read()

tempfile

创建临时文件对象

from tmpfile import TemporaryFile
with TemporaryFile('w+') as f:
    p = Popen('echo hello', shell=True, stdout=f)
    code = p.wait()
    f.seek(0)
    out = f.read()

uuid

URN 获得不同的key或id

import uuid 
key = uuid.uuid4().urn    # uuid4随机生成
id = uuid.uuid4().hex
uuid1()  #  根据本机网络地址生成, 生成固定的id

collections模块

deque 双向队列

que = deque(maxlen=5)
创建一个固定大小的队列, 队列已满的时候, 新加入元素, 老的元素会被移除
方法:append, appendleft, pop, popleft, extend, remove, rotate
在开头插入或删除元素都是O(1), 而list是O(N)

namedtuple 命名元组

命名元组
namedtuple(typename, field_names)
field_names可以是以空白符或逗号分割的字段的字符串,可以是字段的列表
nameedtuple有一个总的名字,同时每一个字段都对应一个字段名
相当于实现一个类,对应不同的属性,需要的时候,实例化,给每个属性赋值

    >>> Point = namedtuple('Point', ['x', 'y'])
    >>> Point.__doc__                   # docstring for the new class
    'Point(x, y)'
    >>> p = Point(11, y=22)             # instantiate with positional args or keywords
    >>> p[0] + p[1]                     # indexable like a plain tuple
    33
    >>> x, y = p                        # unpack like a regular tuple
    >>> x, y
    (11, 22)
    >>> p.x + p.y                       # fields also accessible by name
    33
    >>> Point(**d)                      # convert from a dictionary
    Point(x=11, y=22)

defaultdict

默认值字典
defaultdict(default_factory)
提供一个空字典,当key不存在的时候,会调用工厂函数来生成key对应的value
例: defaultdict(list)

OrderedDict

定义一个有序的字典, 记录元素插入的顺序, 迭代时按顺序迭代

od = OrderedDict.fromkeys('abcd')
od.popitem(last=True)       #  last=True, FILO;  last=False, FIFO
od.move_to_end('b', last=True)  # 移动元素位置, last=True, 移动到最后

heapq

堆队列, FIFO

nums = [1, 8, 2, 23, 7]
heapq.heapify(nums) # 堆排序后, 放入列表
heapq.heappush(nums, item) # 先将nums heapify, 再在队列中添加item, 顺序是从小到大
heapq.heappop(nums) #从index0开始pop
heapq.nlargest(n, nums, key) # 容器中n个最大值, key是函数
heapq.nsmallest(n, nums, key) # 容器中n个最小值
使用heapq实现一个简单的优先队列


random

随机模块

random.seed()系统默认设置
random.randint(start,stop) -> int 指定范围
random.randrange([start,]stop[,step]) -> 指定范围,按指定基数递增的集合中取一个
random.choice(seq) -> 从非空序列中随机挑选一个元素
random.shuffle(seq) ->None 就地修改,重新洗牌
random.sample(population,k) -> list ,随机取k个元素组成新列表,元素位置不同
random.uniform(a,b) 生成一个[a,b]之间的随机小数
getrandbits(k) 生成一个k比特长的随机整数
del lst[index] 删除一个列表元素


functools

The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.
高阶函数模块, 多作为装饰器使用
@wraps(wrapped)装饰器源码:

@functools.wraps(wrapped,assigned=WRAPPER_ASSIGNMENTS,updated=WRAPPER_UPDATES)
元组WRAPPER_ASSIGNMENTS中是要被覆盖的属性
module‘,’name‘,’qualname‘,’doc‘,
annotations
模块名,名称,限定名,文档,参数注解
元组WRAPPER_UPDATED中是要被更新的属性
dict‘字典
增加了一个wrapped属性,保留wrapped函数
return partial(update_wrapper, wrapped=wrapped,
assigned=assigned, updated=updated)
wrapper is the function to be updated
wrapped is the original function

partial偏函数:把函数部分参数固定下来,相当于为部分参数添加一个固定的默认值,并返回一个新函数

def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*args, *fargs, **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc
from functools import partial 查看原码

inspect.signature(foo)查看签名
partial函数保留原函数所有参数,本质是将固定的参数和后来收集的参数,都传给原参数
注意: 先固定靠后的位置参数, 因为被固定参数后面的位置参数都变成了keyword_only参数

@functools.lru_cache(maxsize=128,typed=False)

Least-recently-used缓存装饰器, 传入的参数作为key, 函数返回值最为
maxsize设置为None,则禁用LRU功能,缓存可以无限制增长,maxsize是二的幂,LRU功能执行的最好
typed设置为True是,不同类型的函数参数将单独缓存,f(3),f(3.0)视为不同调用


inspect模块

There are four main kinds of services provided by this module: type checking, getting source code, inspecting classes and functions, and examining the interpreter stack.
类型检查, 获得源码, 检查类和函数, 检查解释器栈

注解, python3.6加入:

参数注解 func(para: int) -> int:
变量注解 val: int = 10

获取函数签名

检查类型:
inspect.isfunction()
inspect.ismethod()
inspect.isgenerator()
inspect.isgeneratorfunction()
inspect.isclass()
inspect.ismodule()
inspect.isbuildin()

inspect.signature(func) 获取函数签名

signature对象:
sig.parameters -> OrderedDict [(parameter.name:parameter object),,]
sig.return_annotation -> 返回值参数注解类型

Parameter 对象:保存在元组中,只读
.name , 名字
.annotation 注解
.default 默认值
.empty == inspect._empty 表示空, 作为default,annotation的值
.kind 表示实参如何绑定到形参:
- POSITIONAL_ONLY # python没有这个类型的参数
- POSITIONAL_OR_KEYWORD
- VAR_POSITIONAL
- KEYWORD_ONLY
- VAR_KEYWORD
.replace(*, name=_void, kind=_void, annotation=_void, default=_void)
- 返回一个parameter的copy, Creates a customized copy of the Parameter

猜你喜欢

转载自blog.csdn.net/qq_33287645/article/details/81299040