jasonjean 发表于 2011-02-17 15:57

求解:try_except捕获ctrl+D和ctrl+C的异常的问题

本帖最后由 jasonjean 于 2011-02-17 15:59 编辑

代码内容:
#!/usr/bin/env python
while True:
      try:
                filename=raw_input('Enter the filename:')
                fobj=open(filename,'r')
      except (IOError,EOFError,KeyboardInterrupt),e:
                print str(e)
      else:
                break
for eachLines in fobj:
      print eachLines,
print fobj.closed
fobj.close()
print fobj.closed
期望是:当输入的文件无法正常打开,或者用户按下了ctrl+D,或ctrl+C,程序不会退出,且提示重新输入需要打开的文件名。

实际执行结果发现一个问题:
当按下了ctrl+D之后紧接着按Ctrl+C,则程序退出,如下:
# ./9-4-1.py
Enter the filename:                  #ctrl+C
Enter the filename:                  #ctrl+C
Enter the filename:                  #ctrl+D
Enter the filename:                  #ctrl+D
Enter the filename:Traceback (most recent call last):   #这里是ctrl+C,为何这个异常就没有捕捉到了呢???
File "./9-4-1.py", line 4, in ?
    filename=raw_input('Enter the filename:')
KeyboardInterrupt

tank064 发表于 2014-07-07 17:22

本帖最后由 tank064 于 2014-07-07 17:23 编辑

在外面再加一个try$ python test.py
Enter the filename:
Enter the filename:
Enter the filename:
Enter the filename:
Enter the filename:
Enter the filename:
Enter the filename:
Enter the filename:test.py
#!/usr/bin/env python

import sys
while True:
    try:
      try:
            filename=raw_input('Enter the filename:')
            fobj=open(filename,'r')
            for line in fobj:
                sys.stdout.write(line)
      except (IOError, EOFError, KeyboardInterrupt), e:
            sys.stdout.write(str(e) + '\n')
      else:
            break
    except (Exception, KeyboardInterrupt), e:
      sys.stdout.write(str(e) + '\n')
页: [1]
查看完整版本: 求解:try_except捕获ctrl+D和ctrl+C的异常的问题