我试图使用环境变量抑制来自第三方模块(在本例中,是通过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")'
的东西来完成,但是这对我的用例来说非常不方便。我也可以解决潜在的问题,但这不是一项小任务)
出现问题的原因是
PerformanceWarning
不是内置的警告类别(list here)根据您的用例,您可以使用下面的方法,但要小心,因为一些严厉的方法也可能会抑制有用的警告
如果要在从命令行运行脚本时忽略所有警告,可以使用:
你的例子是:
在脚本内部,您可以使用:
你的例子是:
我建议使用第二种方法的一些变体,明确忽略您不想看到的特定警告
相关问题 更多 >
编程相关推荐