运行 Dash 回调中的 Python 脚本
Run a Python script in Dash Callback
我正在尝试 运行 Dash 回调函数中的 Python 脚本,但我当前的代码没有按预期执行。例如,有一个名为“打开”的按钮,一旦用户单击它,它将打开一个模式和 运行 python 脚本。在模态页面上,还有另一个名为“关闭”的按钮,如果用户单击关闭按钮,它只会关闭模态页面而不是 运行 python 脚本。
这是我当前的回调函数,但问题是当我点击“关闭”按钮时,它 运行 也是 python 脚本。只有当用户单击“打开”按钮而不是“关闭”按钮时,我应该更改哪一部分才能使 python 脚本 运行?
@app.callback(
Output("modal", "is_open"),
[Input("open-button", "n_clicks"), Input("close-button", "n_clicks")],
[State("modal", "is_open")],
)
def activate_modal(n1, n2, is_open):
if n1 or n2:
script_fn = my_script.py"
exec(open(script_fn).read())
return not is_open
return is_open
如果is_open == True
,则模态打开。所以检查它是否不等于 True(因为当你点击打开时它还没有被更改为 True),在这种情况下 运行 脚本,否则只是 return not is_open
没有运行宁它。示例:
@app.callback(
Output("modal", "is_open"),
[Input("open-button", "n_clicks"), Input("close-button", "n_clicks")],
[State("modal", "is_open")],
)
def activate_modal(n1, n2, is_open):
if n1 or n2:
if not is_open:
script_fn = "my_script.py"
exec(open(script_fn).read())
return not is_open
return is_open
这是因为n_clicks
实际上是一个表示按钮被点击次数的整数(原值为None
)。
你应该使用 dash.callback_context
来正确 determine which input has fired :
@app.callback(
Output("modal", "is_open"),
[Input("open-button", "n_clicks"), Input("close-button", "n_clicks")],
[State("modal", "is_open")],
)
def activate_modal(n1, n2, is_open):
ctx = dash.callback_context
if ctx.triggered:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id == "open-button"
script_fn = my_script.py
exec(open(script_fn).read())
return True
else
return False
return is_open
我正在尝试 运行 Dash 回调函数中的 Python 脚本,但我当前的代码没有按预期执行。例如,有一个名为“打开”的按钮,一旦用户单击它,它将打开一个模式和 运行 python 脚本。在模态页面上,还有另一个名为“关闭”的按钮,如果用户单击关闭按钮,它只会关闭模态页面而不是 运行 python 脚本。
这是我当前的回调函数,但问题是当我点击“关闭”按钮时,它 运行 也是 python 脚本。只有当用户单击“打开”按钮而不是“关闭”按钮时,我应该更改哪一部分才能使 python 脚本 运行?
@app.callback(
Output("modal", "is_open"),
[Input("open-button", "n_clicks"), Input("close-button", "n_clicks")],
[State("modal", "is_open")],
)
def activate_modal(n1, n2, is_open):
if n1 or n2:
script_fn = my_script.py"
exec(open(script_fn).read())
return not is_open
return is_open
如果is_open == True
,则模态打开。所以检查它是否不等于 True(因为当你点击打开时它还没有被更改为 True),在这种情况下 运行 脚本,否则只是 return not is_open
没有运行宁它。示例:
@app.callback(
Output("modal", "is_open"),
[Input("open-button", "n_clicks"), Input("close-button", "n_clicks")],
[State("modal", "is_open")],
)
def activate_modal(n1, n2, is_open):
if n1 or n2:
if not is_open:
script_fn = "my_script.py"
exec(open(script_fn).read())
return not is_open
return is_open
这是因为n_clicks
实际上是一个表示按钮被点击次数的整数(原值为None
)。
你应该使用 dash.callback_context
来正确 determine which input has fired :
@app.callback(
Output("modal", "is_open"),
[Input("open-button", "n_clicks"), Input("close-button", "n_clicks")],
[State("modal", "is_open")],
)
def activate_modal(n1, n2, is_open):
ctx = dash.callback_context
if ctx.triggered:
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
if button_id == "open-button"
script_fn = my_script.py
exec(open(script_fn).read())
return True
else
return False
return is_open