Python中exit、return、sys.exit()等使用实例和区别


Posted in Python onMay 28, 2015

有这样一道题目:  字符串标识符.修改例 6-1 的 idcheck.py 脚本,使之可以检测长度为一的标识符,并且可以识别 Python 关键字,对后一个要求,你可以使用 keyword 模块(特别是 keyword.kelist)来帮你.

我最初的代码是:

#!/usr/bin/env python
import string

import keyword

import sys
#Get all keyword for python

#keyword.kwlist

#['and', 'as', 'assert', 'break', ...]

keyWords = keyword.kwlist
#Get all character for identifier

#string.letters ==> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

#string.digits  ==> '0123456789'

charForId = string.letters + "_"

numForId = string.digits
idInput = raw_input("Input your words,please!")
if idInput in keyWords:

    print "%s is keyword fot Python!" % idInput

else:

    lenNum = len(idInput)

    if(1 == lenNum):

        if(idInput in charForId and idInput != "_"):

            print "%s is legal identifier for Python!" % idInput

        else:

            #It's just "_"

            print "%s isn't legal identifier for Python!" % idInput
    else:

        if(idInput[0:1] in charForId):

            legalstring = charForId + numForId

            for item in idInput[1:]:

                if (item not in legalstring):

                    print "%s isn't legal identifier for Python!" % idInput

                    sys.exit(0)

            print "%s is legal identifier for Python!2" % idInput

        else:

            print "%s isn't legal identifier for Python!3" % idInput

    

代码完毕后,我测试每一条分支,测试到分支时,必须输入_d4%等包含非法字符的标识符才能进行测试,我最初以为,sys.exit(0)---正常退出脚本,sys.exit(1)非正常退出脚本,但是实际情况是/9sys.exit(1),仅输出返回码不同):

  if (item not in legalstring):

      print "%s isn't legal identifier for Python!" % idInput

     sys.exit(0)
Input your words,please!_d4%

_d4% isn't legal identifier for Python!
Traceback (most recent call last):

  File "E:/python/idcheck.py", line 37, in <module>

    sys.exit(0)

SystemExit: 0

>>>

由此可见,这样做没有达到我预期如下输出的效果,那么,问题在哪里呢?在于sys.exit()始终会抛出一个SystemExit异常。

Input your words,please!_d4%

_d4% isn't legal identifier for Python!
#!/usr/bin/env python
import string

import keyword

import sys

import traceback
try:

    #Get all keyword for python

    #keyword.kwlist

    #['and', 'as', 'assert', 'break', ...]

    keyWords = keyword.kwlist
    #Get all character for identifier

    #string.letters ==> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'

    #string.digits  ==> '0123456789'

    charForId = string.letters + "_"

    numForId = string.digits
    idInput = raw_input("Input your words,please!")
    if idInput in keyWords:

        print "%s is keyword fot Python!" % idInput

    else:

        lenNum = len(idInput)

        if(1 == lenNum):

            if(idInput in charForId and idInput != "_"):

                print "%s is legal identifier for Python!" % idInput

            else:

                #It's just "_"

                print "%s isn't legal identifier for Python!" % idInput
        else:

            if(idInput[0:1] in charForId):

                legalstring = charForId + numForId

                for item in idInput[1:]:

                    if (item not in legalstring):

                        print "%s isn't legal identifier for Python!" % idInput

                        sys.exit()

                print "%s is legal identifier for Python!2" % idInput

            else:

                print "%s isn't legal identifier for Python!3" % idInput
except SystemExit:

    pass

except:

    traceback.print_exc()

上面的代码获取sys.exit()抛出的SystemExit异常。

return:在定义函数时从函数中返回一个函数的返回值,终止函数的执行。

exit:下面的代码中,如果把sys.exit()替换成exit,则exit仅仅跳出离它最近的for循环, print "%s is legal identifier for Python!2" % idInput语句会被输出,这里,exit的作用类似于break. 但实际上break和exit作用并不同

                for item in idInput[1:]:

                    if (item not in legalstring):

                        print "%s isn't legal identifier for Python!" % idInput

                        sys.exit()

                print "%s is legal identifier for Python!2" % idInput
Python 相关文章推荐
python去掉字符串中重复字符的方法
Feb 27 Python
Python打印斐波拉契数列实例
Jul 07 Python
在Django中管理Users和Permissions以及Groups的方法
Jul 23 Python
Python3.2模拟实现webqq登录
Feb 15 Python
深入解析Python中函数的参数与作用域
Mar 20 Python
Python实现多态、协议和鸭子类型的代码详解
May 05 Python
对pyqt5中QTabWidget的相关操作详解
Jun 21 Python
Python将视频或者动态图gif逐帧保存为图片的方法
Sep 10 Python
PyCharm2019安装教程及其使用(图文教程)
Sep 29 Python
Python argparse模块应用实例解析
Nov 15 Python
Python之Matplotlib文字与注释的使用方法
Jun 18 Python
解决pytorch 数据类型报错的问题
Mar 03 Python
Python中的with...as用法介绍
May 28 #Python
python关键字and和or用法实例
May 28 #Python
Python yield 使用浅析
May 28 #Python
Python中super的用法实例
May 28 #Python
Python中的super用法详解
May 28 #Python
Python读写ini文件的方法
May 28 #Python
Python实现给文件添加内容及得到文件信息的方法
May 28 #Python
You might like
php+dojo 的数据库保存拖动布局的一个方法dojo 这里下载
2007/03/07 PHP
支持php4、php5的mysql数据库操作类
2008/01/10 PHP
用PHP程序实现支持页面后退的两种方法
2008/06/30 PHP
php防攻击代码升级版
2010/12/29 PHP
php输出1000以内质数(素数)示例
2014/02/16 PHP
[原创]PHP字符串中插入子字符串方法总结
2016/05/06 PHP
PHP用户注册邮件激活账户的实现代码
2017/05/31 PHP
IE浏览器PNG图片透明效果代码
2008/09/02 Javascript
jquery之empty()与remove()区别说明
2010/09/10 Javascript
一些主流JS框架中DOMReady事件的实现小结
2011/02/12 Javascript
jQuery之折叠面板的深入解析
2013/06/19 Javascript
jquery实现页面虚拟键盘特效
2015/08/08 Javascript
详解JavaScript正则表达式之RegExp对象
2015/12/13 Javascript
高效利用Angular中内置服务$http、$location等
2016/03/22 Javascript
js实现刷新页面后回到记录时滚动条的位置【两种方案可选】
2016/12/12 Javascript
jquery滚动条插件slimScroll使用方法
2017/02/09 Javascript
js正则表达式验证表单【完整版】
2017/03/06 Javascript
Iphone手机、安卓手机浏览器控制默认缩放大小的方法总结(附代码)
2017/08/18 Javascript
vue将对象新增的属性添加到检测序列的方法
2018/02/24 Javascript
在Python中用has_key()方法查找键是否存在的教程
2015/05/21 Python
python实现文件路径和url相互转换的方法
2015/07/06 Python
Python统计日志中每个IP出现次数的方法
2015/07/06 Python
十条建议帮你提高Python编程效率
2016/02/16 Python
python的依赖管理的实现
2019/05/14 Python
Python3.x+pyqtgraph实现数据可视化教程
2020/03/14 Python
python nohup 实现远程运行不宕机操作
2020/04/16 Python
Berghaus官网:户外服装和设备,防水服
2020/01/17 全球购物
50岁生日感言
2014/01/23 职场文书
遗嘱继承公证书
2014/04/09 职场文书
大学新生军训自我鉴定范文
2014/09/13 职场文书
婚礼嘉宾致辞
2015/07/28 职场文书
团队合作精神学习心得体会
2016/01/19 职场文书
小学一年级语文教学反思
2016/03/03 职场文书
美甲店的创业计划书模板
2019/08/23 职场文书
 分享一个Python 遇到数据库超好用的模块
2022/04/06 Python
HTML页面点击按钮关闭页面的多种方式
2022/12/24 HTML / CSS