我使用Try Catch Else Else块来创建这个函数。
下面是我的代码:
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
发布于 2018-06-06 07:57:44
这与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
https://stackoverflow.com/questions/50710383
复制相似问题