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计算书页码的统计数字问题实例
Sep 26 Python
Python基于有道实现英汉字典功能
Jul 25 Python
Python 编码Basic Auth使用方法简单实例
May 25 Python
Python Socket使用实例
Dec 18 Python
python dataframe astype 字段类型转换方法
Apr 11 Python
用python处理图片之打开\显示\保存图像的方法
May 04 Python
Python 输入一个数字判断成绩分数等级的方法
Nov 15 Python
Django+uni-app实现数据通信中的请求跨域的示例代码
Oct 12 Python
Python 装饰器@,对函数进行功能扩展操作示例【开闭原则】
Oct 17 Python
Python 面向对象部分知识点小结
Mar 09 Python
pygame用blit()实现动画效果的示例代码
May 28 Python
Python基于smtplib协议实现发送邮件
Jun 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缓存技术的使用说明
2011/08/06 PHP
php简单判断两个字符串是否相等的方法
2015/07/13 PHP
基于ThinkPHP实现批量删除
2015/12/18 PHP
php监测数据是否成功插入到Mysql数据库的方法
2016/11/25 PHP
PHP数据库操作二:memcache用法分析
2017/08/16 PHP
不提示直接关闭网页窗口的JS示例代码
2013/12/17 Javascript
20条学习javascript的编程规范的建议
2014/11/28 Javascript
js添加绑定事件的方法
2016/05/15 Javascript
JavaScript基础重点(必看)
2016/07/09 Javascript
javascript中的 object 和 function小结
2016/08/14 Javascript
BootStrap 实现各种样式的进度条效果
2016/12/07 Javascript
基于Vue框架vux组件库实现上拉刷新功能
2017/11/28 Javascript
微信小程序使用wxParse解析html的实现示例
2018/08/30 Javascript
webpack4打包vue前端多页面项目
2018/09/17 Javascript
如何使用VuePress搭建一个类型element ui文档
2019/02/14 Javascript
CKeditor4 字体颜色功能配置方法教程
2019/06/26 Javascript
layer.js open 隐藏滚动条的例子
2019/09/05 Javascript
Vue学习笔记之计算属性与侦听器用法
2019/12/07 Javascript
js实现移动端吸顶效果
2020/01/08 Javascript
[01:00:59]VP VS VG Supermajor小组赛胜者组第二轮 BO3第二场 6.2
2018/06/03 DOTA
python类和继承用法实例
2015/07/07 Python
python中使用正则表达式的连接符示例代码
2017/10/10 Python
Django实现全文检索的方法(支持中文)
2018/05/14 Python
python代码 FTP备份交换机配置脚本实例解析
2019/08/01 Python
tensorflow实现从.ckpt文件中读取任意变量
2020/05/26 Python
Django如何实现密码错误报错提醒
2020/09/04 Python
对Pytorch 中的contiguous理解说明
2021/03/03 Python
canvas 基础之图像处理的使用
2020/04/10 HTML / CSS
美国著名的团购网站:Woot
2016/08/02 全球购物
英国绿色商店:Natural Collection
2019/05/03 全球购物
高中毕业自我鉴定范文
2013/10/02 职场文书
捐款感谢信
2015/01/20 职场文书
清明节扫墓活动总结
2015/02/09 职场文书
2015年父亲节活动总结
2015/02/12 职场文书
2019公司借款合同范本2篇!
2019/07/24 职场文书
Springboot如何同时装配两个相同类型数据库
2021/11/17 Java/Android