Forums

Trouble getting environment variables to work with virtualenv and scheduled task, please advise!

Hello! I have been trying to figure out this problem on and off for a couple weeks. I have googled and read several posts in this forum but either I do not understand how my problem is related or I haven't found a related one. I'll try to be brief:

I have a scheduled task, that archives and backs up a database daily. Once a week I want the latest backup sent to me by mail. Because I read that hard coding emails and passwords is a bad idea, I want to use environmental variables for this. The backups work flawlessly, however the mail never goes through. I thought it was a problem with my credentials or mail service, but a simple test lead me to believe it may be the variables.

I have this part in my code:

sender_email = environ.get('VARIABLE_NAME')

print("CHECK HERE IF variable gets read correctly.")

print(sender_email)

If executed through the scheduled task, it returns this:

CHECK HERE IF variable gets read correctly.

None

My scheduled task is set up like this:

/home/username/.virtualenvs/myvirtualenv/bin/python /home/username/backup.py

The virtualenv in question has their /home/username/.virtualenvs/myvirtualenv/bin/postactivate set up like this:

set -a; source ~/folder/variables.env; set +a

When using the virtualenv in a regular bash, the variables work. I have double checked the .env and

export VARIABLE_NAME=email@email.com

exists.

I may be fundamentally misunderstanding how the scheduled task executes with the virtualenv and how it uses the environment variables, but I could not find the information anywhere. I would be very grateful for some insight into how to set this up without hard coding my credentials. Thank you for your time!

Edit: I forgot to mention, that if I run the code manually through a virtualenv console, it executes and sends the email without issue.

I wondering if when you're running /home/michanoku/.virtualenvs/myvirtualenv/bin/python /home/michanoku/backu.. in the scheduled task if it's not running the post activate hook. Have you tried a command in the scheulded action along the lines of source virtualenvwrapper.sh && workon myenv && python /home/myusername/myproject/myscript.py . Other than that you could try writing a short bash script as an entrypoint which sources the variables.env then runs the python

Hello sboyd, thank you for your help.

I have set up the scheduled task to run with the code line you provided and it worked immediately.

Again, thank you for the support.

Have a nice day!

Glad to hear that!