我希望在一段时间后停止我的Dash程序执行(当我关闭浏览器窗口时更好,尽管我怀疑这是可能的)。有没有办法通过python中断它?
我已经尝试过了
sys.exit()
在调用app.run_server之后。据我所知,很难
app.run_server
是一个无限循环,因此我永远不会到达sys.exit()
if __name__ == '__main__':
app.title = 'foo'
app.run_server(debug=False)
sys.exit("Bye!")
由于plotly
使用flask
作为服务器。所以你实际上从未达到过代码sys.exit("Bye!")
,因此你的服务器永远不会停止。所以有两种方法可以阻止你的服务器,
以下是Flask的代码,您需要将其转换为等效的plotly代码:
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()
现在您可以通过调用此函数来关闭服务器:
@app.route('/shutdown', methods=['POST'])
def shutdown():
shutdown_server()
return 'Server shutting down...'
更新:对于plotly,您可以按以下方式编写代码。
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')
])
def shutdown():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
@app.callback(dash.dependencies.Output('page-content', 'children'),
[dash.dependencies.Input('url', 'pathname')])
def display_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)