How to create a Python virtual environment

A virtual environment works in only a specified folder, doesn't influence other environment. You can avoid the version conflict of Python packages (libraries) between other projects. It is easy to create the virtual environment as follows.

1. Move to the directory where you want to make a virtual environment.

Enter the following command on the address bar of the development folder opening with the explore.

cmd

Or, open the command prompt, then enter the following command on it.

cd [Address]

2. Create a virtual environment.

Enter the following command.

py -m venv .venv

Here you can also specify the python version by the following command.

py -3.xx -m venv .venv

3. Activate Python in the virtual environment.

Enter the following command.

.venv\Scripts\activate

You can confirm the activated Python version by the following command.

py -V

4. Install packages in the virtual environment.

If you want to install packages individually, enter the following command.

pip install [Package Name]

Here, you can also specify the version of installing package by the following command.

pip install [Package Name]==[Version No.]

If you want to copy same packages from other environment, you can use a requirement.txt.

  1. In order to create package lists in a requirements.txt, enter the following command in the environment you want to save.

    pip freeze > requirements.txt
  2. Move or copy the requirement.txt to the directory which has .env folder you created. Enter the following command.

    pip install -r requirements.txt
  3. You can confirm the list of installed packages by the following command.

    pip list

5. Deactivate Python in the virtual environment after that.

deactivate

6. Use the virtual environment in your IDE.

Set the Python exe file (.venv\Scripts\python.exe) in the virtual environment as the interpreter of your Python IDE (e.g. PyCharm and VS Code).