brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -I runs a script without your local files or user packages getting in

Python
~/tips/tip-python-isolated-mode-i

python3 -I -c 'import json; print(json.__file__)' # the real json module

Run Python in isolated mode so the current folder and environment can't change imports.

Python normally puts the script’s folder on the import path and reads PYTHON* environment variables. The -I flag turns all of that off, which I like for scripts that run as root or from a folder I don’t control.

echo 'X = 1' > json.py
python3 -c 'import json; print(json.__file__)'      # ./json.py  (oops)
python3 -I -c 'import json; print(json.__file__)'   # the real json module
rm json.py

The first run imports the stray json.py from the current folder, which shadows the standard library module. In isolated mode the current and script folders aren’t added to sys.path, the user site packages folder is skipped, and environment variables like PYTHONPATH are ignored, so you get the real thing.

That makes it a nice extra layer for a cron job or a system script running from a folder where other people can write files. Someone dropping a logging.py next to it can’t hijack your imports.

The flip side is that your own modules next to the script aren’t found either. A script that does import helpers from its own folder fails under -I. For that case, install your code as a package in a venv and run it from there, or use the milder -P flag (Python 3.11 and newer), which only stops the folder from being added to the path.

Further reading: python -I, python -P

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link