November 21, 2024

How to Properly Create Python Virtual Environments in Windows Using Command Line and Install Packages

In this Python tutorial, we explain how to properly create Python virtual environments in Windows by using the Windows command line (Windows Command Prompt). We explain how to create environment, activate the environment, install packages, run a Python program, and deactivate the created environment. The YouTube video accompanying this video is given below.

In every virtual environment, we can install a set of packages with specific versions. Packages installed in one virtual environment will not be seen by another virtual environment or the global Python environment that is run directly from the command prompt. In this way, we can avoid issues with different versions of packages since some old programs will not be compatible with newer packages.

Let us start. Open a Windows command prompt, and type

where python

you should see the path to the python.exe file. If you cannot see it, then try

where py

and you should see the path to the Python executable file in the Windows folder. That is, sometimes Python can be called as py (adjust all the commands in the sequel accordingly).

Then, we need to create a workspace folder. In my case, the folder will be located on  my D: drive:

D: 
mkdir test1 
cd test1

Then, inside test1 folder we will create a Python virtual environment. We do that by typing:

python -m venv env1

The name of the environment is “env1”. The command “python -m venv” is used to create an environment.

By typing

dir

We will see that there is a new folder called “env1”. This folder is the environment folder.

Next, we need to activate the environment. We do that by typing

env1\Scripts\activate.bat

This will execute the script file called “activate.bat” and that will activate the environment. After executing this file, you will see

(env1) D:\test1>

This means that the virtual environment called “env1” is activated. Next, let us create a python file and try to execute it in this environment.

Type

notepad test1.py

This will open Notepad and create the file test1.py. Next, let us type the code given bellow

import numpy as np
print("My first virtual environment")
a=np.pi/4
b=np.pi/6
c=np.sin(a)+np.cos(b)
print(c)

To execute this file, type

python test1.py

You will get this error

Traceback (most recent call last):
  File "D:\test1\test1.py", line 1, in <module>
    import numpy as np
ModuleNotFoundError: No module named 'numpy'

This is because numpy package is not installed in our virtual environment. Note that this package might be installed in the global Python environment that is called from the command line (without activating the virtual environment). To install NumPy, type

pip install numpy

Next, try to run

python test1.py

The output is

My first virtual environment
1.5731321849709863

To deactivate the environment, type

deactivate