如何在一定时间后停止执行?

4
我想在一定时间后停止我的Dash程序(最好在关闭浏览器窗口时停止,虽然我怀疑这是不可能的)。是否有一种通过Python中断它的方法?
我已经尝试过放置一个``标签在HTML头部,但这并不能真正停止执行。
sys.exit() 

在调用app.run_server之后。尽管我理解app.run_server是在一个无限循环中运行代码,因此我永远不会到达sys.exit()

if __name__ == '__main__':
    app.title = 'foo'
    app.run_server(debug=False)
    sys.exit("Bye!")
2个回答

8
由于`plotly`使用`flask`作为服务器,因此您的`sys.exit(“Bye!”)`代码实际上永远不会被执行,因此服务器永远不会停止。因此有两种方法可以停止服务器:
  • Ctrl + C,我假设你正在做

  • 现在您也可以使用代码来完成,因此,如果您确实需要在一段时间后停止代码,则应停止flask服务器。要停止flask服务器,您需要创建一个路由。因此,每当您点击该网址时,服务器都将停止。

以下是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)

感谢您的快速回复,但是我遇到了以下 AttributeError 错误:'Dash' 对象没有 'route' 属性。 - wieli99
1
抱歉我给你的是Flask的语法。你需要将代码转换为Plotly。 https://dash.plot.ly/urls - Arghya Saha
@wieli99 不确定。但我猜你的第一个问题现在已经解决了。你可以关闭应用程序了。 - Arghya Saha
大家好,当我使用之前的代码来停止在我的本地机器上运行的Dash应用时,我遇到了一个错误。这是什么意思?我该如何找到它正在使用的正确服务器??raise RuntimeError('Not running with the Werkzeug Server') RuntimeError: Not running with the Werkzeug Server - undefined
当我在浏览器中访问insect时,我看到以下数值:服务器:Werkzeug/2.2.2 Python/3.9.17尽管如此,访问/shutdown端点时却出现错误,提示“未在Werkzeug服务器上运行”。 - undefined

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

这是PyQt代码,不是Dash。我猜这个账户是一个机器人? - Axel Jacobsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接