Python cheatsheet

Posted by John Liu on Sunday, February 4, 2024

To find the Python installed pathes, under DOS command:

where python

In the Python interpreter, type following Python commands:

import os
import sys
os.path.dirname(sys.executeable)

or under DOS command:

py -c "import os, sys; print(os.path.dirname(sys.executable))"

To find the Python version, under DOS command:

py --version
py -V
py -VV

To create a dedicated environment.

# from PowerShell / cmd
python -m venv .env

To use/activate the dedicated environment created above

.\.env\Scripts\activate   # PowerShell: .\.env\Scripts\Activate.ps1

To uninstall modules

pip uninstall -y <module name>

To display module version, location etc. info

pip show torch optimum onnx onnxruntime

When installing Python package, to prevent package be installed under personal profile folder, disable the user site-package via environment variable

set PYTHONNOUSERSITE=1
"C:\Program Files\Python310\python.exe" -m pip install azure-storage-blob pyarrow

Logging

import logging

# Set up logging to track failures: INFO, ERROR, CRITICAL
logging.basicConfig(level=logging.INFO)
# logging.basicConfig(level=logging.ERROR)
# logging.basicConfig(level=logging.CRITICAL)
logger = logging.getLogger(__name__)

# your code

logger.info("your custom message.")

# your code