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网页请求urllib2模块简单封装代码
Feb 07 Python
python进程管理工具supervisor的安装与使用教程
Sep 05 Python
Python实现的多线程同步与互斥锁功能示例
Nov 30 Python
Python cookbook(数据结构与算法)让字典保持有序的方法
Feb 18 Python
JSON文件及Python对JSON文件的读写操作
Oct 07 Python
基于python实现百度翻译功能
May 09 Python
python 3.6.7实现端口扫描器
Sep 04 Python
Python之变量类型和if判断方式
May 05 Python
Python 3.9的到来到底是意味着什么
Oct 14 Python
协程Python 中实现多任务耗资源最小的方式
Oct 19 Python
class类在python中获取金融数据的实例方法
Dec 10 Python
python基础之停用词过滤详解
Apr 21 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数组索引的Key加引号和不加引号的区别
2014/08/19 PHP
php读取目录及子目录下所有文件名的方法
2014/10/20 PHP
解决PHP curl或file_get_contents下载图片损坏或无法打开的问题
2019/10/11 PHP
给moz-firefox下添加IE方法和属性
2007/04/10 Javascript
JSON辅助格式化处理方法
2013/03/26 Javascript
不用锚点也可以平滑滚动到页面的指定位置实现代码
2013/05/08 Javascript
js判读浏览器是否支持html5的canvas的代码
2013/11/18 Javascript
JavaScript中计算网页中某个元素的位置
2015/06/10 Javascript
nodejs爬虫抓取数据乱码问题总结
2015/07/03 NodeJs
用JavaScript来美化HTML的select标签的下拉列表效果
2015/11/17 Javascript
jquery.qtip提示信息插件用法简单实例
2016/06/17 Javascript
jQuery双向列表选择器select版
2016/11/01 Javascript
jQuery查找和过滤_动力节点节点Java学院整理
2017/07/04 jQuery
在React 组件中使用Echarts的示例代码
2017/11/08 Javascript
react脚手架如何配置less和ant按需加载的方法步骤
2018/11/28 Javascript
解决Layui数据表格的宽高问题
2019/09/28 Javascript
Python smtplib实现发送邮件功能
2018/05/22 Python
使用selenium模拟登录解决滑块验证问题的实现
2019/05/10 Python
Python绘制股票移动均线的实例
2019/08/24 Python
Python写出新冠状病毒确诊人数地图的方法
2020/02/12 Python
jupyter notebook oepncv 显示一张图像的实现
2020/04/24 Python
Scrapy-Redis之RedisSpider与RedisCrawlSpider详解
2020/11/18 Python
python解包概念及实例
2021/02/17 Python
canvas 下载二维码和图片加水印的方法
2018/03/21 HTML / CSS
高级Java程序员面试要点
2013/08/02 面试题
音乐器材管理制度
2014/01/31 职场文书
优秀高中生事迹材料
2014/02/11 职场文书
创先争优活动方案
2014/02/12 职场文书
企业党员公开承诺书
2014/03/26 职场文书
机关保密承诺书
2014/06/03 职场文书
加强干部作风建设整改方案
2014/10/24 职场文书
社区重阳节活动总结
2015/03/24 职场文书
酒店员工管理制度
2015/08/05 职场文书
2020年元旦晚会策划书模板
2019/12/30 职场文书
详解vue身份认证管理和租户管理
2021/05/25 Vue.js
关于python中readlines函数的参数hint的相关知识总结
2021/06/24 Python