1 min read

Python Runpy Module

The runpy module is used to locate and execute Python modules without importing them first. Its main use is to implement the -m command line switch that allows scripts to be located using the Python module namespace rather than the filesystem.

Importing the Module

import runpy

Executing Modules

The runpy.run_module() function executes the code of the specified module and returns the resulting module globals dictionary.

import runpy

# Execute the http.server module (similar to python -m http.server)
# Note: This might block execution depending on the module
# runpy.run_module('http.server', run_name='__main__')

You can capture the globals:

import runpy

# Assuming you have a module named 'mymodule'
# result = runpy.run_module('mymodule')
# print(result['some_variable'])

Executing Paths

The runpy.run_path() function executes the code at the named filesystem location and returns the resulting module globals dictionary.

import runpy

# Execute a script file
# result = runpy.run_path('myscript.py')

This is similar to running a script from the command line, but within the current process.

programming/python/python