由于更新到最新的操作系统版本,因此无法停止Web服务器

时间:2019-01-15 15:39:08

标签: python-2.7 tornado raspbian

我将程序分解为简单的60 Liner,它应在2秒钟后启动和停止Tornado服务器。这段代码可用于早期的Debian版本,但会挂起并且不会在当前版本中停止:

> uname -a
Linux xyz 4.14.79-v7+ #1159 SMP Sun Nov 4 17:50:20 GMT 2018 armv7l GNU/Linux

import time
import threading
import logging
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.websocket

class HTTPHandler(tornado.web.RequestHandler):
    """HTTP request handler for my simplyfied web-server."""

    def initialize(self):
        pass

    def get(self):
        """Execute HTTP GET commands."""
        self.set_status(200)
        self.set_header('Content-type', "text/html; charset=utf-8")
        self.write("HI")

class WebServer(threading.Thread):

    def __init__(self):
        """Setup web-server on a configured port."""
        threading.Thread.__init__(self)
        self.port = 4030

    def run(self):
        """Start listening on port as a web-server."""
        application = tornado.web.Application([(r"/.*", HTTPHandler)])
        httpd = tornado.httpserver.HTTPServer(application)
        interface, ip = ("eth0", "192.168.2.4")
        httpd.listen(self.port, address=ip)
        logging.info("WebServer Starts - %s(%s):%s", ip, interface, self.port)
        log = logging.getLogger("tornado.access")
        log.setLevel(logging.NOTSET)

        tornado.ioloop.IOLoop.instance().start()

        logging.info("WebServer exiting")

    def stop(self):
        """Set shutdown flag for the thread to stop."""
        tornado.ioloop.IOLoop.instance().stop()

if __name__ == '__main__':
    rootLogger = logging.getLogger('')
    rootLogger.setLevel(logging.DEBUG)
    logging.getLogger("tornado.general").setLevel(logging.NOTSET)
    logging.getLogger("tornado.application").setLevel(logging.NOTSET)
    logging.getLogger("tornado.access").setLevel(logging.NOTSET)

    ws = WebServer()
    ws.start()

    time.sleep(2.0)
    logging.debug("Stopping")
    ws.stop()

说实话,我不记得以前的OS版本是什么,但它至少是一年以前的版本。知道我该怎么做吗?

1 个答案:

答案 0 :(得分:0)

您正在从主线程调用IOLoop.instance().stop(),这是不允许的。在Tornado中,可以安全地从运行IOLoop的线程之外的其他线程调用的 only 方法是IOLoop.add_callback。要在IOLoop在另一个线程上运行时从主线程启动关闭,请用以下方法替换您的stop方法:

def stop(self):
    """Instruct the IOLoop to stop itself."""
    IOLoop.instance().add_callback(IOLoop.instance().stop)