Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting Python's console output to Dash

How can I redirect/show the console output (including outputs I print inside the program) so it would appear inside a Dash app (On the screen the user sees)?

like image 634
Roee Anuar Avatar asked Aug 28 '18 12:08

Roee Anuar


People also ask

What is the use of dash in Python?

Dash is an open source framework for building data visualization interfaces. Released in 2017 as a Python library, it's grown to include implementations for R and Julia. Dash helps data scientists build analytical web applications without requiring advanced web development knowledge.

Is Plotly and dash the same?

Dash is a python framework created by plotly for creating interactive web applications. Dash is written on the top of Flask, Plotly. js and React.

Can a dash callback have multiple outputs?

Dash App With Chained CallbacksYou can also chain outputs and inputs together: the output of one callback function could be the input of another callback function. This pattern can be used to create dynamic UIs where, for example, one input component updates the available options of another input component.

Is Python dash secure?

It might not be easy to access, but if you could be a sensitive target then no, dash on your machine is not secure.


1 Answers

I didn't find a way for Dash to read the console output directly, so I used a workaround using a text file. Here is a sample code which prints the last 20 lines of the console output to an Iframe (as to keep the line breaks, which do not show in other text/div components):

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)
like image 153
Roee Anuar Avatar answered Sep 29 '22 08:09

Roee Anuar