简体   繁体   中英

Crontab not executing Python script on Ubuntu

I have a Python script with the following code:

import subprocess
import sys

default = "Take a 20 second break - look at least 20 feet away!"
message = sys.argv[1] if len(sys.argv) > 1 else default

def sendmessage(message):
    subprocess.Popen(['notify-send', message])
    return

sendmessage(message)

called takebreak.py , which will send a system notification.

When I try to automate it using crontab like so:

* * * * * /usr/bin/python /home/polo/git-repositories/takebreak/takebreak.py

It doesn't work. Running the command

/usr/bin/python /home/polo/git-repositories/takebreak/takebreak.py

in the terminal does work, which means it's not a file location problem, but rather something to do with cron . Any ideas?

EDIT1:

After debugging and looking at the logs, I can verify that cron is actually executing the commmand export DISPLAY=:0; /usr/bin/python /home/polo/git-repositories/takebreak/takebreak.py export DISPLAY=:0; /usr/bin/python /home/polo/git-repositories/takebreak/takebreak.py every minute like I set it to do, but for some reason this command, while it should send a system notification, is not doing so. Any ideas?

EDIT2:

The solution was to add some address bus thing (forget the exact code) that I found in another post, that ended up fixing it. Unfortunately, none of the answers or comments here helped with solving the problem, but thanks regardless!

Most likely, the problem is that notify-send is not in your $PATH when running from crontab . First, figure out where it's stored:

$ which notify-send
/usr/bin/notify-send

For me, it's in /usr/bin .

At the top of your crontab file ( crontab -e ), set $PATH :

PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

If you want to include whatever $PATH may have already been set before (safer), do this instead:

PATH="${PATH}:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

Make sure this includes the directory where your command is installed, if it's not installed in /usr/bin .

Of course, the other option, is to simply specify the full command path in your Python script:

subprocess.Popen(['/usr/bin/notify-send', message])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM