'Cronjob: Run Python script on server in virtual env

I went through tons of questions and answers in the net. However, I couldnt make my code work. So sorry for raising this question as so many others did.

I have a python script in my directory:

test_codes/test_mail/test_crawler.py 

I have my virtualenv in:

.virtualenvs/test_crawler/bin/python

So I have set up a cronjob like this:

* * * * * .virtualenvs/test_crawler/bin/python test_codes/test_mail/test_crawler.py > /test_codes/test_mail/cronlogs.log 2>&1

I have two troubles with that:

  1. The script should send me an test mail, which I do not receive (manually starting the script works fine(
  2. The cronlog-file does not appear. Do I need to create this one first? In my opinion this file will be created when executing the first cronjob

Thanks for help in advance



Solution 1:[1]

First try this :

  1. cd to the folder where your script is (.py file)
  2. activate your virtualenv
  3. launch python3 with script

Start with an easier cronjob first to see if it works : Make a test.py file :

import datetime

with open("test.txt", mode="a") as file:
    file.write(str(datetime.datetime.now())+"\n")

Add this your cron, make sure you have the right path for the virtualenv

* * * * * cd ~/test_codes/test_email && ../venv/bin/python3 test.py > /tmp/cronlog_test.txt 2>&1

Path :

test_codes
??? venv
??? test_email
    ??? test.py

Regarding your 2nd question, the cronlog_test.txt will be generated with the cronjob

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aravinth Balakrishnan