Based on hippy's code.Running python from python to grab the stdout is not a good way.
Use modules as intended. Import it and use the function to get a state of GPIO pins.
If there is a problem with access rights for gpio, then add your user to the group gpio.
main.py
pins.pytemplates/index.tpl
Use modules as intended. Import it and use the function to get a state of GPIO pins.
If there is a problem with access rights for gpio, then add your user to the group gpio.
main.py
Code:
import timefrom flask import Flask, render_templatefrom pins import get_stateapp = Flask(__name__)@app.route("/")def home(): state = get_state() return render_template( "index.tpl", now=time.strftime("%Y-%m-%d %H:%M:%S"), state=state )app.run(host="127.0.0.2", port=8080, debug=True)pins.py
Code:
import randomfrom gpiozero import Button, Device# remove this, if you run the code on a Raspberry Pi# otherwise it's emulatedfrom gpiozero.pins.mock import MockFactoryPINS = (0, 1, 5, 6)# remove this, if GPIO is availableDevice.pin_factory = MockFactory()# creating Button from Pins# Buttons do have helpful attributes and methods# callbacks are also supportedBUTTONS = [Button(n) for n in PINS]def _choice() -> bool: """ Function which returns True or False It's used only for random states of GPIOs """ return random.choice([True, False])def get_state() -> dict[str, bool]: # setting random state of Buttons # don't do this, if you want the real state of GPIOs for button in BUTTONS: if _choice(): button.pin.drive_high() else: button.pin.drive_low() # retuns a dict, where the keys are str like Pin 0, Pin 1, ... # the values are int, which are converted to boolean to represent the state return {f"Pin {str(b.pin).removeprefix('GPIO')}": bool(b.value) for b in BUTTONS}Code:
<html> <head> <meta http-equiv="refresh" content="1"> </head> <body> <h2>It is now {{ now }}</h2> <table> {% for item in state.items() %} <tr> <td color="{{ '#00FF00' if item[1] else '#FF0000' }}">{{ item[0] }}</td> </tr> {% endfor %} </table> </body></html>Statistics: Posted by DeaD_EyE — Thu Nov 27, 2025 10:19 am