How to get virtualenv to use dist-packages on Ubuntu?

后端 未结 5 1909
一向
一向 2020-12-13 20:06

I know that virtualenv, if not passed the --no-site-packages argument when creating a new virtual environment, will link the packages in /usr/local/lib/py

5条回答
  •  执笔经年
    2020-12-13 20:49

    What you want to achieve here is essentially add specific folder (dist-packages) to Python search path. You have a number of options for this:

    1. Use path configuration (.pth) file, entries will be appended to the system path.
    2. Modify PYTHONPATH (entries from it go to the beginning of system path).
    3. Modify sys.path directly from your Python script, i.e. append required folders to it.

    I think that for this particular case (enable global dist-packages folder) third option is better, because with first option you have to create .pth file for every virtualenv you'll be working in (with some external shell script?). It's easy to forget it when you distribute your package. Second option requires run-time setup (add a envvar), which is, again, easy to miss.

    And only third option doesn't require any prerequisites at configure- or run-time and can be distributed without issues (on the same-type system, of course).

    You can use function like this:

    def enable_global_distpackages():
        import sys
        sys.path.append('/usr/lib/python2.7/dist-packages')
        sys.path.append('/usr/local/lib/python2.7/dist-packages')
    

    And then in __init__.py file of your package:

    enable_global_distpackages()
    

提交回复
热议问题