Virtualenvwrapper environment variables when running crons

谁说我不能喝 提交于 2019-12-13 04:23:20

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/54186439/virtualenvwrapper-environment-variables-when-running-crons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!