TransWikia.com

Do I need to call Python in a cron job script?

Ask Ubuntu Asked on January 6, 2022

I’m trying to run a cron job from a home server that runs Ubuntu 24/7, using a Python script to clear a remote mailbox.

In a folder "scripts" in my home folder, I’ve put in a Python script, garbage.py.

I’ve made it executable:

chmod +x garbage.py 

The script is (with the username and password updated to the real username and password):

#!/bin/env python3

import imaplib
import ssl
from datetime import datetime
# your IMAP server credentials
IMAP_HOST = 'mail.us.opalstack.com'
IMAP_USER = 'mail_username'
IMAP_PASS = 'mail_password'
def clear_old_messages():

today = datetime.today().strftime('%d-%b-%Y')

ctx = ssl.create_default_context()
server = imaplib.IMAP4_SSL(host=IMAP_HOST, ssl_context=ctx)
server.login(IMAP_USER, IMAP_PASS)
server.select()

resp, items = server.search(None, f"SENTBEFORE {today}")
items = items[0].split()
for i in items:
    server.store(i, '+FLAGS', '\Deleted')

server.expunge()
    server.logout()
if __name__ == '__main__':
    clear_old_messages()

I’ve opened up crontab in Ubuntu with

crontab -e

and added

0 1 * * * /home/[user]/scripts/garbage.py

I’m a bit stymied as to what’s not working. Do I need to call Python in the cron task, even though it’s called at the top of the script? Or is there something I’m missing?

One Answer

Famous mistake with cron : there is no env :: Edit the shebang #!/bin/env python3 with the full path of python 3 binary. Find it with whereis python3

The shebang could be something like #!/usr/bin/python3.7

OR you can also call the python binary in the crontab file

0 1 * * * /usr/bin/python3.7  /home/[user]/scripts/garbage.py 

Answered by cmak.fr on January 6, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP