Python 从脚本中获取 virtualenv 的 bin 文件夹路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22003769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get virtualenv's bin folder path from script
提问by José Tomás Tocino
I'm using virtualenvwrapper with a django project that has a management task that automatically writes some config files, so the user just has to
我将 virtualenvwrapper 与 django 项目一起使用,该项目具有自动写入一些配置文件的管理任务,因此用户只需
./manage.py generate_configuration > much_nice.conf
And then move the file elsewhere. One of the generated config files is a task for supervisord that launches a celery worker. The problem I'm getting is that I don't know how to output the path of the celery executablethat is within the bin folderof the virtualenv. Essentially, I'd like to have the output of the command
然后将文件移到别处。生成的配置文件之一是 supervisord 启动芹菜工作者的任务。我得到的问题是,我不知道如何输出芹菜可执行文件的路径是bin文件夹内的virtualenv中的。本质上,我想要命令的输出
which celery
One option is using sys.executable, get the folder (which seems to be the binfolder of the virtualenv) and that's it... but I'm not sure.
一种选择是使用sys.executable, 获取文件夹(这似乎是binvirtualenv的文件夹),就是这样......但我不确定。
Doesn't virtualenv have any kind of method to get the path itself?
virtualenv 没有任何方法来获取路径本身吗?
采纳答案by Brad Culberson
The path to the virtual env is in the environment variable VIRTUAL_ENV
虚拟环境的路径在环境变量 VIRTUAL_ENV 中
echo $VIRTUAL_ENV
回答by glmvrml
回答by Laurent LAPORTE
The VIRTUAL_ENVenvironment variable is only available if the virtual environment is activated.
该VIRTUAL_ENV如果虚拟环境中被激活的环境变量才可用。
For instance:
例如:
$ python3 -m venv myapp
$ source myapp/bin/activate
(myapp) $ python -c "import os; print(os.environ['VIRTUAL_ENV'])"
/path/to/virtualenv/myapp
If not activated, you have an exception:
如果没有激活,你有一个例外:
(myapp) $ deactivate
$ myapp/bin/python -c "import os; print(os.environ['VIRTUAL_ENV'])"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib64/python3.4/os.py", line 635, in __getitem__
raise KeyError(key) from None
KeyError: 'VIRTUAL_ENV'
IMO, you should use sys.executableto get the path of your Python executable,
and then build the path to celery:
IMO,您应该使用sys.executable来获取 Python 可执行文件的路径,然后构建 celery 的路径:
import sys
import os
celery_name = {'linux': 'celery', 'win32': 'celery.exe'}[sys.platform]
celery_path = os.path.join(os.path.dirname(sys.executable), celery_name)

