Python模块

sys

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

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
View Code

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
View Code

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

在python3.6.2解释器,在pycharm的run里运行依然显示,可是在cmd和tterminal下没有问题html

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



import getpass

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

示例代码
getpass 示例

shelve

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

'''
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、一、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
'''
View Code

see also: shelvepython

 


see also: http://www.paramiko.org/
Paramiko

from retry import retry
@retry(tries=5, delay=1)
def foo():
    print('自动重复执行')
    raise 
foo()
retry

 1 import shutil
 2 '''
 3 shutil模块对文件和文件集合提供了许多高级操做。特别是,提供了支持文件复制和删除的功能
 4 '''
 5 
 6 # shutil.copy(src, dst)   # 拷贝文件
 7 # shutil.move(src, dst)  # 移动目录或者文件
 8 
 9 # shutil.rmtree(path)   # 递归删除目录,没法直接删除文件
10 # shutil.make_archive(base_name, format('zip'))   # 将目录或者文件以指定格式压缩
11 # shutil.unpack_archive(filename, extract_dir)  # 解压缩
12 
13 # see also: https://docs.python.org/3/library/shutil.html
shutil
 1 '''
 2 tqdm在阿拉伯语意为"进步"的意思,是一个快速、扩展性强的进度条工具库,只须要封装任意的tqdm(iterable)便可
 3 tqdm有较小的开销,智能预测剩余时间和没必要要的迭代显示。
 4 tqdm使用与任何平台:Linux、windows、Mac、FreeBSD、NetBSD、Solaris/SunOS,能够是任何控制台或GUI,而且较好的支持Ipython和Jupyter
 5 tqdm须要任何依赖,只要经过下面的下载就能够了
 6 pip install tqdm
 7 '''
 8 
 9 import tqdm
10 import time
11 
12 
13 # 基本用法: tqdm.tqdm
14 for i in tqdm.tqdm(range(1000)):
15     time.sleep(0.01)
16 
17 # 能够这样:tqdm.trange
18 for i in tqdm.trange(1000):
19     time.sleep(0.01)
20 
21 # 使用with语句对tqdm进行手动控制
22 with tqdm.tqdm(total=1000) as f:
23     for i in range(1000):
24         time.sleep(0.01)
25         f.update(10)
26 
27 # 应用于文件传输中,最后不要忘记close
28 import os
29 send_size = 0
30 file_name = 'a.mp4'
31 file_size = os.stat(file_name).st_size
32 t = tqdm.tqdm(total=file_size, desc='下载进度')
33 with open(file_name, 'rb') as f:
34     while send_size < file_size:
35         if file_size - send_size < 1024:
36             total_data = f.read(file_size - send_size)
37         else:
38             total_data = f.read(1024)
39         send_size += len(total_data)
40         t.update(len(total_data))
41 t.close()
42 
43 
44 # see also: https://tqdm.github.io/
45 # 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:\python36\Scripts】这个目录内
3. 以管理员权限打开cmd,将目录切换到C:\python36\Scripts下的解压后的ansible目录内,好比我安装的是ansible的2.7.4版本,那么, 此时cmd目录就应该在【C:\python36\Scripts\ansible-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生成表单数据

 

 


see also:三方库整理git

that's allgithub

相关文章
相关标签/搜索