zoukankan      html  css  js  c++  java
  • python异常处理及内置模块

    异常处理

    有时候我们在写程序的时候会出现错误或者异常,导致程序终止,如下这个例子:

    #!/usr/bin/env python
    a = 2/0
    print(a)

    结果提示如下错误:

    Traceback (most recent call last):
      File "002.py", line 2, in <module>
        a = 2/0
    ZeroDivisionError: integer division or modulo by zero

    上面提示被除数不能为0,从而导致程序运行中断,为了能够让程序正常执行,我们可以添加tey...except...语句:

    try:
        a = 2/0
        print(a)
    except Exception as e:
        print("除数不能为0")
        #raise e  # 把异常抛出来
    finally:
        print("无论发生什么情况,都执行此步。")
    
    结果:
    除数不能为0
    无论发生什么情况,都执行此步。

    上面如果加上了raise e,则会把异常信息打印出来:ZeroDivisionError: integer division or modulo by zero。其中except部分是对错误信息进行处理,finally是不管之前有没有异常,都会执行此步骤。

    python标准异常类:

    异常名称描述
    BaseException 所有异常的基类
    SystemExit 解释器请求退出
    KeyboardInterrupt 用户中断执行(通常是输入^C)
    Exception 常规错误的基类
    StopIteration 迭代器没有更多的值
    GeneratorExit 生成器(generator)发生异常来通知退出
    SystemExit Python 解释器请求退出
    StandardError 所有的内建标准异常的基类
    ArithmeticError 所有数值计算错误的基类
    FloatingPointError 浮点计算错误
    OverflowError 数值运算超出最大限制
    ZeroDivisionError 除(或取模)零 (所有数据类型)
    AssertionError 断言语句失败
    AttributeError 对象没有这个属性
    EOFError 没有内建输入,到达EOF 标记
    EnvironmentError 操作系统错误的基类
    IOError 输入/输出操作失败
    OSError 操作系统错误
    WindowsError 系统调用失败
    ImportError 导入模块/对象失败
    KeyboardInterrupt 用户中断执行(通常是输入^C)
    LookupError 无效数据查询的基类
    IndexError 序列中没有没有此索引(index)
    KeyError 映射中没有这个键
    MemoryError 内存溢出错误(对于Python 解释器不是致命的)
    NameError 未声明/初始化对象 (没有属性)
    UnboundLocalError 访问未初始化的本地变量
    ReferenceError 弱引用(Weak reference)试图访问已经垃圾回收了的对象
    RuntimeError 一般的运行时错误
    NotImplementedError 尚未实现的方法
    SyntaxError Python 语法错误
    IndentationError 缩进错误
    TabError Tab 和空格混用
    SystemError 一般的解释器系统错误
    TypeError 对类型无效的操作
    ValueError 传入无效的参数
    UnicodeError Unicode 相关的错误
    UnicodeDecodeError Unicode 解码时的错误
    UnicodeEncodeError Unicode 编码时错误
    UnicodeTranslateError Unicode 转换时错误
    Warning 警告的基类
    DeprecationWarning 关于被弃用的特征的警告
    FutureWarning 关于构造将来语义会有改变的警告
    OverflowWarning 旧的关于自动提升为长整型(long)的警告
    PendingDeprecationWarning 关于特性将会被废弃的警告
    RuntimeWarning 可疑的运行时行为(runtime behavior)的警告
    SyntaxWarning 可疑的语法的警告
    UserWarning 用户代码生成的警告

      

    模块

    模块和目录的区别,看整个文件夹里面是否有__init__.py文件,有就是模块,没有就是普通目录。__init__.py一般是一个空文件。
    通常一个.py文件我们就可以称之为一个模块。
    a.py
    #!/usr/bin/env python
    def hello():
        print("hello")
    hello()
    
    def world():
        print("world")
    world()
    
    b.py
    #!/usr/bin/env python
    import a
    
    运行python b.py结果:
    hello
    world

    如上 ,当我们在b.py中将a.py作为模块导入之后,在运行b.py的时候,直接会运行a.py里面的所有函数,但是如果我们只想要在b.py中调用a.py中指定函数的时候运行,就需要在a.py中加入if __name__ == "__main__":语句:

    a.py
    #!/usr/bin/env python
    def hello():
        print("hello")
        
    def world():
        print("world")
    
    if __name__ == "__main__":
        hello()
        world()
    
    b.py
    #!/usr/bin/env python
    import a
    a.hello()
    a.world()
    
    运行python b.py之后的结果:
    hello
    world
    由上可以看出,加上if __name__ == "__main__":语句之后,就能满足我们的需求。
    总结:
        1、文件夹里面需要有__init__.py文件的才能当做模块使用。
        2、if __name__ == "__main__":语句的使用。
     
    内置模块
     
    datetime
    import datetime
    # 下面我们使用的是datetime模块下面的datetime模块,所以使用的时候需要datetime.datetime,为了更方便的使用,也可以直接使用from datetime import datetime
    print(datetime.datetime.now())          # 打印当前时间  2018-04-23 09:33:32.055974
    print(datetime.datetime.now().year)     # 打印当前时间中的年份 2018
    print(datetime.datetime.now().month)    # 打印当前时间中的月份 4
    print(datetime.datetime.now().day)      # 打印当前时间中的天 23
    print(datetime.datetime.now().hour)     # 打印当前时间中的小时 9
    print(datetime.datetime.now().minute)   # 打印当前时间中的分钟 33
    print(datetime.datetime.now().second)   # 打印当前时间中的秒   32
    print(datetime.datetime.now().microsecond)  # 打印当前时间中的毫秒 56063
    print(datetime.datetime.now().strftime("%Y-%m-%d"))  # 从时间格式转换成字符串,满足"%Y-%m-%d"格式的字符串格式    2018-04-23 09:33:32.055974  -->  2018-04-23
    print(datetime.datetime.now().strftime("%c"))        # 标准时间,类似于这种格式  Mon Apr 23 09:50:45 2018
    print(datetime.datetime.now().strftime("%a"))        # 本地简化星期名称  Mon
    print(datetime.datetime.now().strftime("%b"))        # 本地简化月份名称  Apr
    print(datetime.datetime.now().strftime("%d"))        # 当前这天是一个月中的第几天  23
    # 直接导入datetime模块下面的datetime
    #from datetime import datetime
    #print(datetime.now())
    %Y    带世纪部分的十进制年份
    %m   十进制表示的月份
    %d    十进制表示的每月的第几天
    %H    24小时制的小时
    %M    十进制表示的分钟数
    %S    十进制的秒数
     
    如果我们需要表示昨天、上周等情况:
    #!/usr/bin/env python
    from datetime import datetime
    from datetime import timedelta
    now_time = datetime.now()   # 当前时间
    print(now_time)
    b = now_time + timedelta(days = -1)  # 一天前
    print(b)
    c = now_time + timedelta(days = -1,weeks = -1)  # 一个周前的前一天
    print(c)
    
    结果:
    2018-04-23 10:35:40.245370
    2018-04-22 10:35:40.245370
    2018-04-15 10:35:40.245370
    time模块
    这个time模块不是datetime下面的那个模块,它是一个单独的模块。
    #!/usr/bin/env python
    import time
    time.sleep(2)  # 暂停2秒后,打印
    print("Hello")
    print(time.time()) # 打印时间戳,即从1970-01-01到现在的秒数
    
    
    print(time.localtime())
    # time.struct_time(tm_year=2018, tm_mon=4, tm_mday=23, tm_hour=10, tm_min=47, tm_sec=59, tm_wday=0, tm_yday=113, tm_isdst=0)
    time.strptime(string,[,format])  # 把一个格式化时间字符串转化为struct_time,它和strftime是逆操作。

    commands模块

    有时候我们需要使用shell命令,就用到了commands模块。

    #!/usr/bin/env python
    import commands
    output = commands.getoutput("ls -ll")  # 返回执行完命令后的结果
    print(output)
    status, output = commands.getstatusoutput("ls -l")  # 返回一个元组,如果shell执行成功,第一个值(状态码)是0表示成功,第二个值是shell执行结果
    print(status,output)

    subprocess模块

    和commands模块用法类似,都是用来执行shell命令的。

    #!/usr/bin/env python
    from subprocess import PIPE,Popen
    p = Popen(['ifconfig'],stdout=PIPE)
    data = p.stdout.read()
    print(data)
  • 相关阅读:
    Java.io.outputstream.PrintStream:打印流
    Codeforces 732F. Tourist Reform (Tarjan缩点)
    退役了
    POJ 3281 Dining (最大流)
    Light oj 1233
    Light oj 1125
    HDU 5521 Meeting (最短路)
    Light oj 1095
    Light oj 1044
    HDU 3549 Flow Problem (dinic模版 && isap模版)
  • 原文地址:https://www.cnblogs.com/yangjian319/p/8921526.html
Copyright © 2011-2022 走看看