zcfx

1、try except

num = input(\'num : \')
#try在阶段中处理异常
try:
    f = open(\'file\', \'w\')
    int(num)
except ValueError:                      #发现这个异常不会报错只会输出后面的代码
    print(\'请输入一个数字\')

\'\'\'
输出结果:
num : ss
请输入一个数字
\'\'\'

2、万能异常

num = input(\'num : \')
#
try:
    f = open(\'file\', \'w\')
    int(num)
except :                   #万能异常    
    print(\'异常啦\')
\'\'\'
输出结果:

num : ss
异常啦

\'\'\'
#这样抛异常非常不礼貌因为你无法分析是哪里出问题了









num = input(\'num : \')
#
try:
    f = open(\'file\', \'w\')
    int(num)
except Exception as e:                   #万能异常   #这样抛异常更加好能让人分析是什么问题
    print(e,\'异常啦\')

\'\'\'
输出结果:
num : ss
invalid literal for int() with base 10: \'ss\' 异常啦

\'\'\'



num = input(\'num : \')
#当在这一块代码块这里可能出现的问题千奇百怪,去解决你想不到的具体的错误的时候
try: f = open(\'file\', \'w\') int(num) except ValueError: print(\'请输入一个数字\') except Exception as e: #万能异常
# 
 print(\'异常啦\') \'\'\' 输出结果: num : ss 请输入一个数字 \'\'\' 组合异常 

3、else

num = input(\'num : \')
#
try:
    f = open(\'file\', \'w\')
    int(num)
except ValueError:
    print(\'请输入一个数字\')
except Exception as e:                   #万能异常
    print(\'异常啦\')
else:
    print(\'else 被执行\')                     #当前面代码没有出现异常时会执行者这个
\'\'\'
输出结果:
num : 1
else 被执行
\'\'\'

4、finally

num = input(\'num : \')
#
try:
    f = open(\'file\', \'w\')
    int(num)
except ValueError:
    print(\'请输入一个数字\')
except Exception as e:                   #万能异常
    print(\'异常啦\')
else:
    print(\'else 被执行\')
finally:                                          #当遇见必须要执行的代码就用finally
    print(\'finally\')
\'\'\'
num : s
请输入一个数字
finally
\'\'\'

5、断言

assert 2==1   断言一个会抛出异常的判断

6、总结

# # strat.py
# def main():pass

# try:
#     pass
# except ValueError:
#     pass
# except Exception as e:
#     print(\'统筹处理所有错误的措施\')
# else:
#     print("针对这段try中的代码没有异常要特别处理的")
# finally:
#     print("不管有没有异常都要执行的代码")
#
#
# assert 1 == 2  #认识

#什么时候用异常处理:你能想到有异常,并且可能出现在这一块代码的异常有很多种,不能一一枚举
#禁止在大段代码外面套异常处理

 

补充模块

1、hashlib

# 文件校验
    # 文件是否被改变
# 登录密码
    #不能解密,但可以“撞库”
    #加盐 hashlib.md5(\'nezha\'.encode(\'utf-8\'))

# user = \'alex\'
# pwd = \'3713\'
# md5_obj = hashlib.md5(user.encode(\'utf-8\'))
# md5_obj.update(pwd.encode(\'utf-8\'))
# print(md5_obj.hexdigest())              #加密


\'\'\'
输出结果:
06516a702c45b79e2e31aaf047d3863b
\'\'\'
user=\'alex\'
pwd=\'3713\'
md5_obj =hashlib.md5(user.encode(\'utf-8\'))
md5_obj.update(\'123\'.encode(\'utf-8\'))
s=md5_obj.hexdigest()             #进行密码加密
                    

name=input(\'请输入用户名:\')
password=input(\'请输入密码: \')
md5_obj =hashlib.md5(name.encode(\'utf-8\'))         #当用户输入用户名和密码在加密一次然后进行判断
md5_obj.update(password.encode(\'utf-8\'))
ss=md5_obj.hexdigest()
if ss ==s :
    print(\'登陆成功 \')
else:
    print("登陆失败")
用法

2、import configparser

生成配置文件

增删改操作

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 configfile:    #然后把生成的内容保存到文件中

   config.write(configfile)
生成配置文件
import configparser

config = configparser.ConfigParser()
s=config.read(\'example.ini\')
print(config[\'DEFAULT\'][\'Compression\'])

\'\'\'
输出结果:
yes
\'\'\'
import configparser
config = configparser.ConfigParser()
s=config.read(\'example.ini\')
#
config.add_section(\'yuan\')                         #添加了组yuan
with open(\'example.ini\', \'w\') as configfile:
   config.write(configfile)



#example.ini 文件内容
[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[topsecret.server.com]
host port = 50022

[yuan]                   #可以看到已经添加了

 3、loggin模块

import logging
def my_logger(filename,file=True,stream = True):
    logger = logging.getLogger()
    formatter = 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(filename,encoding=\'utf-8\')
        file_handler.setFormatter(formatter)  # 文件流 文件操作符
        logger.addHandler(file_handler)
    if stream:
        stream_handler = logging.StreamHandler()
        stream_handler.setFormatter(formatter) #屏幕流 屏幕操作符
        logger.addHandler(stream_handler)
    return logger

logger = my_logger(\'logging\')
logger.warning("出错了")
logger.debug("debug")
import logging  
logging.debug(\'debug message\')  
logging.info(\'info message\')  
logging.warning(\'warning message\')  
logging.error(\'error message\')  
logging.critical(\'critical message\') 

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

灵活配置日志级别,日志格式,输出位置:

配置参数

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

 

分类:

技术点:

相关文章: