Skip to main content
 首页 » 编程设计

python之在 Tornado 网络服务器中运行 Python 脚本

2025年04月02日1552php

我的问题对你来说可能真的很简单,但我才刚刚开始,所以请帮助我。

我正在运行家庭自动化脚本并尝试将其与 Tornado 网络服务器结合使用。

最好的方法是什么?

基本 Tornado 服务器:

import tornado.ioloop 
import tornado.web 
import os.path 
 
class MainHandler(tornado.web.RequestHandler): 
    def get(self): 
        self.render('index.html') 
 
application = tornado.web.Application([ 
    (r"/", MainHandler) 
application = tornado.web.Application([ 
    (r"/check", MainHandler) 
]) 
 
if __name__ == "__main__": 
    print 'Starting Server' 
    print 'Press ctrl+c to close' 
    application.listen(8888) 
    tornado.ioloop.IOLoop.instance().start() 

和一个 Python 脚本:

import RPi.GPIO as GPIO 
import time 
import os 
 
motion = 14 
relay = 2 
 
GPIO.setmode(GPIO.BCM) 
GPIO.setup(motion, GPIO.IN, GPIO.PUD_DOWN) 
GPIO.setup(relay, GPIO.OUT) 
GPIO.output(relay, GPIO.HIGH) 
 
previous = False 
current = False 
 
while True: 
    time.sleep(1) 
    previous = current 
    current = GPIO.input(motion) 
    if current != previous: 
        new = "HIGH" 
        GPIO.output(relay, GPIO.LOW) 
        print("GPIO pin %s is %s" % (motion, new)) 
        os.system("sudo omxplayer ring.mp3 &") 
        time.sleep(5) 
    else: 
        GPIO.output(relay, GPIO.HIGH) 
        print("No motions") 

请您参考如下方法:

如果您的脚本是作为函数编写的,您可以导入它并调用它。但是,由于它包含同步代码,您需要使用 ThreadPoolExecutor 从 Tornado 调用它。

或者,最好将其作为子进程启动。请参阅 tornado.process.Subprocess 和标准库的 subprocess 模块。