On this page
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
- Executes arbitrary Python code: Never call
run_path()orrun_module()on untrusted files or user-controlled module names. - Pass
run_name="__main__"only when you wantif __name__ == "__main__":blocks to execute. - Use
importlib.import_module()when you want normal cached module imports rather than fresh script execution.
Common Functions
- runpy.run_module() —
run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)— Execute a module's code without importing it. - runpy.run_path() —
run_path(path_name, init_globals=None, run_name=None)— Execute code located at the specified filesystem location.
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/rlcompleter
- tuts/python3/stdlib_module/runpy/run_module
- tuts/python3/stdlib_module/runpy/run_path
- tuts/python3/stdlib_module/sched
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/tutorials/intermediate_python_and_software_engineering/modules_packages_and_tooling
Related notes
- tuts/python3/stdlib_module/rlcompleter Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/runpy/run_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/runpy/run_path Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/sched Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/builtins Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/sys Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/sysconfig Linked here; shared tags: #stdlib