背景
写python脚本时当代码抛出异常的时候需要终止脚本的运行。
函数介绍及举例
exit()
Constants added by the site module
The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.
exit(code=None)
Objects that when printed, print a message like “Use quit() or Ctrl-D (i.e. EOF) to exit”, and when called, raise SystemExit with the specified exit code.
exit(), 抛出 SystemExit 异常。 一般在交互式 Shell 中退出时使用。
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (
Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>exit
Use exit() or Ctrl-Z plus Return to exit
>>>
sys.exit()
Exit from Python. This is implemented by raising the SystemExit exception, so cleanup actions specified by finally clauses of try statements are honored, and it is possible to intercept the exit attempt at an outer level.
sys.exit(),退出程序引发 SystemExit 异常,一般主程序中使用此退出。
import sys
try:
sys.exit(0)
except:
print('exception')
else:
print('no exception')
exception
import sys
try:
a=1
except:
print('exception')
else:
print('no exception')
no exception
return
return [表达式] 结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None
def add(a,b):
x = a + b
return x
Reference
[1].https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python/
[2].https://docs.python.org/3/library/constants.html#exit
[3].https://docs.python.org/3/library/sys.html?highlight=exit#sys.exit
[4].http://www.runoob.com/python3/python3-function.html