← All notes

runpy: locate and run Python modules without importing first

Answer: The runpy module locates and runs Python modules without importing them first. Its main use is the -m command line switch. This is not a sandbox: code runs in the current process, and side effects remain.

Why it exists

Use this module to locate and run Python modules without importing them first.

The main use is the -m command line switch. Scripts can be located using the Python module namespace rather than the filesystem.

It is not a sandbox. Code runs in the current process, and side effects stay after the functions return.

The two functions

run_module runs a named module and returns that module's globals dictionary.

run_path runs the code at a filesystem location and also returns a globals dictionary.

run_module accepts mod_name, init_globals, run_name, and alter_sys.

See also

Claims

Sources

License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python Software Foundation, runpy — Locating and executing Python modules; CPython, runpy documentation (source). PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python Software Foundation, runpy — Locating and executing Python modules; CPython, runpy documentation (source). PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.

Cite this

Permanent ID: iil:note:m0fh02mp

iinventedlight. 2026. "runpy: locate and run Python modules without importing first." iinventedlight Library, iil:note:m0fh02mp, version of 2026-11-23. https://iinventedlight.com/library/notes/python-runpy/. License: CC-BY-4.0.

@misc{iil_note_m0fh02mp,
  author = {{iinventedlight}},
  title = {{runpy: locate and run Python modules without importing first}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-23},
  url = {https://iinventedlight.com/library/notes/python-runpy/},
  note = {Permanent ID iil:note:m0fh02mp. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).

Extra files beside this note

These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.

All artifact files (JSON index)

For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-runpy.md.