0
votes

I tried to make a cron job on crontab which runs a python script on AWS ec2. My python script includes a module that is only available for python3. Using the following command I changed the ec2 default python interpreter from python2.7 to python3.4 Source /home/ec-2user/venv/python34/bin/activate and then using pip install, I installed the required module for python3.4. So now the default interpreter is python3.4 and when I run the script on ec2-user directory using the following command: python test.py the program runs without any problem (so I am sure the module is installed correctly). But when I assign python file to a cronjob * * * * * python test.py

It does not work. Checking the mail, the error is: “No module found named “xxxxx” “

But as I said it worked fine outside of the cron.

I was wondering if you can help me with this problem. I appreciate your time and information.

2

2 Answers

2
votes

You have to make a shell script which will do the steps of changing to script directory, activating virtual environment and then running it.

Example:

#!/bin/bash

cd $YOUR_DIR
. venv/bin/activate
python3.4 test.py

Then you call this script in cron with /bin/bash /.../script.sh


What you could do additionally is

chmod +x test.py

and add/update first line to:

#!/usr/bin/env python3.4

This way you can just run Python script with ./test.py

0
votes

Create file as 'user_cron.sh'

#!/bin/bash
cd '/root/my_new_project_python'
. my_project_venv/bin/activate
python3 main.py

set the cron using crontab -e