5

I have become aware that the print statements in my django app are causing wsgi to error and fail. Without going over all my code and removing/commenting out the print statements, is there a way I can disable them when running wsgi. It needs to be a simple as possible.

Thanks

2 Answers 2

9

Use WSGIRestrictStdout option:

WSGIRestrictStdout Off

or replace sys.stdout with sys.stderr in Django WSGI star script:

import sys
sys.stdout = sys.stderr

Writing To Standard Output

No WSGI application component which claims to be portable should write to standard output. That is, an application should not use the Python print statement without directing output to some alternate stream. An application should also not write directly to sys.stdout.

4
  • Excellent. Worked spot on. I used the second option. Thanks for your help Feb 24, 2011 at 9:59
  • I have to disagree with the statement about logging to stdout. There are a lot of applications which adhere to the 12factor app principles 12factor.net/logs Nov 11, 2015 at 7:43
  • @LloydMoore I can certainly see the value of the 12factor app principle linked, and I agree with all the advantages (though stderr has similar advantages): The problem is that logging to stdout conflicts with writing request responses to stdout, which some WSGI implementations require that, the same way CGI did (which is sorta going with the original Unix-y take on file output streams, where stdout is where the results or answer of a program to its requested task go, and stderr is where other diagnostics/etc go).
    – mtraceur
    Dec 22, 2017 at 23:16
  • @mtraceur I completely agree. My comment was more a gripe with the WSGI policy although the documentation does explain why it's in place. Dec 27, 2017 at 19:58
2

In general, it is better to use logging for any kind of debug output in a web app and never use print statements at all. Or use them in the form:

print >> environ['wsgi.errors'], "message to be printed"

It is best to get rid of sys.stdout by making it a copy of sys.stderr just in case.

If you do development on a UNIX server, you can have two terminal windows open, one to run Django and the second one to do

tail -f loggingfile

And you get pretty much the same effect as using print statements, but you can use the standard logging module to generate the output, and in the production app, you just change the filter setting to not show DEBUG level messages.

1
  • In the future that sounds Ideal. I will try and add this to my code as I go through it. I knew I was doing it wrong when I started doing it, but it was just more to add to my learning curve. Thanks :D Feb 24, 2011 at 10:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .