如何从 Flask @app.route 打印到 python 控制台
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32550487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print from Flask @app.route to python console
提问by Robert Filter
I would like to simply print a "hello world" to the python console after /button is called by the user.
我想在用户调用 /button 后简单地将“hello world”打印到 python 控制台。
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!
背景:我想从flask(不是shell)执行其他python命令。“打印”应该是最简单的情况。我相信我还没有理解这里的基本转折。提前致谢!
采纳答案by Gabe
It seems like you have it worked out, but for others looking for this answer, 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
Flask 将在控制台中显示打印到 stderr 的内容。有关打印到 stderr 的其他方式,请参阅此 stackoverflow 帖子
回答by Viraj Wadate
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)
回答by Chris
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).
我认为 Flask 的核心问题是 stdout 被缓冲。我能够使用print('Hi', flush=True)
. 您还可以通过设置PYTHONUNBUFFERED
环境变量(任何非空字符串)来禁用缓冲。