如何在virtualenv中设置环境变量 [英] How to set environment variables in virtualenv

查看:62
本文介绍了如何在virtualenv中设置环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有像这样激活 virtualenv 的 python 脚本:

If I have python script which activates the virtualenv like this:

#!/path/to/venv/bin/python

如何在不修改此脚本的情况下为该脚本设置变量?

How can I set variables for this script without modifying this script?

我希望这个环境变量对使用这个 virtualenv 的所有脚本有效.

I want this environment variable to be active for all scripts which use this virtualenv.

这意味着修改这个脚本不是一个解决方案,因为有二十个脚本,我不想修改二十个脚本.

This means modifying this script is not a solution, since there are twenty scripts, and I don't want to modify twenty scripts.

围绕 python 脚本编写一个 shell 包装器脚本是可行的,但我想避免这种情况.

Writing a shell wrapper-script around the python scripts would work, but I would like to avoid this.

过去我认为自定义 sitecustomize.py 可以用于启动代码.但是 Ubuntu(AFAIK 是唯一执行此操作的发行版)带有自己的 sitecustomize.py 文件,结果是我的 sitecustomize.py 不会被调用.请参阅 https://bugs.launchpad.net/ubuntu/+source/python2.5/+bug/197219

In the past I thought a custom sitecustomize.py can be used for start-up code. But Ubuntu (AFAIK the only distribution which does this) comes with its own sitecustomize.py file, with the effect that my sitecustomize.py does not get called. See https://bugs.launchpad.net/ubuntu/+source/python2.5/+bug/197219

以下是我想如何使用 virtualenv 的一些方法:

Here are some ways how I want to use the virtualenv:

(我又考虑过这个问题.我想设置变量不是python或virtualenv的工作.我需要一种统一的方式来设置环境变量.在我的情况下,我想在不使用shell的情况下做到这一点包装器).

(I have thought about this again. I guess it setting the variables is not the job of python or virtualenv. I need a unified way to set environment variables. And in my case I would like to do this without using a shell wrapper).

推荐答案

同时编写 sitecustomize.py 文件和更改 bin/python 都是可行的解决方案,我建议另一种不涉及直接更改virutalenv内部内容的方法,只需安装一个.pth文件:

while writing sitecustomize.py file and changing bin/python all are feasible solutions, I would suggest another method that does not involve directly change contents inside virutalenv, by simply install a .pth file:

./venv/lib/python2.7/site-packages/_set_envs.pth

内容:

import os; os.environ['FOO'] = 'bar'

测试:

$ ./venv/bin/python -c "import os; print os.getenv('FOO')"
bar

诀窍是,python 会加载每个 .pth 文件 启动时,如果有一行以import开头,这一行将被执行,允许注入任意代码.

the trick is, python will load every .pth file on startup, and if there is a line starts with import, this line will be get executed, allowing inject arbitrary code.

优点是,你可以简单地写一个python包来安装这个.pth 文件和 setuptools,安装到你想要改变的 virtualenv.

the advantage is, you could simply write a python package to install this .pth file with setuptools, install to the virtualenv you want to change.

这篇关于如何在virtualenv中设置环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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