Reputation: 461
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()
Upvotes: 0
Views: 206
Reputation: 897
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.
Upvotes: 0
Reputation: 1
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)
.
Upvotes: 0
Reputation: 4670
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
Upvotes: 1