2017-10-20 5 views
1

Ceci est mon code que j'écrit:Comment utiliser: python warnings.warn()?

#usr/bin/python3 
import warnings 

def tt(): 

    warnings.warn("123") 

    return 10 

x = tt() 

print(x) 

Il imprime:

test.py:5: UserWarning: 123 

warnings.warn("123") 

10 

Je veux seulement imprimer:

test.py:5: UserWarning: 123 
10 

Sans warnings.warn("123").

Que dois-je faire?

Répondre

0

Vous pouvez remplacer la fonction utilisée pour formater les messages; par exemple:

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

0
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!