python sys.exitfunc (回调函数)

来源:互联网 发布:adobe软件破解补丁 编辑:程序博客网 时间:2024/06/02 02:40
通过sys.exitfunc来注册程序退出时的回调函数,我们可以在这个回调函数中做一些资源清理的操作,

但通过它只能注册一个回调,而且还不支持参数(可以带默认参数)。

【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
原创粉丝点击