Quick and Easy Virtual Environment Tutorial

When I first started playing with Python, keeping track of library versions was not very high on my list of priorities. My projects and experiments were for me alone, so I was perfectly happy using my base environment and crossing my fingers that I would never run into version problems.

(In my defense, I have been very lucky on that front)

However, with more time coding under my belt, I realize the naivety of my old ways and am now making a conscious effort to create a virtual environment for each of my projects. This helps my projects be more seamlessly sharable.

This blog exists to serve as a zero-frills no nonsense tutorial on how to create a fresh virtual environment using Conda. Many of these steps can be combined or modified to meet different needs or increase efficiency, but these steps will get you from point A to virtual point B.

  • Install Anaconda or Miniconda. Making virtual environments can be done with pip, but Conda makes life easy, and that is what we are aiming for right?
  • Create a virtual environment using the code below in your terminal. Name it something project related. For our purposes we will call it env-name

conda create -n env-name

  • Enable the environment. You can confirm your environment is activated by observing the beginning of your command line in your terminal.

conda activate env-name

  • Install packages as necessary! An example of how to do this is shown below. Versions can be specified if necessary. In our example we are installing python version x.x as well as the newest versions of jupyter, numpy, and pandas.

conda install python=x.x jupyter numpy pandas

  • I find it is a good idea to occasionally review what packages have been installed on my current environment. this can be done using:

conda list

  • Code away, adding packages as needed! If you don’t care about your environment being lean and mean, you can always install all stock Anaconda packages ( conda install anaconda ), though sharing a more minimal environment with your projects will likely be appreciated by viewers and collaborators.
  • When you’re ready to share your environment, you can export it as a .yml file using the code below. This code exports your current directory to the file name env-name.yml. Make sure you are in the directory in which you would like to save the file before exporting!!

conda env export > env-name.yml

Bonus Tip: if you are coding in a Jupyter Notebook, the kernel labeled Python 3 will always utilize the activated virtual environment.

Second Bonus Tip: If you’re working off of a project that includes a .yml file for you, navigate in your terminal to the directory containing the file and run the code below to add the virtual environment to your own machine. Don’t forget to activate it!

conda env create -f env-name.yml