Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use: python warnings.warn()?

This is my code that I wrote:

#usr/bin/python3
import warnings

def tt():

    warnings.warn("123")

    return 10

x = tt()

print(x)

It prints:

test.py:5: UserWarning: 123

warnings.warn("123")

10

I want it to only print:

test.py:5: UserWarning: 123
10

Without warnings.warn("123").

What should I do?

like image 358
zichuan Avatar asked Nov 07 '22 15:11

zichuan


2 Answers

You can replace the function used to format the messages; for example:

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

Python Module of the week article

like image 117
AndrewS Avatar answered Nov 15 '22 12:11

AndrewS


import warnings
# import pdb

def format_Warning(message, category, filename, lineno, line=''):
    return str(filename) + ':' + str(lineno) + ': ' + category.__name__ + ': ' +str(message) + '\n'

warnings.formatwarning = format_Warning

def tt():

    warnings.warn("123")

    return 10

x = tt()

print(x)

Hope it helps!

like image 21
Avijit Dasgupta Avatar answered Nov 15 '22 11:11

Avijit Dasgupta