Jeon
Jeon

Reputation: 4076

How to set PYTHONPATH differently for version 2 and 3?

Let's assume that I set PYTHONPATH in .bashrc as below:

export PYTHONPATH=$PYTHONPATH:/ver2packages

And when I check my python path in Python 3:

$ python3
>>> import sys
>>> print(sys.path)
['', '/home/user', '/ver2packages', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/usr/local/lib/python3.4/dist-packages', '/usr/lib/python3/dist-packages']

In ver2packages, if there are packages having the same name with packages for version 3, there might be conflicts and errors.

Is there a way to set pythonpath for each version of Python?

Upvotes: 9

Views: 7552

Answers (4)

林果皞
林果皞

Reputation: 7793

Alternatively way is set alias in ~/.bashrc or ~/.bash_aliases, e.g.(Assume python2 is your existing python 2 command):

alias py2='PYTHONPATH=/usr/local/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages python2'

, which this path can get from import site; site.getsitepackages()

In future simply issue command py2 instead of python2 to do the task with version 2 packages.

Upvotes: 0

Assem
Assem

Reputation: 12097

For Linux, you can create a symbolic link to you library folder and place it in your aimed version:

ln -s /your/path /usr/local/lib/python3.6/site-packages

This is not about changing PYTHONPATH but an alternative solution.

Upvotes: 5

Eugene Yarmash
Eugene Yarmash

Reputation: 149796

You can set different sys.path for Python 2 and Python 3 using path configuration (.pth) files.

For instance, to add a directory to sys.path for Python 2, create a .pth file in any of Python 2 site-packages directories (i.e. returned by site.getsitepackages() or site.getusersitepackages()):

Python 2.7.11 (default, Dec  6 2015, 15:43:46) 
[GCC 5.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import site
>>> site.getsitepackages()
['/usr/lib/python2.7/site-packages', '/usr/lib/site-python']

Then create a .pth file (as root):

echo "/ver2packages" > /usr/lib/python2.7/site-packages/ver2packages.pth

See site module documentation for more.

Upvotes: 5

Gil Hamilton
Gil Hamilton

Reputation: 12347

Your options are dependent on the operating system.

For ubuntu, if you're using the standard python packages...

If you wish to do this system-wide (and you have administrative privileges), you can add additional paths to sys.path via /usr/lib/pythonN.M/site.py.

For yourself only, the system default site.py files already put $HOME/.local/lib/pythonN.M/site-packages into your sys.path (iff it exists) so you can just create the directories and put version-specific packages there.

Upvotes: 0

Related Questions