How to print from Flask @app.route to python console
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)
Related videos on Youtube

Robert Filter
If you like electrodynamic problems with solutions and their connections to current research, please visit photonics101.com
Updated on July 16, 2021Comments
-
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 over 7 yearsYou'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 over 7 yearsHi @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 over 7 yearsThere are no silly questions :)
-
dirn over 7 yearsFlask 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 over 7 yearsHow are you starting flask?
-
Robert Filter over 7 yearsHi @ciaran, i am starting the script from pyscripter. This should be equivalent to python myscript.py
-
Robert Filter over 7 yearsJust to add that all have been right. Print is simply not meant here to provide output in the console.
-
Austin Pray over 4 yearsMight be worth checking this out: gitlab.com/meltano/meltano/issues/106#note_105372174
-
-
Robert Filter over 7 yearsThx @Gabe, this seems to be a way to go.
-
e271p314 almost 6 yearsDo I really need to go over all files and add
from __future__ import print_function
alsofile=sys.stderr
for every print? is there a short way to it? -
Gabe almost 6 yearsI 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 over 4 yearsYou could also save a little bit of repetition with:
from sys import stderr
,file=stderr
. In Python 3+, you don't needfrom __future__ import print_function
, that is the default functionality. -
jcroll about 4 yearsIf dumping an object this seems to work
pprint(vars(myobject), sys.stderr)
-
gunslingor over 3 yearsSee this if you cannot get the info logger to work: flask.palletsprojects.com/en/1.0.x/logging
-
learner0000 about 3 yearsThis is the best way for print-debugging, especially in small projects
-
thanos.a about 3 yearsWhat is the value that should be set in the PYTHONUNBUFFERED env variable ?
-
Chris about 3 years@thanos.a You can set it to any non-empty string. I updated the answer.
-
thanos.a about 3 yearsYou can add an example like PYTHONUNBUFFERED="anything_here"
-
Anonymous12332313 almost 2 yearsI'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?