Creating a Python Virtual Environment with Anaconda Distribution
Why do we need a Virtual Environment?
As of writing this article I am a Graduate Student at the University of New Haven doing my Master of Science in Data Science. In my first semester, I have enrolled in a course called Intro to AI. This is by far my favorite subject this semester. In this course, we were learning different algorithms to solve Search problems. At the end of every two weeks, we were given a project based on Pacman.
The score for the completion of our project is determined by an autograder.py file. This particular file was also included in our project to help us know how far we have come with regard to our project. Now the problem with this auto grader was that It works only with Python 3.6 version. But my system was running an anaconda distribution which was of Python 3.8.
So, what should I do in such situations, where I need to run a different version of python. Should I uninstall my Anaconda Distribution and install python 3.6?. Fortunately for me, I know how to create a Virtual Environment to deal with such kinds of scenarios.
These Environments are like an entire new python distribution isolated to a specific directory in which where we create them. They don't interfere with the original distribution nor Anaconda distribution will interact with it.
Creating Virtual Environment using CMD
Assuming that you have installed Anaconda Distribution in your system, go to the directory where you want the Virtual environment to be and open CMD from that directory. Here is a trick on opening CMD from within the Directory. Once you are in the Directory type “cmd” to open the CMD.
Command to create a Virtual Environment:
conda create -n env_name python=3.x
- Instead of “env_name” type the name you want to assign to the virtual environment you are gonna create
- if you want to create a virtual environment based on python 3.6 type in python=3.6
Command to Activate Virtual Environment:
conda activate env_name
Note that the cmd must be in the directory where we have created the Virtual Environment
Command to Deactivate Virtual Environment:
Command to completely remove Virtual Environment:
conda remove -n env_name --all
Running a python file within the Virtual Environment:
Put the python file you want to run in the directory where the Virtual Environment is created and in the cmd activate the environment and run the python file as usual.
I hope this article is useful.
Give it some claps to make others find it too! Make sure you follow me on Medium not to miss anything.