关于python:print语句在try catch else finally块中不起作用

Print statement is not working in try catch else finally block

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

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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语句才有效。

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

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

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

您必须导入这些包

1
2
3
4
import pandas as pd
from functools import reduce
from pathlib import Path
import os


这与doctest无关。 该行为是预期的,因为当您return时,不执行else:子句。 来自文档:

The optional else clause is executed if and when control flows off the end of the try clause. [2]

...

[2] Currently, control"flows off the end" except in the case of an exception or the execution of a return, continue, or break statement.

因此,如果您希望The file is there!出现,当且仅当没有引发异常时,丢失else:子句并移动

1
print('The file is there!')

以上

1
return file_handle