Snippet
Environemnt Variables
import os
os.getenv("ENV_VAR_NAME", "default_value")
os — Miscellaneous operating system interfaces — Python 3.12.3 documentation
Command Line Argument
import argparse
parser = argparse.ArgumentParser(description='Parse command line options.')
parser.add_argument('integers', metavar='c', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args(['--sum', '7', '-1', '42'])
print(args.accumulate(args.integers))
argparse — Parser for command-line options, arguments and sub-commands — Python 3.12.3 documentation
Random number
import random
x = random.randint(0, 100) # 0 <= x <= 100
Logging
from logging import basicConfig, getLogger, DEBUG
# put in entry point file
CHAR_GREEN = '\033[32m'
CHAR_RESET = '\033[0m'
FORMAT = f"{CHAR_GREEN}%(asctime)s %(levelname)s %(name)s {CHAR_RESET}: %(message)s"
basicConfig(level=INFO, format=FORMAT)
# put in all files
logger = getLogger(__name__)
# logging code
logger.info('hello')
Ref: ログ出力のための print と import logging はやめてほしい #Python - Qiita
Packages
Code formatter
Install packages
pip install \
black \
autopep8 \
isort \
;
Run installed packages
black .
autopep8 --recursive --in-place --aggressive --aggressive .
isort .
Package Manager
Poetry
Setup project
cd <project_root>
poetry init
Add a package
poetry add <package_name>
Install dependencies using poetry
poetry install
venv
Create venv
python -m venv .venv
Activate venv
source .venv/bin/activate
Install package
pip install <package_name>
pyenv
Check installed version list
pyenv versions
Get version list
pyenv install -l
Install specific version
pyenv install <python_version>
Get global version
pyenv global
Get local version
pyenv local
Top comments (0)