blog/content/posts/20220619_using_virtual_envi...

127 lines
2.6 KiB
Markdown
Raw Normal View History

2024-03-10 11:11:07 +01:00
---
title: How to use virtual environments
date: 2022-06-19
lastmod: 2022-06-19
tags: code
Tags: [python, R, julia]
slug: using-virtual-environments
author: Samuel Ortion
lang: en
status: 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.
```bash
sudo apt install python3-venv
```
And now you can create venvs for your project:
```bash
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:
```bash
source .venv/myproject/bin/activate
```
And deactivate it when you are done:
```bash
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:
```bash
pip freeze > requirements.txt
```
That way, you can allow other people to use your project and installi its dependencies with the following command:
```bash
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.
```R
install.packages("packrat")
```
And create your virtual environment with:
```R
packrat::init("myproject")
```
Similarly, you can then install packages:
```R
install.packages("dplyr")
```
And create a snapshot of your dependencies with:
```R
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:
```bash
julia -e 'using Pkg; Pkg.add("VirtualEnv")'
```
And add `~/.julia/bin` to your path:
```bash
julia -e 'using VirtualEnv; VirtualEnv.comonicon_install_path()'
```
Then you can use `venv` to create a virtualenv for your project:
```bash
venv .venv/myproject
```
And you can activate/deactivate it:
```bash
source .venv/myproject/bin/activate
deactivate
```
That's it !
## References
- [Python venv documentation](https://docs.python.org/3/library/venv.html)
- [Packrat documentation](https://rstudio.github.io/packrat/)
- [Julia venv documentation](https://juliapackages.com/p/virtualenv)