The venv module allows us to create a virtual environment within a project’s directory. Each virtual environment has its own Python library and can have its own independent set of installed Python packages, keeping dependencies separate. In this tutorial, we will use Python and the Command Prompt to create and activate a virtual environment.
Create a Virtual Environment
First, we have to navigate to the directory where we want to create our virtual environment. Use the command venv to create it. For instance, let’s create a directory called environment, and create a virtual environment inside that directory as shown below.
python -m venv environment
Alternatively, we can directly specify the absolute path of the directory. For instance, the command below will create a directory called environment and set up the virtual environment inside the specified path.
python -m venv /directory/site/environment
Activate a Virtual Environment
Once a virtual environment has been created, we need to activate it using a platform-specific script located in the virtual environment’s directory. The following commands can be used to activate a virtual environment based on your operating system and shell.
| Platform | Shell | Command to activate virtual environment |
| Windows | Command Prompt | venv\Scripts\activate.bat |
| PowerShell | venv\Scripts\Activate.ps1 |
|
| POSIX (Linux/macOS) | bash/zsh | source venv/bin/activate |
| fish | source venv/bin/activate.fish |
|
| csh/tcsh | source venv/bin/activate.csh |
Note: Remember to replace venv with the actual path or name of the directory containing your virtual environment.
For instance, in this tutorial, we created a virtual environment inside a directory called environment. To activate it on Windows using the Command Prompt, we would use the specific activation script as follows:
environment\Scripts\activate.bat
Our virtual environment is now active, which is confirmed when it displays the name (environment) as a prefix in the command line prompt.