all Python 3Modules & importsfunction
runpy.run_path()
running
Executes a script, a directory or a zip file with __main__.py by path and returns its globals dictionary — like python path.py.
Syntax
runpy.run_path(path_name, init_globals=None, run_name=None)
By default __name__ becomes '<run_path>', and the code under if __name__ == '__main__' silently does not run; pass run_name='__main__'. The script runs in the same process: its sys.exit() ends your program too, and exceptions propagate. Unlike exec(open(...).read()), __file__ and the import path for a directory or archive are set correctly.
Examples
import runpy
with open('script.py', 'w') as f:
f.write('result = 6 * 7\nif __name__ == "__main__":\n print("main!")\n')
g = runpy.run_path('script.py')
print(g['result'], g['__name__']) # → 42 <run_path>
g = runpy.run_path('script.py', run_name='__main__') # → main!
See also
Open in the full glossarydocs.python.orgReport an inaccuracy