day29_python

2021/9/19 17:06:27

本文主要是介绍day29_python,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

参考Eva_J的博客,原文连接:https://www.cnblogs.com/Eva-J/p/7277026.html

要导的文件

from re import findall
import logging
import configparser

configparse

用于生成.ini文件

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 configfile:

    config.write(configfile)
# 查找文件
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'下所有键值对

# yes       get方法Section下的key对应的value
print(config.get('bitbucket.org', 'compression'))
# 在配置文件中default是一个关键字, 通过其他节来取值可以取到default下的内容
# 增删改操作
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

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

错误优先级

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

basicconfig配置log文件的输出

缺点:中文乱码问题,不能同时往文件和屏幕上输出

file_handler = logging.FileHandler(
    filename='x1.log', mode='a', encoding='utf-8',)
logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S %p',
    handlers=[file_handler, ],
    level=logging.ERROR
)
# print('(key)s'%{'key': 'value'})  # 一种格式化的方法
logging.error('你好')
# logging.debug('frjfrkgjk')
# logging.info('info message')
# logging.warning('warning message')
# logging.critical('critical message')
try:
    int(input('num>>'))
except ValueError:
    logging.error('输入的值不是一个数字')

知识

'''
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用户输出的消息
'''

配置log对象

# 配置log对象的形式,功能较多
logger = logging.getLogger()
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler('demo.log', encoding='utf-8')  # 可以写中文

# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setLevel(logging.DEBUG)
# 文件操作符和格式关联
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.addHandler(fh)  # logger对象可以添加多个fh和ch对象
logger.addHandler(ch)

logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')
# 程序充分解耦,变得高可定制,zabbix做监控,具有高可定制性
# 有5种级别的日志记录模式
# 两种配置方式, basicconfig ,log对象

去重甜点

ss = 'fvnrnkgfkjghethreughtrfj'
lis = []
for i in ss:
    if i not in lis:
        lis.append(i)
s = '123.33vjgfb3424.34nbvjgb323.324'
ret = findall(r'\d+\.\d|\d+', s)  # ret = '+'.json(ret)
# 精确数字位数
ret = [float(i) for i in ret]   # eval(ret)
print(sum(ret))

课后练习知识补充

'''
练习题
处理文件7th——questions,输出所有'T'开头的行
with open('7th——questions')  as f:
    for i in f:
        if i.startswith('T'):
            print(i)

一个闭包函数需要满足,内部嵌套函数,内部函数用到外部的变量
文件夹存不存在,os.path.isdir
获取文件夹的大小 循环文件夹里面的所有文件,把大小加起来
匹配手机号的正则表达式
1[3456789][\\d][9]
有四个数字,1,2,3,4,能组成多少个互不相同且无重复数字的三位数,各是多少
count = 0
for i in range(1,5):
    for j in range(1,5):
        for k in range(1,5):
            if i ==j or i == k or j == k:
                continue
            count += 1
            print(str(i)+str(j)+str(k))

'''


这篇关于day29_python的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程