Skip to content Skip to sidebar Skip to footer

Plotly / Dash - Python How To Stop Execution After Time?

I want to stop my Dash Program from executing after a certain amount of time (even better when I close the browser window, though I doubt that's possible). Is there a way to interr

Solution 1:

Since plotly uses flask for the server. So you code sys.exit("Bye!") is actually never reached, hence your server is never stopped. So there are 2 ways to stop your server,

  • Ctrl + c which I assume you would be doing now

  • Now you can do it using code too, so if you really need to stop the code after some time you should stop the flask server. To stop flask server you need to create a route. So whenever you hit that url the server would stop.

Following is the code is for Flask, you need to transform it to equivalent plotly code:

from flask import request

def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

Now you can shutdown the server by calling this function:

@app.route('/shutdown', methods=['POST'])defshutdown():
    shutdown_server()
    return'Server shutting down...'

Update: For plotly you can write the code in the following way.

import dash
import dash_core_components as dcc
import dash_html_components as html
from flask import request

print(dcc.__version__) # 0.6.0 or above is required

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div([
    # represents the URL bar, doesn't render anything
    dcc.Location(id='url', refresh=False),

    dcc.Link('Navigate to "/"', href='/'),
    html.Br(),
    dcc.Link('Navigate to "/page-2"', href='/page-2'),

    # content will be rendered in this element
    html.Div(id='page-content')
])

defshutdown():
    func = request.environ.get('werkzeug.server.shutdown')
    if func isNone:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@app.callback(dash.dependencies.Output('page-content', 'children'),
              [dash.dependencies.Input('url', 'pathname')])defdisplay_page(pathname):
    if pathname =='/shutdown':
        shutdown()
    return html.Div([
        html.H3('You are on page {}'.format(pathname))
    ])


if __name__ == '__main__':
    app.run_server(debug=True)

Solution 2:

def button():
        button_reply = QMessageBox.question(MainWindow, "Bank Management System", "Deposited Successfully", QMessageBox.Ok)
        if button_reply == QMessageBox.Ok:
            Deposit()//execute deposite functionfirst
            threading.Timer(5.0,clearData).start()// clrarData function will execute after 5 seconds

Post a Comment for "Plotly / Dash - Python How To Stop Execution After Time?"