Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic detection of display availability with matplotlib

I'm generating matplotlib figures in a script which I run alternatively with or without a graphical display. I'd like the script to adjust automatically: with display, it should show the figures interactively, while without a display, it should just save them into a file.

From an answer to the question Generating matplotlib graphs without a running X server, I learnt that one can use the Agg backend for non-interactive plotting.

So I am trying with this code:

import matplotlib
try:
    import matplotlib.pyplot as plt
    fig = plt.figure()
    havedisplay = True
except:
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    fig = plt.figure()
    havedisplay = False
# do the plotting
if havedisplay:
    plt.show()
else:
    fig.savefig("myfig.png")

This works as excepted in the case with a display. However, without a display, the call to matplotlib.use is not effective, since the display has already been chosen. It's clear that I should call matplotlib.use before import matplotlib.pyplot, but then I don't know how to test whether a display is available or not.

I have also tried with the experimental function matplotlib.switch_backend instead of matplotlib.use, but this generates a RuntimeError.

Does someone have an idea how to make the above code work as intended, or can suggest an alternative way to detect whether a display is available for matplotlib or not?

like image 421
silvado Avatar asked Nov 24 '11 12:11

silvado


1 Answers

You can detect directly if you have a display with the OS module in python. in my case it's

>>> import os
>>> os.environ["DISPLAY"]
':0.0'
like image 180
oz123 Avatar answered Nov 03 '22 00:11

oz123