Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 272
keisuke Avatar asked Jun 03 '26 21:06

keisuke


1 Answers

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.

like image 123
wjv Avatar answered Jun 06 '26 10:06

wjv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!