首页 技术 正文
技术 2022年11月6日
0 收藏 545 点赞 750 浏览 7542 个字

1.time模块

  1)时间戳

import time
# 通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量
# 偏移量的是float类型
start_time = time.time()
time.sleep(0.5)
stop_time = time.time()
print(stop_time-start_time)

  2)格式化时间

import time
# 格式化时间
# strftime(format[, t]) : 把一个代表时间的元组或者struct_time(如由
# time.localtime()和time.gmtime()返回)转化为格式化的时间字符串
# format默认为:"%a %b %d %H:%M:%S %Y"
# 注意:
# 如果t未指定,将传入time.localtime()
# 如果元组中任何一个元素越界,ValueError的错误将会被抛出
str_time = time.strftime('%Y - %m - %d %X')
print(str_time)

  3)结构化时间

import time
print(time.localtime()) # 本地时区的struct_time
print(time.gmtime()) # UTC时区的struct_timeprint(time.localtime().tm_year)
print(time.localtime().tm_mon)
print(time.localtime().tm_mday)
# asctime()把一个表示时间的元组或者struct_time表示为
# 这种形式:'Sun Jun 20 23:21:05 1993'
# 如果没有参数,将会将time.localtime()作为参数传入
print(time.asctime())# ctime([secs]) : 把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式
# 如果参数未给或者为None的时候,将会默认time.time()为参数
# 它的作用相当于time.asctime(time.localtime(secs))
print(time.ctime())

2.datetime模块

  1)获取时间

import datetime
print(datetime.datetime.now())
# 获取当前时间戳并转换成指定格式
print(datetime.date.fromtimestamp(time.time()))

  2)时间加减、替换

import datetime
# 时间加减
# 当前时间 +-3 天
print(datetime.datetime.now() + datetime.timedelta(3))
print(datetime.datetime.now() + datetime.timedelta(-3))
# 当前时间 +3 小时
print(datetime.datetime.now() + datetime.timedelta(hours=3))
# 当前时间 +30 分
print(datetime.datetime.now() + datetime.timedelta(minutes=30))
# 时间替换
c_time = datetime.datetime.now()print(c_time.replace(minute=30,hour=3))

3.random模块

import random
# 随机输出 0-1 之间的浮点数
print(random.random())# 随机输出 大于等于 x 小于 等于 y 的整数
print(random.randint(1,3))# 随机输出 大于等于 x 小于 y 的浮点数
print(random.randrange(1,3))# 输出随机元素
print(random.choice([1,55,666,7,[222,22,'zhang']]))# 随机输出指定个数的元素的列表
print(random.sample([11,22,33,44,55],2))# 大于x 小于y的小数
print(random.uniform(1,5))# 重点:
# shuffle()生成乱序
res = [11,22,55,33,44]
random.shuffle(res)
print(res)

练习:生成随机验证码

def code_random(num):
res = ''
for item in range(num):
code1 = str(random.randint(0,9)) # 字符串格式
code2 = chr(random.randint(65,90))
code3 = chr(random.randint(97,122))
res += random.choice([code1,code2,code3])
return res
print(code_random(4))

4.os模块

import os# 删除文件
os.remove(r'D:\BaiduYunDownload\code\内置模块\11.png')# 列出指定目录下的文件和子目录,返回列表
res = os.listdir(os.path.dirname(__file__))
print(res)# 返回当前文件的根目录
res1 = os.path.dirname(__file__)
print(res1)

5.shutil()模块

# 将文件内容拷贝到另外一个文件中
src = r'D:\BaiduYunDownload\Python3.0 Project\内置模块\a1.log'
dst = r'D:\BaiduYunDownload\Python3.0 Project\内置模块\a2.log'
shutil.copyfileobj(open(dst,'r',encoding='utf-8'),open(src,'w',encoding='utf-8'))# 拷贝文件,目标文件不一定需要存在
shutil.copyfile(src,r'a1_copy.log')# 仅拷贝全向,内容和组、用户不变,目标文件必须存在
shutil.copymode(src,dst)# 拷贝文件和权限
shutil.copystat(src,dst)

6.json模块—序列化和反序列化

import jsondic = {'name':'zhang','age':18,'hobbies':['sleep','play','girl']}
dic_json = json.dumps(dic)
print(dic,type(dic)) # 序列化前时字典
print(dic_json,type(dic_json))   # 序列化之后是str类型

with open(r'json序列化.json','w',encoding='utf-8') as f:
  # 相当于先把字典序列化成字符串再encoding,然后写入文件
res = json.dumps(dic)
f.write(res)# 反序列化
with open(r'json序列化.json','r',encoding='utf-8') as f:
  res = json.load(f) # 相当于先将文件的内容以字符串的格式读出来,再反序列化,还原原先的数据类型格式
  print(res,type(res)) # 和存之前的类型一致# !!!!强调:
# 无论数据是怎样创建的,只要满足json格式
# 就可以json.loads出来,不一定非要dumps的数据才能loads
# json认双引号,不认单引号,如json文件中字符串用的是单引号将无法读出# pickle()能用于Python,并且可能不同版本的Python彼此都不兼容
# 因此,只能用Pickle保存那些不重要的数据

了解知识点:

shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型

shelve模块

7.sys模块

# sys.argv           命令行参数List,第一个元素是程序本身路径
# sys.exit(n) 退出程序,正常退出时exit(0)
# sys.version 获取Python解释程序的版本信息
# sys.maxint 最大的Int值
# sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
# sys.platform 返回操作系统平台名称# 进度条
print('[%-15s]' %'#')
print('[%-15s]' %'##')
print('[%-15s]' %'###')
print('[%-15s]' %'####')# 指定宽度
# 第三个%的意义在于取消第二个%的意义
print('%s%%' %(100))# 进度条实现
import time,sys,random
def show_process(percent,width=50):
if percent > 1:
percent = 1
show_str = ('[%%-%ds]' %width) %(int(width*percent)*'#')
print('\r%s %d%%' %(show_str,int(100*percent)),file=sys.stdout,flush=True,end='')data_size = 10240
recv_size = 0
while recv_size < data_size:
time.sleep(random.random()*1)
recv_size += random.randint(0,1024) percent = recv_size/data_size
show_process(percent,width=50)

8.logging模块

import logging.config
import logging
# 定义日志文件的路径
LOG_PATH = r'D:\code\内置模块\a1.log'
BOSS_LOG_PATH = r'a2.log'# 定义三种日志输出格式
# name为getlogger指定的名字
standard_format = '%(asctime)s -%(levelname)s - role:%(name)s - %(message)s'
simple_format = '%(asctime)s - role:%(name)s - %(message)s'# log配置字典
LOGGING_DIC = {
'version': 1,
'disable_existing_loggers': False,
# 1.定义日志的格式
'formatters': {
'standard': {
'format': standard_format
},
'simple': {
'format': simple_format
},
},
'filters': {},
# 2.定义日志输出的目标:文件或者终端
'handlers': {
# 打印到文件的日志,收集用户操作日志
'access': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
'formatter': 'standard',
'filename': LOG_PATH, # 用户日志文件路径
'maxBytes': 1024*1024*5, # 日志大小 5M
'backupCount': 5,
'encoding': 'utf-8', # 日志文件的编码,避免中文log乱码
},
# 打印到文件的日志,收集管理员操作日志
'manager': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler',
'formatter': 'standard',
'filename': BOSS_LOG_PATH, # 管理员日志文件路径
'maxBytes': 1024*1024*5,
'backupCount': 5,
'encoding': 'utf-8',
},
},
'loggers': {
# logging.getLogger(__name__)拿到的logger配置
'': {
# 把上面定义的handler都加上,即把log数据写入文件中
'handlers': ['access','manager'],
'level': 'INFO',
'propagate': False, # 向上(更高level的logger)传递
},
},
}msg = '用户:zhang,登陆了个人门户'def logger(name): # name='atm'
logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置
logger = logging.getLogger(name)
return loggerlogger('client').info(msg=msg)

标准日志格式

9.hashlib()模块

  hash:

    一种算法,将传入的内容进过特定的算法计算出一串有数字和字母组成的字符串
  这个字符串叫做哈希值
  特点:  
    1)传入的内容一样,得到的哈希值一样—>实现文件的完整性验证
    2)由哈希值反解成内容—>把密码做成哈希值,不用明文传输
    3)只要使用hash算法,无论校验的内容多大,得到的哈希值不变

使用:

  字符串哈希和文件哈希

import hashlibmsg = 'zhang'
res = hashlib.md5()
res.update(msg.encode('utf-8'))
# # 获取哈希值hexdigest()
print(res.hexdigest())m = hashlib.md5()
with open(r'a1.log','rb') as f:
for line in f:
m.update(line)
hv = m.hexdigest()
print(hv)

  密码加盐

# 密码加盐
pwd = 'zhang'
m = hashlib.md5()
# 加盐部分
m.update('zssss'.encode('utf-8'))
m.update(pwd.encode('utf-8'))
m.update(''.encode('utf-8'))
print(m.hexdigest())

注意:

  选择不同哈希算法,计算得出的哈希不一样

10.subprocess模块

  系统命令解析模块

import subprocessobj = subprocess.Popen('dir',
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# 只能从管道取一次输出的值,第二次取值为空
res1 = obj.stdout.read()
# 读取到的命令结果为二进制格式
# 需要使用相应的编码方式解码
print('正确结果1:',res1.decode('gbk'))res2 = obj.stdout.read()
print('正确结果2:',res2.decode('gbk'))# 获取错误结果
# res3 = obj.stderr.read()
# print('错误结果:',res3.decode('gbk'))

10.re模块

import re# 匹配非数字、字母和下划线
print(re.findall('\W','as2s3s#%@#_ffw_2'))
# 匹配数字、字母和下划线
print(re.findall('\w','as2s3s#%@#_ffw_2'))# 任意空字符
print(re.findall('\S','as2s3s#%@#_ffw_2'))
# 匹配任意空字符
print(re.findall('\s','as2s33s#%@#_ffw_2'))# 匹配任意非字数
print(re.findall('\D','as3s#%@#_ffw_2'))
# 匹配任意数字 0-9
print(re.findall('\d','as2s3s#%@#_ffw_2'))print(re.findall('\Aalex','aasssalex is asle sb'))
print(re.findall('\Aalex','alex is asle sb'))print(re.findall('^alex','alex is alex sb'))
print(re.findall('sb$','alexsb is shakexsb'))# {n,m}代表左边那一个字符出现m次到n次
print(re.findall('ab?','a ab abb abbb abbbb'))
print(re.findall('ab{0,1}','a ab abb abbb abbbb'))# 零到无穷次
print(re.findall('ab*','a ab abb abbb abbbb'))
print(re.findall('ab{0,}','a ab abb abbb abbbb'))# 一到无穷次
print(re.findall('ab+','a ab abb abbb abbbb'))
print(re.findall('ab{1,}','a ab abb abbb abbbb'))# 贪婪匹配 .*匹配任意长度,任意的字符
print(re.findall('a.*c','abhbhcbsbhs^&&^%bhcbhhc'))
# 第一个a和最后一个c之间的所有字符# 推荐使用非贪婪匹配 .*?
print(re.findall('a.*?c','asscddd$$#c'))# [] 中括号,匹配一个指定范围内的字符(这一个字符来自于括号内定义的)
print(re.findall('a[0-9]b','a1sb a55b a2b a9b aDb aAb avb arb'))# 当 - 需要在[]当做普通字符用是,只能加在前面或者后面
print(re.findall('a[*+-]b','a+b a-b a2b a9b a*b aAb avb arb'))# 匹配两个字符之间存在一个大写或者小写字母的字符串
print(re.findall('a[A-Za-z]b','a+b a-b a2b a9b a*b aAb avb arb'))# () 分组
print(re.findall('(alex)_sb','alex_sb asddasjjalex_sb'))print(re.findall(
'href="(.*?)" rel="external nofollow" ',
'<link id="MainCss" type="text/css" rel="stylesheet" href="/skins/bundle-MountainInk.css" rel="external nofollow" />'
))# [] 内的 ^ 代表取反的意思
print(re.findall('a[^A-Za-z]b','a+b a-b a2b a9b a*b aAb avb arb'))

re模块

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,489
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,904
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,737
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,490
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,128
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,291