Search This Blog

Thursday, April 24, 2014

Virtualenv+Git how to

If you do Python development, and don't use virtualenv, you should start right away! Not convinced? Just do some internet searches and get convinced. The problem then becomes, how to handle this with your preferred SCM. I use Git, so that's what I'll describe, but the concepts should easily translate to other SCMs.

 See, the issue is that the actual virtual environment folder shouldn't be under Git's control, cause different developers may use different platforms, so each developer/system combo will require a different virtual environment, suited for their specific need (virtualenv wil take care of this last part). Briefly, the idea is to create an outer folder, where all the code you (and possibly others) write lives. This folder should also contain all the information required to create the virtual environment, which is created as a subfolder. In other words:
- projectFolder/
    - requirements.txt
    - vEnvFolder/
        - .Python -> ...
        - bin/
        - include/
        - lib/
With this directory structure, simply add projectFolder/vEnvFolder/ to the .gitignore file and that's it! The requirements.txt file should be generated by using pip freeze, after installing all necessary dependencies in the virtual environment. Here's my complete workflow:
[~]$ cd gitProject/
[gitProject]$ virtualenv --no-site-packages vEnv
[gitProject]$ source vEnv/bin/activate
(vEnv)[gitProject]$ pip install 
(vEnv)[gitProject]$ pip freeze > requirements.txt
(vEnv)[gitProject]$ echo vEnv >> .gitignore
(vEnv)[gitProject]$ git add .
(vEnv)[gitProject]$ git commit -m "added virtualenv"
When checking out the project, the flow is as follows:
[~]$ git clone gitProject 
[~]$ cd gitProject 
[gitProject]$ virtualenv --no-site-packages vEnv
[gitProject]$ source vEnv/bin/activate
(vEnv)[gitProject]$ pip install -r requirements.txt
(... ready to rumble)
I don't know if this is the best/recommended alternative, but so far it has worked for me.

No comments:

Post a Comment