Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cron job: how to run a script that requires to open display?

I want to set up a cron job to run a python script, but it gives me this error:

RuntimeError: could not open display

This is because I import a module that requires me to open display (pylab, for example). Even though my script does not generates any pictures to display on the monitor.

Is there any way to let crontab run my jobs with display open (just as if I ssh -X into a machine)? I don't actually need to generate any graphs to the monitor. I just need to import my modules correctly.

like image 770
CuriousMind Avatar asked Jun 13 '12 12:06

CuriousMind


1 Answers

You will need a valid DISPLAY and XAUTHORITY to use X-Programms in Cron!

To set DISPLAY is very easy, type in the Bash:

export DISPLAY=":0.0"

In order to get a valid XAUTHORITY you have to look for it. Under Debian/Gnome/gdm3 they are saved in var/run/gdm3/*/database I used the following script:

export DISPLAY=":0.0"
[ -z $USER ] && USER=$( who | awk '{ print $1 }' | sort | uniq >/tmp/test )
for I in /var/run/gdm3/*; do
    AUTHUSER="`echo $I | awk -F '-' '{ print $3 }'`"
    for J in $USER; do
        [ "${AUTHUSER}" = "${J}" ] || continue
        USER="$J"
        export XAUTHORITY="${I}/database" && break
    done
done
sudo -u ${USER} /Path/to/xProgramm

The Var $USER can be empty, than the script looks for a valid user, otherwise you can tell the script the var!

like image 69
Michèle S. Avatar answered Sep 30 '22 11:09

Michèle S.