122

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.

starball
  • 20,030
  • 7
  • 43
  • 238
Robert Filter
  • 1,661
  • 3
  • 12
  • 14

4 Answers4

154

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

Alan W. Smith
  • 24,647
  • 4
  • 70
  • 96
Gabe
  • 1,722
  • 1
  • 11
  • 7
  • 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? – e271p314 Jul 14 '17 at 20:13
  • 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. – Gabe Jul 15 '17 at 21:41
  • 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. – phoenix Jan 13 '19 at 15:32
  • If dumping an object this seems to work `pprint(vars(myobject), sys.stderr)` – jcroll Mar 14 '19 at 19:35
  • 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? – Anonymous12332313 Aug 19 '21 at 19:33
38

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)
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
Viraj Wadate
  • 5,447
  • 1
  • 31
  • 29
26

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).

Chris
  • 4,734
  • 2
  • 19
  • 26
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)

Saurabh
  • 5,176
  • 4
  • 32
  • 46