1

Is there a canonical way of detecting inside the interpreter if IPython was called with options like--pylab=... or --gui=...?

The reason: I want to do some asynchronous plotting in a separate process, as show in the sample script tst_process.py:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" File tst_process.py """
# For better Python 3 compatibility:
from __future__ import absolute_import, print_function, unicode_literals, \
                       division

import matplotlib.pylab as plt
from multiprocessing import Process
import numpy as np

def tst_plot(fgoff=0):
    """ Make a test plot """
    print("Drawing figure {}".format(1+fgoff))
    x = np.linspace(0, 5, 500)
    fg = plt.figure(1+fgoff)
    fg.clf()
    ax = fg.add_subplot(1, 1, 1)
    ax.plot(x, np.sin(x))
    ax.set_title("This is a Test-Plot")
    fg.canvas.draw()
    plt.show()


if __name__ == "__main__":

    print("Doing testplot in new process ...")
    pprc1 = Process(target=tst_plot)
    pprc1.start()
    print("Doing testplot in own process ...")
    tst_plot(10)

When I run it with the command

ipython --i tst_process.py

everything works as expected. Doing:

ipython --pylab=qt --i tst_process.py 

gives:

Python 2.7.9 (default, Dec 11 2014, 08:58:12) 
Type "copyright", "credits" or "license" for more information.

IPython 2.3.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
Doing testplot in new process ...
Doing testplot in own process ...
Drawing figure 11
Drawing figure 1
 : Fatal IO error: client killed
X Error: BadIDChoice (invalid resource ID chosen for this connection) 14
  Major opcode: 1 (X_CreateWindow)
  Resource id:  0x6a00003
X Error: BadIDChoice (invalid resource ID chosen for this connection) 14
  Extension:    139 (RENDER)
  Minor opcode: 4 (RenderCreatePicture)
  Resource id:  0x6a00004
X Error: BadIDChoice (invalid resource ID chosen for this connection) 14
  Major opcode: 1 (X_CreateWindow)
  Resource id:  0x6a00005
[xcb] Unknown sequence number while processing queue
[xcb] Most likely this is a multi-threaded client and XInitThreads has not been called
[xcb] Aborting, sorry about that.
python: ../../src/xcb_io.c:274: poll_for_event: Zusicherung »!xcb_xlib_threads_sequence_lost« nicht erfüllt.
Abgebrochen

Other backends with the exception of wx did not work either.

It would be sufficient for me to detect the existence of the event loop. Then I could use the same script for running from the command line and for inside Spyder.

2
  • 1
    gui event loops + multiprocess don't play will with each other. You either have to do all of your plotting on one thread/process (the main one) and push computation off to the others or use a non-interactive backend..
    – tacaswell
    Jan 30, 2015 at 15:06
  • That is what I noticed too. I guess I have some restructuring to do ...
    – Dietrich
    Jan 30, 2015 at 21:45

2 Answers 2

1
+150

To answer your original question: Is there a canonical way of detecting inside the interpreter if IPython was called with options like--pylab=... or --gui=...?

Yes, there is. The most simple would be to check for the command line arguments:

import sys
print sys.argv # returns the commandline arguments
# ['ipython', '--pylab', 'inline']

A nicer way would be to use the built-in module optparse.

However, this will only allow you to see what mode it is running in, based on the command line arguments - which was your main question. It will not help you solve the gui event looks + multiprocess issues as @tcaswell mentioned in the comments.

1
  • Thanks, this is a nice pragmatic approach. Detecting the mode is sufficient enough for me to work around the gui event issues.
    – Dietrich
    Feb 8, 2015 at 9:36
0

You can check if the qt event loop is running with

import PyQt4.QtCore
if PyQt4.QtCore.QCoreApplication.instance():
    print("Event loop detected")

PS: for finer-grained checking of when the event loop starts, you can use the application startingUp method.

3
  • This is wrong. Merely creating an application object doesn't start the event loop - you have to call exec() to do that. Also, the event loop can be stopped by calling quit() or exit() - but that does not destroy the application object. (And one other point: you cannot directly access modules via the PyQt namespace - they have to be explicitly imported).
    – ekhumoro
    Feb 6, 2015 at 23:50
  • We do NOT want to start the event loop, but check if it exists, that was the question.
    – mdurant
    Feb 9, 2015 at 15:16
  • Your code doesn't check whether the event loop exists. It merely checks whether an application object has been created. The event loop is started/stopped separately. The startingUp function is static and also merely checks whether an application object has been created - it tells you nothing about the status of the event loop. The fact is, Qt just doesn't provide any explicit mechanism at all for checking the status of the event loop (other than simply posting an event and waiting for it to be processed).
    – ekhumoro
    Feb 9, 2015 at 17:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.