python sys.exitfunc (回调函数)
来源:互联网 发布:adobe软件破解补丁 编辑:程序博客网 时间:2024/06/02 02:40
通过sys.exitfunc来注册程序退出时的回调函数,我们可以在这个回调函数中做一些资源清理的操作,
song@ubuntu:~$ python exit_handler2.py
hello world
hello world!
exit is done!
但通过它只能注册一个回调,而且还不支持参数(可以带默认参数)。
【1】exit_handler.py文件:
#!usr/bin/env python#coding:utf-8import sysdef exitfunc(): print 'exit is done!'sys.exitfunc=exitfunc #注册回调函数if __name__=='__main__': print 'hello world' #程序运行结束,在退出解释器之前,会自动调用回调函数。。
运行结果:
song@ubuntu:~$ python exit_handler.py
hello world
exit is done!
song@ubuntu:~$
【2】exit_handler1.py文件:
#!usr/bin/env python #coding:utf-8 import sys def exitfunc(): print 'exit is done!' sys.exitfunc=exitfunc #通过sys.exitfunc来注册程序退出时的回调函数 print 'hello world' sys.exit(1)#执行至主程序的末尾时,解释器会自动退出。 我们也可以调用sys.exit函数使程序中途退出解释器! print 'ok'#该语句不执行
运行结果:
song@ubuntu:~$ python exit_handler1.py
hello world
exit is done!
song@ubuntu:~$
【3】exit_handler2.py文件:
#!usr/bin/env pythoni #coding:utf-8 import sys def exitfunc(arg='hello world!'): #可以带默认参数 print arg print 'exit is done!' sys.exitfunc=exitfunc print 'hello world' sys.exit(1) print 'ok'运行结果:
song@ubuntu:~$ python exit_handler2.py
hello world
hello world!
exit is done!
song@ubuntu:~$
【4】exit_handler3.py文件:
#!usr/bin/env python#coding:utf-8import sysdef exitfunc(): print 'exit is done!'sys.exitfunc=exitfuncif __name__=='__main__': import os print '回调函数没有执行!' os._exit(0) #通过os._exit()退出,注册的回调函数将不会被调用
运行结果:
song@ubuntu:~$ python exit_handler3.py
回调函数没有执行!
song@ubuntu:~$
关于回调函数,sys.exitfunc有其自身的缺点,比如,只能注册一个回调函数,不能传递参数。。。为了更加方便的注册回调,我们一般使用atexit模块。。。
关于atexit模块,请参考:点击打开链接
1 0
- python sys.exitfunc (回调函数)
- PYTHON 回调函数
- Python 回调函数
- PYTHON 回调函数
- python--回调函数
- python 回调函数
- python atexit 模块(回调函数)
- python中的回调函数
- python的回调函数
- callback回调函数--python
- python之回调函数
- callback回调函数 python
- python异步回调函数的实现
- python中的回调函数例子
- python回调函数用法实例分析
- python回调函数的使用方法
- python回调函数与eval函数
- python 构建一个回调函数
- Codeforces Problem 710D Two Arithmetic Progressions(中国剩余定理)
- hdu 4474 数位BFS
- android7.0 系统更新日志
- JAVA全集-02-基本语法
- 例子:'0'和'/0','\0'的输出变化
- python sys.exitfunc (回调函数)
- jquery
- GIS算法--已知一点经纬度,方位角,距离求另一点
- MinInStack
- JQuery优化规范
- *【布局优化】android布局原则
- 深入浅出 RPC - 浅出篇
- Centos配置163 yum源方法
- symbol lookup error: undefined symbol