Locating and executing Python modules (runpy)

The runpy module allows you to locate and execute Python modules using the module namespace rather than the filesystem. This is the same mechanism that supports Python's -m command line option.

Understanding runpy Module

The runpy module defines two main functions for executing modules dynamically:

  • run_module() − Executes a module by name
  • run_path() − Executes a module by file path

run_module() Function

This function executes the code of the specified module and returns the resulting module globals dictionary.

Syntax

runpy.run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)

Parameters

  • mod_name − Absolute module name to execute
  • init_globals − Optional initial globals dictionary
  • run_name − Optional name for __name__ variable
  • alter_sys − Whether to modify sys.modules

The special global variables __name__, __spec__, __file__, __cached__, __loader__ and __package__ are automatically set before execution.

run_path() Function

This function executes code from a file path and returns the module globals dictionary. The path can refer to a Python source file, compiled bytecode, or a valid sys.path entry.

Syntax

runpy.run_path(path_name, init_globals=None, run_name=None)

Example

Let's create a sample module to demonstrate runpy functionality ?

# Create a sample module (save as runpyexample.py)
def add(x, y):
    return x + y

def main():
    x, y = 10, 20
    result = add(x, y)
    print(f"Sum of {x} and {y} is: {result}")
    return result

if __name__ == '__main__':
    main()

Traditional Import Method

# Traditional way - importing the module
# import runpyexample as rp
# rp.main()

# Simulating the traditional approach
def add(x, y):
    return x + y

def main():
    x, y = 10, 20
    result = add(x, y)
    print(f"Sum of {x} and {y} is: {result}")
    return result

main()
Sum of 10 and 20 is: 30

Using run_module()

import runpy
import sys
import os

# Create a temporary module for demonstration
module_code = '''
def add(x, y):
    return x + y

def main():
    x, y = 15, 25
    result = add(x, y)
    print(f"Using run_module: {x} + {y} = {result}")
    return result

if __name__ == '__main__':
    main()
'''

# Write to a temporary file
with open('temp_module.py', 'w') as f:
    f.write(module_code)

# Add current directory to Python path
if '.' not in sys.path:
    sys.path.insert(0, '.')

# Execute using run_module
try:
    globals_dict = runpy.run_module('temp_module', run_name='__main__')
    print("Module executed successfully!")
except ImportError as e:
    print(f"Could not import module: {e}")
finally:
    # Clean up
    if os.path.exists('temp_module.py'):
        os.remove('temp_module.py')
Using run_module: 15 + 25 = 40
Module executed successfully!

Using run_path()

import runpy
import tempfile
import os

# Create a temporary file
module_code = '''
def multiply(x, y):
    return x * y

def main():
    x, y = 6, 7
    result = multiply(x, y)
    print(f"Using run_path: {x} * {y} = {result}")
    return result

if __name__ == '__main__':
    main()
'''

# Create temporary file
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
    f.write(module_code)
    temp_path = f.name

try:
    # Execute using run_path
    globals_dict = runpy.run_path(temp_path, run_name='__main__')
    print("File executed successfully!")
finally:
    # Clean up
    os.unlink(temp_path)
Using run_path: 6 * 7 = 42
File executed successfully!

Command Line Usage

The runpy module supports Python's -m switch for executing modules from the command line ?

# Command line usage
python -m module_name

# Example
python -m runpyexample

Key Differences

Function Input Use Case
run_module() Module name Execute installed modules
run_path() File path Execute scripts by path

Conclusion

The runpy module provides a powerful way to execute Python modules dynamically without traditional imports. Use run_module() for module names and run_path() for file paths, making it ideal for plugin systems and dynamic script execution.

Updated on: 2026-03-25T05:26:41+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements