CherryPy干扰了Windows上的Twisted关闭

2024-09-24 00:33:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个运行Twisted的应用程序,它是在启动其他线程(包括cherrypyweb服务器)之后,在主线程中使用reactor.run()启动reactor。以下是一个程序,当在Linux上按Ctrl+C键而不是在Windows上按下时,它会干净地关闭:

from threading import Thread
from signal import signal, SIGINT

import cherrypy

from twisted.internet import reactor
from twisted.web.client import getPage

def stop(signum, frame):
    cherrypy.engine.exit()
    reactor.callFromThread(reactor.stop)
signal(SIGINT, stop)

class Root:
    @cherrypy.expose
    def index(self):
        reactor.callFromThread(kickoff)
        return "Hello World!"

cherrypy.server.socket_host = "0.0.0.0"
Thread(target=cherrypy.quickstart, args=[Root()]).start()

def print_page(html):
    print(html)

def kickoff():
    getPage("http://acpstats/account/login").addCallback(print_page)

reactor.run()

我认为CherryPy是罪魁祸首,因为我在没有CherryPy的情况下编写了一个不同的程序,当按下Ctrl+C时,它在Linux和Windows上都会干净地关闭:

^{pr2}$

有人知道问题出在哪里吗?我的难题是:

  • 在Linux上一切都正常
  • 在Windows上,当CherryPy不运行时,我可以使用reactor.callFromThread从信号处理程序调用函数
  • 当CherryPy运行时,我从信号处理程序使用reactor.callFromThread调用的任何函数都不会执行(我已经验证了信号处理程序本身确实被调用了)

我该怎么办?在运行CherryPy时,如何从信号处理程序关闭Twisted on Windows?这是一个bug,还是我只是错过了这两个项目文档中的一些重要部分?在


Tags: fromimport程序signallinuxwindowsdeftwisted
1条回答
网友
1楼 · 发布于 2024-09-24 00:33:35

CherryPy在调用quickstart时默认处理信号。在您的情况下,您可能应该展开quickstart,它只有几行,然后进行选择。下面是quickstart在trunk中的基本操作:

if config:
    cherrypy.config.update(config)

tree.mount(root, script_name, config)

if hasattr(engine, "signal_handler"):
    engine.signal_handler.subscribe()
if hasattr(engine, "console_control_handler"):
    engine.console_control_handler.subscribe()

engine.start()
engine.block()

在您的例子中,您不需要信号处理程序,所以可以省略它们。你也不需要打电话发动机缸体如果你不从主线程启动CherryPy。发动机缸体()只是一种使主线程不立即终止,而是等待进程终止的方法(这使得autoreload工作可靠;一些平台在从除主线程之外的任何线程调用execv时出现问题)。在

如果您删除block()调用,那么您甚至不需要quickstart周围的Thread()。所以,换句台词:

^{pr2}$

有:

cherrypy.tree.mount(Root())
cherrypy.engine.start()

相关问题 更多 >