Python 3

The use of __name__ == '__main__'

Adding this to a python file script will ensure that everything inside this condition will be only ran, if the script file was runned directly.

if __name__ == '__main__':

This happens because when you import functions from other files, python runs the entire file. So if you have code executing there, it will execute it on the import.

To avoid this you put this code inside this condition.

Installing Python

Install python with pyenv.

sudo apt update; sudo apt install make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev curl git \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
curl -fsSL https://pyenv.run | bash
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init - bash)"' >> ~/.bashrc
source ~/.bashrc

List available versions to install

pyenv install -l

Install a version

pyenv install <version>

Set global version

pyenv global <version>

Check global version

pyenv global

Creating a Project

Virtual Environement

You can create projects with a package.json alike way, with venv.

When using Virtual Environments, dependencies installed via pip will be installed at a project scope, instead of globally.

Create the environment

python -m venv <.somename-env>

# Usually
python -m venv .venv

Active the environment

# In Windows
.\<.somename-env>\Scripts\activate
.\<.somename-env>\bin\activate

# In Linux
source <.somename-env>/bin/activate

Deactivate

deactivate

Create requirements.txt

This file will act like a package.json, saving the dependencies.

pip freeze > requirements.txt

To reinstall from a requirements.txt

Will have to recreate the environment first.

pip install -r requirements.txt

Last updated