How can you easily select between PyQt or PySide at runtime?

后端 未结 3 1348
长发绾君心
长发绾君心 2021-01-13 06:58

I would like to do something like this in one source file, QT.py:

import sys
import PyQt4

sys.modules[\"Qt\"] = PyQt4

Then import this fil

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-13 07:28

    Use an import hook:

    def set_qt_bindings(package):
        if package not in ('PyQt4', 'PySide'):
            raise ValueError('Unknown Qt Bindings: %s' % package)
        import __builtin__
        __import__ = __builtin__.__import__
        def hook(name, globals=None, locals=None, fromlist=None, level=-1):
            root, sep, other = name.partition('.')
            if root == 'Qt':
                name = package + sep + other
            return __import__(name, globals, locals, fromlist, level)
        __builtin__.__import__ = hook
    
    if __name__ == '__main__':
    
        import sys
    
        if len(sys.argv) > 1:
    
            set_qt_bindings(sys.argv[-1])
    
            import Qt
            print Qt
    
            from Qt import QtCore
            print QtCore
    
            from Qt.QtGui import QWidget
            print QWidget
    

    Output:

    $ python2 test.py PySide
    
    
    
    $ python2 test.py PyQt4
    
    
    
    

提交回复
热议问题