My minimum example is
#!/usr/bin/python3
import warnings
warnings.warn('Run Forest run!', stacklevel=2)
warnings.warn('Run Forest run!')
and it will output
sys:1: UserWarning: Run Forest run!
./file.py:6: UserWarning: Run Forest run!
warnings.warn('Run Forest run!')
The first line gives me to little info. The second line is perfect, giving me source file and line number ... but I'd like to get rid of the redundant third line. Is that possible?
showwarning(message, category, filename, lineno, file=None, line=None): This function Writes a warning to a file. simplefilter(action, category=Warning, lineno=0, append=False): This function adds a single entry into the warnings filter requirements list.
showwarning() This method is used to display the warning to the user.
When nothing else works: $ pip install shutup . Then at the top of the code import shutup;shutup. please() . This will disable all warnings.
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
The reason you are getting the "redundant" line is because if you don't provide the stacklevel
parameter the default stacklevel
is 1, which is basically telling the user the exact line of code that the warning originated from, which is your warning function call warnings.warn('Run Forest Run!')
.
If you're not happy with the way it functions, you can use the warnings.warn_explicit()
function to customise it.
https://docs.python.org/3.1/library/warnings.html#available-functions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With