Creating and managing virtual environments in Python is a best practice to keep the dependencies of different projects separate and avoid version conflicts. Here are the steps to create and manage a virtual environment for Python in Linux:
- Install the virtualenv package by running the following command in your terminal:
sudo apt-get install python3-venv
Create a new directory for your virtual environment by running the following command in your terminal:
mkdir my_project
cd my_project
Create a new virtual environment by running the following command in your terminal:
python3 -m venv venv
- This command creates a new virtual environment inside a directory named
venv. - Activate your virtual environment by running the following command in your terminal:
source venv/bin/activate
- After running this command, you should see your terminal prompt change to indicate that you are now working inside your virtual environment.
- Install the packages you need in your virtual environment using pip. For example, to install the
numpypackage, run the following command:
pip install numpy
When you are finished working in your virtual environment, deactivate it by running the following command in your terminal:
deactivate
- This will return you to your normal shell prompt.
- To use your virtual environment again in the future, simply navigate to your project directory and reactivate it using the
sourcecommand:
cd my_project
source venv/bin/activate
- You can now use the packages you installed in your virtual environment.
That’s it! You now know how to create and manage a virtual environment for Python in Linux using the venv module.
