virtualenv 是如何工作的? [英] How does virtualenv work?
问题描述
我检查了 activate 脚本,在我看来它所做的就是:
I checked the activate script and it looks to me all it does is:
- 设置 VIRTUAL_ENV 环境
- 在 PATH 前面附加 $VIRTUAL_ENV/bin
virtualenv
如何通过这些提供神奇的虚拟环境?我想念什么?
How does virtualenv
provide that magical virtual environment by these? What do I miss?
推荐答案
我将描述基本过程,这是我从 @jcollado 链接的演示文稿中学到的.
I will describe the basic process, which I learned from the presentation @jcollado linked to.
Python 启动时,会查看二进制文件的路径及其前缀.
When Python starts, it looks at the path of the binary, and the prefixes thereof.
假设您的 virtualenv 是 /home/blah/scratch
.Python 进程知道它是从 /home/blah/scratch/bin/python
执行的(通常只是你系统 python 二进制文件 /usr/bin/python
的副本)) 并且它知道自己的版本 XY
因为它已编译到其中.然后 Python 按以下顺序查找 lib/pythonX.Y/os.py
:
So let's say your virtualenv is /home/blah/scratch
. The Python process knows it was executed from /home/blah/scratch/bin/python
(which is usually just a copy of your system python binary /usr/bin/python
) and it knows its own version X.Y
because it's compiled into it. Then Python looks for lib/pythonX.Y/os.py
in this order:
/home/blah/scratch/bin/lib/pythonX.Y/os.py
/home/blah/scratch/lib/pythonX.Y/os.py <-- this file should exist
/home/blah/lib/pythonX.Y/os.py
/home/lib/pythonX.Y/os.py
/lib/pythonX.Y/os.py
它停在 /home/blah/scratch/lib/pythonX.Y/os.py
因为它是第一个实际存在的文件.如果没有,Python 会继续寻找.然后它基于此设置 sys.prefix
.它使用类似的过程设置sys.exec_prefix
,然后根据这些构造sys.path
.
It stops at /home/blah/scratch/lib/pythonX.Y/os.py
because it's the first file that actually exists. If it didn't, Python would keep looking. It then sets sys.prefix
based on this. It uses a similar process to set sys.exec_prefix
, and then sys.path
is constructed based on these.
这篇关于virtualenv 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!