首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Print语句在try catch else finally块中不起作用

Print语句在try catch else finally块中不起作用
EN

Stack Overflow用户
提问于 2018-06-06 07:42:04
回答 1查看 857关注 0票数 0

我使用Try Catch Else Else块来创建这个函数。

下面是我的代码:

代码语言:javascript
复制
def read_a_file():
    """
    >>> out = read_a_file() #while the file is not there
    The file is not there.
    We did something.
    >>> print(out)
    None
    >>> Path('myfile.txt').touch()
    >>> out = read_a_file() #while the file is there
    The file is there!
    We did something.
    >>> type(out)
    <class '_io.TextIOWrapper'>
    >>> out.close()
    >>> os.remove("myfile.txt")
    """
    try:
        file_handle = open('myfile.txt', 'r')
        return file_handle
    except FileNotFoundError:
        print('The file is not there.')
        return None
    else:
        print('The file is there!')
    finally:
        print('We did something.')

但是,当我运行doctest时,print语句永远不会在except和else块中工作。只有finally块中的print语句有效。

我得到了这个结果,这不是我想要的。

代码语言:javascript
复制
>>> out = read_a_file() #while the file is not there
We did something.

救命!如何解决这个问题?

您必须导入这些包

代码语言:javascript
复制
import pandas as pd
from functools import reduce
from pathlib import Path
import os
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-06 07:57:44

这与doctest无关。这种行为是意料之中的,因为当您使用return时,不会执行else:子句。来自the docs

如果控制流出try子句的结尾,则执行可选的else子句。2

..。

2目前,除非出现异常或执行return、continue或break语句,否则控制“流向末尾”。

因此,如果希望在且仅当未引发异常的情况下出现The file is there!,请去掉else:子句并移动

代码语言:javascript
复制
print('The file is there!')

上图

代码语言:javascript
复制
return file_handle
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50710383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档