Search code examples
python-3.xcron

One out of 3 python programs that should run at boot doesn't, using crontab


The following scripts and configurations are on a Raspberry Pi B+ (I believe) running buster.

The script 'check.py' is below

#!/usr/bin/env/ python3
import time
print('sleeping')
time.sleep(15)
print('HEASPIDHAPOISHDOAISHD')

def emailChecker():
    import imaplib
    import email
    import os
    import time
    print('initiating emailinfiniteCheck')

    EMAIL = '[email protected]'
    PASSWORD = 'CENSORED'
    SERVER = 'imap.gmail.com'
    FROM = 'CENSORED'
    # connect to the server and go to its inbox
    mail = imaplib.IMAP4_SSL(SERVER)
    mail.login(EMAIL, PASSWORD)
    while True:
        try:
            mail.select('inbox')
            status, data = mail.search(None, 'ALL')
            mail_ids = []
            for block in data:
                mail_ids += block.split()
            for i in mail_ids:
                status, data = mail.fetch(i, '(RFC822)')
                for response_part in data:
                    refuse = False
                    if isinstance(response_part, tuple):
                        message = email.message_from_bytes(response_part[1])
                        mail_from = message['from']
                        mail_subject = message['subject']
                        mail_date = message['date']
                        if message.is_multipart():
                            mail_content = ''
                            for part in message.get_payload():
                                if part.get_content_type() == 'text/plain':
                                    mail_content += part.get_payload()
                        else:
                            mail_content = message.get_payload()
                            mail_content = message.get_payload()
                        position = 0
                        for i in mail_from:
                            if i == '<':
                                change = True
                                firstPos = position + 1
                            if i == '>':
                                change = True
                                lastPos = position
                            position = position + 1
                        mail_from = (mail_from[firstPos:lastPos])
                        myFile = open('/home/pi/GLaDOS/text-files/read_messages.txt', 'rt')
                        for i in myFile:
                            i = i.replace('\n', '')
                            if i == mail_date:
                                refuse = True
                        myFile.close()
                        if refuse == False:
                            myFile = open('/home/pi/GLaDOS/text-files/read_messages.txt', 'a')
                            myFile.write(mail_date)
                            myFile.close()

                            myFile = open('/home/pi/GLaDOS/text-files/command.txt', 'wt')
                            myFile.write(str(mail_subject))
                            myFile.close()

                            time.sleep(60)
        except Exception as e:
            print('error, retrying', e)
print('well I got here...')
emailChecker()

(note: I have censored some parts such as my email, password, and ifttt key, to prevent any unwanted mischief (; ) (another note: You probably don't need to look at any other program other than 'check.py')

I am using crontab to run three separate python scripts, the output of each script is piped out to a log file, only one of these three python scripts is running with an output.

This is the crontab file:

# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').
# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command
@reboot sleep 60 && sh /home/pi/GLaDOS/launcherCheck.sh >/home/pi/logs/check.log 2>&1
@reboot sleep 60 && sh /home/pi/GLaDOS/test.sh >/home/pi/logs/test.log 2>&1
@reboot sleep 60 && sh /home/pi/GLaDOS/launcherGLaDOS.sh >/home/pi/logs/GLaDOS.log 2>&1

The crontab file opens three distinct .sh files (as shown below), they are all configured with 'chmod 755 [name].sh'.

The .sh file 'test.sh' -

#!/bin/sh
# launcherGLaDOS.sh
# navigate to home directory, then to this directory, then execute python script, then back home

cd /
cd home/pi/GLaDOS
sudo python3 test.py
cd /

The .sh file 'launcherGLaDOS.sh' -

#!/bin/sh
# launcherGLaDOS.sh
# navigate to home directory, then to this directory, then execute python script, then back home

cd /
cd home/pi/GLaDOS
sudo python3 GLaDOS.py
cd /

the .sh file 'launcherCheck.sh' -

#!/bin/sh
# launcher.sh
# navigate to home directory, then to this directory, then execute python script, then back home

cd /
cd home/pi/GLaDOS
sudo python3 check.py
cd /

(note: I have put the time delay because there was some speculation that not all services on the raspberry pi had started by then)

I get no error messages, the program just seemingly does not run - I know this because I reviewed the output of each log files (https://i.sstatic.net/znqJh.png), and as you can see, both scripts worked, but the emailCheck did not.

These programs all work when not in crontab.

Something else worthy of note is that after reformatting the sd card, the program would seem to work (albeit, this was through rc.local), and so I am beginning to suspect some sort of sd card degradation - but because I know very little about the raspberry pi, I think this is probably the best place to go.

All and any solutions are welcome,

Matthew.


Solution

  • Solved!

    The program was running, the only way of telling whether or not it was running was to print to the shell - I wasn't viewing the shell. The solution was to write the logs to a file using (import logger), which meant I could just check a file to see if the script was running.