抑制导入警告?

Suppress warnings on import?

假设我写了一个必须使用 imp 模块的 python 包,我的包是 "TestModule" 如下:

import imp
import pip
import sys

def update_and_reload(module, *args, **kwargs):
    pip.main(['install', module, '--upgrade', '--user'])
    return imp.reload(module)

当我在终端中执行 import TestModule 时,我在 imp 上收到了待处理的弃用警告。我如何使 imp 的警告不发生/过滤掉?

你可以使用 warning 模块:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings("ignore", category=DeprecationWarning)
    import imp
import pip
...