Create and Manage a Virtual Environment for Python in Linux

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:

  1. 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
  1. This command creates a new virtual environment inside a directory named venv.
  2. Activate your virtual environment by running the following command in your terminal:
source venv/bin/activate
  1. After running this command, you should see your terminal prompt change to indicate that you are now working inside your virtual environment.
  2. Install the packages you need in your virtual environment using pip. For example, to install the numpy package, 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
  1. This will return you to your normal shell prompt.
  2. To use your virtual environment again in the future, simply navigate to your project directory and reactivate it using the source command:
cd my_project
source venv/bin/activate
  1. 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.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *