【问题标题】:Print statement is not working in try catch else finally block打印语句在 try catch else finally 块中不起作用
【发布时间】:2018-06-05 23:42:03
【问题描述】:

我使用 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 时,打印语句永远不会在 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

【问题讨论】:

  • 我无法使用 Python 3.6.3 重现此问题
  • 在我看来文件在那里,可能是因为之前的 doctest 在删除文件之前失败了。
  • 我在 python 3.6.0 上运行了你的代码,它按预期工作

标签: python python-3.x


【解决方案1】:

这与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

【讨论】:

  • 你的意思是在 try 子句中将print('The file is there!') 移到return file_handle 之上吗?更好地展示代码的外观。
最近更新 更多