12.2. Creating Virtual Environments

Creating virtual environments in Python allows for isolated project dependencies, preventing conflicts between different projects that might require different versions of the same library.

🡆Navigate to your project directory in the terminal or command prompt. Then, execute the following command, replacing myenv with your desired environment name.

🡆After creation, you need to activate the virtual environment to start using it. The activation command varies slightly depending on your operating system: On Windows

🡆Once activated, your terminal prompt will typically change to include the environment’s name in parentheses, for example, (myenv).

When the environment is active, you can install packages using pip as you normally would. 

The packages will be installed in your project’s isolated environment, not the system-wide Python installation.

Example:

(venv) pip install request

List installed packages

To see what packages are installed in your active virtual environment, use pip list.

(venv) pip lis

The command to activate the environment depends on your operating system and shell.

🡆On Windows (Command Prompt)  venv\Scripts\activate.bat

🡆On Windows (PowerShell).\venv\Scripts\Activate.ps1

🡆On macOS or Linux :source venv/bin/activate

When you are finished working, run the deactivate command to return to your normal system shell.

To make your project’s dependencies reproducible, you can create a requirements.txt file.

Scroll to Top
Tutorialsjet.com