Tuesday, November 14, 2017

Creating a Python Virtual Environment – Step by Step

Hello Techkie,

It’s been a while since my last post. I got caught up with some personal and technical hurdles — but I’m back on track now, ready to share more useful content.

Today, I’ll walk you through how to create and manage a Python virtual environment, a crucial tool for isolating dependencies in your Python projects.


Why Use a Virtual Environment?

A virtual environment allows you to:

  • Keep your project’s dependencies separate from system-wide packages

  • Avoid conflicts between multiple Python projects

  • Easily manage and reproduce environments for development or deployment


Step 1: Install virtualenv

First, ensure you have pip installed. Then run:

bash

sudo pip install virtualenv

If you're using Python 3+ and want to be explicit:

bash

sudo pip3 install virtualenv

Step 2: Create a Virtual Environment

Run the following command to create a virtual environment:

bash

virtualenv -p /usr/bin/python3.5 myenv
  • Replace /usr/bin/python3.5 with the Python interpreter of your choice.

  • Replace myenv with your desired environment name.


Step 3: Activate the Virtual Environment

To activate the environment, run:

bash

source myenv/bin/activate

Once activated, your terminal prompt will change to show the active environment. You can now install packages using pip, and they’ll be scoped to this environment.


Bonus: Deactivating the Environment

To deactivate the environment and return to the global Python setup:

bash

deactivate

Summary

Using virtual environments is a best practice in Python development. It’s quick to set up, easy to use, and essential for managing multiple projects with different dependencies.

Let me know if you’d like a follow-up post on using venv (the built-in alternative) or managing environments with pipenv or Poetry.

0 comments:

Post a Comment