Python 2.4 added the -m option to execute modules as scripts (Python 3.x documentation, 2.x documentation. PEP 338, adopted in Python 2.5, adds the ability to execute modules in the search path.

Executable Standard Library Modules

The following standard library modules work as command-line tools:

Writing Executable Modules

Here's a sample executable Python script:

def main():
    import sys

    for pos, arg in enumerate(sys.argv):
        print('Argument %d: %s' % (pos, arg))

if __name__ == '__main__':

If this file is importable as mylib.script, then running python -m mylib.script foo bar will output:

Argument 0: /full/path/to/mylib/
Argument 1: foo
Argument 2: bar

The starting line #!/usr/bin/env python is used in UNIX-like shells. If the script is given execute permissions, then it can also be executed directly.

A fully-featured script should use a library to parse the command line, such as argparse. See the source for json.tool for a fuller example.

ExecutableModules (last edited 2016-01-13 17:43:24 by JohnWhitlock)

Unable to edit the page? See the FrontPage for instructions.