Skip to content

Instantly share code, notes, and snippets.

@adeisbright
Last active October 5, 2023 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adeisbright/5de9f2b39775e585ef27cd9d1abb7155 to your computer and use it in GitHub Desktop.
Save adeisbright/5de9f2b39775e585ef27cd9d1abb7155 to your computer and use it in GitHub Desktop.
Setting up virtual environments in Python
When building applications using any programming language, we sometimes use codes provided by the programming community.
In Python, without an isolated environment newer version of a particular package will replace older ones and this will in turn
lead to breaking changes for the project that depends on the older package.
To handle this problem, Python provides us a tool(venv) to create an isolated environment for our project dependencies.
When we install a package, we do not want it to be installed on the global path for site packages; we want that package to be
isolated and constrained to the application that needs it.
We can see where system libraries (libraries that are bundled into the python language such as math, string, etc) are installed
on your system using:
```
import sys
print(sys.prefix)
```
To see where third party packages are installed, use:
```
import sitepackages
print(site.getsitepackages())
```
## How to create a virtual environment
Assuming you have a project named hello, this is how you will create and activate a virtual environment before installing any
package:
If you do not have the package for creating a virtual environment on your system, then install it using :
python3 -m pip install virtualenv
1. Create a directory for your project and change into that directory
```
mkdir hello
cd hello
```
2. Create the virtual environment.
Assuming you want to name your virtual environment "env", you will use any of the commands below to create an environment.
If your command was successful, a directory will be created within hello for you.
```
python3 -m venv env
or
python -m venv env
or
py -m venv env
```
3. Now to activate the environment, it depends on which OS you are using.
For Mac or Linux , do :
```
source env/bin/activate
```
For windows , do:
```
.\Scrips\activate
```
Now,once the environment has been activated, you will see the environment name enclosed within parentheses on the terminal.
You can now go ahead to install packages.
Let us install flask.
``` python -m pip install flask```
You can create a requirements.txt file to hold information about your packages using :
python3 -m pip freeze > requirements.txt
Then to install the dependencies, use :
python3 -m pip install -r requirements.txt
If you encounter any problem, drop a comment below .
Thank you
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment