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

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

import sys
import PyQt4

sys.modules["Qt"] = PyQt4

Then import this file into other source files and use it as follows:

import QT
from Qt.QtCore import *

So I can upgrade from PyQt4 to PySide in QT.py without touching all the source files (possibly with an ugly sed script) These modules are mostly API compatible and I would like to test them. Is there an easy way to do this? (Because my attempts do not work)

Maybe I need a module imp, but it seems too low.

+5
source share
3 answers

update. :

:

Qt/
Qt/__init__.py
Qt/QtCore/__init__.py
Qt/QtGui/__init__.py

Qt/__init__.py:

import QtCore, QtGui

Qt/QtCore/__init__.py:

from PyQt4.QtCore import *

Qt/QtGui/__init__.py:

from PyQt4.QtGui import *

:

import sys
from Qt import QtGui
app = QtGui.QApplication(sys.argv)

from Qt.QtGui import *

window = QWidget()
window.show()

app.exec_()

from Qt.QtGui import * , Python, .

: . . :

Qt/QtGui/__init__.py:

import sys
if '--PyQt4' in sys.argv:
    from PyQt4.QtGui import *
else:
    from PySide.QtGui import *
+2

:

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

:

$ python2 test.py PySide
<module 'PySide' from '/usr/lib/python2.7/site-packages/PySide/__init__.py'>
<module 'PySide.QtCore' from '/usr/lib/python2.7/site-packages/PySide/QtCore.so'>
<type 'PySide.QtGui.QWidget'>
$ python2 test.py PyQt4
<module 'PyQt4' from '/usr/lib/python2.7/site-packages/PyQt4/__init__.pyc'>
<module 'PyQt4.QtCore' from '/usr/lib/python2.7/site-packages/PyQt4/QtCore.so'>
<class 'PyQt4.QtGui.QWidget'>
+4

. , "PyQt4":

import sys

if sys.argv[-1] == 'PyQt4':
    import PyQt4
    sys.modules["Qt"] = PyQt4
else:
    import Qt
    from Qt.QtCore import *
0

All Articles