Home > Net >  Run a Python script in Dash Callback
Run a Python script in Dash Callback

Time:03-30

I'm trying to run a Python script in a Dash callback function but my current code is not doing it as I intended. For example, there's a button called "Open" and once a user click on it, it will open a modal and run the python script. On the modal page, there's another button called "Close" and if the user click on the close button, it will simply close the modal page but not run the python script.

This is the current callback function I have but the problem is that it runs the python script when I hit the "Close" button as well. Which part should I change to make the python script run only when a user click on the "Open" button but not the "Close" button?

@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

CodePudding user response:

If is_open == True, then the modal is open. So check if it's NOT equal to True (since when you click on open it hasn't been changed to True yet), in which case run the script, otherwise just return not is_open without running it. Example:

@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

CodePudding user response:

This is because n_clicks is actually an integer that represents the number of times the button has been clicked (original value is None).

You should use dash.callback_context to properly 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
  • Related