Search code examples
pythonbashmatplotlibcron

QxcbConnection error when Python matplotlib run as cron job


I have a plotting script that was scheduled to run as a cron job, but throws an error. The script was written in Python 3.5, and an example is given below.

import pylab as pl

fig = pl.figure(figsize=(4, 4))
ax = fig.add_supblot(111)

ax.plot(range(10), range(10))

I was calling it in a bash script via the following line: ~/anaconda3/bin/ipython test.py

I got the following error in my cron report:

QXcbConnection: Could not connect to display 
/datadrive/cronjobs/test.sh: line 2:  1459 Aborted (core dumped) ~/anaconda3/bin/python ~/Desktop/test.py

I even tried calling directly from the crontab, but got the same error.

I have confirmed that I can run the script from the terminal. Both of these work:

$ ~/anaconda3/bin/ipython ~/Desktop/test.py
$ bash /datadrive/cronjobs/test.sh

It seems the matplotlib does not like to be run under cron, but I cannot see why. Does anyone know why this is and how to fix it?


Solution

  • I came across a similar problem on SO here. The trick is to load in matplotlib before pylab and call matplotlib.use('Agg'). e.g.

    import matplotlib
    matplotlib.use('Agg')
    import pylab
    
    etc. etc. etc.
    

    Apparently, when running under a cron job there is not an active graphical backend (or something, I don't really understand that part). Setting matplotlib's .use as "Agg" solves this.