How to Use Python Virtual Environment: Simple Guide
Use
python -m venv env_name to create a virtual environment, then activate it with source env_name/bin/activate on Linux/macOS or env_name\Scripts\activate on Windows. This keeps your project dependencies separate and organized.Syntax
To create a virtual environment, use the command python -m venv env_name. Here, python calls the Python interpreter, -m venv runs the virtual environment module, and env_name is the folder name for your environment.
To activate the environment, use source env_name/bin/activate on Linux/macOS or env_name\Scripts\activate on Windows. Activation switches your terminal to use the environment's Python and packages.
bash
python -m venv env_name # Activate on Linux/macOS source env_name/bin/activate # Activate on Windows env_name\Scripts\activate
Example
This example shows how to create a virtual environment, activate it, install a package, and check the installed packages inside the environment.
bash
python -m venv myenv # On Linux/macOS source myenv/bin/activate # On Windows myenv\Scripts\activate pip install requests pip list # To exit the environment # deactivate
Output
Package Version
---------- -------
requests 2.31.0
pip 23.1.2
setuptools 68.0.0
Common Pitfalls
- Forgetting to activate the virtual environment before installing packages causes them to install globally.
- Using the wrong activation command for your operating system will not activate the environment.
- Not deactivating the environment when done can cause confusion in other projects.
Always check your prompt changes after activation to confirm you are inside the virtual environment.
bash
## Wrong: Installing without activating pip install requests ## Right: Activate first, then install source myenv/bin/activate pip install requests
Quick Reference
| Command | Description |
|---|---|
| python -m venv env_name | Create a new virtual environment named env_name |
| source env_name/bin/activate | Activate the environment on Linux/macOS |
| env_name\Scripts\activate | Activate the environment on Windows |
| pip install package_name | Install a package inside the active environment |
| deactivate | Exit the virtual environment |
Key Takeaways
Create a virtual environment with 'python -m venv env_name' to isolate project packages.
Always activate the environment before installing or running Python code to use the isolated setup.
Use the correct activation command for your operating system to avoid errors.
Deactivate the environment when finished to return to the global Python setup.
Virtual environments help prevent package conflicts between projects.