day22-Python运维开发基础(正则函数 / 异常处理)
1. 正则函数
# ### 正则表达式 => 正则函数 import re # search 通过正则匹配出第一个对象返回,通过group取出对象中的值 strvar = "5*7 9/8" obj = re.search("(\d+)[*/]\d+",strvar) print(obj) # group 获取匹配的内容 res = obj.group() print(res) res = obj.groups() print(res) # match 验证用户输入内容 """search在正则表达式的前面加上^ 就与math函数一模一样""" strvar = "17166668888" strvar = "y17166668888" obj = re.search("^\d+",strvar) # print(obj.group()) print(obj) obj = re.match("\d+",strvar) # print(obj.group()) print(obj) # split 切割 strvar = "alex|wusir|xboyww-xgirlww" lst = strvar.replace("-","|").split("|") print(lst) # - 具有特殊的含义,使用时需要转义 strvar = "alex|wusir-xboyww&xgirlww" res = re.split(r"[|\-&]",strvar) print(res) strvar = "alex2342wusir23423423242xboyww2222222xgirlww" res = re.split("\d+",strvar) print(res) # split(正则表达式,字符串,[选择分割的次数,可选]) 返回列表 res = re.split("\d+",strvar,1) print(res) # sub 替换 返回的结果是一个字符串 strvar = "alex|wusir-xboyww&xgirlww" res = re.sub(r"[|&-]","%",strvar) print(res) # sub(正则表达式,要替换的字符串,原字符串,[选择替换的次数,可选]) 返回字符串 res = re.sub(r"[|&-]","%",strvar,1) print(res) # subn 替换 用法上与sub一样,但是返回的结果是元组,(替换后的结果,替换的次数) strvar = "alex|wusir-xboyww&xgirlww" res = re.subn(r"[|&-]","%",strvar,1) print(res) # finditer 匹配字符串中相应内容,返回迭代器 """findall 与 finditer用法一样,区别在于 findall返回的是列表,finditer返回迭代器""" from collections import Iterator,Iterable strvar = "sdfsd&^*12招待费34sdf" it = re.finditer("\d",strvar) # 判断是否是迭代器 res = isinstance(it,Iterator) print(res) for i in it: # print(i) #<_sre.SRE_Match object; span=(8, 9), match='1'> res = i.group() print(res) # compile 指定一个统一的匹配规则 """ 正常情况下,需要先编译好正则表达式,再去执行匹配 如果频繁的反复使用,浪费时间和空间 所以使用compile 用来编译一次,终身受益,不用对同一个正则反复编译啦 """ strvar = "sdfsd&^*12招待费34sdf" pattern = re.compile("\d") print(pattern) res = pattern.findall(strvar) print(res) # 修饰符 # re.I 使匹配对大小写不敏感 strvar = "<h1>这是一个大标题</H1>" pattern = re.compile("<h1>(.*?)</h1>",flags=re.I) obj = pattern.search(strvar) print(obj) print(obj.group()) print(obj.groups()) # re.M 使每一行都能够单独匹配(多行匹配),影响 ^ 和 $ strvar = """<a>sdfsdfsd</a> <p>234234234</p> <div>^&^&&%</div> """ pattern = re.compile("^<.*?>(.*?)<.*?>$",flags=re.M) obj = pattern.search(strvar) print(obj.group()) print(obj.groups()) lst = pattern.findall(strvar) print(lst) # re.S 使 . 匹配包括换行在内的所有字符 strvar = """ give 123mefive """ pattern = re.compile(".*?mefive",flags=re.S) obj = pattern.search(strvar) print(obj) """ # 不加修饰符,加上修饰,两个结果的差别; 123mefiiv \ngive\n123mefive """ # 使用多个修饰符的写法 (拓展) strvar = """<a>sdfsdfsd</a> <p>234234234</p> <div>^&^&&%</P> """ pattern = re.compile("^<.*?>(.*?)</p>$",flags=re.I|re.S) obj = pattern.search(strvar) print(obj.group()) print(obj.groups())
2. module(与类相关的魔术属性 / 反射 / sys.modules)
# ### (1)与类相关的魔术属性 class Man(): pass class Woman(): pass class Children(Man,Woman): """ 成员属性:eye skin 成员方法:eat cry 私有sleep """ eye = "天蓝色" skin = "天蓝色" def eat(self): print("小孩下来就会吃奶奶") def cry(self,func): print("小孩哭起来,地动山摇,天崩地裂,海枯石烂") print(func.__name__,type(func.__name__)) # 可以获取函数名或者类名 def __sleep(): print("小孩睡觉的时候,不喜欢别人干扰它") obj = Children() # __dict__ 获取对象或类的内部成员结构 # 对象 res = obj.__dict__ print(res) # 类 res = Children.__dict__ print(res) # __doc__ 获取对象或类的内部文档 print(Children.__doc__) # __name__ 获取类名函数名 def abc(): print("abc") obj.cry(abc) # __class__ 获取当前对象所属的类 res = obj.__class__ print(res) # __bases__ 获取一个类直接继承的所有父类,返回元组 print(Children.__bases__) # ### (2) 反射 # 通过字符串去操对象 或者 模块中的属性方法 # (1)类中的反射 # 1.hasattr() 检测对象/类是否有指定的成员 # 对象 res = hasattr(obj,"eye") print(res) res = hasattr(obj,"eat") print(res) # 类 res = hasattr(Children,"skin") print(res) # 2.getattr() 获取对象/类成员的值 # 对象 res = getattr(obj,"eye") print(res) # 通过对象把方法反射出来,是绑定方法 func = getattr(obj,"eat") print(func) func() # 通过类把方法反射出来,是普通方法 func = getattr(Children,"eat") print(func) func(1) # 可以为getattr设置默认值,如果找不到该成员,在第三个参数上可以设置相应的返回值 res = getattr(Children,"abc","对不起,没有该成员") print(res) # 小应用 """ strvar = input("请输入你要操作的成员:") if hasattr(obj,strvar): func = getattr(obj,strvar) func() else: print("对不起,没有该成员") """ # 3.setattr() 设置对象/类成员的值 # 对象 setattr(obj,"hair","天蓝色的") print(obj.hair) # 类 setattr(Children,"age",lambda : print("小孩下生后,是一个肉球")) Children.age() # 4.delattr() 删除对象/类成员的值 # 对象 delattr(obj,"hair") # print(obj.hair) # 类 delattr(Children,"age") # Children.age() # (2)模块的反射 import sys # sys.modules 返回一个系统字典,字典的键是加载的所有模块 print(sys.modules) """ __main__ {'builtins': <module 'builtins' (built-in)>, 'sys': <module 'sys' (built-in)>, '_frozen_importlib': <module '_frozen_importlib' (frozen)>, '_imp': <module '_imp' (built-in)>, '_warnings': <module '_warnings' (built-in)>, '_thread': <module '_thread' (built-in)>, '_weakref': <module '_weakref' (built-in)>, '_frozen_importlib_external': <module '_frozen_importlib_external' (frozen)>, '_io': <module 'io' (built-in)>, 'marshal': <module 'marshal' (built-in)>, 'posix': <module 'posix' (built-in)>, 'zipimport': <module 'zipimport' (built-in)>, 'encodings': <module 'encodings' from '/usr/lib/python3.6/encodings/__init__.py'>, 'codecs': <module 'codecs' from '/usr/lib/python3.6/codecs.py'>, '_codecs': <module '_codecs' (built-in)>, 'encodings.aliases': <module 'encodings.aliases' from '/usr/lib/python3.6/encodings/aliases.py'>, 'encodings.utf_8': <module 'encodings.utf_8' from '/usr/lib/python3.6/encodings/utf_8.py'>, '_signal': <module '_signal' (built-in)>, '__main__': <module '__main__' from '/mnt/hgfs/gongxiang8/day22/2.module.py'>, 'encodings.latin_1': <module 'encodings.latin_1' from '/usr/lib/python3.6/encodings/latin_1.py'>, 'io': <module 'io' from '/usr/lib/python3.6/io.py'>, 'abc': <module 'abc' from '/usr/lib/python3.6/abc.py'>, '_weakrefset': <module '_weakrefset' from '/usr/lib/python3.6/_weakrefset.py'>, 'site': <module 'site' from '/usr/lib/python3.6/site.py'>, 'os': <module 'os' from '/usr/lib/python3.6/os.py'>, 'errno': <module 'errno' (built-in)>, 'stat': <module 'stat' from '/usr/lib/python3.6/stat.py'>, '_stat': <module '_stat' (built-in)>, 'posixpath': <module 'posixpath' from '/usr/lib/python3.6/posixpath.py'>, 'genericpath': <module 'genericpath' from '/usr/lib/python3.6/genericpath.py'>, 'os.path': <module 'posixpath' from '/usr/lib/python3.6/posixpath.py'>, '_collections_abc': <module '_collections_abc' from '/usr/lib/python3.6/_collections_abc.py'>, '_sitebuiltins': <module '_sitebuiltins' from '/usr/lib/python3.6/_sitebuiltins.py'>, '_bootlocale': <module '_bootlocale' from '/usr/lib/python3.6/_bootlocale.py'>, '_locale': <module '_locale' (built-in)>, 'sysconfig': <module 'sysconfig' from '/usr/lib/python3.6/sysconfig.py'>, '_sysconfigdata_m_linux_x86_64-linux-gnu': <module '_sysconfigdata_m_linux_x86_64-linux-gnu' from '/usr/lib/python3.6/_sysconfigdata_m_linux_x86_64-linux-gnu.py'>, 'sitecustomize': <module 'sitecustomize' from '/usr/lib/python3.6/sitecustomize.py'>, 'encodings.cp437': <module 'encodings.cp437' from '/usr/lib/python3.6/encodings/cp437.py'>} """ mymodule = sys.modules["__main__"] print(mymodule) def func1(): print(1) def func2(): print(2) def func3(): print(3) def func4(): print(4) # 通过字符串操作模块中的成员 while True: func = input("请用户输入您要操作的函数") if hasattr(mymodule,func): # 反射真实的函数 fuc = getattr(mymodule,func) fuc() else: print("这个函数不存在")
3. 异常处理
# ### 了解异常处理 # IndexError 索引超出序列的范围 # lst = [1,2,3] # print(lst[100]) # KeyError 字典中查找一个不存在的关键字 # dic = {"a":1} # print(dic["b"]) # NameError 尝试访问一个不存在的变量 # wangwen = 10 # print(wangwen) # IndentationError 缩进错误 """ if 5 == 5: print(1) print(2) """ # AttributeError 尝试访问未知的对象属性 class MyClass(): a = 5 obj = MyClass() # obj.b # StopIteration 迭代器没有更多的值 """ it = iter(range(3)) res = next(it) res = next(it) res = next(it) res = next(it) print(res) """ # AssertionError 断言语句(assert)失败 # assert 5>3 # assert 猜一猜 5<2是不是正确的,如果错误,直接抛出异常 assert 5<2
# ### 异常处理 """ try: code1 except: code2 把可能存在问题的代码放到try这个代码块之后, 如果出现异常直接执行except这个代码块里面内容 如果没有异常,就不走except; """ # 1.基本语法 try: lst = [1,2,3] print(lst[100]) except: pass # 2.带有分支的异常处理 try: # lst = [1,2,3] # print(lst[100]) # dic = {"a":1} # print(dic["b"]) print(wangwen) except IndexError: print("我是IndexError错误类") except KeyError: print("我是KeyError错误类") except: print("有异常错误") # 3.解决StopIteration错误异常,并且获取返回值 def gen(): yield 1 yield 2 return 334343 # 初始化生成器 => 返回生成器对象 => 简称生成器 """StopIteration as e 是给StopIteration这个类实例化出来的对象起别名叫e""" try: mygen = gen() res = next(mygen) res = next(mygen) res = next(mygen) except StopIteration as e: """ 对象可以直接打印,会自动触发__str__魔术方法, 在系统内部自动接收return的返回值 在打印对象时候,自动打印返回值 """ print(e) print("我是StopIteration错误") # 4.关于异常处理的扩展写法 # try ... finally 如果再报错时,也必须要执行,就使用finally """ try: print(wangwen) finally: print(1) print(2) print(3) """ # try ... except ... else # 如果不报错就走else分支,报错了就不执行else """ try: # print(lisi) print(1234) except: pass else: print(1) print(2) """ # finally 和 else 不能够同时存在 """ try: print(wangwen) except: pass finally: print(5) else: print(6) """ # for/while ... else ... (了解) """ 如果循环异常终止(break,或者在函数中通过return终止的),不走else分支 """ for i in range(10): # if i == 5: # break pass else: print(111222)
# ### 主动抛出异常 raise """ 所有异常类的父类(基类,超类) BaseException 所有普通异常类的父类(基类,超类) Exception raise + 异常类/异常类的对象 """ # (1) 基本用法 try: raise BaseException except BaseException: pass # 简写 """raise 后面如果什么也不写 , 默认抛出的是BaseException""" try: raise except : pass # (2) 自定义异常类 # 只能在异常的情况下,才能获取到相应的数据 def return_errorinfo(n): import sys f = sys.exc_info()[2].tb_frame.f_back if n==1: return str(f.f_lineno) #返回当前行数 elif n == 2: return f.f_code.co_filename #返回文件名 # 自定义异常类:(必须继承BaseException异常类父类) class MyException(BaseException): def __init__(self,num,msg,file,fileline): # 错误号码 self.num = num # 错误消息 self.msg = msg # 错误文件 self.file = file # 错误行号 self.fileline = fileline # get_info 通过抛出异常触发return_errorinfo函数,从而获取异常的行号和文件 def get_info(n): try: raise except: return return_errorinfo(n) # 实际使用 sex = "中性" try: if sex == "中性": # 主动抛出异常 (对象) raise MyException(200,"人类没有中性的",get_info(2),get_info(1)) except MyException as e: print("错误的号码是{}".format(e.num)) print("错误的原因是{}".format(e.msg)) print("错误的文件是{}".format(e.file)) print("错误的行号是{}".format(e.fileline))
day22