Virtualenv and Virtualenvwrapper tutorial
Virtualenv is a helpful tool to create isolated Python environments. So, inside those environments you can create your own projects and install it’s python packages and dependencies without affecting your system’s site-packages. Also, you can control packages versions for each project and much more.
We are going to need pip
, if you are on Mac OS X, you can installing via easy_install
:
Installing virtualenv and virtualenvwrapper
Install virtualenv via pip:
We are going to use also virtualenvwrapper, a tool to create/delete virtualenvs in an easier way. This because virtualenv itself is too verbose and a bit complicated.
Install virtualenvwrapper via pip:
Let’s create where our virtual environments would live. NOTE: our project folder does not need live in this folder too. We can set it anywhere.
You can name it as you want, I rather prefer to use virtualenvs.
If you are using standard shell, open your ~/.bashrc
or ~/.zshrc
if you use oh-my-zsh. Add this two lines
Starting a new virtual environment
Let’s create a virtualenv called myenv
You will notice a change in your command prompt, it will contain the virtualenv name that indicates that it has been activated. Now, all the python packages that your install without using sudo
and having your env activated will install inside virtualenv own site-packages.
Our new env is located at ~/.virtualenvs/myenv
Now, we can create our project folder, It does not matter where is located, we just need to have our virtualenv activated and no more.
Specifying a python version
By default, python virtualenv executable is took from python system version, if you want to specify your own version, add --python=your_python_path
. If you don’t know your python path, use which
command:
For more information, read virtualenvwrapper docs
Shutting down an enviroment
In order to deactivate your virtualenv:
Activating an environment
To activate an existing virtualenv, use command workon
:
Binding our virtualenv to a project path
If we want to bind our virtualenv to specified folder in order to each time that we activate it, that folder will become in our current directory, let’s use setvirtualenvproject [virtualenv_path project_path]
command.
We need to have our virtualenv activated, go to our project folder and set it.
Now each time we activate our virtualenv using workon
, ~/ourproject
would be our current directory.
Testing our virtualenv
In order to test our virtualenv, let’s install Django.
Run a Django command, in this case, let’s try to create a new project.
Our command just worked as expected. Now we are going to deactivate our virtualenv and try to create a new project.
We can be sure that our Django library is only available inside our new virtualenv.
Please, share if you found this post useful :)
Check out my others posts here…
If you like my content or it was helpful, you can motivate me to write more, just by buying me a coffee