Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set PYTHONPATH differently for version 2 and 3?

Tags:

python

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?

like image 243
Jeon Avatar asked Jan 06 '16 12:01

Jeon


People also ask

Can you have more than one Pythonpath?

Background. Setting the PYTHONPATH environment variable is an easy way to make Python modules available for import from any directory. This environment variable can list one or more directory paths which contain your own modules. On Windows, multiple paths are separated by semicolons.

How do I run a different version of Python?

If you want to use a different version, you can do so by inserting a special line at the top of your file, called a hashbang. You can also use a hashbang to run your script in a virtualenv that you've defined by pointing it at the python executable in the virtualenv.

What is Pythonpath and how do you set it?

PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. For most installations, you should not set these variables since they are not needed for Python to run. Python knows where to find its standard library.


2 Answers

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.

like image 84
Assem Avatar answered Sep 28 '22 06:09

Assem


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.

like image 22
Eugene Yarmash Avatar answered Sep 28 '22 07:09

Eugene Yarmash