Python学习第十天——《A Byte of Python》笔记 10

Back to school

很遗憾,打卡记录未到两位数就嘎然而至,因工作虽然昨天看了一部分,但是没时间做笔记。
所以做事情还是要有规划,要放提前量,戒之拖拉

Exceptions(异常)

我们的程序常会因异常情况导致出错,比如我们要读一个文件但文件不存在,不小心删除了正在运行的某程序,这些都要用Exceptions来控制。

Errors(错误)

简单的以Print和print函数来举例,Python提示了一个语法错误:

>>> Print("hello")
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'Print' is not defined
>>> print('hello')
hello

Exceptions(异常)

Windows系统,在接受用户输入时,最后结尾时不按回车而按[ctrl-c],就会提示KeyboardInterrupt(键盘中断)

>>> s=input("Enter something")
Enter something Traceback(most recent call last):Traceback (most recent call last):
  File "", line 1, in 
KeyboardInterrupt
>>>

如果用的是苹果Mac,按[ctrl-d][ctrl-d]是文末的标识,但是Python没有找到文末,所以会出现一个EOFError的错误提示

Handling Exceptions(控制异常)

我们用try...except*语句来控制异常,普通语句我们放在try块中,出错处理放在excetp块中

try:
    text=input('Enter something:')
except EOFError:
    print('Why did you do an EOF on me?')
except KeyboardInterrupt:
    print('You cancelled the operation.')
else:
    print('you entered {}'.format(text))

Output:

Enter something:^D
Why did you do an EOF on me?
Enter something:12345
you entered 12345

Raising Exceptions(抛出异常)

定义一个ShortInputException类,当用户输入没有达到最低长度要求,抛出异常。

class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self,length,atleast):
        Exception.__init__(self)
        self.length=length
        self.atleast=atleast

try:
    text = input('Enter something --> ')
    if len(text) < 3:
        raise ShortInputException(len(text), 3)
        # Other work can continue as usual here
except EOFError:
    print('Why did you do an EOF on me?')
except ShortInputException as ex:
    print(('ShortInputException: The input was ' +
               '{0} long, expected at least {1}')
              .format(ex.length, ex.atleast))
else:
    print('No exception was raised.')

Output:

Enter something --> ok
ShortInputException: The input was 2 long, expected at least 3
Enter something --> good
No exception was raised.

Try ... Finally

在程序在读一个文件时,如果出现一个异常,我们怎么保证文件对象是否被马上关闭了? 我们可以用finally

import sys
import time

f = None
try:
    f = open("poem.txt")
    # Our usual file-reading idiom
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        print(line, end='')
        sys.stdout.flush()
        print("Press ctrl+c now")
        # To make sure it runs for a while
        time.sleep(2)
except IOError:
    print("Could not find file poem.txt")
except KeyboardInterrupt:
    print("!! You cancelled the reading from the file.")
finally:
    if f:
        f.close()
    print("(Cleaning up: Closed the file)")

Output:(用PyCharm一直按不下ctrl+c,本来想复制代码代替,O(∩_∩)O 后来在DOS编译器下运行,一开始找不到poem.txt,后来cd到该.py目录下,然后再编译器执行,搞定。)

Programming is fun
Press ctrl+c now
When the works is done
Press ctrl+c now
!!You cancelled the reading from the file.
(cleaning up: closed the file)

The with statement(with 语句)

在try 块中获得资源,随后又在finally 块中释放资源,这是一种常见的模式。今
后,也有一种with 语句能以清晰的方式完成这样的功能。

with open("poem.txt") as f:
    for line in f:
        print(line,end='')

(ps.下面这一段不甚明白,姑且先抄下先)
输出与前面例子的输出一样,用with open 就能使得在结束的时候自动关闭文件。在屏幕后面发生的事情就是with 语句使用了一种协议。获得了open 语句返回的对象,就叫做’thefile’ 好了。
在启动代码块之前,在后台总会调用thefile.__ enter__ 函数,在代码块结束后又会调用thefile.__ exit__ 函数。
所以我们用finally 块写的代码应该自行注意__ exit__ 方法。这就能帮助我们避免反复使用显式的try..finally 语句。


持之以恒,方得始终

你可能感兴趣的:(Python学习第十天——《A Byte of Python》笔记 10)