By default Python were installed on Ubuntu 22.04 with version 3.10. So, first thing to begin the python journey is by installing pip
(python package manager) and virtualenv (manage python package inside an environment).
Check the python version to make sure the python is already installed:
$ python3 -V
Install pip
:
$ sudo apt install pip
Install virtualenv
:
$ pip install virtualenv
Then create virtual environment with specific python version:
$ virtualenv venv -p /usr/bin/python3.10
Activate the virtual environment:
On Linux/Mac:
$ source venv/bin/activate
Then you can working with pip
inside the virtual environment and install the packages that you wanna use. Then use this command to backup all the packages that you've install:
$ pip freeze > <file name>.txt
For example:
$ pip freeze > requirements.txt
Use this command to install the all backup packages:
$ pip install -r <file name>.txt
For example:
$ pip install -r requirements.txt
Use this command to exit or deactivate the virtual environment:
$ deactivate
Install python 3.11 or latest:
$ sudo apt install python3.11
Install python 3.9 or oldest (e.g. 3.8, 3.7, and etc):
$ sudo apt install python3.9 python3.9-distutils
Create new virtual environment, usually in the specific project directory that used for development (e.g. my-python-app
).
$ mkdir my-python-app
$ cd my-python-app
$ virtualenv venv -p /usr/bin/python3.10
Activate the virtual environment:
On Linux/Mac:
$ source venv/bin/activate
Create your own code (e.g. main.py
) and runs with this command:
$ python main.py
This step is not recommended to do, it will change the entire OS python system since Ubuntu were build and runs python too.
Set the ID of each python version in Update Alternative.
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.10 1
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.11 2
$ sudo update-alternatives --install /usr/bin/python python /usr/local/bin/python3.9 3
$ sudo update-alternatives --install /usr/bin/python python /usr/local/bin/python3.8 4
List or look at the list of update alternative:
$ update-alternatives --list python
/usr/bin/python3.10
/usr/bin/python3.11
/usr/local/bin/python3.9
/usr/local/bin/python3.8
Change or update the default pyhton version who run in operating system (Ubuntu):
$ sudo update-alternatives --config python
Select the pyhton version by enter it's ID:
There are 2 choices for the alternative python (providing /usr/bin/python).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/local/bin/python3.8 2 auto mode
1 /usr/bin/python3.6 1 manual mode
2 /usr/local/bin/python3.8 2 manual mode
Press <enter> to keep the current choice[*], or type selection number: