将Python的控制台输出重定向到Dash

时间:2018-08-28 12:09:25

标签: python plotly plotly-dash

如何重定向/显示控制台输出(包括我在程序内部打印的输出),使其显示在Dash应用程序中(用户看到的屏幕上)?

3 个答案:

答案 0 :(得分:1)

我没有找到Dash直接读取控制台输出的方法,因此我使用了一种使用文本文件的解决方法。 以下是示例代码,该示例代码将控制台输出的最后20行打印到iframe(以保持换行符的作用,这些行不显示在其他text / div组件中):

import dash_core_components as dcc
import dash_html_components as html
import dash
import sys

f = open('out.txt', 'w')
f.close()


app = dash.Dash()

app.layout = html.Div([
    dcc.Interval(id='interval1', interval=1 * 1000, 
n_intervals=0),
    dcc.Interval(id='interval2', interval=5 * 1000, 
n_intervals=0),
    html.H1(id='div-out', children=''),
    html.Iframe(id='console-out',srcDoc='',style={'width': 
'100%','height':400})
])

@app.callback(dash.dependencies.Output('div-out', 
'children'),
    [dash.dependencies.Input('interval1', 'n_intervals')])
def update_interval(n):
    orig_stdout = sys.stdout
    f = open('out.txt', 'a')
    sys.stdout = f
    print 'Intervals Passed: ' + str(n)
    sys.stdout = orig_stdout
    f.close()
    return 'Intervals Passed: ' + str(n)

@app.callback(dash.dependencies.Output('console-out', 
'srcDoc'),
    [dash.dependencies.Input('interval2', 'n_intervals')])
def update_output(n):
    file = open('out.txt', 'r')
    data=''
    lines = file.readlines()
    if lines.__len__()<=20:
        last_lines=lines
    else:
        last_lines = lines[-20:]
    for line in last_lines:
        data=data+line + '<BR>'
    file.close()
    return data

app.run_server(debug=False, port=8050)

答案 1 :(得分:0)

执行此操作的一种可能方法是将其提供为Dash Core Component Text Area的value属性的输入。如果它是字符串,这应该可以工作。

答案 2 :(得分:0)

创建一个 custom LoggerHandler,并使用 dcc.Interval 进行刷新。

import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import dash
import logging

class DashLoggerHandler(logging.StreamHandler):
    def __init__(self):
        logging.StreamHandler.__init__(self)
        self.queue = []

    def emit(self, record):
        msg = self.format(record)
        self.queue.append(msg)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
dashLoggerHandler = DashLoggerHandler()
logger.addHandler(dashLoggerHandler)

app = dash.Dash()

app.layout = html.Div([
    dcc.Interval(id='interval1', interval=5 * 1000, n_intervals=0),
    html.H1(id='div-out', children='Log'),
    html.Iframe(id='console-out',srcDoc='',style={'width': '100%','height':400})
])

@app.callback(
    Output('console-out', 'srcDoc'),
    Input('interval1', 'n_intervals'))
def update_output(n):
    return ('\n'.join(dashLoggerHandler.queue)).replace('\n', '<BR>')

app.run_server(debug=False, port=8050)