AnswerBun.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!

Related Questions

Dark Mode not working in 20.04

2  Asked on December 10, 2021 by digvijay-singh

     

My xubuntu gateway is slowing my internet speeds

0  Asked on December 10, 2021 by q3ait-administrator

     

Unable to set interface up in Ubuntu 18.04

1  Asked on December 10, 2021 by josep-pascual

         

IO_PAGE_FAULT with new server installation

1  Asked on December 10, 2021 by lobert

   

What is the systemctl equivalent

3  Asked on December 8, 2021 by marnaw

   

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir