python虚拟env和“ activate_this.py” python是什么实际上吗?

发布于 2025-01-29 14:48:46 字数 786 浏览 5 评论 0原文

我正在研究一个Python CLI项目,不幸的是,该项目在虚拟环境方面有些复杂,因为它必须处理多个。

为了使我的工具正常工作,我遇到了Virtual Env的“ Activate_this.py”文件,该文件是在.venv/ bin/ Directory中生成的。 我认为这对我的需求可能很有用,因此我开始尝试它,但是我还没有真正了解它在引擎盖下实际在做什么。

例如,它说必须在必须从现有的Python解释器调用文件时使用脚本(我的情况),但必须激活虚拟环境。

我正在努力理解的是:在给定文件上的虚拟环境到底是什么意思? (由于我们没有更改解释器)。

此外,在Activate_this.py文件上,有一定的代码:

# add the virtual environments libraries to the host python import mechanism
prev_length = len(sys.path)
for lib in "../lib/python3.9/site-packages".split(os.pathsep):
    path = os.path.realpath(os.path.join(bin_dir, lib))
    site.addsitedir(path.decode("utf-8") if "" else path)
sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]

这是否意味着您现在可以导入您刚刚激活的虚拟设备上安装的库,即使它们是未安装在基础解释器的环境中?

I'm working on a python CLI project that, unfortunately, is a little complex on the virtual environments side, as it has to deal with multiple ones.

In my quest to get my tool to work properly and robustly, I came across Virtual Env's "activate_this.py" file, which is generated inside the .venv/bin/ directory.
I thought this could be useful for my needs so I started experimenting with it, but I haven't truly understood what it is actually doing under the hood.

For example, it says that the script should be used when a file must be called from an existing python interpreter (which is my case), but the virtual environment must be activated.

What I'm struggling to understand is: What exactly does activating a virtual environment on a given file mean? (Since we're not changing the interpreter)

Also, on the activate_this.py file there's this bit of code:

# add the virtual environments libraries to the host python import mechanism
prev_length = len(sys.path)
for lib in "../lib/python3.9/site-packages".split(os.pathsep):
    path = os.path.realpath(os.path.join(bin_dir, lib))
    site.addsitedir(path.decode("utf-8") if "" else path)
sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]

Does this mean that you can now import libraries that are installed on the virtual env you've just activated, even if they are not installed in the environment of the base interpreter?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清欢 2025-02-05 14:48:46

你知道了。它重写了您的sys.path以公开虚拟环境中安装的东西,并切断了对虚拟环境中全球安装的第三方库不是的访问。

You've got it. It rewrites your sys.path to expose the stuff installed in the virtual environment, and it cuts off access to the globally installed third-party libraries not in the virtual environment.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文