LaVOZs

The World’s Largest Online Community for Developers

'; How to run python script on clicking button? - LavOzs.Com

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.

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
Related
How do I merge two dictionaries in a single expression?
How do I check whether a file exists without exceptions?
Calling an external command from Python
What are metaclasses in Python?
Is there a way to run Python on Android?
Does Python have a ternary conditional operator?
How to get the current time in Python
<button> vs. <input type=“button” />. Which to use?
How to create an HTML button that acts like a link?
Does Python have a string 'contains' substring method?