Python .pth files run before your code, even with -I

In a clean venv, a one-line .pth file ran in 5 of 6 modes of python -c pass, including -I; only -S turned it off. The 5 AI packages I installed brought 0 .pth files.

Rogério Rodrigues

Rogério Rodrigues

Engenheiro de IA · mestrando em Informática em Saúde (UFSC)

Seis modos de rodar python -c pass num venv limpo (Python 3.11, 3.12 e 3.13): um .pth de uma linha rodou sem flag, com -I, -s, -E e no pip --version; só com -S não rodou, e com -S o import openai quebrou. Os 5 pacotes de IA instalados trouxeram 0 arquivos .pth.

Originally published in Portuguese on 24 November 2026: Portuguese version.

I wrote a one-line .pth file into the site-packages of a fresh venv and ran python -c pass. A program that does nothing. My marker showed up in the terminal. It also showed up with -I, isolated mode. I’ll admit I thought -I protected me from this. It only went away with -S, and then import openai broke along with it.

The other number surprised me in a good way. The 5 AI packages I installed (openai, anthropic, langchain-core, huggingface-hub and tiktoken; 49 packages in the venv at the end, counting dependencies, pip, setuptools and the synthetic package) brought 0 .pth files. The scan that counts this takes less than half a millisecond.

Code and real output: demos/17-pth-venv-sem-import, in nursia-research-lab. It runs on CPU, with no account and no key.

Where did the question come from?

On 19 November 2026 my news radar picked up that two versions of agent-framework, 1.26.1 and 1.26.2, had been pulled from PyPI. I couldn’t find a public notice I could open to confirm it. What I did check: on 23 November 2026, the PyPI API lists 1.26.0 as the latest, and the two don’t appear.

I couldn’t confirm what was in those versions. So this post doesn’t link the case to .pth. The case just made me ask something I had never measured.

When you run pip install, what starts running in your Python before your code, without you importing anything?

What is a .pth file and why does it run on its own?

When Python starts, the site module reads every .pth file in site-packages. Most lines are just paths, which go into sys.path. But the site documentation says, in these words: “lines starting with import (followed by space or tab) are executed with exec()“. And further down: they run at startup “regardless of whether a particular module is actually going to be used”.

It’s like a doorman who carries out any note left at the front desk, without asking who left it. Most of the time the note is harmless.

This has legitimate uses. setuptools uses one of these .pth files to swap out distutils, as the table below shows. The point is that any package can do the same.

It’s going to change. The CPython documentation (site.rst, main branch) marks import lines in .pth files as deprecated in 3.15 and introduces .start files as their replacement. The text says they “will be silently ignored in Python 3.18 and 3.19”. Up to 3.17 they keep running. The versions I tested, 3.11, 3.12 and 3.13, execute them.

How did I run it?

  • Linux, CPU, Python 3.11.18, 3.12.3 and 3.13.18. One fresh venv per version, in a temporary folder.
  • 4 stages: E0 empty venv; E1 plus the 5 AI packages (openai 3.58.0, anthropic 2.13.0, langchain-core 1.8.4, huggingface-hub 2.4.0, tiktoken 0.14.0); E2 plus setuptools 84.2.1, which a lot of pipelines install; E3 plus a synthetic package installed with pip install -e.
  • At each stage, a script lists the .pth files and sorts the lines by the site rule: comment, path or executable.
  • At the end, I write my own .pth and run python -c pass in 6 modes.

The marker .pth is harmless. It only writes one line to stderr:

import sys; sys.stderr.write("MARCA-DEMO17: .pth executado antes do seu codigo\n")

No compromised package was downloaded. The core of the scan is this:

def classifica(linha: str) -> str:
    if not linha.strip() or linha.startswith("#"):
        return "vazia_ou_comentario"
    if linha.startswith(("import ", "import\t")):
        return "executavel"
    return "caminho"

for d in site.getsitepackages():
    for pth in sorted(Path(d).glob("*.pth")):
        linhas = pth.read_text(encoding="utf-8", errors="replace").splitlines()
        executaveis = [l for l in linhas if classifica(l) == "executavel"]

How many .pth files did the venv load?

Numbers from results/resultado.txt. In each cell, total .pth files / how many have an import line:

Stage 3.11.18 3.12.3 3.13.18
E0 empty venv 1 / 1 0 / 0 0 / 0
E1 + 5 AI packages 1 / 1 0 / 0 0 / 0
E2 + setuptools 1 / 1 1 / 1 1 / 1
E3 + editable package 2 / 1 2 / 1 2 / 1
scan (ms) 0.30 to 0.48 0.21 to 0.37 0.26 to 0.49

The only executable .pth in all three versions is distutils-precedence.pth, from setuptools. On 3.11 it’s already in the empty venv, because the 3.11 ensurepip installs setuptools along with pip. On 3.12 and 3.13, only after you install setuptools. (On 3.11, stage E2 just upgrades the setuptools that was already there.) The line is this:

import os; var = 'SETUPTOOLS_USE_DISTUTILS'; enabled = os.environ.get(var, 'local') == 'local'; enabled and __import__('_distutils_hack').add_shim();

Notice that it’s exactly the kind of line the rule allows: arbitrary code, on one line, starting with import.

The editable package’s .pth has only a path, no import.

In which modes did my .pth run?

Command Did the marker show up?
python -c pass yes, 3 of 3 versions
python -I -c pass (isolated) yes, 3 of 3
python -s -c pass (no user site) yes, 3 of 3
python -E -c pass (ignores PYTHON* variables) yes, 3 of 3
python -m pip --version yes, 3 of 3
python -S -c pass (no site module) no, 0 of 3

The pip --version line is there on purpose: even the tool you use to inspect the environment runs the .pth before it answers.

And -S comes at a price. With it, site-packages doesn’t even go into sys.path, and this was the result, on all three versions:

$ python -S -c "import openai"
ModuleNotFoundError: No module named 'openai'

Why didn’t -I protect me?

Because it wasn’t made for that. -I turns off the PYTHON* variables, the script’s directory in sys.path and the user site (~/.local). The venv’s site-packages isn’t the user’s. It belongs to the environment, and it still gets processed. I had this wrong in my head.

What didn’t work?

Two of my bets were wrong. First: I expected to find .pth files with import among the AI packages. It was 0 out of 5. The one that shows up is setuptools’. Second: I expected an import line in the editable package’s .pth. It came with just a path.

And I wanted to link this test to the agent-framework case. It didn’t work out. What I could check doesn’t say what was in the pulled versions, and without that I don’t make the claim.

Who is it for, and when is it overkill?

It’s for anyone running CI or a coding agent that installs packages on its own. The scan itself takes less than 0.5 ms; the whole step costs basically Python’s startup. It fits right after pip install:

python varre_pth.py | python -c "import json,sys; d=json.load(sys.stdin); print(d['pth_com_executavel'], 'arquivo(s) .pth com import')"

The work is in what to do with the result. It only counts. Deciding what’s suspicious is up to you. In practice, you keep a list of what’s expected (distutils-precedence.pth, for example) and fail the build when one shows up that isn’t on it, on every lock change. In my humble opinion, it belongs in the same CI step that already checks dependencies.

When not to use it:

  • If you already install with --require-hashes, from a reviewed lock, in a disposable environment, the scan becomes redundant.
  • If your risk is sitecustomize.py, usercustomize.py or the 3.15 .start files, it doesn’t look at any of them.
  • Don’t use -S as a defense in an application that depends on installed packages: your imports break along with it.

How far does this test go?

  • 5 packages, one date (23 November 2026), Linux. Other packages may bring .pth files with import, legitimate or not. Zero here isn’t zero in your environment.
  • It doesn’t reproduce any incident. The .pth is mine and harmless.
  • I didn’t test Windows, conda or the system Python outside a venv.
  • The scan counts executable lines. Whether a line is malicious is for you to read and decide.

Source and how to reproduce

Documentation for the site module in the CPython repository: Doc/library/site.rst (3.12, 3.13 and main branches, read on 23 November 2026). Package versions checked on PyPI on the same date.

Code and real output: demos/17-pth-venv-sem-import. You need python3.11, python3.12 and/or python3.13 on PATH. Three commands:

git clone https://github.com/rogeriorrodrigues/nursia-research-lab
cd nursia-research-lab/demos/17-pth-venv-sem-import && pip install -r requirements.txt
python3 demo.py 3.11 3.12 3.13

Then python3 -m pytest tests -q -s. The test creates a venv without pip, writes a .pth with a marker and checks: it shows up by default, it shows up with -I, it goes away with -S. The output goes to results/resultado.txt and results/resultado.json.

Does anyone out there already have a CI step that fails when a new .pth shows up? How did you build the list of what’s expected?

The demo is part of the NursIA research repository (PPGINFOS/UFSC, FAPESC grant).

Conhece alguém que precisa ler isso?

Manda pra essa pessoa. Leva dez segundos e é o que mais ajuda esse trabalho a chegar em quem usa IA com dado de verdade.

Rogério Rodrigues

Rogério Rodrigues

Engenheiro de IA há 20 anos em software, mestrando em Informática em Saúde na UFSC. Escrevo o que rodei: IA com dado de saúde, FHIR e LGPD, com código aberto.

Ficou uma dúvida? Discorda de algo? Me chama.

Ver publicações científicas