python中sys.exit() os._exit() exit() quit()的简单使用

1》sys.exit() 
>>> import sys
>>> help(sys.exit)
Help on built-in function exit in module sys:
exit(...)
    exit([status])
    
    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is an integer, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).

执行该语句会直接退出程序,这也是经常使用的方法,也不需要考虑平台等因素的影响,一般是退出Python程序的首选方法。
退出程序引发SystemExit异常,(这是唯一一个不会被认为是错误的异常), 如果没有捕获这个异常将会直接退出程序执行,
当然也可以捕获这个异常进行一些其他操作(比如清理工作)。
sys.exit()函数是通过抛出异常的方式来终止进程的,也就是说如果它抛出来的异常被捕捉到了的话程序就不会退出了,
而是去进行一些清理工作。
SystemExit 并不派生自Exception 所以用Exception捕捉不到该SystemEixt异常,应该使用SystemExit来捕捉。
该方法中包含一个参数status,默认为0,表示正常退出, 其他都是异常退出。
还可以这样使用:sys.exit("Goodbye!"); 一般主程序中使用此退出.


捕获到SystemExit异常,程序没有直接退出!
song@ubuntu:~$ vi systemExit.py
song@ubuntu:~$ more systemExit.py
#!/usr/bin/python
#!coding:utf-8
import sys
if __name__=='__main__':
    try:
        sys.exit(825)
    except SystemExit,error:
        print 'the information of SystemExit:{0}'.format(error)
        print "the program doesn't exit!"
    print 'Now,the game is over!'
song@ubuntu:~$ python systemExit.py
the information of SystemExit:825
the program doesn't exit!
Now,the game is over!
song@ubuntu:~$ 


没有捕获到SystemExit异常,程序直接退出,后边的代码不执行!
song@ubuntu:~$ vi systemExit.py
song@ubuntu:~$ more systemExit.py
#!/usr/bin/python
#!coding:utf-8
import sys
if __name__=='__main__':
    try:
        sys.exit(825)
    except Exception,error:
        print 'the information of SystemExit:{0}'.format(error)
        print "the program doesn't exit!"
    print 'Now,the game is over!'
song@ubuntu:~$ python systemExit.py
song@ubuntu:~$ 


没有捕获到SystemExit异常,输出'Goodbye!'后,程序直接退出,后边的代码不执行!
song@ubuntu:~$ vi systemExit.py
song@ubuntu:~$ more systemExit.py
#!/usr/bin/python
#!coding:utf-8
import sys
if __name__=='__main__':
    try:
        sys.exit('Goodbye!')
    except Exception,error:
        print 'the information of SystemExit:{0}'.format(error)
        print "the program doesn't exit!"
    print 'Now,the game is over!'
song@ubuntu:~$ python systemExit.py
Goodbye!
song@ubuntu:~$ 

2》os._exit(), 直接退出 Python 解释器, 不抛异常, 不执行相关清理工作,其后的代码都不执行,
其使用会受到平台的限制,但我们常用的Win32平台和基于UNIX的平台不会有所影响, 常用在子进程的退出.
一般来说os._exit() 用于在线程中退出,sys.exit() 用于在主线程中退出。

3》exit()/quit(), 抛出SystemExit异常. 一般在交互式shell中退出时使用.


友情链接:

关于python中format()方法的使用,参考:python format()方法

(完)


  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值