我想做的是,当浏览器尝试访问我的 Raspberry Pi URL ( http://192.168.10.191:5000/console ) 时,LED 将亮起,无需在前端输入任何 python,但目前,我仍然需要在 Web 控制台上输入 python 使其按预期运行。
代码如下:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/user')
def here():
return '<h1>user here</h>'
@app.route('/console')
def console():
import pexpect
child = pexpect.spawn('python')
child.expect('\n>>>')
child.sendline('import os')
child.sendline('os.system("cd /sys/class/leds/led0 && sudo sh -c \'echo 1 > brightness\' ")')
child.expect('\n>>>')
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)
最佳答案
您想要使用 /console
URL 有什么原因吗?如果您使用其他的,则不会出现此问题。
Werkzeug 默认使用它进行调试。
您需要通过设置 use_evalex=False
将其关闭。请参阅this question了解更多详情。
此外,您不需要使用pexpect
。直接调用os.system
:
@app.route('/console')
def console():
import os
os.system("cd /sys/class/leds/led0 && sudo sh -c \'echo 1 > brightness\' ")
return '<h1>changed brightness</h>'
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, use_evalex=False)
关于python - 访问 URL 时打开 LED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29535456/