blog/content/posts/20220619_using_virtual_envi...

2.6 KiB
Executable File

title date lastmod tags Tags slug author lang status
How to use virtual environments 2022-06-19 2022-06-19 code
python
R
julia
using-virtual-environments Samuel Ortion en published

To not interfere with your os configuration and keep your project reproducible, you should use a virtual environment as long as possible.

Virtual environment are a way to isolate your project from the rest of the system, and to avoid dependencies conflicts.

Python Virtualenv

Lets start by installing the virtualenv package.

sudo apt install python3-venv

And now you can create venvs for your project:

python3 -m venv .venv/myproject

It is a good practice not to create a virtualenv with name "venv", but to use a name that reflects the project you are working on, in order to see directly in which venv you are working.

Now you can activate the virtualenv:

source .venv/myproject/bin/activate

And deactivate it when you are done:

deactivate

One other way to create a virtualenv is to use the virtualenv command.

Once you installed python packages, you should create a snapshot of your project dependencies using:

pip freeze > requirements.txt

That way, you can allow other people to use your project and installi its dependencies with the following command:

pip install -r requirements.txt

You could also use conda, as a package manager, to create a virtualenv.

R Virtualenv

R also has its own virtualenv gestionnal system named packrat.

First install packrat with R.

install.packages("packrat")

And create your virtual environment with:

packrat::init("myproject")

Similarly, you can then install packages:

install.packages("dplyr")

And create a snapshot of your dependencies with:

packrat::snapshot()

The dependency list is available in packrat/packrat.lock.

Julia Virtualenv

Julia venv is very similar to Python venv.

First, you install the VirtualEnv package:

julia -e 'using Pkg; Pkg.add("VirtualEnv")'

And add ~/.julia/bin to your path:

julia -e 'using VirtualEnv; VirtualEnv.comonicon_install_path()'

Then you can use venv to create a virtualenv for your project:

venv .venv/myproject

And you can activate/deactivate it:

source .venv/myproject/bin/activate

deactivate

That's it !

References