尽管我正在检查反应堆是否已经 运行,但出现 ReactorNotRestartable 错误

Getting ReactorNotRestartable error when though I am checking if the reactor is already running

代码:

def hook(ui, repo, hooktype, node=None, source=None, **kwargs):

    from buildbot.clients import sendchange
    from twisted.internet import defer, reactor

    for master in masters:
        s = sendchange.Sender(master, auth=(username, password))
        d = defer.Deferred()
        reactor.callLater(0, d.callback, None)

        for rev in range(start, end):
            # some code here
            d.addCallback(dummy, "calling dummy")

    def _printSuccess(res):
        pass

    def _printFailure(why):
        pass

    d.addCallbacks(_printSuccess, _printFailure)
    d.addBoth(lambda _: reactor.stop())
    try:
        logger.info("before starting reactor")
        if not reactor.running:
            reactor.run()
            logger.info("after reactor.run")
        else:
            logger.info("reactor is already running")

    except Exception as e:
        logger.info("in exception")
        logger.exception("exception occurred")
        if reactor.running:
            reactor.stop()


def dummy(content):
    with open("/home/rhodecode/hg_buildbot_hooks/dummy.txt", "w") as f:
        f.write("dummy" + "\n")
        f.write("{}".format(content))

错误:

File "/home/rhodecode/hg_buildbot_hooks/hooks.py", line 291, in hook
    reactor.run()
File "/home/rhodecode/buildbot_venv/lib/python2.7/site-packages/twisted/internet/base.py", line 1266, in run
    self.startRunning(installSignalHandlers=installSignalHandlers)
File "/home/rhodecode/buildbot_venv/lib/python2.7/site-packages/twisted/internet/base.py", line 1246, in startRunning
    ReactorBase.startRunning(self)
File "/home/rhodecode/buildbot_venv/lib/python2.7/site-packages/twisted/internet/base.py", line 754, in startRunning
    raise error.ReactorNotRestartable()
ReactorNotRestartable

ReactorNotRestartable。也许关键字是 re-startable。您不能多次启动 Twisted reactor - 即使您在两次尝试之间停止它也是如此。

出于两个不同的原因,我在两个不同的地方遇到过这个问题

  1. 反应器由 python 主线程启动,但非主线程正在调用 reactor.stop(),并且没有反应器 运行 停止。 ref: reactor.callFromThread(reactor.stop)

  2. Reactor 作为 reactor.run() 从非主线程被调用,并且它不是事件启动。 ref: reactor.run(installSignalHandlers=False)