0

Situation:

I have a python script on my raspberry pi. If I execute it manually there is no problem, it works exactly as it's supposed to.

When I create a cron job with :

sudo crontab -e 

the script is "executed", because it appears in /var/log/syslog at the correct time. Other cron jobs are executed correctly.

My entry:

0 18 * * * /usr/bin/python /home/user/script.py

In the log it's correct: every day at 18:00:00. But nothing happens. I have no idea why the script isn't executed correctly.

It's maybe a stupid mistake, but I am not soooo skilled in linux.

script.py:

#!/usr/bin/python

import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import *
import datetime
import sys
import site
import logging

MailReceiveSRV = 'imap.gmail.com'
MailSendUSER = '[email protected]'
MailSendPWD = 'pw!'
MailSendSRV = 'smtp.gmail.com'
MailSendFROM = MailSendUSER

def readFile():
    """
    Liest die txt Datei ein und gibt ein Array von Arrays zurueck. In jedem Subarray steht ein Abholtag.
    """
    file = open("/home/pi/Termine_2015.txt", "r")
    all_dates = []
    for line in file:
        all_dates.append(line.split(";"))
    return all_dates

def sendMail(subj, msg, MailSendTO):
    """
    Send Mails ueber abc
    """
    try:
        # E-Mail zusammensetzen
        mime = MIMEMultipart()
        mime['From'] = MailSendFROM
        mime['To'] = MailSendTO
        mime['Subject'] = Header(subj, 'utf-8')
        mime.attach(MIMEText(msg, 'plain', 'utf-8'))
        # Mail versenden
        smtp = smtplib.SMTP(MailSendSRV)
        smtp.starttls()
        smtp.login(MailSendUSER, MailSendPWD)
        smtp.sendmail(MailSendFROM, [MailSendTO], mime.as_string())
        smtp.quit()
    except Exception, e1:
        print "Error in sendMail: " + str(e1)

def checkPaperGreenYellowRedXmas(dates):
    """
    checkt ob das morgige Datum in der Liste der Arrays auftaucht. Falls ja gehen Mails raus
    """
    tomorrow = str(datetime.datetime.today() + timedelta(days=1))[:10]
    for date in dates:
        if date[2] == tomorrow:
            subject = "Muell-Erinnerung! Morgen kommt " + date[0]
            body = date[0] + "\n\n" + date[1] + "\n\nWo? -> " + date[3]
            sendMail(subj=subject, msg=body, MailSendTO="[email protected]")
            sendMail(subj=subject, msg=body, MailSendTO="[email protected]")
            return True
    return False

def checkBlackBrown():
    """
    checkt auf Mittwoch + geradeWoche, wenn ja kommt braun
    checkt auf Mittwoch + ungeradeWoche, wenn ja kommt schwarz
    """
    wednesday = lambda x: x==2
    tomorrow = datetime.date.today() + timedelta(days=1)
    evenWeek = lambda x: x % 2 == 0
    subj_braun = "Muell-Erinnerung! Morgen kommt Braun"
    subj_schwarz = "Muell-Erinnerung! Morgen kommt Schwarz"
    body_braun = "Braune Tonne\n\nWo? -> Vor der Haustuer"
    body_schwarz = "Schwarze Tonne\n\nWo? -> Vor der Haustuer"
    if wednesday(tomorrow.weekday()) and evenWeek(tomorrow.isocalendar()[1]):
        sendMail(subj=subj_braun, msg=body_braun, MailSendTO="[email protected]")
        sendMail(subj=subj_braun, msg=body_braun, MailSendTO="[email protected]")
        return True
    elif wednesday(tomorrow.weekday()) and not evenWeek(tomorrow.isocalendar()[1]):
        sendMail(subj=subj_schwarz, msg=body_schwarz, MailSendTO="[email protected]")
        sendMail(subj=subj_schwarz, msg=body_schwarz, MailSendTO="[email protected]")
        return True
    return False

def Main():
    paths = site.getsitepackages()
    for path in paths:
        sys.path.append(path)
    logging.basicConfig(filename='muell.log',
                    format='%(levelname)s %(asctime)s :: %(message)s',
                    level=logging.DEBUG)
    PaperGreenYellowRedXmas = readFile()
    x = checkPaperGreenYellowRedXmas(PaperGreenYellowRedXmas)
    y = checkBlackBrown()
    if x or y:
        logging.info("Process finished.. mail sent.")
    else:
        logging.info("Process finished.. no mail sent.")

if __name__ == '__main__':
    Main()
5
  • Depends what the script is doing; if it depends on some shell functions or relatives paths that could all be a reason. You really need to post the contents of the script. Commented Aug 1, 2015 at 12:27
  • 2
    It's very likely that cron is sending all errors from your failed script execution to root's e-mail. So execute "su - root" to log in as root, then check root's mail with "mail" command. Look for any error messages that would have been the output of crontab's failed execution of your python script. Commented Aug 1, 2015 at 12:33
  • If your script output is file, change it it absolute path. Commented Aug 1, 2015 at 14:23
  • You might review the checklist here: askubuntu.com/questions/23009/reasons-why-crontab-does-not-work Commented Aug 1, 2015 at 14:33
  • @jlyoung: "mail: command not found" Commented Aug 1, 2015 at 22:44

3 Answers 3

1

It seems that there is something bad happened when running the script using crontab. Try this one and then go to the output file to get to know what happened actually(this command redirect the stdout and stderr to the file):

0 18 * * * /usr/bin/python /home/user/script.py >/tmp/output 2>&1
Sign up to request clarification or add additional context in comments.

Comments

0

If you are importing modules make sure they are reachable.

If not reachable, append the absolute path of the module to the list sys.path using sys.path.append(path).

1 Comment

didn't work :( you can see my version in the original post now.
0

When I have this problem happen I just take the command and run it in the command line. It will show me the errors that are happening.

/usr/bin/python /home/user/script.py

I had this same problem with when I got my Raspberry Pi. When I ran the script manually I found out that the path I had typed was wrong.

2 Comments

When I execute my script manually, there are no errors. Everything works fine.
What directory are you running the command from? Is that the same directory your cron is running the command from?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.