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实现方法
Nov 18 Python
Python连接mssql数据库编码问题解决方法
Jan 01 Python
Python实现的使用telnet登陆聊天室实例
Jun 17 Python
关于Python中浮点数精度处理的技巧总结
Aug 10 Python
启动targetcli时遇到错误解决办法
Oct 26 Python
python机器人行走步数问题的解决
Jan 29 Python
python使用turtle绘制分形树
Jun 22 Python
Django migrations 默认目录修改的方法教程
Sep 28 Python
Python中logging.NullHandler 的使用教程
Nov 29 Python
python实现kNN算法识别手写体数字的示例代码
Aug 16 Python
解决python cv2.imread 读取中文路径的图片返回为None的问题
Jun 02 Python
Pytorch实现WGAN用于动漫头像生成
Mar 04 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许愿墙模块功能分析
2013/06/25 PHP
php事务处理实例详解
2014/07/11 PHP
win7 64位系统 配置php最新版开发环境(php+Apache+mysql)
2014/08/15 PHP
php中substr()函数参数说明及用法实例
2014/11/15 PHP
Yii框架实现多数据库配置和操作的方法
2017/05/25 PHP
ThinkPHP实现的rsa非对称加密类示例
2018/05/29 PHP
PhpStorm+xdebug+postman调试技巧分享
2020/09/15 PHP
JS在IE和FireFox之间常用函数的区别小结
2010/03/12 Javascript
jQuery中的siblings用法实例分析
2015/12/24 Javascript
AngularJS创建自定义指令的方法详解
2016/11/03 Javascript
微信小程序图片宽100%显示并且不变形
2017/06/21 Javascript
基于JavaScript实现微信抢红包功能
2017/07/20 Javascript
快速将Vue项目升级到webpack3的方法步骤
2017/09/14 Javascript
Vue头像处理方案小结
2018/07/26 Javascript
全面分析JavaScript 继承
2019/05/30 Javascript
vue iview多张图片大图预览、缩放翻转
2019/07/13 Javascript
vue使用codemirror的两种用法
2019/08/27 Javascript
Python格式化压缩后的JS文件的方法
2015/03/05 Python
浅要分析Python程序与C程序的结合使用
2015/04/07 Python
Python实现求两个csv文件交集的方法
2017/09/06 Python
pygame游戏之旅 python和pygame安装教程
2018/11/20 Python
Django 路由控制的实现
2019/07/17 Python
Python实现报警信息实时发送至邮箱功能(实例代码)
2019/11/11 Python
浅谈Python中re.match()和re.search()的使用及区别
2020/04/14 Python
python3.8动态人脸识别的实现示例
2020/09/21 Python
使用CSS3配合IE滤镜实现渐变和投影的效果
2015/09/06 HTML / CSS
全球知名旅游社区巴西站点:TripAdvisor巴西
2016/07/21 全球购物
美国在线面料商店:Fashion Fabrics Club
2020/01/31 全球购物
写一个函数,求一个字符串的长度。在main函数中输入字符串,并输出其长度
2015/11/18 面试题
什么是反射
2012/03/17 面试题
学校门卫工作职责
2013/12/07 职场文书
开业主持词
2014/03/21 职场文书
2014年房产销售工作总结
2014/12/08 职场文书
2015年世界无车日活动总结
2015/03/23 职场文书
2015年护士节活动策划方案
2015/05/04 职场文书
三八妇女节新闻稿
2015/07/17 职场文书