简体   繁体   中英

calling python function from html button to run shell command

What I am trying to do is call a function from the python script I have defined to run a simple gpio shell command.

I don't need it to return or go anywhere, just run the command and stay on the page.

Here is what I have.

from flask import Flask, render_template
import subprocess

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/main')
def main():
    return render_template('main.html')

#setup calls for hardware to set state
subprocess.call(['./gpio-out.sh'])


def pin0on():
    subprocess.call(['gpio write 0 1'])

def pin0off():
    subprocess.call(['gpio write 0 0'])

I have been trying to call it with {{ pin0on }} or off.

The page with the buttons is main.html with just a simple page with two buttons. I am using href to call it. I can't seem to find anything along these lines anywhere. Or I may be just doing this wrong.

You have to put the code in a view function:

@app.route('/on')
def turn_on():
    subprocess.call(['gpio write 0 1'], shell=True)
    return '', 204  # no content

Then in the template, the button will like this:

<a href="{{ url_for('turn_on') }}">Turn on</a>

When the button was clicked, it will trigger the turn_on view function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM