python常用模块三(hashlib,configparser,logging,os)

hashlib模块                             

hashlib提供了常见的摘要算法,如md5和sha1等等。

那么什么是摘要算法呢?摘要算法又称为哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个长度固定的数据串(通常用16进制的字符串表示)。

注意:摘要算法不是一个解密算法。(摘要算法,检测一个字符串是否发生了变化)

用途:1.做文件校验

   2.登录密码

      密码不能解密,但可以撞库,用‘加盐’的方法就可以解决撞库的问题。所有以后设置密码的时候要设置的复杂一点。

import hashlib

# md5_obj = hashlib.md5()  未加盐
md5_obj = hashlib.md5('nihao'.encode('utf-8'))  # 加盐后(就让你的密码更牢固了)
md5_obj.update('123456'.encode('utf-8'))
print(md5_obj.hexdigest())
md5_obj.update('hello'.encode('utf-8'))
print(md5_obj.hexdigest())


user = 'haiyan'
password = '123456'
md5_obj= hashlib.md5(user.encode('utf-8'))  #加盐(哪怕被人的密码和你的密码一样,
# 那你加盐以后就只有你的用户名对应的是你的密码了)
md5_obj.update(password.encode('utf-8'))
print(md5_obj.hexdigest())


# 文件校验(检测文件改变了没)
import hashlib
md5_obj = hashlib.md5()
import os
filesize = os.path.getsize('filename')  #文件大小
f = open('filename','rb')
while filesize>0:
    if filesize > 1024:
        content = f.read(1024)
        filesize -= 1024
    else:
        content = f.read(filesize)
        filesize -= filesize
    md5_obj.update(content)
# for line in f:
#     md5_obj.update(line.encode('utf-8'))
md5_obj.hexdigest()

  

configparser模块                     

创建文件
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
                     }
config['bitbuck et.org'] = {'User':'hg'}
config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
with open('example.ini', 'w') as configfile:
   config.write(configfile)


查找文件
import configparser
config = configparser.ConfigParser()
# print(config.sections())
config.read('example.ini')
print(config.sections())  #读出来的是文件里面的组,
# 而且里面的[DEFAULT]组没有显示出来
print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True
print(config['bitbucket.org']["user"])  # hg
print(config['DEFAULT']['Compression']) #yes
print(config['topsecret.server.com']['ForwardX11'])  #no
print(config['bitbucket.org'])          #<Section: bitbucket.org>
for key in config['bitbucket.org']:     # 注意,有default会默认default的键
    print(key)
print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键
print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对
print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key对应的value

增删改操作
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
config.add_section('yuan')
# config.remove_section('bitbucket.org') #删除组
# config.remove_option('topsecret.server.com',"forwardx11") #删除组里面的项
config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')
config.write(open('new2.ini', "w"))

  

 

logging模块

默认情况下Python的logging模块将日志打印到了标准输出中,且只显示了大于等于WARNING级别的日志,这说明默认的日志级别设置为WARNING(日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG),默认的日志格式为日志级别:Logger名称:用户输出消息。

只显示大于等于warning基本的日志,这说明默认的日志级别设置为warning
(日志级别等级critical>error>warning>info>debug)
import logging
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')  #warning 警告(从警告开始才执行)
logging.error('error message') #error 错误
logging.critical('critical message') #比错误更严重的级别



配置参数
logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:

filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。

format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息

  

有两种方式去应用logging模块

设置config
import logging
logging.basicConfig(
    level=logging.DEBUG ,    #多输出一些细节
    # level = logging.WARNING  #就不用输出那些细节了
    format = '%(name)s %(asctime)s [%(lineno)d] ---%(message)s', #本身就存在在python语法中,拿过来用就行了
    # level和format也是不能变的,它是参数,不是变量
    # %(lineno)d指定代码块的行
    # %(name)s当前管理员的用户
    datefmt = '%d/%m/%Y %H:%M:%S',#指定日期时间格式
    filename = 'logging_info' #自动创建了一个文件,并且把日志写到了文件里

)
logging.debug('debug message')
logging.info('info message')
logging.warning('warning message')
logging.error('error message')
logging.critical('critical message')

logger对象配置
可以控制输入到文件,也可以输入到屏幕
import logging
def mylogger(filename,file=True,stream=True):
    logger = logging.getLogger()
    formater = logging.Formatter(
        fmt='%(name)s %(asctime)s [%(lineno)d] ---%(message)s',
        datefmt='%d/%m/%Y %H:%M:%S'  # 时间格式
    )
    logger.setLevel(logging.DEBUG)  #指定日志打印的等级
    if file:
        file_handler = logging.FileHandler('logging.log',encoding='utf-8')# 创建一个handler,用于写入日志文件
        file_handler.setFormatter(formater)  # 文件流,文件操作符
        logger.addHandler(file_handler)
    if stream:
        stream_handler = logging.StreamHandler()  # 再创建一个handler,用于输出到控制台
        stream_handler.setFormatter(formater) #屏幕流,屏幕操作流
        #如果想让文件流和屏幕流输出的东西的格式不一样,那么就在写一个 格式formater1,这样就可以了
        logger.addHandler(stream_handler)
    return logger
logger = mylogger('logging.log',file=False)
logger.warning('啦啦啦啦')
logger.debug('debug message')

 

  

import os
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
os.curdir  返回当前目录: ('.')
os.pardir  获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2')    可生成多层递归目录
os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove()  删除一个文件
os.rename("oldname","newname")  重命名文件/目录
os.stat('path/filename')  获取文件/目录信息
os.sep    输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep    输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep    输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command")  运行shell命令,直接显示
os.popen("bash command)  运行shell命令,获取执行结果
os.environ  获取系统环境变量


os.path
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的大小

  

 

posted @ 2019-04-08 10:10  呆呆114  阅读(132)  评论(0)    收藏  举报