1、time模块
import time
print(time.time())
print(time.strftime('%Y-%m-%d %H:%M:%S '))
res = time.localtime()
print(res)
import datetime
print(datetime.datetime.now())
print(datetime.datetime.now()) + datetime.timedelta(days=3)
s_time = time.localtime()
print(time.mktime(s_time))
tp_time = time.time()
print(time.localtime(tp_time))
s_time=time.localtime()
print(time.strftime('%Y-%m-%d %H:%M:%S',s_time))
print(time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S')
struct_time = time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S')
timestamp = time.mktime(struct_time)+7*86400
print(timestamp)
time.strftime('%Y-%m-%d %X',time.localtime(timestamp))
time.sleep(3)
print(time.asctime())
print(datetime.datetime.now())
print(datetime.datetime.utcnow())
print(datetime.datetime.fromordinal(333))
2、random模块
import random
def make_code(size=4):
res = ''
for i in range(size):
s1=chr(random.randint(65,90))
s2=str(random.randint(0,9))
res+=random.choice([s1,s2])
return res
print(make_code(1))
3、OS模块
import os
os.remove() 删除一个文件
os.rename("oldname","newname") 重命名文件/目录
os.system("bash command") 运行shell命令,直接显示
os.environ['aaa']='11' 获取系统环境变量,规定:key与value必须都为字符串
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) 如果path是绝对路径,返回True
os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小
4、sys模块
import sys
import time
def progress(percent):
if percent >1
percent=1
res = int(50 * percent) * '#'
print('\r[%-50s] %d%%' % (res, 100 * percent), end='')
a1=0
a2=100000
while a1 < a2:
time.sleep(0.01)
a1+=1024
percent = a1 / a2
res=int(50*percent)*'#'
print('\r[%-50s] %d%%'%(res,100*percent),end='')
5、shutil模块
import shutil
shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
shutil.copyfile('f1.log', 'f2.log')
shutil.copymode('f1.log', 'f2.log')
shutil.copystat('f1.log', 'f2.log')
shutil.copy('f1.log', 'f2.log')
shutil.copy2('f1.log', 'f2.log')
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
shutil.rmtree('folder1')
shutil.move('folder1', 'folder3')
6、json&pickle模块
'''
1、什么是序列化?
3、内存中的数据类型 ---》序列化---》特定的格式(json格式或者pickle格式)
4、内存中的数据类型 《---反序列化《---特定的格式(json格式或者pickle格式)
土办法:
{‘aa’:11}-->序列化str({‘aa’:11})--->'{'aa':11}'
{‘aa’:11}<--反序列化str({‘aa’:11})<---'{'aa':11}'
2、为什么要有序列化
1、序列化得到的结果 =》特定的格式的内容有两种用途
1、可用于存储 =》用于存档
2、传输给其他平台使用 =》跨平台数据交互
2、针对用途1的特定格式:可是一种专用的格式 =》pickle只有python可以识别
针对用途2的特定格式:应该是一种通用的,能够被所有语言识别的格式 =》json
3、怎么用
import json
json模块
#序列化的结果写入文件的复杂方法
json_res=json.dumps([True,False,'aaa',1])
# print(json_res,type(json_res)) #[true, false, "aaa", 1]
with open('test.json',mode='wt',encoding='utf-8')as f:
f.write(json_res)
#将序列化的结果写入文件的简单方法
with open('test.json',mode='wt',encoding='utf-8')as f:
json.dumps([1,'aaa',True,False],f)
#从文件读取json格式的字符串进行反序列化操作的复杂方法
with open('test.json',mode='rt',encoding='utf-8')as f:
json_res=f.read()
l=json.loads(json_res)
print(l,type(l))
#从文件读取json格式的字符串进行反序列化操作的简单方法
with open('test.json',mode='rt',encoding='utf-8')as f:
l=json.loads(f)
print(l,type(l))
import pickle
pickle模块
#序列化
res = pickle.dumps({1,2,3,4,5})
print(res,type(res))
#反序列化
s = pickle.loads(res)
print(s,type(s))
'''
7、shelve模块(了解)
shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型
import shelve
f=shelve.open(r'sheve.txt')
print(f['stu1_info']['hobby'])
f.close()
8、xml模块(了解)
xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过,古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业的很多系统的接口还主要是xml。
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
xml数据
9、configparser模块
'''
配置文件
# 注释1
; 注释2
[section1]
k1 = v1
k2:v2
user=egon
age=18
is_admin=true
salary=31
[section2]
k1 = v1
'''
使用方法:
import configparser
config=configparser.ConfigParser()
config.read('file.ini')
print(config.sections())
print(config.options('section1'))
print(config.items('section1'))
'''
'''
10、hashlib 模块
'''
1、什么是hash
hash是一类算法,该算法接收传入的内容,经过运算得到一串hash值
hash值的特点:
1、传入的内容一样,得到的hash值必然一样 ==》明问
2、不能由hash值反解成内容
3、只要使用的hash算法不变,无论校验内容多大,得到的hash值的长度是固定的
2、hash的用途:
1、密文传输与验证
2、文件完整性校验
3、用途
import hashlib
m=hashlib.md5()
m.update('hello'.encode('utf-8'))
m.update('world'.encode('utf-8'))
res = m.hexdigest() #'helloworld'
print(res)
1、模拟撞库
cryptograph = 'asd78979zcx654qa65d4sa1c65f'
passwd = [
'asd1',
'qwe2',
'ads54'
]
import hashlib
dic = {}
for p in passwd:
res = hashlib.md5(p.encode('utf-8'))
dic[p]=res.hexdigest()
print(dic)
for k,v in dic.items():
if v == cryptograph:
print('撞库成功,铭文密码是'%k)
break
2、提升撞库的成本 =》密码加盐
import hashlib
m = hashlib.md5()
m.update('加'.encode('utf-8'))
m.update('password'.encode('utf-8'))
m.update('盐'.encode('utf-8'))
print(m.hexdigest())
'''
11、suprocess模块
import subprocess
obj=subprocess.Popen('ls /',shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
res = obj.stdout.read()
print(res.decode('utf-8'))
err_res=obj.stderr.read()
print(err_res.decode('utf-8'))
12、logging模块
import logging
日志级别与配置:
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=30,
)
logging.debug('调试debug')
logging.info('消息info')
logging.warning('警告warn')
logging.error('错误error')
logging.critical('严重critical')
'''
# 注意下面的root是默认的日志名字
WARNING:root:警告warn
ERROR:root:错误error
CRITICAL:root:严重critical
'''
日志配置字典
"""
logging配置
"""
import os
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
'[%(levelname)s][%(message)s]'
simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
test_format = '%(asctime)s] %(message)s'
LOGGING_DIC = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': standard_format
},
'simple': {
'format': simple_format
},
'test': {
'format': test_format
},
},
'filters': {},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'default': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'standard',
'filename': 'a1.log',
'maxBytes': 1024*1024*5,
'backupCount': 5,
'encoding': 'utf-8',
},
'other': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'formatter': 'test',
'filename': 'a2.log',
'encoding': 'utf-8',
},
},
'loggers': {
'': {
'handlers': ['default', 'console'],
'level': 'DEBUG',
'propagate': False,
},
'专门的采集': {
'handlers': ['other',],
'level': 'DEBUG',
'propagate': False,
},
},
}
日志配置字典LOGGING_DIC
使用:
import settings
import logging.config
logging.config.dictConfig(settings.LOGGING_DIC)
logger1=logging.getLogger('用户交易')
logger1.info('egon儿子alex转账3亿冥币')
common.py
13、re模块
常用匹配模式:http://blog.csdn.net/yufenghyc/article/details/51078107
import re
print(re.findall('\w','hello egon 123'))
print(re.findall('\W','hello egon 123'))
print(re.findall('\s','hello egon 123'))
print(re.findall('\S','hello egon 123'))
print(re.findall('\s','hello \n egon \t 123'))
print(re.findall(r'\n','hello egon \n123'))
print(re.findall(r'\t','hello egon\t123'))
print(re.findall('\d','hello egon 123'))
print(re.findall('\D','hello egon 123'))
print(re.findall('\Ahe','hello egon 123'))
print(re.findall('123\Z','hello egon 123'))
^ 指定匹配必须出现在字符串的开头或行的开头。
\A 指定匹配必须出现在字符串的开头(忽略 Multiline 选项)。
$ 指定匹配必须出现在以下位置:字符串结尾、字符串结尾的 \n 之前或行的结尾。
\Z 指定匹配必须出现在字符串的结尾或字符串结尾的 \n 之前(忽略 Multiline 选项)。
print(re.findall('^h','hello egon 123'))
print(re.findall('3$','hello egon 123'))
print(re.findall('a.b','a1b'))
print(re.findall('a.b','a1b a*b a b aaab'))
print(re.findall('a.b','a\nb'))
print(re.findall('a.b','a\nb',re.S))
print(re.findall('a.b','a\nb',re.DOTALL))
print(re.findall('ab*','bbbbbbb'))
print(re.findall('ab*','a'))
print(re.findall('ab*','abbbb'))
print(re.findall('ab?','a'))
print(re.findall('ab?','abbb'))
print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3"))
print(re.findall('a.*b','a1b22222222b'))
print(re.findall('a.*?b','a1b22222222b'))
print(re.findall('ab+','a'))
print(re.findall('ab+','abbb'))
print(re.findall('ab{2}','abbb'))
print(re.findall('ab{2,4}','abbb'))
print(re.findall('ab{1,}','abbb'))
print(re.findall('ab{0,}','abbb'))
print(re.findall('a[1*-]b','a1b a*b a-b'))
print(re.findall('a[^1*-]b','a1b a*b a-b a=b'))
print(re.findall('a[0-9]b','a1b a*b a-b a=b'))
print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb'))
print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb'))
print(re.findall(r'a\\c','a\c'))
print(re.findall('a\\\\c','a\c'))
print(re.findall('ab+','ababab123'))
print(re.findall('(ab)+123','ababab123'))
print(re.findall('(?:ab)+123','ababab123'))
print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>'))
print(re.findall('href="(?:.*?)"','<a href="http://www.baidu.com">点击</a>'))
print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))