How to install Python packages or libraries in a virtual environment of Unix/macOS?

What is a Virtual Environment?

  by Dharmesh Lathiya

A virtual environment is a tool that allows you to create an isolated Python environment for your project. This is useful when you have multiple projects with different dependencies and different Python versions (Python, Python3, etc.), or when you want to test out new packages without affecting your system-wide Python installation.

Steps to Create a Virtual Environment

Here are the steps to create and activate a virtual environment using venv and install packages or libraries:

Step 1

Open your terminal and navigate to the directory where you want to create your virtual environment.

Step 2

Create a new virtual environment using the following command:

python3 -m venv myenv

This command will create a new virtual environment named myenv.

Step 3

Activate the virtual environment by running the following command:

source myenv/bin/activate

This will activate the virtual environment, and you should see the name of your virtual environment in your terminal prompt.

Step 4

Install any Python packages or libraries that you need using pip, just like you would with a regular Python installation. For example, to install the requests library, you would run:

pip install requests

This will install the requests library in your virtual environment, and it will only be available when the virtual environment is activated. 

Step 5

When you're done working in the virtual environment (Install python packages or libraries in a virtual environment), you can deactivate it by running the following command:

deactivate

This will deactivate the virtual environment, and you'll return to your system-wide Python installation.

That's it! Using a virtual environment with venv is a simple and effective way to manage your Python dependencies.

Dharmesh Patel 12 April, 2023
Archive
Sign in to leave a comment
Native vs. Cross-Platform Apps: Understand the differences
Choose the Right Mobile App Development Approach for Your Business