Home > Enterprise >  Crontab isn't running my python script in macOs although the script works when run manually
Crontab isn't running my python script in macOs although the script works when run manually

Time:12-17

My school always wants us to download pptx and docx for lecture and practicals and I hate that I'll need to always manually delete it after reading finish. Therefore I'd created a script that trashes whatever's in the folder and would like crontab to schedule it to run every hour.

Everything works fine when I manually run this code through the terminal.

def remove_trash():
    import os
    dir_path = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(dir_path, "trash_script.py")
    with open(filename, "r") as f:
        _ = f.read()
    os.system(f"rm -df {dir_path}/* && touch {filename}")
    with open(filename, "w") as f:
        f.write(_)
        
if __name__ == "__main__":
    remove_trash()

But when I had added this in my crontab,

0 * * * * python ~/Desktop/Projects/script/Trash/trash_script.py

I tried giving the file permission to execute but it still wouldn't run at every minute 0.

chmod  x trash_script.py

CodePudding user response:

I'll suggest to move your script into a bash script first, and add some logs to find the issue. The bash script will look like this:

trash.sh

cd ~/Desktop/Projects/script/Trash
python trash_script.py

Change the execution permissions of your script

chmod  x trash.sh

Modify your cron job to look like this:

0 * * * * sh <path_to_bash_script>/trash.sh >> ~/Desktop/Projects/script/Trash/trash.log 2>&1

This will help to have some output every time the script runs.

  • Related