Take the 2-minute tour ×

I would like to test whether graphical interface is available when running a program which optionally uses PyQt4. If I do

$ DISPLAY= python
>>> import PyQt4.QtGui
>>> PyQt4.QtGui.QApplication()
: cannot connect to X server

python crashes ($?=1).

It is not enough to check for DISPLAY environment variable (the value could be invalid, XAuth could fail etc.)

What is the proper way to detect dysfunctional display with PyQt4?

My current approach is a bit of hack (I would like to avoid using python-xlib, since it does not seem to be maintained):

import XLib.display:
   # display was opened fine, PyQt4 won't crash
   # don't use PyQt4 since display had some error
share|improve this question
You're setting X11's DISPLAY variable to python? –  Linuxios Jul 8 '12 at 13:42
DISPLAY= with the space after it sets DISPLAY to nothing and runs python (you can try that). –  eudoxos Jul 8 '12 at 13:47
Ok. Thanks. That makes sense –  Linuxios Jul 8 '12 at 13:48

1 Answer 1

Since Qt insists on crashing the process, you could do a test in another process:

import subprocess, time, sys
p = subprocess.Popen(sys.executable, stdin=subprocess.PIPE)
p.stdin.write('from PyQt4 import QtGui\napp = QtGui.QApplication([])\n')
if p.poll() != 0:
    except OSError:
    print "No X server"
    print "X ok"

The timeout might be too short if it's a networked X connection..

share|improve this answer

Your Answer


