Thursday, August 31, 2023

Installing python's virtual environment in ubuntu linux

Python's virtual environment, is a way that developer can use to separate python's packages for different projects, in a single machine. The packages installed in this lightweight virtual environment, would be available in other virtual environment, thus removing the possibility of packages, org packages' version clashing inside a single machine.


First, we need to determine which python version is currently installed in our machine
$ python -V

 




Then, we need to install python-venv
$ sudo apt update && sudo apt install python3.10-venv -y

Once we have venv, we can start creating virtual environment. Let's say we wanted to have a virtual environment for a project called myproject, run this command
$ python3 -m venv myproject

The above command will create a directory called myproject, with necessary files in it. To activate the virtual environment, and start using it, we can run below commands
$ cd myproject
$ source bin/activate

How do we know that we are already inside the virtual environment? We will see the name of the virtual environment at our bash prompt, like below






We can now install any package that we need inside the virtual environment using pip, and that packages can only be used if we activate "myproject" virtual environment









To exit from the virtualenvironment, simply run deactivate command, and we will get back our standard bash prompt
$ deactivate


No comments: