无法使用 warnings.catch_warnings() 捕获 python 警告

问题描述 投票:0回答:1
我正在使用Python中的

Camelot库从pdf中读取表格。

如果没有识别出表格,而是其他内容(例如文本),则库会发出警告:

UserWarning: No tables found in table area 1 [stream.py:365]

。
我的想法是用 
warnings.catch_warnings()
 函数捕捉这个警告。

这是我的代码:

with warnings.catch_warnings(record=True) as w: # reading tables from pdf parsed_tables = camelot.read_pdf( tmp_file.name, pages=page, flavor="stream", row_tol=row_tol, table_areas=["30,480,790,100"], surpress_stdout=False ) # warning.warn("TEST") print("warning", w)
我的问题是变量 w 始终为空。如果我取消注释“TEST”警告,该警告将出现在变量 w 中(它与我自己的警告一起使用)。

我在库中搜索了警告过滤器,但没有找到。 我尝试添加

warnings.filterwarnings("default")

warnings.simplefilter("always")
。
为什么我听不到这个警告?是因为它发生在库中而不是我的代码中吗?

python pdf warnings python-camelot
1个回答
0
投票
请尝试将

action

 设置为 
ignore
。当您写下 
always
 时,您请求在所有情况下显示警告...

作为

小回顾,您可以使用上下文管理器来捕获警告。您需要指定上下文管理器捕获警告时的操作。默认情况下,它可能不会执行您想要的操作。

  • Python 3.11

    之前,您必须在不同的行上编写所需的操作(这就是执行此操作的方法,我检查了文档,请参见下文)。

  • Python 3.11

    之后,您可以以一种非常好的方式和简洁的方式将操作传递给上下文管理器的构造函数。

请参阅下面的示例。

# works in python 3.8: https://docs.python.org/3.8/library/warnings.html import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore") fn_triggering_warnings() # works in python 3.11: https://docs.python.org/3.11/library/warnings.html import warnings with warnings.catch_warnings(action="ignore"): fn_triggering_warnings()
    
© www.soinside.com 2019 - 2024. All rights reserved.