运行crons时的Virtualenvwrapper环境变量 [英] Virtualenvwrapper environment variables when running crons

查看:116
本文介绍了运行crons时的Virtualenvwrapper环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个基本的cron,它需要使用 virtualenvwrapper 设置的环境变量。在 /home/ubuntu/.virtualenvs/testcron/bin/activate

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

运行命令 cd / home / ubuntu / test_script&& /home/ubuntu/.virtualenvs/testcron/bin/python3 my_script.py 脚本按预期运行,没有错误。脚本会导入环境变量并进行打印。

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.

但是,当我通过cron运行相同的脚本时( * * * * * cd / home / ubuntu / test_script& / amp; /home/ubuntu/.virtualenvs/testcron/bin/python3 my_script.py )我收到此错误。

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'

我错过了一些明显的东西,我对virtualenvwrapper的配置有问题吗?还是有这种方式运行克朗的陷阱?

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?

推荐答案

从virtualenv运行python ( /home/ubuntu/.virtualenvs/testcron/bin/python3 )允许访问venv site-packages ,但是它不会激活静脉。如果您在 bin / activate 中遇到异常,则必须在每次需要时进行查找:

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

这篇关于运行crons时的Virtualenvwrapper环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆