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,

I’ve made it executable:

chmod +x 

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_USER = 'mail_username'
IMAP_PASS = 'mail_password'
def clear_old_messages():

today ='%d-%b-%Y')

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

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

if __name__ == '__main__':

I’ve opened up crontab in Ubuntu with

crontab -e

and added

0 1 * * * /home/[user]/scripts/

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/ 

Answered by on January 6, 2022

Add your own answers!

Ask a Question

Get help from others!

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