1

I can't get Warnings module to work in Python 2.7 Inside a user defined function I have:

warnings.simplefilter('always', UserWarning) #added after wouldn't work 
warnings.warn('WARNING: ....')
print "Why didn't the warning above show up?"

The print statement appears, but not the warning on the terminal. I made sure to do import warnings as well. Not sure what is happening.

1 Answer 1

2

Try placing under warnings.warn('WARNING: ....') this call: sys.stderr.flush()

If you check warnings module documentation, you would find: "The determination whether to issue a warning message is controlled by the warning filter, which is a sequence of matching rules and actions." Could be a filter issue. Try to flush stderr first and see what happens.

Sign up to request clarification or add additional context in comments.

6 Comments

Ayy that worked! Thank you! I'm a bit confused why this occurred? If I didn't have stackoverflow then I would be screwed right now. It seems weird it would work sometimes and not others...
Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush() / sys.stderr.flush() forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.
Okay thanks. Also, why can't I write on the next line? warnings.warn('.....\ continuing') where continuing is on the next line in the IDE. It gives me an error yet it's the same line continuation as always
Unsure what you mean by next line; but, you may want to look into python's escape characters like \n, which forces output to a new line. It looks like warnings.formatwarning(message, category, filename, lineno[, line]) supports output to a newline. docs.python.org/2/library/warnings.html
Hi no I just mean I can't continue where I left off on the new line. My message is rather long and I don't want to write everything on the same line so I want to continue where I left off on the next line without issuing a new warning. \ is the character which usually works, but it's not working here
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.