使用换行符过滤第三方Python警告

2024-09-28 22:01:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用环境变量抑制来自第三方模块(在本例中,是通过Pandas的PyTables)的警告。警告以换行符开头

警告示例:

python -c 'import pandas as pd; pd.DataFrame([None]).to_hdf("test.h5", "/data")'
/usr/lib/python3.9/site-packages/pandas/core/generic.py:2606: PerformanceWarning: 
your performance may suffer as PyTables will pickle object types that it cannot
map directly to c-types [inferred_type->mixed,key->block0_values] [items->Int64Index([0], dtype='int64')]

  pytables.to_hdf(

根据Python文档,我可以通过将PYTHONWARNINGS设置为action:message:category:module:line格式来指定要忽略的警告

使用category

我尝试了PYTHONWARNINGS=ignore::PerformanceWarning,但是这给了我一个信息Invalid -W option ignored: unknown warning category: 'PerformanceWarning'

PYTHONWARNINGS=ignore::pytables.PerformanceWarning给了我Invalid -W option ignored: invalid module name: 'pytables'

使用message

我最初尝试了PYTHONWARNINGS=ignore:your performance may suffer,但没有任何效果,可能是因为警告消息以换行符开头

为了进一步研究换行符的情况,我尝试插入一条换行符,但它要么被转义,要么被删除:

PYTHONWARNINGS="ignore:\nyour performance" python -c "import warnings as w; [print(f) for f in w.filters]"
('ignore', re.compile('\\\\nyour\\ performance', re.IGNORECASE), <class 'Warning'>, None, 0)
// ...
PYTHONWARNINGS="$(echo -n "ignore:\nyour performance")" python -c "import warnings as w; [print(f) for f in w.filters]"
('ignore', re.compile('your\\ performance', re.IGNORECASE), <class 'Warning'>, None, 0)
// ...
PYTHONWARNINGS="ignore:.your performance" python -c "import warnings as w; [print(f) for f in w.filters]"
('ignore', re.compile('\\.your\\ performance', re.IGNORECASE), <class 'Warning'>, None, 0)
// ...

如何禁用此警告

(我知道我可以使用类似python -c 'import pandas as pd; import warnings as w; w.filterwarnings("ignore", "\nyour performance"); pd.DataFrame([None]).to_hdf("test.h5", "/data")'的东西来完成,但是这对我的用例来说非常不方便。我也可以解决潜在的问题,但这不是一项小任务)


Tags: toimportrenone警告pandasyouras
1条回答
网友
1楼 · 发布于 2024-09-28 22:01:52

出现问题的原因是PerformanceWarning不是内置的警告类别(list here

根据您的用例,您可以使用下面的方法,但要小心,因为一些严厉的方法也可能会抑制有用的警告

如果要在从命令行运行脚本时忽略所有警告,可以使用:

python -W ignore myscript.py

你的例子是:

python -W ignore -c 'import pandas as pd; pd.DataFrame([None]).to_hdf("test.h5", "/data")'

在脚本内部,您可以使用:

import pandas as pd
import warnings

# Create your own warning filter
warnings.simplefilter(action='ignore', category=pd.errors.PerformanceWarning)

你的例子是:

python -c 'import warnings; import pandas as pd; warnings.simplefilter(action='ignore', category=pd.errors.PerformanceWarning); pd.DataFrame([None]).to_hdf("test.h5", "/data")'

我建议使用第二种方法的一些变体,明确忽略您不想看到的特定警告

相关问题 更多 >