To create a virtual environment in Python, you use the built-in venv
module.
Here are the steps:
- Open a terminal or command prompt and navigate to the directory where you want to create the virtual environment.
- Create the virtual environment by running the command:
-
On Windows:
python -m venv myenv
-
On macOS/Linux:
python3 -m venv myenv
-
Replace myenv
with your desired environment name. This creates a new
directory named myenv
containing the virtual environment files
- Activate the virtual environment :
-
On Windows:
myenv\Scripts\activate
-
On macOS/Linux:
source myenv/bin/activate
-
After activation, your terminal prompt will change to indicate the environment is active, and Python commands will use this environment's interpreter
-
Deactivate the virtual environment when done by running:
deactivate
This returns you to the system's global Python environment
Summary
Step| Windows Command| macOS/Linux Command
---|---|---
Create environment| python -m venv myenv
| python3 -m venv myenv
Activate environment| myenv\Scripts\activate
| source myenv/bin/activate
Deactivate environment| deactivate
| deactivate
This method isolates project dependencies, allowing different projects to use different package versions without conflicts
. For more detailed info, see the official Python documentation on venv