A Python virtual environment refers to a self-contained workspace that allows students and researchers to develop and run Python projects with specific libraries and dependencies isolated from their system-wide Python installation. These environments enable seamless experimentation and learning by creating separate environments for different projects, ensuring compatibility and avoiding conflicts between project requirements. Virtual environments promote efficient and focused coding practices while maintaining a controlled and organized environment for educational purposes.
Please choose Windows or Linux how-to guide:
- How to create a virtual environment in Python (Ubuntu)?
- How to create a virtual environment in Python ( Windows)?
Here’s how you can create a virtual environment step by step:
- Open Command Prompt:
Open the Command Prompt by pressing the Win + R keys, typing cmd and then pressing Enter.
- Navigate to the Desired Directory:
Use the cd command to navigate to the directory to create your virtual environment. For example, to navigate to the C:\Projects directory, you would enter:
- Create the Virtual Environment:
Once you’re in the desired directory, use the following command to create a virtual environment named “engineering” (you can replace “engineering” with your preferred name):
python -m venv engineering
This will create a directory named “engineering” in your current directory, containing the virtual environment.
- Activate the Virtual Environment:
To activate the virtual environment, navigate to the “Scripts” subdirectory within the virtual environment directory and run the activate script. Use the following commands:
cd myenv\Scripts activate
You’ll notice the prompt changes, indicating you’re now in the virtual environment.
- Install Packages:
While the virtual environment is active, you can use the pip command to install packages, and they will be installed only in the virtual environment, keeping them separate from your system-wide Python installation. For example:
pip install package_name
- Deactivate the Virtual Environment:
When you’re done working within the virtual environment, you can deactivate it by running the deactivate command:
Once deactivated, you’ll return to the system-wide Python environment.
Remember that you’ll need to activate the virtual environment whenever you want to work within it and deactivate it when you’re done. This helps to keep your project’s dependencies isolated from other projects and your system-wide Python environment.
The steps might vary slightly based on your Python installation and environment variables, but the general approach remains the same.