python-hashlib模块configparser模块logging模块

主要内容:

1.hashlib模块

2.configparser模块

3.logging模块

 

1.hashlib

主要有两个算法,一个是md5,一个是sh1算法.

md5和sh1算法都是单向不可逆的.

具体使用说明如下:

字符串调用:

import hashlib
s = "123"
ob1 = hashlib.md5()
ob1.update(s.encode("utf-8"))
print(ob1.hexdigest())

如果想"加盐"的话,示例如下:

import hashlib
s = "123"
ob1 = hashlib.md5("wo".encode("utf-8"))
ob1.update(s.encode("utf-8"))
print(ob1.hexdigest())

如果是文件的话,操作示例如下:

#版本1,自写
# import hashlib
# def file_md5(file_name):
#     with open(file_name,mode="rb") as f :
#         content = f.read()
#         return content
#
# ret = file_md5("1.txt")
#
# md5 = hashlib.md5()
# md5.update(ret)
# print(md5.hexdigest())


#版本2,参考其他人

import hashlib
def file_md5(file_name):
    with open(file_name,mode="rb") as f :
        content = f.read()
        md5 = hashlib.md5()
        md5.update(content)
        return md5.hexdigest()
p = file_md5("1.txt")
print(p)

如果大文件的话,会撑爆内存的.大文件参考如下:

import hashlib
def bigfile(file_name):
    md5 = hashlib.md5()
    with open(file_name,mode="rb") as f :
        while True:
            content = f.read(1024)
            if content:
                md5.update(content)
            else:
                break
        return md5.hexdigest()
print(bigfile("1.txt"))

 hashlib.sh1的用法和md5用法一致.

 

 

2.logging 模块:

日志模块.

主要有五种状态

logging.debug("debug message")  #调试信息

logging.info("info message")  #正常信息

logging.warning("warnging message")  # 警告信息

logging.error("error message')  # 错误信息

logging.critical("critical message") # 严重错误信息

 

使用示例:

import logging
try:
    s = input(">>>>>")
    p = int(s)
    print(p)
except ValueError:
    logging.error("%s 错误信息是"% ValueError )

 

 

默认是只有警告级别以上的信息,如果想显示debug或者info的信息,可以通过以下的方法

import logging
logging.basicConfig(level=logging.DEBUG)
try:
    s = input(">>>>>")
    p = int(s)
    print(p)
except ValueError:
    logging.debug("debug message")  # 调试信息
    logging.info("info message")  # 正常信息
    logging.warning("warnging message")  # 警告信
    logging.error("error message")  # 错误信息
    logging.critical("critical message")  # 严重错误信息

如果想要格式化输出,需要参考如下:

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s (line:%(lineno)d) %(levelname)s %(message)s')
try:
    s = input(">>>>>")
    p = int(s)
    print(p)
except ValueError:
    logging.debug("debug message")  # 调试信息
    logging.info("info message")  # 正常信息
    logging.warning("warnging message")  # 警告信
    logging.error("error message")  # 错误信息
    logging.critical("critical message")  # 严重错误信息


"""
下面是运行结果
2018-07-09 11:44:44,773 测试.py (line:50) DEBUG debug message
2018-07-09 11:44:44,774 测试.py (line:51) INFO info message
2018-07-09 11:44:44,774 测试.py (line:52) WARNING warnging message
2018-07-09 11:44:44,774 测试.py (line:53) ERROR error message
2018-07-09 11:44:44,774 测试.py (line:54) CRITICAL critical message
"""

如果要写入文件,可以这样.

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s (line:%(lineno)d) %(levelname)s %(message)s',filename="log.log")
try:
    s = input(">>>>>")
    p = int(s)
    print(p)
except ValueError:
    logging.debug("debug message")  # 调试信息
    logging.info("info message")  # 正常信息
    logging.warning("warnging message")  # 警告信
    logging.error("error message")  # 错误信息
    logging.critical("critical message")  # 严重错误信息


"""
这个默认会写入文件,而且不显示错误信息.
生成的文件内容如下:
2018-07-09 11:46:14,602 ²âÊÔ.py (line:50) DEBUG debug message
2018-07-09 11:46:14,603 ²âÊÔ.py (line:51) INFO info message
2018-07-09 11:46:14,603 ²âÊÔ.py (line:52) WARNING warnging message
2018-07-09 11:46:14,603 ²âÊÔ.py (line:53) ERROR error message
2018-07-09 11:46:14,604 ²âÊÔ.py (line:54) CRITICAL critical message
2018-07-09 11:46:49,752 ²âÊÔ.py (line:50) DEBUG debug message
2018-07-09 11:46:49,753 ²âÊÔ.py (line:51) INFO info message
2018-07-09 11:46:49,753 ²âÊÔ.py (line:52) WARNING warnging message
2018-07-09 11:46:49,753 ²âÊÔ.py (line:53) ERROR error message
2018-07-09 11:46:49,753 ²âÊÔ.py (line:54) CRITICAL critical message
"""

 

如果想要直接覆盖的话,可以用filemode = "w"

import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s (line:%(lineno)d) %(levelname)s %(message)s',filename="log.log",filemode= "w")
try:
    s = input(">>>>>")
    p = int(s)
    print(p)
except ValueError:
    logging.debug("debug message")  # 调试信息
    logging.info("info message")  # 正常信息
    logging.warning("warnging message")  # 警告信
    logging.error("error message")  # 错误信息
    logging.critical("critical message")  # 严重错误信息

 

 

3.configparser模块

configparser 帮助你操作(创建,增,删,改,查)一个配置文件

 

创建一个配置文件

示例:

import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {
                    'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11':'yes'
}

config["MYSQL"] ={"ip addr ":"192.168.1.1"}
with open("config.py","w") as configfile:
    config.write(configfile)

"""
运行结果如下:
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[MYSQL]
ip addr  = 192.168.1.1
"""

 

查找文件内容,基于字典的形式

import configparser
config = configparser.ConfigParser()
config.read("config.py")
print(config.sections())  # # #为什么没有 DEFAULT,它是特殊的,可以看做成一个全局的.
print(config['DEFAULT']['Compression'])  #对配置文件中的节对应的项 取值
print(config["MYSQL"])  # #<Section: MYSQL> 可迭代对象
for i in config["MYSQL"]:  # 这样会把默认default的对象给迭代出来的
    print(i)

print(config.options('MYSQL'))  # 同for循环,找到'bitbucket.org'下所有键

print(config.items('MYSQL'))    #找到'bitbucket.org'下所有键值对

print(config.get('MYSQL',"ip addr")) #       get方法Section下的key对应的value

 

 

增删改:

# 增删改
# import configparser
#
# config = configparser.ConfigParser()
# # config.read('new2.ini')
# # config.add_section('日天')
# 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"))

 

posted @ 2018-07-09 11:10  auxiaoliu  阅读(148)  评论(0编辑  收藏  举报