3

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?

tnknepp
  • 5,888
  • 6
  • 43
  • 57

2 Answers2

5

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.

Community
  • 1
  • 1
tnknepp
  • 5,888
  • 6
  • 43
  • 57
  • 1
    this is probably the right answer. I removed my answer again because apparently you *can* start a python script with `ipython` it's just not recommended to do so – hansaplast Jan 23 '17 at 21:07
1

If you happen to be working remotely or wo screen add this to your bashrc:

export QT_QPA_PLATFORM='offscreen'
Benedict K.
  • 836
  • 2
  • 8
  • 22