How to create a virtual environment by Python?

In this blog, I talked about why we create a virtual environment, how to create a virtual environment by Python and how to use virtual environment in Jupyter Notebook.

Imagine that you are creating a project with python, and you need to import a package which is not the same version as other project, what should we in this situation? Maybe creating a virtual environment for this project is a good choice. In this blog, I’ll talk about virtual environment with the following points:

  • Why we create a virtual environment?
  • How to create a virtual environment by Python?
  • How to use virtual environment in Jupyter Notebook?

Why we create a virtual environment?

In case of what I mentioned at the beginning, the virtual environment allows you to use a certain version of a module for one project and another version for another project: if you install the module system-wide and don’t use venv, then you can only use one version of the module.

In a word, virtual environment is able to ensure your modules’ version for a python project.

How to create a virtual environment by Python?

Before creating a virtual environment by Python, you should make sure that you have installed pip. For creating the virtual environment, we firstly install virtualenv module:

pip install --user --upgrade virtualenv

Now you can create a virtual environment in the corresponding directory by typing:

python -m venv _venvname

Creating a virtual environment

_venvname can be replaced by the name you want for your venv. In my example, the name of venv is “_restauration_venv”.

After creating your venv, you can activate it with:

.\_venvname\Scripts\activate.bat

and install the modules you need:

pip install -r requirements.txt

Activate the virtual environment

Before leaving, you need to deactivate the venv:

.\_venvname\Scripts\deactivate.bat

Deactivate the virtual environment

How to use virtual environment in Jupyter Notebook?

If you want to use virtual environment in Jupyter Notebook, you need to add a kernel with it. First, activate your virtual environment; then install ipykernel:

pip install --user ipykernel

Now you can add your venv to Jupyter Notebook:

ipython kernel install --user --name=_venvname 

Create a kernel

Next, you can choose your kernel as following:

Choose the kernel

As soon as you choose, the kernel will update at the right top corner:

Kernel updated

Conclusion

In this blog, I talked about why we create a virtual environment, how to create a virtual environment by Python and how to use virtual environment in Jupyter Notebook. Hope it’s useful for you.

References