Python environments are used to isolate specific Python environments on a single machine, allowing for separate dependencies and packages for different projects. This is particularly useful when working on multiple projects that may require different versions of packages or modules.
One way to create a Python environment is to use the virtualenv package. virtualenv allows you to create a separate environment for your Python projects, complete with its own installation directories and environment variables.
To install virtualenv, you will need to have pip installed on your machine. pip is a package manager for Python that allows you to install and manage additional packages and modules that are not part of the Python standard library.
To install pip, follow these steps:
- Open a terminal window and enter the following command:
python -m ensurepip --default-pip
This will install pip if it is not already installed on your machine.
- Once pip is installed, you can use it to install virtualenv by entering the following command:
pip install virtualenv
Once virtualenv is installed, you can create a new Python environment by using the following command:
virtualenv env_name
Replace “env_name” with the name you want to give to your environment. This will create a new directory with the given name and will install a copy of Python and the necessary libraries within it.
To activate the environment, enter the following command and remember to replace ‘env_name’ with your environment name e.g ‘venv’ &c:
source env_name/bin/activate
Another way to activate an existing environment assuming your environment folder is in the working tree is to use the below command:
.\.env_name\Scripts\activate
This will change your terminal prompt to indicate that you are now working within the environment you created. To exit the environment, enter the following command:
deactivate
Using virtualenv to create separate Python environments can be a useful tool for managing dependencies and packages for different projects. This can help to prevent conflicts and allow you to work with the specific versions of packages that your projects require.
More Resources:
Python programming language— https://www.python.org/about/gettingstarted/
Python packages — https://packaging.python.org/en/latest/tutorials/installing-packages/
