Locating and executing Python modules (runpy)


The –m option of command line option searches for a given module and execute it as the __main__ module. This mechanism is internally supported by runpy module from Python's standard module that allows scripts to be located using the Python module namespace rather than the filesystem.

This module defines two functions

run_module()

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

The mod_name argument should be an absolute module name. If the module name refers to a package rather than a normal module, then that package is imported and the __main__ submodule within that package is then executed and the resulting module globals dictionary returned.

The special global variables __name__, __spec__, __file__, __cached__, __loader__ and __package__ are set in the globals dictionary before the module code is executed.

__name__ is set to mod_name + '.__main__' if the named module is a package and to the mod_name argument otherwise.

__file__, __cached__, __loader__ and __package__ are set as normal based on the module spec.

run_path()

This function executes the code in the file at given path and returns the resulting module globals dictionary. The supplied path may refer to a Python source file, a compiled bytecode file or a valid sys.path entry containing a __main__ module (e.g. a zipfile containing a top-level __main__.py file).

The special global variables __name__, __spec__, __file__, __cached__, __loader__ and __package__ are set in the globals dictionary before the module code is executed.

__name__ is set to run_name if this optional argument is not None and to '<run_path>' otherwise.

Example

Save following script as runpyeample.py

#runpy example
def add(x,y):
   return x+y
def main():
   x,y = 10,20
   print (add(x,y))
   return
if __name__=='__main__':
   main()

The usual process of executing above example is as follows

>>> import runpyexample as rp
>>> rp.main()
30
>>>

However, we now use runpy module to execute it without actually importing it.

>>> import runpy
>>> runpy.run_module('runpyexample', run_name='__main__')
30

You can also use run_path() function.

>>> runpy.run_path('runpyexample.py', run_name='__main__')
30

As said earlier, runpy supports the –m switch of Python command line.

E:\python37>python -m runpyexample
30

Updated on: 30-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements