简体   繁体   中英

Python Pyside QT - Prevent Initialization of QT due to imports when running on CLI

So we have a rather large program written in Python using PySide/QT to get most of its GUI work done. We use Chaco to do some plotting.

This program also has a full CLI interface.

Every now and then a developer accidentally creates an import chain that causes our CLI runs to try and import something from PySide or Chaco. This causes our CLI runs to die with "cannot connect to x server" as either PySide or Chaco is trying to initialize X via QT.

Any tips on how to prevent this? Can we stub out and override some function that is doing this? Some flag we can pass along? Currently our prevention mechanism is track down the bad import and refactor.

So one semi-solution is to do the following. Essentially stub out the QApplication class and have it print a stack trace on init. This will break things but you will get a stack trace to do the first spot QtApplication tries to initialize.

_oldQtApplication = QtGui.QApplication

class BogusQApplication(QtGui.QApplication):
    def __init__(self, *args):
        import traceback
        print traceback.print_stack()

        _oldQtApplication.__init__(self, args)

QtGui.QApplication = BogusQApplication

A better solution would be to essentially stub the whole QtApplication class in such a way that users of it still work but essentially have a NullQtApplication. Unfortunately this appears to be a ton of work based on the usage of QtApplication in libraries like PySide of Chaco.

Rather than avoiding initialising Qt altogether, perhaps you could use QCoreApplication in your CLI applications. See the detailed description of QApplication in http://doc.qt.io/qt-5/qapplication.html for some example code you could adapt.

The good practice for such kind of pattern is to have a proper organisation of the code where the code using the user interface can't be imported when running on the CLI.

You can do that by designing your application in a pluggable way and only load the plugins needed by the CLI when running in CLI mode and the full set of plugins when running with the UI. We extensively use the Envisage framework to build pluggable application and solve those kind of problems. It requires a bit more upfront effort in designing your app.

For reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM