1.3.1 Command line interface

Note: PyQt-4.3 and later has most of the functionality of the iqt module.

The programming style imposed by PyQt (before version 4.3) and other GUI toolkit wrappers is to create an application instance with some widgets and to enter an event loop that locks you from the Python command line interpreter.

The iqt module enables you to:

When Python has the GNU readline module, the iqt module works by hooking qApp->processEvents() on the event hook of the readline module. The GNU readline library closes the event loop by calling qApp->processEvent() at a maximum rate of 10 times per second while reading your keyboard input.

When Python does not have the GNU readline module, the iqt module uses the techniques suggested on the PyQt mailing list.

To see how the iqt works, play with ICompass.py by running

python -i ICompass.py
or
python ICompass.py
or
ipython ICompass.py

My .pythonrc.py file (a symbolic link to /usr/lib/python2.5/site-packages/PyQt4/Qwt5/pythonrc.py) tries to import the modules numpy and scipy. Then, it tries to import everything from the modules PyQt4.Qt, PyQt4.Qwt5, and PyQt4.Qwt5.qplt before creating an QApplication instance. Finally, it configures readline for tab-completion and history saving and cleans up the global namespace:

# Set your PYTHONSTARTUP environment variable to $HOME/.pythonrc.py
#
# inspired by:
# http://opag.ca/wiki/OpagCode/OpagSnippets

# Import Numpy and SciPy
try:
    import numpy as np
    import scipy as sp
    sp.pkgload()
except ImportError:
    pass

# Import PyQt4.Qt and PyQt4.Qwt5; initialize an application.
# Note: hides the builtins hex and oct.
try:
    from PyQt4.Qt import *
    from PyQt4.Qwt5 import *
    from PyQt4.Qwt5.qplt import *
    application = QApplication([])
except ImportError:
    application = None

# Setup readline and history saving
from atexit import register
from os import path
import readline
import rlcompleter

# Set up a tab for completion; use a single space to indent Python code.
readline.parse_and_bind('tab: complete')

history = path.expanduser(' /.python_history')
readline.set_history_length(1000)

# Read the history of the previous session, if it exists.
if path.exists(history):
    readline.read_history_file(history)

# Set up history saving on exit.
def save(history=history, readline=readline, application=application):
    readline.write_history_file(history)

register(save)

# Clean up the global name space; save, history, readline, and application
# will continue to exist, since del decrements the reference count by one.
del register, path, readline, rlcompleter, history, save, application

# Local Variables: ***
# mode: python ***
# End: ***