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 -P stops the script directory from landing on sys.path

Python
~/tips/tip-python-safe-path-p-flag

python -P script.py

Keeps the script's own folder off the import path so local files cannot shadow modules.

Put a file called random.py next to your script and import random quietly loads your file instead of the standard library. Python 3.11 added a switch to stop that.

Normally Python puts the script’s directory first on sys.path, so a local file can shadow a standard library module. The docs describe -P as not prepending a potentially unsafe path to sys.path. The environment variable form is PYTHONSAFEPATH.

python -P script.py
export PYTHONSAFEPATH=1

A short test shows the difference. With a random.py next to s.py, and s.py containing this:

import random
print(random.__file__)

a normal run prints the path of your local random.py. With python -P s.py it prints the path of the standard library module instead. This is handy for a script in a download folder or a shared directory, where you do not control which files sit next to it.

With python -m, the flag keeps the current directory out of sys.path instead. For stricter control the docs point to -I, isolated mode, which also ignores the PYTHON* environment variables and the user site directory.

Caveat: if your script does import helpers from a sibling file, that import fails with ModuleNotFoundError once -P is on. Turn your code into a package and start it with python -m, or leave the flag off for that project. The option does not exist before Python 3.11.

Further reading: Command line and environment

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