A common practice when developing programs in Python is to set up a working environment by installing Python and the required third-party libraries and modules all in one place. This approach is typically convenient for beginners as it eliminates the need to configure their own environment, which can be complex. However, it's essential to eventually grasp this process because relying solely on this approach can lead to frustrating dependency issues and challenges in the long run.
A virtual environment is like a sandbox for your Python projects. It allows you to create isolated, self-contained environments where you can install the specific packages and dependencies your project needs. This isolation prevents conflicts between different projects and ensures that you can easily manage your project's environment, no matter how many you have.
-
Installation
To install virtual environment, run this command in your terminal:
pip install virtualenv
-
Initialization
To use it, go to the root of your project directory and run the following command:
python -m venv <virtual-env-name>
replacing
<virtual-env-name>
with the actual name of the virtual environment folder that will be created after you run the command. -
Activation
To activate the virtual environment, run the following command:
If you're in Linux or MacOS:
source <virtual-env-folder>/bin/activate
If you're in Windows (cmd):
<virtual-env-folder>/Scripts/activate.bat
Powershell:
<virtual-env-folder>/Scripts/Activate.ps1
This will activate your virtual environment, and (<virtual-env-name>)
will now appear in your terminal.
Now that you're inside the virtual environment, you can install packages just as you would in your system-wide Python installation. For example:
pip install package_name
This will install the package within your virtual environment, keeping it isolated from other projects.
To save your project's dependencies to a requirements.txt file for easy sharing and reproducibility, use the following command:
pip freeze > requirements.txt
or, if requirements.txt
is available and you want to install all the packages needed in a specific project, you can run the following command to install everything listed in requirements.txt
file:
pip install -r requirements.txt
And that's it! We have learned about setting up our own virtual environment in Python, as well as installing and saving the packages in a file.