使用Python CGI执行Linux命令
我正在尝试制作一个Python CGI脚本来控制我的树莓派板子,我想通过网页来开关一个LED灯,但这个脚本不工作,这是我试验的代码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"])
我已经在命令行中把23号引脚设置为输出模式
如果我用命令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
但是如果我从localhost/cgi-bin/trial.py运行它,就会打印“Hello World”,而且没有错误
有什么想法吗?
谢谢你
1 个回答
0
使用树莓派时,有几种方法可以控制GPIO引脚的开关。不过,按照我的了解,这里提到的方法并不是其中之一。
一种简单的方法是只需运行以下代码一次。
open("/sys/class/gpio/export", "w").write("23")
open("/sys/class/gpio/gpio23/direction", "w").write("out")
这段代码会将GPIO引脚设置为输出模式。
然后,运行以下代码可以把引脚打开。
open("/sys/class/gpio/gpio23/value", "w").write("1")
如果你用0代替1,那么引脚就会关闭。
另外,你也可以使用RPI.GPIO库,代码大致如下。
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
希望这些信息对你有帮助。