Virtualenvwrapper environment variables when running crons
Asked Answered
B

1

0

I'm running a basic cron that requires environment variables which I've set up using virtualenvwrapper. The environment variables are set up in /home/ubuntu/.virtualenvs/testcron/bin/activate

When I run the command cd /home/ubuntu/test_script && /home/ubuntu/.virtualenvs/testcron/bin/python3 my_script.py the script runs as intended with no errors. The script imports an environment variable and prints it.

However, when I run the same script through a cron ( * * * * * cd /home/ubuntu/test_script && /home/ubuntu/.virtualenvs/testcron/bin/python3 my_script.py) I get this error.

Traceback (most recent call last):
  File "my_script.py", line 7, in <module>
    main()
  File "my_script.py", line 4, in main
    print(os.environ['SOME_ENV_VARIABLE'])
  File "/home/ubuntu/.virtualenvs/testcron/lib/python3.5/os.py", line 725, in __getitem__
    raise KeyError(key) from None
KeyError: 'SOME_ENV_VARIABLE'

When I run the following I don't seem to have any issues

~$ /home/ubuntu/.virtualenvs/testcron/bin/python3
>>> import os
>>> os.environ['SOME_ENV_VARIABLE']
'my_env_variable_value'

Am I missing something obvious, do I have some issue with virtualenvwrapper's configuration or is there a catch to running crons in this way?

Biestings answered 14/1, 2019 at 17:29 Comment(0)
B
2

Running python from the virtualenv (/home/ubuntu/.virtualenvs/testcron/bin/python3) allows access to the venv site-packages but it doesn't activate the venv. If you have something unusual in bin/activate you have to source it every time you need it:

* * * * * cd /home/ubuntu/test_script && . /home/ubuntu/.virtualenvs/testcron/bin/activate && /home/ubuntu/.virtualenvs/testcron/bin/python3 my_script.py
Bandog answered 15/1, 2019 at 5:28 Comment(4)
And if the env doesn't set this variable for you then your question is barking up the wrong tree, and you just need to set it explicitly for your cron job.Halfslip
The question says: The environment variables are set up in /home/ubuntu/.virtualenvs/testcron/bin/activateBandog
@Bandog It looks like source doesn't work. You need to replace it with . instead. Otherwise, it worked great. Thanks for the helpBiestings
Fixed source.Bandog

© 2022 - 2024 — McMap. All rights reserved.