繁体   English   中英

使用Python CGI执行Linux命令

[英]Execute linux command with Python CGI

我正在尝试制作一个Python CGI脚本来控制我的Raspberry PI开发板,我想打开/关闭网页上的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且没有错误

任何想法 ?

感谢你

对于树莓派,您可以使用几种方法来打开和关闭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

希望这会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM