Search code examples
pythontwistedpyside2reactor

Cannot stop twisted reactor when calling reactor.stop()


I'm using twisted, PySide2 and qt5reactor to make a simple program that sends data through network. I want the reactor to stop when I closed the PySide2 window:

class MyWindow(QWidget):
    --snip--
    def closeEvent(self, event):
        super().closeEvent(event)
        reactor.callFromThread(reactor.stop)

However, the code above don't work at all. It don't produce any errors, but after the window closes, the program don't stop. It just closes the connection to the server. That means the reactor haven't stopped.

I've tried to call sys.exit() after calling reactor.callFromThread(...), but it was no use either. This time, the window also refuses to shut down! The whole program turned unresponsive, but no errors.

So how do I shut down the reactor cleanly?


Solution

  • Since you're using qt5reactor, your GUI code runs in the same thread as the Twisted reactor. This means you can just call Twisted APIs directly - you don't need reactor.callFromThread.

    This shouldn't be related to your problem since it is also allowed to use reactor.callFromThread from the reactor thread - though it's possible qt5reactor does not implement this unusual usage correctly.

    There isn't currently enough detail in the question for me to come up with another hypothesis though. If you find that calling reactor.stop() directly fixes the issue then it may be worth filing a bug report against qt5reactor. If it doesn't, try adding more detail to the question.