problem with cronjob to run python script on ubuntu server

Question:

I have installed python3 following the Digital Ocean guide and to run my python scripts just by command line, this is the bash I use and it works:

    ~$ source /home/username/python_projects/project_name/bin/activate
    ~$ python3 /home/username/python_projects/project_name.py
    ~$ deactivate

if I put that commands in crontab in the same order, nothing happens.

    0 7 * * * source /home/username/python_projects/project_name/bin/activate
    0 7 * * * python3 /home/username/python_projects/project_name.py
    0 7 * * * deactivate

What am I doing wrong?

Cronjob is active and running.

    ~$ systemctl status cron

The python file has this permissions:

    -rw-rw-r-- 1 user_name user_name 17075 Feb  7 02:30 python_projects/project_name.py
Asked By: Neuran

||

Answers:

There are a few things that could be causing your cronjob not to run:

Environmental variables: The source command in your cronjob sets up the virtual environment, but this environment is not passed on to the cron process. You should specify the full path to the Python executable in your virtual environment, e.g. /home/username/python_projects/project_name/bin/python3.

Permission issues: Ensure that the cron user has permission to execute the script and access the virtual environment.

Output: By default, cron does not send any output to the terminal. If your script produces output, you may want to redirect it to a file for debugging purposes. You can do this by adding > /tmp/output.log 2>&1 to the end of your crontab entry.

You can check the system logs for any error messages related to your cron job. The logs are usually located in /var/log/syslog or /var/log/messages.

I hope this helps!

Answered By: Dog9w23

The activate job runs, then exits, and then the next cron job knows nothing about what it did. You want to run them all in the same process (though running deactivate at the end is pointless, as everything that activate did will be wiped when the job ends anyway).

In practice, you can run the Python interpreter from within the virtual environment directly.

For what it’s worth, the error message about "no MTA installed" means that the output from cron was discarded because the system could not figure out how to send it by email. You’ll probably want to change the rule to write the output to a file.

0 7 * * * cd python_projects && ./project_name/bin/python3 project_name.py >>project_name.log 2>&1

Perhaps notice that cron always starts in your home directory, so you don’t have to spell out /home/username (provided of course that username is the user whose crontab this runs from).

Answered By: tripleee
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.