将模块从Python标准库安装到本地目录的标准方法是什么?

时间:2012-03-26 06:03:12

标签: python environment-variables python-module

我发现我正在使用的服务器的管理员往往使python模块过时,我没有时间等待这个人更新全局目录。

有没有什么方法可以让我的本地python模块优先于全局库而无需手动修改sys.path?

1 个答案:

答案 0 :(得分:4)

有各种选择。如果您使用的是Python 2.6或更高版本,则可以使用Python的Distutils支持的user installation scheme在您的主目录中安装Python模块。只需将--user添加到setup.py install命令,如链接中所述。另一个流行的选择是使用第三方virtualenv包来创建一个或多个孤立的本地Python环境。

更新:对于user installation scheme,在Python启动期间检查用户site-packages目录。如果该目录存在,则会在系统site-packages目录之前将其添加到sys.path。例如,使用Debian Linux安装:

$ python2.7 -c 'import site; print(site.USER_SITE)'
/home/nad/.local/lib/python2.7/site-packages
$ ls -l /home/nad/.local/lib/python2.7/site-packages
ls: cannot access /home/nad/.local/lib/python2.7/site-packages: No such file or directory
$ python2.7 -c 'import sys; print(sys.path)'
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/pymodules/python2.7']
# user site-packages dir doesn't exist so it's not in sys.path
$ mkdir -p ~/.local/lib/python2.7/site-packages
$ python2.7 -c 'import sys; print(sys.path)'
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/home/nad/.local/lib/python2.7/site-packages', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PIL', '/usr/lib/pymodules/python2.7']
# now user site-packages dir exists so it is in sys.path and before /usr/lib ones