Set Up Virtual Environment in Python

syscrews
2 min readFeb 20, 2024

--

Creating and using virtual environments in Python is a best practice for managing project dependencies and isolating them from system-wide installations. Python’s built-in venv module provides a simple way to create and manage virtual environments. Below, I'll provide instructions for creating virtual environments in both Windows and Linux:

Windows:

Creating a Virtual Environment:

  1. Open Command Prompt.
  2. Navigate to the directory where you want to create the virtual environment using the cd command.
  3. Run the following command to create a virtual environment named myenv:
python -m venv myenv

Activating the Virtual Environment:

  1. Navigate to the directory where the virtual environment is created.
  2. Run the following command to activate the virtual environment:
myenv\Scripts\activate

Deactivating the Virtual Environment:

To deactivate the virtual environment, simply type deactivate and press Enter in the Command Prompt.

Linux:

Creating a Virtual Environment:

  1. Open a terminal.
  2. Navigate to the directory where you want to create the virtual environment using the cd command.
  3. Run the following command to create a virtual environment named myenv:
python3 -m venv myenv

Activating the Virtual Environment:

  1. Navigate to the directory where the virtual environment is created.
  2. Run the following command to activate the virtual environment:
source myenv/bin/activate

Deactivating the Virtual Environment:

To deactivate the virtual environment, simply type deactivate and press Enter in the terminal.

Common Operations:

  • Installing packages: After activating the virtual environment, use pip install <package_name> to install packages.
  • Listing installed packages: Use pip list to see the list of installed packages.
  • Freezing installed packages: Use pip freeze > requirements.txt to freeze the installed packages into a requirements.txt file for easier replication on other environments.
  • Installing packages from requirements.txt: Use pip install -r requirements.txt to install packages from a requirements.txt file.

Using virtual environments helps in managing project dependencies efficiently and avoids conflicts between different projects. It’s a good practice to always use virtual environments for Python development.

--

--

Responses (1)