zichuan
zichuan

Reputation: 111

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?

Upvotes: 9

Views: 8553

Answers (2)

Avijit Dasgupta
Avijit Dasgupta

Reputation: 2065

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!

Upvotes: 1

AndrewS
AndrewS

Reputation: 1676

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

Upvotes: 4

Related Questions