Python warning management

I would like some kind of warning to sound like errors, but only the first entry. How to do it?

I am reading http://docs.python.org/library/warnings.html and I do not know how to combine these two types of behavior.

+4
source share
1 answer

Looking at the code for warnies.py, you cannot assign a warning to more than one filter, and you cannot (easily) define your own actions, for example, "raise_once".

However, if you want to raise a warning as an exception, but only once, it means that you catch the exception. Why not put a line in your except clause that sets the ignore action for this particular warning?

#!/usr/bin/python import warnings warnings.filterwarnings('error','Test') for i in range(2): try: warnings.warn('Test'); except UserWarning, e: print "Error caught" warnings.filterwarnings('ignore','Test') 
+7
source

All Articles