Radoslaw Smigielski

18 July 2019

Python __main__.py

by Radosław Śmigielski

Why?

Just recently I discovered Python 3 support for __main__.py file, which seems to be unknown even to Python developers. It allows to make Python modules executable.

How?

Executable module

Make module directory and module/__main__.py file indise it:

# file: module/__main__.py

def main():
    print("I am your module, executing {}".format(__name__))

if __name__ == '__main__':
    # execute only if run as the entry point into the program
    main()

Execute it now

> python module
I am your module, executing __main__

Compressed executable module

Compress module and execute it:

> python -m zipfile -c module.zip module/*
> python module
I am your module, executing __main__
tags: Python