Creating a Python Virtual Environment
Installing the venv
Module
The venv
module is a standard library in Python, so it is already installed by default. However, if you are using an older version of Python, you may need to install the virtualenv
package instead. You can do this using the system's package manager, such as apt-get
on Ubuntu:
sudo apt-get install python3-venv
Creating a Virtual Environment
To create a new Python virtual environment, you can use the python3 -m venv
command followed by the name of the virtual environment directory:
python3 -m venv my_venv
This will create a new directory called my_venv
that contains the Python interpreter and all the necessary files and directories for the virtual environment.
Activating the Virtual Environment
To start using the virtual environment, you need to activate it. The activation process varies slightly depending on your operating system:
On Linux/macOS:
source my_venv/bin/activate
On Windows:
my_venv\Scripts\activate
After activating the virtual environment, you should see the name of the virtual environment in your terminal prompt, indicating that you are now working within the isolated environment.
Installing Packages in the Virtual Environment
Once the virtual environment is activated, you can install Python packages using pip
as you normally would. Any packages you install will be installed within the virtual environment, not the system-wide Python installation.
pip install numpy
Deactivating the Virtual Environment
When you're done working in the virtual environment, you can deactivate it by running the following command:
deactivate
This will return you to the system-wide Python environment.