Automatic detection of display availability with matplotlib Automatic detection of display availability with matplotlib linux linux

Automatic detection of display availability with matplotlib


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'


try this?

import matplotlib,osr = os.system('python -c "import matplotlib.pyplot as plt;plt.figure()"')if r != 0:    matplotlib.use('Agg')    import matplotlib.pyplot as plt    fig = plt.figure()    fig.savefig('myfig.png')else:    import matplotlib.pyplot as plt    fig = plt.figure()    plt.show()


The code below works for me in Linux and Windows (where it assumes there is a display device):

import osimport matplotlibif os.name == 'posix' and "DISPLAY" not in os.environ:    matplotlib.use('Agg')

See https://stackoverflow.com/a/1325587/896111.

Note that the line matplotlib.use('Agg') must appear after the first import of matplotlib (otherwise you will get an error).