Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I activate a pyvenv vitrualenv from within python? (activate_this.py was removed?)

Tags:

I'm using Python 3.4, and having created a pyvenv, I'm looking to activate it from within a python process. With virtualenv, I used to use activate_this.py, but that appears to be gone in pyvenv.

Is there now an easy way to effectively change the current interpreter to the virtualenv interpreter? I could probably mess around with the PATH (which is what activate_this.py did), but I'd like a simpler and stabler way.

This is for use in a wsgi.py.

like image 313
Chris Cooper Avatar asked Dec 13 '14 19:12

Chris Cooper


People also ask

What does Pyvenv CFG do?

The pyvenv. cfg is a configuration file which stores information about the virtual environment such as the original Python that the environment was cloned from (and which will provide the standard library) and the version of the interpreter.

How do I disable Python virtual environment in Windows?

Just type "workon" with no arguments and hit enter. The command to leave is "deactivate", as answered below.


1 Answers

pyvenv and the venv module don't support this out of the box. The third party virtualenv package does support this using activate_this.py, but that feature was not included in the built-in venv module.

You could try to borrow a copy of activate_this.py from a virtualenv based environment; it seems to work, though I can't swear it will be perfect (venv/pyvenv uses some magic during startup; unclear if all of it is replicated via activate_this.py).

The virtualenv docs for it are out of date for Python 3 (they claim you use execfile, which doesn't exist). The Python 3 compatible alternative would be:

activator = 'some/path/to/activate_this.py'  # Looted from virtualenv; should not require modification, since it's defined relatively with open(activator) as f:     exec(f.read(), {'__file__': activator}) 

Nothing activate_this.py does is magical, so you could manually perform the same changes without looting from virtualenv (adjusting PATH, sys.path, sys.prefix, etc.), but borrowing makes it much simpler in this case.

like image 88
ShadowRanger Avatar answered Sep 20 '22 15:09

ShadowRanger