如何在树莓派上通过Nginx从HTML页面运行Python脚本?
Got it, let’s get your web interface to trigger that motor script—here’s a couple of solid approaches tailored to your existing Raspberry Pi Zero setup:
Since you already have Nginx up and running, using CGI is the easiest way to bridge your static HTML page to your Python motor script.
First, install
fcgiwrap(Nginx doesn’t handle CGI directly, so this tool acts as a middleman):sudo apt-get update && sudo apt-get install fcgiwrapEdit your Nginx config (usually at
/etc/nginx/sites-available/default) to enable CGI support. Add this block inside your existingserversection:location /cgi-bin/ { root /var/www; fastcgi_pass unix:/var/run/fcgiwrap.socket; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }Restart Nginx to apply changes:
sudo systemctl restart nginxCreate a CGI script to trigger your motor code. Make a
/var/www/cgi-bin/directory if it doesn’t exist, then add a file namedrun_motor.cgi:#!/usr/bin/env python3 print("Content-Type: text/html\n") print("<html><body>") import subprocess try: # Replace with the actual path to your motor script subprocess.run(["python3", "/home/pi/motor_run.py"], check=True) print("<p>Motor started successfully!</p>") except subprocess.CalledProcessError as e: print(f"<p>Error running motor: {str(e)}</p>") print("<a href='/'>Back to control page</a>") print("</body></html>")Fix permissions so the Nginx user (
www-data) can run the script:sudo chmod +x /var/www/cgi-bin/run_motor.cgi # Give www-data access to GPIO (critical for motor control) sudo usermod -aG gpio www-dataUpdate your
/var/www/html/index.htmlto add a trigger button:<!DOCTYPE html> <html> <body> <h1>Motor Control</h1> <button onclick="window.location.href='/cgi-bin/run_motor.cgi'">Start Motor</button> <!-- Alternative: Use a POST form to avoid browser caching issues --> <form action="/cgi-bin/run_motor.cgi" method="post" style="margin-top:10px;"> <input type="submit" value="Start Motor (POST)"> </form> </body> </html>
Since you mentioned wanting to let users customize parameters (like run time or schedule), a lightweight Flask app is perfect for this—it lets you build interactive forms easily.
Install Flask:
sudo pip3 install flaskCreate a Flask app file (e.g.,
/home/pi/motor_app.py):from flask import Flask, render_template, request import subprocess app = Flask(__name__) # Main page with parameter form @app.route('/') def index(): return render_template('index.html') # Handle motor trigger with custom params @app.route('/trigger_motor', methods=['POST']) def trigger_motor(): # Get user input from form (default to 5 seconds if not specified) run_seconds = request.form.get('run_seconds', default=5, type=int) try: # Pass the custom run time to your motor script subprocess.run(["python3", "/home/pi/motor_run.py", str(run_seconds)], check=True) return f"<p>Motor running for {run_seconds} seconds! <a href='/'>Back to control</a></p>" except subprocess.CalledProcessError as e: return f"<p>Error: {str(e)} <a href='/'>Back to control</a></p>" if __name__ == '__main__': # Run the app on all network interfaces (so your phone can reach it) app.run(host='0.0.0.0', port=80, debug=True)Create a
templatesfolder next to your Flask app, and addindex.htmlinside it:<!DOCTYPE html> <html> <body> <h1>Custom Motor Control</h1> <form action="/trigger_motor" method="post"> <label>Run time (seconds):</label> <input type="number" name="run_seconds" min="1" max="60" value="5"> <br><br> <input type="submit" value="Start Motor"> </form> </body> </html>Run the Flask app (to keep it running in the background, use
nohupor set up a systemd service):nohup python3 /home/pi/motor_app.py &
- Connect your phone to the Pi’s AP, visit
192.168.4.1, and click the button—your motor should run! - If it doesn’t work, check logs:
# Nginx error logs sudo tail -f /var/log/nginx/error.log # Flask logs (if using that approach) cat nohup.out - Double-check that
www-datais in thegpiogroup (you may need to reboot the Pi for this to take full effect).
内容的提问来源于stack exchange,提问作者Bradderz

