exception handling
Sometimes when we write a program, an error or exception occurs, causing the program to terminate, as in the following example:
#!/usr/bin/env python a = 2/0 print(a)
The result shows the following error:
Traceback (most recent call last): File "002.py", line 2, in <module> a = 2/0 ZeroDivisionError: integer division or modulo by zero
The above prompts that the dividend cannot be 0, which will cause the program to run interrupted. In order to allow the program to execute normally, we can add a tey...except... statement:
try: a = 2/ 0 print (a) except Exception as e: print ( "The divisor cannot be 0 " ) # raise e # Raise the exception finally : print ( " No matter what happens, this step is executed. " ) result: Divisor cannot be 0 Do this step no matter what happens.
If raise e is added above, the exception information will be printed: ZeroDivisionError: integer division or modulo by zero. The except part is to process the error information, and finally this step will be executed regardless of whether there is an exception before.
Python standard exception class:
exception name | describe |
---|---|
BaseException | Base class for all exceptions |
SystemExit | interpreter request to exit |
KeyboardInterrupt | User interrupts execution (usually by typing ^C) |
Exception | base class for general errors |
StopIteration | iterator has no more values |
GeneratorExit | Generator (generator) exception to notify exit |
SystemExit | Python interpreter request to quit |
StandardError | Base class for all built-in standard exceptions |
ArithmeticError | Base class for all numerical computation errors |
FloatingPointError | floating point calculation error |
OverflowError | Numerical operation exceeds maximum limit |
ZeroDivisionError | divide (or modulo) zero (all data types) |
AssertionError | Assertion statement failed |
AttributeError | Object does not have this property |
EOFError | No built-in input, reaching the EOF marker |
EnvironmentError | Base class for operating system errors |
IOError | I/O operation failed |
OSError | operating system error |
WindowsError | system call failed |
ImportError | Failed to import module/object |
KeyboardInterrupt | User interrupts execution (usually by typing ^C) |
LookupError | Base class for invalid data queries |
IndexError | There is no such index in the sequence (index) |
KeyError | There is no such key in the map |
MemoryError | Out of memory error (not fatal to the Python interpreter) |
NameError | undeclared/initialized object (no properties) |
UnboundLocalError | access uninitialized local variable |
ReferenceError | Weak reference attempts to access objects that have been garbage collected |
RuntimeError | General runtime errors |
NotImplementedError | Method not yet implemented |
SyntaxError | Python syntax error |
IndentationError | Indentation error |
TabError | Mixing Tabs and Spaces |
SystemError | General interpreter system errors |
TypeError | Invalid operation on type |
ValueError | Invalid parameter passed in |
UnicodeError | Unicode related errors |
UnicodeDecodeError | Error in Unicode decoding |
UnicodeEncodeError | Error in Unicode encoding |
UnicodeTranslateError | Error during Unicode conversion |
Warning | base class for warnings |
DeprecationWarning | Warning about deprecated features |
FutureWarning | Warning about future semantic changes of constructs |
OverflowWarning | Old warning about auto-promotion to long |
PendingDeprecationWarning | Warning that features will be deprecated |
RuntimeWarning | 可疑的运行时行为(runtime behavior)的警告 |
SyntaxWarning | 可疑的语法的警告 |
UserWarning | 用户代码生成的警告 |
模块
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
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())
#!/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
#!/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)