Python development and virtualenv
Using virtualenv for Python development
When starting out with Python development it’s really easy to have some bad practices spread in your workflow. And when all you want is just to have this or that module get installed so you can import it in your script, who cares where the library would get installed.
Easy_install, pip install… do I have to put a sudo in front of it to make it work? Let’s just do whatever and then try importing the thing in the Python shell, if it work’s I will be happy.
Okay, but…
This mode of operation will work in the beginning and to a certain degree, but it has its limits and in the worst of all cases you will even touch system libraries and or destroy their references when just carelessly using
sudo pip install
sudo easy_install
Getting into the habit of using virtualenv
At first I tried to avoid virtualenv because I thought while it would be suited for bigger environments where you’d need a ton of different Python versions and dependencies in different versions this would not be necessary for my small projects.
Well, this is not true and its better to manage your Python modules properly from the start. Also as mentioned above it can have very bad consequences when just installing every module globally to your system’s Python libraries. If you won’t run into a problem today, you will eventually one day :/
Setting up virtualenv
Since Python3.4 virtualenv is included, so you don’t even need to install it anymore. If for an older version you might want to run pip install --user virtualenv
or apt-get install python3-virtualenv
to get it installed.
Then, I think it’s a good idea to keep environment and code separate. This also helps with git version control, so I don’t need to add the env folder to my .gitignore.
So I will create a folder .envs in my home directory where to put them:
mkdir ~/.envs/
Now I will create my default environment for python3 development python3 -m venv ~/.envs/myPy3
this will install all files to get you ready. You can then activate the environment by sourcing the bin/activate
in your environment. So in our case we will do source ~/.envs/myPy3/bin/activate
To be sure this has worked, you should see your shell transform into (myPy3) $
We’ve got our default environment all set up and we can install any module we’d like into it, just by using pip3 install
Leaving the virtualenv
Now, with the virtualenv activated you can do your development work. When you want to leave the virtualenv you just type deactivate