Where in a virtualenv does the custom code go?

后端 未结 4 1449
情深已故
情深已故 2020-12-07 07:42

What sort of directory structure should one follow when using virtualenv? For instance, if I were building a WSGI application and created a virtualenv called

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 08:12

    If you only have a few projects every so often, nothing stops you from creating a new virtualenv for each one, and putting your packages right inside:

    /foobar
      /bin
        {activate, activate.py, easy_install, python}
      /include
        {python2.6/...}
      /lib
        {python2.6/...}
      /mypackage1
        __init__.py
      /mypackage2
        __init__.py
    

    The advantage of this approach is that you can always be sure to find find the activate script that belongs to the project inside.

    $ cd /foobar
    $ source bin/activate
    $ python 
    >>> import mypackage1
    >>>
    

    If you decide to be a bit more organized, you should consider putting all your virtualenvs into one folder, and name each of them after the project you are working on.

      /virtualenvs
        /foobar
          /bin
            {activate, activate.py, easy_install, python}
          /include
            {python2.6/...}
          /lib
            {python2.6/...}
      /foobar
        /mypackage1
          __init__.py
        /mypackage2
          __init__.py
    

    This way you can always start over with a new virtualenv when things go wrong, and your project files stay safe.

    Another advantage is that several of your projects can use the same virtualenv, so you don't have to do the same installation over and over if you have a lot of dependencies.

    $ cd /foobar
    $ source ../virtualenvs/foobar/bin/activate
    $ python 
    >>> import mypackage2
    >>>
    

    For users that regularly have to set up and tear down virtualenvs it would make sense to look at virtualenvwrapper.

    http://pypi.python.org/pypi/virtualenvwrapper
    

    With virtualenvwrapper you can

    * create and delete virtual environments
    
    * organize virtual environments in a central place
    
    * easily switch between environments
    

    You no more have to worry about where your virtualenvs are when working on the projects "foo" and "bar":

      /foo
        /mypackage1
          __init__.py
      /bar
        /mypackage2
          __init__.py
    

    This is how you start working on project "foo":

    $ cd foo
    $ workon
    bar
    foo
    $ workon foo
    (foo)$ python
    >>> import mypackage1
    >>>
    

    Then switching to project "bar" is as simple as this:

    $ cd ../bar
    $ workon bar
    (bar)$ python
    >>> import mypackage2
    >>>
    

    Pretty neat, isn't it?

提交回复
热议问题