Python 2.x multiple version issues regarding PYTHONPATH

后端 未结 3 1932
没有蜡笔的小新
没有蜡笔的小新 2021-01-03 01:41

There\'s Python 2.6 installed in the system.

Now I want to use modules introduced in Python 2.7. Because I have no root privilege, I have built & installed 2.7 u

3条回答
  •  [愿得一人]
    2021-01-03 02:37

    On startup Python takes PYTHONPATH environment variable and puts it into sys.path variable. When you try to import a module it looks to the paths in sys.path

    Because of:

    export PYTHONPATH=$HOME/local/lib/python2.7:$PYTHONPATH
    

    your Python 2.7 paths are in the beginning of sys.path, before the paths of Python 2.6 (You can print sys.path to check). That means that modules from $HOME/local/lib/python2.7 will have a priority.

    To customize the paths for some of your scripts, either set PYTHONPATH per script, or modify sys.path (sys.path.insert(0, '/home/user/local/lib/python2.7') right in your script before any import is done.

    Or copy a specific module to your project under a different name. For example i copied collections module from Python 2.7 to my project with as collections27.py, and in places where i need OrderedDict i do from collection27 import OrderedDict

    Is it possible to load only 2.6 modules when Python 2.6 is invoked?

    Yes, i guess. Just assure that only Python 2.6 modules are in the path - don't use:

    export PYTHONPATH=$HOME/local/lib/python2.7:$PYTHONPATH
    

提交回复
热议问题