使用Python CGI执行linux命令

时间:2014-07-29 15:26:06

标签: python cgi raspberry-pi

我试图制作一个用于控制我的Raspberry PI板的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"])

我已将pin 23设置为shell

的out模式

如果我使用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 :(得分: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

希望这有帮助。

相关问题