打印语句不能在try catch else finally块中工作

时间:2018-06-05 23:42:04

标签: python python-3.x

我使用Try Catch Else Finally块来创建此功能。

这是我的代码:

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语句正在工作。

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

>>> out = read_a_file() #while the file is not there
We did something.

帮助!!!如何解决这个问题?

您必须导入这些包

import pandas as pd
from functools import reduce
from pathlib import Path
import os

1 个答案:

答案 0 :(得分:4)

这与doctest无关。这种行为是预期的,因为当您return时,else:子句执行。来自the docs

  

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

     

...

     

[2]目前,除了例外情况或执行return,continue或break语句外,控制“流出结束”。

因此,如果您希望{且仅在未引发异常的情况下显示The file is there!,请丢失else:子句并移动

print('The file is there!')

以上

return file_handle