Python IDLE: Run main?

Nick Heiner picture Nick Heiner · May 29, 2010 · Viewed 33.4k times · Source

I'm in IDLE:

>>> import mymodule
>>> # ???

After importing a module with:

if __name__ == '__main__':
    doStuff()

How do I actually call main from IDLE?

Answer

Carles Barrobés picture Carles Barrobés · May 29, 2010

The if condition on __name__ == '__main__' is meant for code to be run when your module is executed directly and not run when it is imported. There is really no such concept of "main" as e.g. in Java. As Python is interpreted, all lines of code are read and executed when importing/running the module.

Python provides the __name__ mechanism for you to distinguish the import case from the case when you run your module as a script i.e. python mymodule.py. In this second case __name__ will have the value '__main__'

If you want a main() that you can run, simply write:

def main():
   do_stuff()
   more_stuff()

if __name__ == '__main__':
   main()