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抓取网页图片并放到指定文件夹
Apr 24 Python
Python2.7下安装Scrapy框架步骤教程
Dec 22 Python
Python 经典面试题 21 道【不可错过】
Sep 21 Python
一看就懂得Python的math模块
Oct 21 Python
python实现视频分帧效果
May 31 Python
python3.x+pyqt5实现主窗口状态栏里(嵌入)显示进度条功能
Jul 04 Python
Django2 连接MySQL及model测试实例分析
Dec 10 Python
打印tensorflow恢复模型中所有变量与操作节点方式
May 26 Python
opencv 阈值分割的具体使用
Jul 08 Python
Python 开发工具通过 agent 代理使用的方法
Sep 27 Python
python 检测nginx服务邮件报警的脚本
Dec 31 Python
python 常用的异步框架汇总整理
Jun 18 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
支持oicq头像的留言簿(一)
2006/10/09 PHP
php使用Cookie实现和用户会话的方法
2015/01/21 PHP
PHP中的异常处理机制深入讲解
2020/11/10 PHP
ThinkPHP5.1的权限控制怎么写?分享一个AUTH权限控制
2021/03/09 PHP
基于jquery1.4.2的仿flash超炫焦点图播放效果
2010/04/20 Javascript
用方法封装javascript的new操作符(一)
2010/12/25 Javascript
电子商务网站上的常用的js放大镜效果
2011/12/08 Javascript
javascript中的void运算符语法及使用介绍
2013/03/10 Javascript
js实现无需数据库的县级以上联动行政区域下拉控件
2013/08/14 Javascript
Jquery实现侧边栏跟随滚动条固定(兼容IE6)
2014/04/02 Javascript
再谈Jquery Ajax方法传递到action(补充)
2014/05/12 Javascript
jquery实现搜索框常见效果的方法
2015/01/22 Javascript
教你如何终止JQUERY的$.AJAX请求
2016/02/23 Javascript
深入解析JavaScript中的arguments对象
2016/06/12 Javascript
html5 canvas 详细使用教程
2017/01/20 Javascript
实例详解JSON取值(key是中文或者数字)方式
2017/08/24 Javascript
layui radio单选限制下一个radio单选的实例
2019/09/03 Javascript
vue前端和Django后端如何查询一定时间段内的数据
2021/02/28 Vue.js
Python使用metaclass实现Singleton模式的方法
2015/05/05 Python
python代码 if not x: 和 if x is not None: 和 if not x is None:使用介绍
2016/09/21 Python
python中模块查找的原理与方法详解
2017/08/11 Python
Python 输入一个数字判断成绩分数等级的方法
2018/11/15 Python
对python模块中多个类的用法详解
2019/01/10 Python
Pycharm 实现下一个文件引用另外一个文件的方法
2019/01/17 Python
不归路系列:Python入门之旅-一定要注意缩进!!!(推荐)
2019/04/16 Python
如何基于pythonnet调用halcon脚本
2020/01/20 Python
Python实现从N个数中找到最大的K个数
2020/04/02 Python
解决pytorch 交叉熵损失输出为负数的问题
2020/07/07 Python
python 使用建议与技巧分享(四)
2020/08/18 Python
Python 实现RSA加解密文本文件
2020/12/30 Python
纽约家具、家居装饰和地毯店:ABC Carpet & Home
2017/06/21 全球购物
大学生职业生涯规划书参考模板
2014/03/05 职场文书
奥巴马胜选演讲稿
2014/05/15 职场文书
房屋认购协议书
2015/01/29 职场文书
新兵入伍决心书
2015/09/22 职场文书
python自动化测试之Selenium详解
2022/03/13 Python