Skip to content

Instantly share code, notes, and snippets.

@mshroyer
Created June 30, 2023 02:51
Show Gist options
  • Save mshroyer/90be2fb10858984bd0ca56745323f181 to your computer and use it in GitHub Desktop.
Save mshroyer/90be2fb10858984bd0ca56745323f181 to your computer and use it in GitHub Desktop.
"""
Make a Python .pth file so external Pythons can use QGIS's packages and extensions
"""
import os
from pathlib import Path
import sys
if sys.platform == "win32":
import win32api
def normalize_path(path: Path) -> Path:
return Path(win32api.GetLongPathName(str(path)))
else:
def normalize_path(path: Path) -> Path:
return path
def get_qgis_python_paths() -> list[Path]:
python_paths = map(normalize_path, filter(lambda path: path.exists(), map(Path, sys.path)))
# QGIS_PREFIX_PATH refers to the apps/qgis-ltr directory, but we're actually interested in all Python paths under
# the QGIS top-level installation directory.
qgis_path = normalize_path(Path(os.environ["QGIS_PREFIX_PATH"]).parents[1])
return [path for path in python_paths if path.is_relative_to(qgis_path)]
def get_pth_file_contents() -> str:
return os.linesep.join(map(str, get_qgis_python_paths()))
print(get_pth_file_contents())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment