Running modules from the command line

In Chapter 2, Writing Your First Modular Program, we saw your system's main program is often named and typically has the following structure:

def main():

if __name__ == "__main__":

The __name__ global variable will be set to the value "__main__" by the Python interpreter when the user runs your program. This has the effect of calling your main() function when the program is run.

There is nothing special about the program, however; it's just another Python source file. You can take advantage of this to make your Python modules executable from the command line.

Consider, for example, the following module, which we will call

def double(n): return n * 2 if __name__ == "__main__": ...

Get Modular Programming with Python now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.