'How to export PYTHONPATH when I activate a virtual environment on pyenv-virtualenv?
I am using pyenv and its plugin pyenv-virtualenv.
My questions is: How to modify PYTHONPATH environment variable when I activate some virtual environment on pyenv-virtualenv?
$ pyenv activate myenv
$ echo $PYTHONPATH # I want this variable!
When I used simple virtualenv, I could modify PYTHONPATH via editing virtualenv_home/your_env/bin/activate
export OLD_PYTHONPATH=$PYTHONPATH
export PYTHONPATH="/path/to/you/want"
Which file should I edit for pyenv-virtualenv?
Solution 1:[1]
You simply set PYTHONPATH
as per normal, whether that is in your shell startup script or elsewhere. When you switch to a pyenv-controlled virtualenv with pyenv virtualenv
, it will automatically append all the necessary directories for this virtualenv to sys.path
, but any directories you defined in the PYTHONPATH
variable will precede them.
Added based on discussion in comments below:
You can create hook scripts for a given pyenv command <command>
in $PYENV_HOME/pyenv.d/<command>/
. You can even do this for pyenv’s “porcelain” commands which aren’t normally called directly by the user.
It should be possible to create a hook for activate
(which is implicitly called by pyenv-virtualenv when switching to a virtualenv) which parses the name of the virtualenv and sets $PYTHONPATH
based on that.
Note: I’ve written pyenv hooks before but haven’t explicitly tested this solution.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |