• Python模块


    sys:

    从Python3.2版本开始,sys模块移除了sys.setdefaultencoding方法,因为该setfaultencoding方法是在解决Python2.x中的字符编码的问题,而Python3.x中使用utf8后,就不再需要使用该方法

    hashlib:

    import hashlib
    import os
    import time

    print(hashlib.md5('abc'.encode('UTF-8')).hexdigest())
    print(hashlib.sha1('abc'.encode('UTF-8')).hexdigest())
    print(hashlib.sha256('abc'.encode('UTF-8')).hexdigest())
    print(hashlib.sha512('abc'.encode('UTF-8')).hexdigest())
    '''
    900150983cd24fb0d6963f7d28e17f72
    a9993e364706816aba3e25717850c26c9cd0d89d
    ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
    ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f
    '''

    random_str = lambda: hashlib.sha1(bytes("%s%s" % (os.urandom(16), time.time()), encoding='utf8')).hexdigest()

    print(random_str()) # 29c7f2f6ecaabb603db82854c7d58ca258d9aff9


    def random_str1():
    byt = bytes('%s%s' % (os.urandom(16), time.time()), encoding='utf8')
    sh = hashlib.sha1(byt)
    return sh.hexdigest()


    print(random_str1()) # 3b142a3e7c804ee5dc67d802eda1d43a44399c31


    # md5返回的字符串

    def md5str():
    md = hashlib.md5(bytes('%s%s' % (os.urandom(16), time.time()), encoding='utf8'))

    return md.hexdigest()


    print(md5str()) # d40ae2d0fa337673aee598f82bb3180e

    math:

    '''
    Python3.x中,math.floor(x)返回x的下舍整数
    Python2.x中,返回的是float类型
    '''

    # floor示例
    import math

    print(math.floor(32.5)) # 32
    print(type(math.floor(32.3))) # python3默认为int类型 <class 'int'>
    print(int(math.floor(32.9))) # 32
    print(float(math.floor(32.9))) # 32.0
    print(math.floor(-32.93)) # -33
    print(math.floor(math.pi)) # 3
    print(math.pi) # 3.141592653589793

    # 4的2次方
    print(math.pow(4, 2)) # 16.0
    # 4的3次方
    print(math.pow(4, 3)) # 64.0
    # 16开2次方
    print(math.sqrt(16)) # 4.0
    # 16开2次方
    print(pow(16, 0.5)) # 4.0
    # 16开3次方
    print(pow(16, 0.3)) # 2.2973967099940698
    # 16开4次方
    print(pow(16, 0.25)) # 2.0
    # 16开5次方
    print(pow(16, 0.2)) # 1.7411011265922482

    keyword:

    # keyword模块可以判断一个字符串是否为Python内的关键字
    keyword.iskeyword(s)
    # 如果s是Python中的关键字,如果是则返回True,否则返回False
    keyword.kwlist
    # 以列表的形式返回Python中的所有关键字

    # see also: https://docs.python.org/3.7/library/keyword.html

    for example:
    '''
    >>> import keyword
    >>> keyword.iskeyword("and")
    True
    >>> keyword.kwlist
    ['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
    '''

    keyword

    platform:

    Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import platform
    >>> platform.machine() # 返回机器类型,不确定则返回空字符串
    'AMD64'
    >>> platform.node() # 返回机器网络名称,不确定则返回空字符串
    'DESKTOP-D7UG7RC'
    >>> platform.platform() # 返回机器系统平台信息
    'Windows-10-10.0.14393-SP0'
    >>> platform.processor() # 返回机器的处理器信息
    'Intel64 Family 6 Model 60 Stepping 3, GenuineIntel'

    see also:https://docs.python.org/3.7/library/platform.html

    platform:访问系统平台的底层信息

    getpass:

    # import msvcrt
    # def pwd_input():
    # chars = []
    # while True:
    # try:
    # newChar = msvcrt.getch().decode(encoding="utf-8")
    # except:
    # return input("你很可能不是在cmd命令行下运行,密码输入将不能隐藏:")
    # if newChar in ' ': # 如果是换行,则输入结束
    # break
    # elif newChar == '': # 如果是退格,则删除密码末尾一位并且删除一个星号
    # if chars:
    # del chars[-1]
    # msvcrt.putch(''.encode(encoding='utf-8')) # 光标回退一格
    # msvcrt.putch( ' '.encode(encoding='utf-8')) # 输出一个空格覆盖原来的星号
    # msvcrt.putch(''.encode(encoding='utf-8')) # 光标回退一格准备接受新的输入
    # else:
    # chars.append(newChar)
    # msvcrt.putch('*'.encode(encoding='utf-8')) # 显示为星号
    # return (''.join(chars) )
    #
    # print("请输入密码:")
    # pwd = pwd_input()
    # print(" 密码是:{0}".format(pwd))
    # input("按回车键退出")

    import getpass

    user = getpass.getuser()
    print('user:',user)
    pwd = getpass.getpass('pwd:')
    print(pwd)

    示例代码

    getpass 示例

    shelve
    shelve模块是一个简单的以字典形式存储的轻量级的持久化Python对象的模块

    '''
    shelve可以用来持久化任意的Python的对象,pickle能处理的,shelve都能持久化,一般我们通过字典的形式来操作shelve对象
    shelve对象支持字典支持的所有方法。
    f = shelve.open(filename) # 通过open方法打开一个文件,并拿到文件对象f
    f['a'] = "Python's obj" # 以字典的方式将Python中的任意对象持久化

    a = f['a']
    a = 'new str'
    f['a'] = a

    f.close() # 最后要显示的调用close方法,保存并关闭f对象
    # 如果觉得每次f.close()麻烦,请用with负责管理:
    with shelve.open(filename) as f:
    f['auth'] = {'name': 'wang', 'age': 18}

    # 参数
    shelve.open(filename, flag='c', protocol=None, writeback=False)
    filename: 打开的文件
    flag: 'c'为打开数据库进行读写,如果不存在则创建它,详情参阅dbm模块的关于flag的参数 https://docs.python.org/3/library/dbm.html#dbm.open
    protocol: 遵循pickle的协议版本,这里可选为0、1、2
    ps:目前pickle的protocol参数默认为3,Python3中的新协议,see also https://docs.python.org/3/library/pickle.html#pickle.DEFAULT_PROTOCOL
    writeback: 如果writeback参数为True,则对象将保存所有访问条目的缓存,并在同步和关闭时将它们写回dict。 这允许对可变条目进行自然操作,
    但可以消耗更多内存并使同步和关闭需要很长时间。
    ps:shelve对象不支持多应用同时写入,并且对于该对象不知道那些字典的内容被修改,
    所以需要制定writeback,在最后 保存的时候,将全部的字典写回文件,这样难免占用了大量的时间和内存消耗
    '''

    import shelve

    f = shelve.open('a.txt')


    ''' shelve: add '''

    class A:
    x = 'AD钙奶'
    def test(self):
    y = 2
    obj = A()
    f['obj'] = obj
    f['auth'] = {'name': 'wang', 'age': 18}
    f['list'] = [1, 2, 3, 4]
    f['tuple'] = ('a', 'b')
    f.close()

    ''' shelve: select '''
    f1 = shelve.open('a.txt') # open file
    print(f1['obj'].x) # AD钙奶
    print(f1['auth']['name']) # wang
    print(f1['list']) # [1, 2, 3, 4]
    print(f1['tuple']) # ('a', 'b')
    f1.close()

    ''' shelve: update '''
    f2 = shelve.open('a.txt')
    obj1 = f2['obj']
    obj1.x = 'wahaha'
    f2['obj'] = obj1
    print(f2['obj'].x) # wahaha
    auth = f2['auth']
    auth['age'] = 16
    f2['auth'] = auth
    print(f2['auth']) # {'name': 'wang', 'age': 16}
    f2.close()
    ''' shelve: delete '''

    # with shelve.open('a.txt') as f3:
    # del f3['tuple']
    with shelve.open('a.txt') as f4:
    for i in f4:
    print(i)
    '''
    obj
    auth
    list
    '''
    from retry import retry
    @retry(tries=5, delay=1)
    def foo():
    print('自动重复执行')
    raise
    foo()

    retry

    import shutil
    '''
    shutil模块对文件和文件集合提供了许多高级操作。特别是,提供了支持文件复制和删除的功能
    '''

    # shutil.copy(src, dst) # 拷贝文件
    # shutil.move(src, dst) # 移动目录或者文件

    # shutil.rmtree(path) # 递归删除目录,无法直接删除文件
    # shutil.make_archive(base_name, format('zip')) # 将目录或者文件以指定格式压缩
    # shutil.unpack_archive(filename, extract_dir) # 解压缩

    # see also: https://docs.python.org/3/library/shutil.html

    shutil

    '''
    tqdm在阿拉伯语意为"进步"的意思,是一个快速、扩展性强的进度条工具库,只需要封装任意的tqdm(iterable)即可
    tqdm有较小的开销,智能预测剩余时间和不必要的迭代显示。
    tqdm使用与任何平台:Linux、windows、Mac、FreeBSD、NetBSD、Solaris/SunOS,可以是任何控制台或GUI,并且较好的支持Ipython和Jupyter
    tqdm需要任何依赖,只要通过下面的下载就可以了
    pip install tqdm
    '''

    import tqdm
    import time


    # 基本用法: tqdm.tqdm
    for i in tqdm.tqdm(range(1000)):
    time.sleep(0.01)

    # 可以这样:tqdm.trange
    for i in tqdm.trange(1000):
    time.sleep(0.01)

    # 使用with语句对tqdm进行手动控制
    with tqdm.tqdm(total=1000) as f:
    for i in range(1000):
    time.sleep(0.01)
    f.update(10)

    # 应用于文件传输中,最后不要忘记close
    import os
    send_size = 0
    file_name = 'a.mp4'
    file_size = os.stat(file_name).st_size
    t = tqdm.tqdm(total=file_size, desc='下载进度')
    with open(file_name, 'rb') as f:
    while send_size < file_size:
    if file_size - send_size < 1024:
    total_data = f.read(file_size - send_size)
    else:
    total_data = f.read(1024)
    send_size += len(total_data)
    t.update(len(total_data))
    t.close()


    # see also: https://tqdm.github.io/
    # https://github.com/tqdm/tqdm#documentation

    tqdm:进度条

    '''
    ansible在windows下通过普通的pip方式很难(我没有安装成功)安装成功,但在Linux下通过
    pip install ansible
    就可以很简单的安装成功
    '''
    接下来就说说windows下如何安装。
    1. 从pypi官网下载你想要的版本的tar包,地址是:https://pypi.org/project/ansible/
    2. 当下载到本地之后,解压到Python安装目录的Script目录内,比如我的Python解释器安装在C盘的Python目录内,那么就把tar包解压到【C:python36Scripts】这个目录内
    3. 以管理员权限打开cmd,将目录切换到C:python36Scripts下的解压后的ansible目录内,比如我安装的是ansible的2.7.4版本,那么, 此时cmd目录就应该在【C:python36Scriptsansible-2.7.4】这个目录下,然后cmd中输入
    python setup.py install
    然后经过一番安装,其中夹杂两个语法错误之后,就磕磕绊绊的安装成功了。
    4. 打开解释器
    输入
    import ansible
    不报错就说明安装成功了。

    see also: https://blog.csdn.net/weixin_42356309/article/details/83411437

    ansible


    '''
    pip install tabulate
    '''
    import tabulate

    table = [('vip%s' % i, 20 * i, 50000 * 10 * i) for i in range(1, 11)]
    headers = ('vip_level', 'price', 'storage')

    for fmt in tabulate._table_formats.keys():
    print(''.center(20, '*'), fmt, ''.center(20, '*'))
    print(tabulate.tabulate(table, headers=headers, tablefmt=fmt))


    # a = ''.join(tabulate.tabulate(table, headers=headers, tablefmt='psql'))
    # print(a)

    tabulate生成表单数据
  • 相关阅读:
    0909初识操作系统
    实验四主存空间的分配和回收
    实验一 DOS命令解释程序的编写
    0909关于操作系统
    实验四主存空间的分配和回收
    实验3评价
    实验一 DOS命令解释程序的编写
    实验三、进程调度模拟程序实验
    实验二、作业调度实验
    0909 第一次上机课之《为什么学操作系统?》
  • 原文地址:https://www.cnblogs.com/zhang-da/p/12236606.html
Copyright © 2020-2023  润新知