Make Python's `warnings.warn()` not mention itself

后端 未结 3 665
遇见更好的自我
遇见更好的自我 2021-01-11 22:13

My minimum example is

#!/usr/bin/python3

import warnings

warnings.warn(\'Run Forest run!\', stacklevel=2)
warnings.warn(\'Run Forest run!\')
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-11 22:25

    Turns out it is possible to let warnings.warn() collect all the info and just costumize the way the info is printed:

    #!/usr/bin/python3
    
    import warnings
    
    def warning_on_one_line(message, category, filename, lineno, file=None, line=None):
        return '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, message)
    
    warnings.formatwarning = warning_on_one_line
    
    warnings.warn('Run Forest run!', stacklevel=2)
    warnings.warn('Run Forest run!')
    

    Output:

    sys:1: UserWarning: Run Forest run!
    ./file.py:15: UserWarning: Run Forest run!
    

    Source: Python module of the week

提交回复
热议问题