Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python IDLE: Run main?

I'm in IDLE:

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

After importing a module with:

if __name__ == '__main__':
    doStuff()

How do I actually call main from IDLE?

like image 868
Nick Heiner Avatar asked May 29 '10 16:05

Nick Heiner


1 Answers

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()
like image 135
Carles Barrobés Avatar answered Sep 28 '22 09:09

Carles Barrobés