all Python 3Modules & importsfunction
runpy.run_module()
running
Locates a module by name through the import system and executes its code, returning its globals dictionary — this is how python -m works.
Syntax
runpy.run_module(mod_name, init_globals=None, run_name=None, alter_sys=False)
By default __name__ is the module name, so the if __name__ == '__main__' block does not run — pass run_name='__main__' to mimic python -m. The module is executed afresh on every call and is not left in sys.modules. Without alter_sys=True, sys.argv[0] and sys.modules['__main__'] are unchanged, and the executed code sees the caller's arguments.
Examples
import runpy, sys
sys.path.insert(0, '.')
with open('tool.py', 'w') as f:
f.write('x = 6 * 7\nif __name__ == "__main__":\n print("main!")\n')
g = runpy.run_module('tool')
print(g['x'], g['__name__']) # → 42 tool
g = runpy.run_module('tool', run_name='__main__') # → main!
print('tool' in sys.modules) # → False
See also
Open in the full glossarydocs.python.orgReport an inaccuracy