MSD
MSD

Reputation: 161

How to run python script on clicking button?

Goal: I have never done this before, and am new to python. I want to run a python script on call as a button is pushed.

Question: Can someone give pointers as to how to go about solving this?

My Code:

**Button HTML**
    # Layout of Dash App HTML
    app.layout = html.Div(
        children=[
            html.Div(
                            html.Button('Detect', id='button'),
                            html.Div(id='output-container-button',
                            children='Hit the button to update.')
                         ],
                    ),
                ],
            )

@app.callback(
    dash.dependencies.Output('output-container-button', 'children'),
    [dash.dependencies.Input('button')])
def run_script_onClick():
    return os.system('python /Users/ME/Desktop/DSP_Frontend/Pipeline/Pipeline_Dynamic.py')

Currently this gives the error:

Traceback (most recent call last):
  File "app.py", line 592, in <module>
    [dash.dependencies.Input('button')])
TypeError: __init__() missing 1 required positional argument: 'component_property'

EDIT:

I think the solution might be to add some_argument to the run_script_onClick:

def run_script_onClick(some_argument):
        return os.system('python /Users/ME/Desktop/DSP_Frontend/Pipeline/Pipeline_Dynamic.py')

I am currently browsing through this list to find an appropriate item() to use as argument.

Upvotes: 2

Views: 4017

Answers (2)

Abimbola Ojikutu
Abimbola Ojikutu

Reputation: 477

@ Yaakov Bressler. This works for me without using the following lines. Thanks a lot.

output_content = some_loading_function('output file')
    return output_content

Upvotes: 1

Yaakov Bressler
Yaakov Bressler

Reputation: 12018

Here's what I would use:

from subprocess import call
from dash.exceptions import PreventUpdate

@app.callback(
    dash.dependencies.Output('output-container-button', 'children'),
    [dash.dependencies.Input('button', 'n_clicks')])
def run_script_onClick(n_clicks):
    # Don't run unless the button has been pressed...
    if not n_clicks:
        raise PreventUpdate

    script_path = 'python /Users/ME/Desktop/DSP_Frontend/Pipeline/Pipeline_Dynamic.py'
    # The output of a script is always done through a file dump.
    # Let's just say this call dumps some data into an `output_file`
    call(["python3", script_path])

    # Load your output file with "some code"
    output_content = some_loading_function('output file')

    # Now return.
    return output_content

Upvotes: 5

Related Questions