Creating a Virtual Environment (venv) using Terminal
You can create a virtual environment using the built-in venv module in Python. Here's a step-by-step guide:
For Python 3.x (Recommended)
Open your terminal:
On macOS/Linux: Terminal.app or iTerm2
On Windows: Command Prompt (cmd.exe) or PowerShell
Navigate to your project directory:
Use cd command to change directories. Example: cd ~/Projects/my_project
Create a new virtual environment:
Run the following command: python -m venv myenv (replace myenv with your desired environment name)
This will create a new directory myenv (or your specified name) containing the virtual environment.
Example:
bash
cd ~/Projects/my_project
python -m venv myenv
For Python 2.x (Legacy)
If you're still using Python 2.x, you'll need to install virtualenv using pip:
bash
pip install virtualenv
Then, create a new virtual environment:
bash
virtualenv myenv
Activating the Virtual Environment
To start using the virtual environment, you need to activate it:
On macOS/Linux:
bash
source myenv/bin/activate
On Windows (cmd.exe):
cmd
myenv\Scripts\activate
On Windows (PowerShell):
powershell
myenv\Scripts\Activate.ps1
You'll notice the command prompt changes to indicate that you're now operating within the virtual environment: (myenv) user@hostname:~/Projects/my_project$
Verifying the Virtual Environment
Run which python (or where python on Windows) to confirm you're using the virtual environment's Python interpreter:
bash
(myenv) user@hostname:~/Projects/my_project$ which python
~/Projects/my_project/myenv/bin/python
Deactivating the Virtual Environment
When you're done working in the virtual environment, simply run:
bash
deactivate
This will return you to your system's default Python environment.
Tips:
You can specify a Python version when creating the venv: python3.9 -m venv myenv
Use pip freeze > requirements.txt to save dependencies and pip install -r requirements.txt to restore them in another environment.
Delete the venv directory to remove the virtual environment: rm -rf myenv (be cautious!)
Now you're all set to work with virtual environments using the terminal!