Today I needed to add the printing of warning messages to a command line tool written in Python. So Instead of writing things out using print, wich is not flexible enough and goes against my way to avoid user interaction deep inside functions and classes, I decided to use the warnings module.
That was easy enough, just send a UserWarning, but I didn't like the way how the warning was printed, with line number and everything. So I had to find a way to make this nicer in this case. What I ended up with is this code in the beginning of the module:
# Overide the default format for warnings. _formatwarningBackup = warnings.formatwarning def _formatwarning(message, category, filename, lineno): if category is UserWarning: return 'WARNING: %s\n' % message else: return _formatwarningBackup(message, category, filename, lineno) warnings.formatwarning = _formatwarning
It seems a little bit dirty, but I think it is an acceptable solution. If a module somwhere uses the wanrings mechanism for something it should still appear as normal, while my own warnings are masked nicely and conforming with the other output of the program.
As I couldn't find any examples of how to do this when searching, I have now provided one. ;-)
[Sorry about the fact that indentation seems to go all wonky in the code block]