Virtual Environment in Python

Python Usage Tips (1)

Posted by Fan Gong on Sep 26, 2018

Creating Virtual Environment is very important. It solves the problem that people will have different dependencies and versions with yours.

This blog summarizes the typical way I used when creating virtual environment.

1.Complete Process

To create a virtual environment, we need to install virtualenv module first.

  • Open terminal or cmd in windows, change the directory to the place you want to store all your virtual environment files.
  • Type virtualenv <env_name>. We can also specify which version's of python like virtualenv python <path of python.exe> <env_name>
  • Change to <env_name>\Scripts directory and enter activate

Now we are in this virtual environment, we then can install necessary packages within it. In most cases, we will install packages by following a requirements.txt file. This file is generated by type pip freeze > requirements.txt when you are in a virtual environment and it will lists all the packages you have installed. You will always need to share this file to others when people want to reproduce your work.

  • To install all the packages in requirements.txt, we simply type pip install -r requirements.txt
  • At the same time, if you want to use IDE, we can also install IPython or Spyder within this environment and use them. (For using anaconda's IDE, we can also use anaconda navigator to set up the virtual enviornment)
  • Finally, if you want to deactivate this virtual environment, just type deactivate in your terminal or cmd.

2. With Jupyter Notebook

If we want to make life more easier and this is a long project, we can also add a new kernel for Jupyter Notebook especially use this virtual environment. To do it:

  • activate your environment by following the last procedure
  • Type pip install ipykernel within this virtualenv
  • Type python -m ipykernel install --user --name=<kernel_name>
  • Then if you re-open your Jupyter Notebook. You will find your new kernel is there.

Hope it helps!