How to print from Flask @app.route to python console

146,107

Solution 1

An easy way to do this is by printing to stderr. You can do that like this:

from __future__ import print_function # In python 2.7
import sys
@app.route('/button/')
def button_clicked():
    print('Hello world!', file=sys.stderr)
    return redirect('/')

Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post

Solution 2

We can also use logging to print data on the console.

Example:

import logging
from flask import Flask
app = Flask(__name__)
@app.route('/print')
def printMsg():
    app.logger.warning('testing warning log')
    app.logger.error('testing error log')
    app.logger.info('testing info log')
    return "Check your console"
if __name__ == '__main__':
    app.run(debug=True)

Solution 3

I think the core issue with Flask is that stdout gets buffered. I was able to print with print('Hi', flush=True). You can also disable buffering by setting the PYTHONUNBUFFERED environment variable (to any non-empty string).

Solution 4

I tried running @Viraj Wadate's code, but couldn't get the output from app.logger.info on the console.

To get INFO, WARNING, and ERROR messages in the console, the dictConfig object can be used to create logging configuration for all logs (source):

from logging.config import dictConfig
from flask import Flask
dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {'wsgi': {
        'class': 'logging.StreamHandler',
        'stream': 'ext://flask.logging.wsgi_errors_stream',
        'formatter': 'default'
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    }
})
app = Flask(__name__)
@app.route('/')
def index():
    return "Hello from Flask's test environment"
@app.route('/print')
def printMsg():
    app.logger.warning('testing warning log')
    app.logger.error('testing error log')
    app.logger.info('testing info log')
    return "Check your console"
if __name__ == '__main__':
    app.run(debug=True)
Share:
146,107

Related videos on Youtube

Robert Filter
Author by

Robert Filter

If you like electrodynamic problems with solutions and their connections to current research, please visit photonics101.com

Updated on July 16, 2021

Comments

  • Robert Filter
    Robert Filter almost 2 years

    I would like to simply print a "hello world" to the python console after /button is called by the user.

    This is my naive approach:

    @app.route('/button/')
    def button_clicked():
        print 'Hello world!'
        return redirect('/')
    

    Background: I would like to execute other python commands from flask (not shell). "print" should be the easiest case. I believe I have not understood a basic twist here. Thanks in advance!

    • Daniel Roseman
      Daniel Roseman over 7 years
      You're confusing two things here. You can call any functions you like from a handler; but the issue with print is what Flask is doing to stdout.
    • Robert Filter
      Robert Filter over 7 years
      Hi @DanielRoseman and thanks for the comment! So flask is somewhat routing the print to http? What should I do to prevent this? Sorry if the question is silly :)
    • Ciaran Liedeman
      Ciaran Liedeman over 7 years
      There are no silly questions :)
    • dirn
      dirn over 7 years
      Flask does not route print to the response. If you are running the development server from a terminal session, you will see the output there. If you are running it through a WSGI server such as uWSGI, the output will appear in the logs instead.
    • Ciaran Liedeman
      Ciaran Liedeman over 7 years
      How are you starting flask?
    • Robert Filter
      Robert Filter over 7 years
      Hi @ciaran, i am starting the script from pyscripter. This should be equivalent to python myscript.py
    • Robert Filter
      Robert Filter over 7 years
      Just to add that all have been right. Print is simply not meant here to provide output in the console.
    • Austin Pray
      Austin Pray over 4 years
      Might be worth checking this out: gitlab.com/meltano/meltano/issues/106#note_105372174
  • Robert Filter
    Robert Filter over 7 years
    Thx @Gabe, this seems to be a way to go.
  • e271p314
    e271p314 almost 6 years
    Do I really need to go over all files and add from __future__ import print_function also file=sys.stderr for every print? is there a short way to it?
  • Gabe
    Gabe almost 6 years
    I would recommend taking a look at the post I linked to in the original answer. There's one person recommends defining a function which always prints to stderr (you could put this in a util file that you already import). Another person recommends sys.stderr.write.
  • phoenix
    phoenix over 4 years
    You could also save a little bit of repetition with: from sys import stderr, file=stderr. In Python 3+, you don't need from __future__ import print_function, that is the default functionality.
  • jcroll
    jcroll about 4 years
    If dumping an object this seems to work pprint(vars(myobject), sys.stderr)
  • gunslingor
    gunslingor over 3 years
    See this if you cannot get the info logger to work: flask.palletsprojects.com/en/1.0.x/logging
  • learner0000
    learner0000 about 3 years
    This is the best way for print-debugging, especially in small projects
  • thanos.a
    thanos.a about 3 years
    What is the value that should be set in the PYTHONUNBUFFERED env variable ?
  • Chris
    Chris about 3 years
    @thanos.a You can set it to any non-empty string. I updated the answer.
  • thanos.a
    thanos.a about 3 years
    You can add an example like PYTHONUNBUFFERED="anything_here"
  • Anonymous12332313
    Anonymous12332313 almost 2 years
    I'm using flask run to run the app from command prompt. I'm using pycharm as my IDE. In run configurations I have it set to emulate terminal in output console. When I try this, nothing prints in either the terminal or the python console. Any idea of what's not working?