Flask doesn't print to console

前端 未结 5 1545
生来不讨喜
生来不讨喜 2020-12-28 12:49

I\'m new to flask, and I\'m trying to add print info to debug server side code. When launch my flask app with debug=True, i can\'t get any info print to console

I tr

相关标签:
5条回答
  • 2020-12-28 13:25

    By default the level for logging is warning. So you won't see a logging message of level DEBUG. To fix this just enable debug logging with the basicConfig() function of the logging module:

    import logging
    logging.basicConfig(level=logging.DEBUG)
    
    0 讨论(0)
  • 2020-12-28 13:38

    Try this and see if it helps:

    For python2:

    from __future__ import print_function
    import sys
    
    print('This is error output', file=sys.stderr)
    print('This is standard output', file=sys.stdout)
    

    For python3 you don't need to import from future print_function:

    import sys
    
    print('This is error output', file=sys.stderr)
    print('This is standard output', file=sys.stdout)
    

    See if it helps to print to console.

    0 讨论(0)
  • 2020-12-28 13:38

    You can force to flush stdout directly from print:

    print('enter getJSONReuslt', flush=True)
    

    This way you don't have to print to sys.stderr (which flushes by default).

    The reason for your problem is line buffering. Line buffering makes I/O more efficient with the drawback of not immediately showing prints under some conditions.

    0 讨论(0)
  • 2020-12-28 13:40

    you can use the app instance in development mode besause the logging level is set to DEBUG app.logger.info('This is info output') in production mode you need to use a more sever level or you can set the logging level to DEBUG

    from flask import Flask
    import logging
    
    app = Flask(__name__)
    
    logging.basicConfig(level=logging.DEBUG)
    
    @app.route('/')
    def hello_world():
        app.logger.info('Processing default request')
        return 'Hello World!'
    
    if __name__ == '__main__':
        app.run()
    

    this article talk about logging into flask https://www.scalyr.com/blog/getting-started-quickly-with-flask-logging/

    0 讨论(0)
  • 2020-12-28 13:52

    Had the same printing problem. Using sys.stdout.flush() after the print solved the issue.

    0 讨论(0)
提交回复
热议问题