(1)configparse 模块
如何创建如下配置文件
- [DEFAULT]
- ServerAliveInterval = 45
- Compression = yes
- CompressionLevel = 9
- ForwardX11 = yes
- [ http://bitbucket.org/ ]
- User = hg
- [ http://topsecret.server.com/ ]
- Port = 50022
- ForwardX11 = no
- import configparser
- conf = configparser.ConfigParser()
- # 直接创建
- conf['DEFAULT'] = {'ServerAliveInterval': '45',
- 'Compression': 'yes',
- 'CompressionLevel': '9',
- 'ForwardX11': 'yes'
- }
- conf['http://bitbucket.org/'] = {}
- conf['http://bitbucket.org/']['User'] = 'hg'
- conf['http://topsecret.server.com/'] = {}
- topsecret = conf['http://topsecret.server.com/']
- topsecret['Host Port'] = '50022'
- topsecret['ForwardX11'] = 'no'
- conf['DEFAULT']['ForwardX11'] = 'yes'
- with open('conf.ini', 'w') as conf_file:
- conf.write(conf_file)
- #-------------------- 读
- conf.read('conf.ini', encoding='utf8')
- f = conf.sections()
- print(f)
- ['http://bitbucket.org/', 'http://topsecret.server.com/']
- d = conf.options('http://bitbucket.org/')
- print(d)
- print(conf.default_section) #? 发现没有打印? 如何去读出 DEFAULT 呢
- DEFAULT
- print(list(conf['http://topsecret.server.com/'].values()))# 取值和字典类似
- ['50022', 'no', '45', 'yes', '9'] #当自定义 section 和默认 section 时有相同的值时, 这是取出的是自定义的那部分的值
- if 'ServerAliveInterval' in conf['DEFAULT']: #也可以判断摸个值是否存在
- print('yes')
- else:
- print('no')
- ############# 增
- conf.add_section('groups')
- conf['groups'] = {
- 'name': 'alex',
- 'age': '18'
- }
- with open('conf.ini', 'r+', encoding='utf8') as file:
- conf.write(file)
- ########## 改
- conf.set('groups', 'age', '34')
- conf.write(open('conf.ini', 'r+'))
- ########### 删除内容 option 是删除某个系列下的某个值, section 是删除文件下某一部分
- conf.read('conf.ini')
- conf.remove_option('groups', 'name')
- conf.write(open('conf.ini', 'r+'))
- conf.remove_section('groups')
- conf.write(open('conf.ini', 'r+'))
(2)hashlib 模块
- import hashlib
- m = hashlib.md5()
- m.update(b'hello')
- print(m.digest)
- hash = hashlib.sha256()
- hash.update('admin')
- print(hash.hexdigest())
(3)subprocess 模块
可以与操作系统交互
三种执行命令的方法
- subprocess.run() #官方推荐
- subprocess.call()
- subprocess.Popen() #上面各种方法的底层封装
标准写法
>>> subprocess.run(['df','-h'],stderr=subprocess.PIPE,stdout=subprocess.PIPE,check=True)
涉及到管道 | 的命令的写法
- >>> subprocess.run('df -h|grep disk1',shell=True)# 将接将该条命令交给系统去处理
- >>> a=subprocess.call(['ls','-l'])
(4)logging 模块 (参考)
FATAL - 导致程序退出的严重系统级错误, 不可恢复, 当错误发生时, 系统管理员需要立即介入, 谨慎使用.
ERROR - 运行时异常以及预期之外的错误, 也需要立即处理, 但紧急程度低于 FATAL, 当错误发生时, 影响了程序的正确执行. 需要注意的是这两种级别属于服务自己的错误, 需要管理员介入, 用户输入出错不属于此分类.
WARN - 预期之外的运行时状况, 表示系统可能出现问题. 对于那些目前还不是错误, 然而不及时处理也会变成错误的情况, 也可以记为 WARN, 如磁盘过低.
INFO - 有意义的事件信息, 记录程序正常的运行状态, 比如收到请求, 成功执行. 通过查看 INFO, 可以快速定位 WARN,ERROR, FATAL.INFO 不宜过多, 通常情况下不超过 TRACE 的 10%.
DEBUG - 与程序运行时的流程相关的详细信息以及当前变量状态.
TRACE - 更详细的跟踪信息. DEBUG 和 TRACE 这两种规范由项目组自己定义, 通过该种日志, 可以查看某一个操作每一步的执行过程, 可以准确定位是何种操作, 何种参数, 何种顺序导致了某种错误的发生
主要分为四个部分:
Loggers: 提供应用程序直接使用的接口
Handlers: 将 Loggers 产生的日志传到指定位置
Filters: 对输出日志进行过滤
Formatters: 控制输出格式
日志级别
Level | Numeric value | When it’s used |
DEBUG | 10 | Detailed information, typically of interest only when diagnosing problems. |
INFO | 20 | Confirmation that things are working as expected. |
WARNING | 30 | An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
ERROR | 40 | Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL | 50 | A serious error, indicating that the program itself may be unable to continue running. |
- # 打印在控制台上
- import logging
- logging.warning('use error')
- logging.critical('sever is down')
- logging.info('111')
- logging.debug('222')
- logging.error('333')
- # 记录在文件中
- logging.basicConfig(filename='logging_test.log',
- level=logging.INFO,
- format='%(asctime)s :%(levelname)s:%(message)s',
- datefmt='%Y-%m-%d' '%I:%M:%S' '%p'
- )# 文件配置
- logging.warning('lower power action')
- logging.info('use error')
- logging.debug('sever is down')
- # 即可以记录在文件中也可以在控制台中
- # 1. 生成 logger 对象
- # 2. 生成 handler 对象
- # 2.1 把 handler 对象, 绑定到 logger
- # 3. 生成 formatter 对象
- # 3.1 生成的 formatter 对象绑定 handler 对象
- logger = logging.getLogger('MySQL')
- logger.setLevel(logging.DEBUG)# 设置级别
- s = logging.StreamHandler()# 屏幕 handler 对象
- s.setLevel(logging.INFO) #设置屏幕输出级别
- f = logging.FileHandler('web.log') #文件 handler 对象
- f.setLevel(logging.DEBUG)#s 设置文件级别
- logger.addHandler(s)
- logger.addHandler(f)
- s.setFormatter('%(asctime)s :%(levelname)s:%(message)s')
- f.setFormatter('%(asctime)s :%(name)s:%(message)s')
来源: http://www.bubuko.com/infodetail-2661604.html