Roe*_*uar 5 python plotly plotly-dash
如何重定向/显示控制台输出(包括我在程序中打印的输出),以便它出现在 Dash 应用程序中(在用户看到的屏幕上)?
我没有找到让 Dash 直接读取控制台输出的方法,所以我使用了一个使用文本文件的解决方法。这是一个示例代码,它将控制台输出的最后 20 行打印到 Iframe(以保留换行符,不会在其他文本/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)
Run Code Online (Sandbox Code Playgroud)