Python全栈(第一期)Day29

今日主要内容:
常用模块的:生成+查找+修改文件
logging

一,今日内容大纲

# 学习态度
# python基础 2个月
# html css js jq  1个月

# 上课困

# 学习方法 :
    # 列出知识点
    # 例子 写了哪些

# 面向对象学了哪些块
    # 为什么要讲面向对象
        # 角色的不清晰,导致了方法的调用混乱
        # 重复的代码
    # 类和对象的定义 语法
    # 对象与对象之间的交互  : 人打狗 狗掉血
    # 面向对象的命名空间
    # 组合

    # 面向对象的三大特性
        # 继承  单继承 父类 子类
               #多继承 经典类和新式类的区别 抽象类和接口类(规范)
        # 多态(其他语言中的,python天生支持) 鸭子类型(list和tuple)
        # 封装 私有的 __变量
        # @property
        # @classmethod
        # @staticmethod

    # 面向对象的进阶
        # issubclass isinstance
        # 反射 hasattr getattr
        # 内置的方法:
            # 内置方法和内置函数和内置的数据类型以及内置的模块都有着千丝万缕的联系
            # __new__ 创建self 构造方法
            # __call__ 对象()

# 写代码 两种思路
# 面向过程
# 面向函数
# 面向对象

二,常用模块

1,生成配置文件

# configparse:生成配置文件
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                      'Compression': 'yes',
                     'CompressionLevel': '9',
                     'ForwardX11': 'yes'
                     }

config['bitbucket.org'] = {'User':'hg'}

config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}

with open('example.ini', 'w') as f:
   config.write(f)

输出结果:
在这里插入图片描述

2,查找配置文件

# 查找文件
import configparser

config = configparser.ConfigParser()
#---------------------------查找文件内容,基于字典的形式
# print(config.sections())        #  [] 获取所有的组
# 但是不给文件直接读的话,什么也读不到
config.read('example.ini')
print(config.sections())           # ['bitbucket.org', 'topsecret.server.com']

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

输出结果:
[‘bitbucket.org’, ‘topsecret.server.com’]
False
True
hg
yes
no
<Section: bitbucket.org>
user
serveraliveinterval
compression
compressionlevel
forwardx11
[‘user’, ‘serveraliveinterval’, ‘compression’, ‘compressionlevel’, ‘forwardx11’]
[(‘serveraliveinterval’, ‘45’), (‘compression’, ‘yes’), (‘compressionlevel’, ‘9’), (‘forwardx11’, ‘yes’), (‘user’, ‘hg’)]
yes

3,修改配置文件

# 修改:
import configparser
config = configparser.ConfigParser()
config.read('example.ini')   # 读文件
config.add_section('yuan')   # 增加section
config.remove_section('bitbucket.org')   # 删除一个section
config.remove_option('topsecret.server.com', "forwardx11")  # 删除一个配置项
config.set('topsecret.server.com', 'k1', '11111')
config.set('yuan', 'k2', '22222')
f = open('new2.ini', "w")
config.write(f)   #写进文件
f.close()

输出结果:

在这里插入图片描述

三,logging

1,基本知识点

# login   登录
# log     日志
# logging 日志模块

# 什么叫日志?
# 日志 用来记录用户行为 或者 代码的执行过程

# logging
# 我能够“一键”控制
    # 排错的时候需要打印很多细节来帮助我排错
    # 严重的错误记录下来
    # 有一些用户行为 有没有错都要记录下来


# 补充:一种更厉害的格式化方法:
print('%(key)s' % {'key': 'value'})

输出结果:
value

2,例子一

import logging
logging.basicConfig(level=logging.WARNING,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S',
                    # filename='test.log', # 可以选择输出到屏幕上 or 写到文件里。
                    # filemode='a'
                    )
try:
    int(input('num >>'))
except ValueError:
    logging.error('输入的值不是一个数字')


logging.debug('debug message')          # 低级别的 # 排错信息
logging.info('info message')            # 正常信息
logging.warning('warning message')      # 警告信息
logging.error('error message')          # 错误信息
logging.critical('critical message')    # 高级别的 # 严重错误信息





# 两种配置logging的方法:
# basicconfig 简单 能做的事情相对少,存在以下两个问题:
    # 中文的乱码问题
    # 不能同时往文件和屏幕上输出

# 配置log对象 稍微有点复杂 能做的事情相对多

输出结果:
num >>+
Mon, 21 Jan 2019 17:13:39 3.logging.py[line:41] ERROR 输入的值不是一个数字
Mon, 21 Jan 2019 17:13:39 3.logging.py[line:46] WARNING warning message
Mon, 21 Jan 2019 17:13:39 3.logging.py[line:47] ERROR error message
Mon, 21 Jan 2019 17:13:39 3.logging.py[line:48] CRITICAL critical message

3,例子二

import logging


# 创建一个logger对象
logger = logging.getLogger()

# 创建一个handler,用于写入日志文件。
fh = logging.FileHandler('log.log', encoding='utf-8')


# 再创建一个handler,用于输出到控制台
sh = logging.StreamHandler()    # 创建一个屏幕控制对象
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter2 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s [line:%(lineno)d] : %(message)s')
# 文件操作符 和 格式关联
fh.setFormatter(formatter)
sh.setFormatter(formatter2)
# logger 对象 和 文件操作符 关联
logger.addHandler(fh)
logger.addHandler(sh)

# 五种级别
logging.debug('debug message')          # 低级别的---> 排错信息
logging.info('info message')            # 正常信息
logging.warning('警告错误')             # 警告信息
logging.error('error message')          # 错误信息
logging.critical('critical message')    # 高级别的---> 严重错误信息

输出结果:
2019-01-21 17:14:24,957 - root - WARNING [line:99] : 警告错误
2019-01-21 17:14:24,957 - root - ERROR [line:100] : error message
2019-01-21 17:14:24,957 - root - CRITICAL [line:101] : critical message

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_42615032/article/details/86579099
今日推荐