Issue
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?
Solution
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.
Answered By - ShadowRanger Answer Checked By - Terry (WPSolving Volunteer)