On this page
  1. runpy
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Invoking a Package Entry Point Programmatically (run_module)
  7. Gotchas & Boundaries
  8. Common Functions

runpy

Prev: rlcompleter | Up: stdlib_module | Next: sched
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — runpy
Tags: #public #python3 #stdlib


Import

import runpy

Overview

Locates and executes Python modules (run_module) or script files (run_path) using the same mechanism as python -m <module>, returning the executed global namespace dictionary cleanly without mutating sys.modules unexpectedly.

Quick Start

from pathlib import Path
import runpy
import tempfile

with tempfile.TemporaryDirectory() as tmp:
    script = Path(tmp) / "cfg.py"
    script.write_text("VALUE = 21 * 2\n", encoding="utf-8")
    ns = runpy.run_path(str(script))
    assert ns["VALUE"] == 42

Implementation Walkthrough

1. Invoking a Package Entry Point Programmatically (run_module)

import runpy

# Equivalent to `python -m json.tool` (pass run_name="__main__" to trigger the __main__ guard):
# runpy.run_module("my_pkg.cli", run_name="__main__")
assert callable(runpy.run_module)

Gotchas & Boundaries

Common Functions

Linked from

Related notes