Welcome, guest | Sign In | My Account | Store | Cart

Given a filesystem path, use it to create a valid Python module. Based on runpy.run_path(), so accepts Python source files, compiled Python files and directories and zipfiles containing __main__.py files as valid targets.

Python, 16 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import runpy
import imp

def mod_from_file(mod_name, path):
    """Runs the Python code at path, returns a new module with the resulting globals"""
    attrs = runpy.run_path(path, run_name=mod_name)
    mod = imp.new_module(mod_name)
    mod.__dict__.update(attrs)
    return mod

# Example usage

>>> import timeit
>>> timeit2 = mod_from_file("timeit2", timeit.__file__)
>>> dir(timeit2)
['Timer', '__all__', '__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '_template_func', 'default_number', 'default_repeat', 'default_timer', 'dummy_src_name', 'gc', 'itertools', 'main', 'reindent', 'repeat', 'sys', 'template', 'time', 'timeit']

To backport this to earlier Python versions, it is possible to replace the runpy.run_path() usage with execfile():

def mod_from_file(mod_name, path):
    """Runs the Python code at path, returns a new module with the resulting globals"""
    mod = imp.new_module(mod_name)
    mod.__file__ = path
    execfile(path, mod.__dict__)
    return mod

Note that in this variant, path must refer directly to a Python source file, as execfile() doesn't know how to handle anything else.