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!

Related Questions

How to give a 64-bit windows app at least 4gb with Wine?

0  Asked on December 6, 2020 by lelorrain


Secondary partition -I cant Execute files

0  Asked on December 5, 2020 by martin-andersen


can’t execute a script via the startmenu in Gnome

0  Asked on December 5, 2020 by vrms


Uneven refresh rate on display

0  Asked on December 5, 2020 by curiousstudent


Cursor stuck in select mode

1  Asked on December 5, 2020 by mohand-andel


Where’s the Flatpak on Ubuntu 20.04?

2  Asked on December 4, 2020 by user1079583


How to install trello in ubuntu

3  Asked on December 3, 2020 by ujjal-das


Bluetooth not working hp pavillion g6

0  Asked on December 3, 2020 by fastonkill


Convert Ubuntu Physical machine to Virtual machine

3  Asked on December 3, 2020 by cyberquarks


Music Production Tools (DJ)

1  Asked on December 2, 2020 by user244589


Ask a Question

Get help from others!

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