简体   繁体   中英

Execute linux command with Python CGI

i'm trying to making a Python CGI script for control my Raspberry PI board, i would like to turn on/off a led from a web page, but the script don't work, this is the code for trial.py :

#!/usr/bin/python
import subprocess
import cgi
print("Content-Type: text/html\n\n")
print('<html><body>')
print('<p>Hello World!</p>')
print('</body></html>')

subprocess.call(["/bin/gpio -g write 23 1"])

where i have set the pin 23 to out mode from shell

i get the following error if i run it with python trial.py

Traceback (most recent call last):
  File "trial.py", line 9, in <module>
    subprocess.call(["/bin/gpio -g write 23 1"])
  File "/usr/lib/python3.4/subprocess.py", line 537, in call
    with Popen(*popenargs, **kwargs) as p:
  File "/usr/lib/python3.4/subprocess.py", line 858, in __init__
    restore_signals, start_new_session)
  File "/usr/lib/python3.4/subprocess.py", line 1456, in _execute_child
    raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: '/bin/gpio -g write 23 1

while if i run it from localhost/cgi-bin/trial.py it print Hello World with no Error

Any Idea ?

Thank U

With the raspberry pi, there are several methods you can use to turn on and off the GPIO pins. This is not to my knowledge one of them.

An easy way is simply to call the following code once.

open("/sys/class/gpio/export", "w").write("23")
open("/sys/class/gpio/gpio23/direction", "w").write("out")

This will export and set up the gpio pin for output mode. Then, call the following code to turn the pin on.

open("/sys/class/gpio/gpio23/value", "w").write("1")

If you use a 0 instead of a 1, then the pin will be turned off.

Alternatively, you could use RPI.GPIO , with something resembling the following code.

import RPi.GPIO as GPIO
# You need to use pin 16, as RPi.GPIO maps to the physical locations of the pins,
# not their BCM names.
GPIO.setup(16, GPIO.OUT)
GPIO.output(16, 1) # Or 0

Hope this is of help.

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