I'm in IDLE:
>>> import mymodule
>>> # ???
After importing a module with:
if __name__ == '__main__':
doStuff()
How do I actually call main
from IDLE?
I'm in IDLE:
>>> import mymodule
>>> # ???
After importing a module with:
if __name__ == '__main__':
doStuff()
How do I actually call main
from IDLE?
I suppose that you are calling 'main' what you have after if __name__ == '__main__'
. So to call it:
>> import mymodule
>> mymodule.doStuff()
Otherwise if you actually have a main function in your module then,
>> import mymodule
>> mymodule.main()
If you import something it's not main. You need to run it from the menu or as an argument when you start idle.
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()
All you would have to do is call the main function itself like joaquin said.
How I do it is just keep a terminal open at the location of the file and rerun the command when I need it.
A last method would be to use an IDE like geany or Idle and open it with (file>open) and push F5.
The:
if __name__ == '__main__':
doStuff()
you have is actually made to keep the main function from running if it's imported.
Use execfile(filename) instead of using import.
Update:
The purpose of the condition if __name__ == '__main__'
is to have the code inside the "if" block not be executed when importing the module. Such code will only be run when the file is run directly, for example by running "python filename" from the command line, or by using execfile(filename).
As requested, an example of using execfile. In C:\my_code.py:
if __name__ == '__main__':
print "Hello World!"
Then, in an interpreter:
>>> execfile("C:\\my_code.py")
Hello world!
I found another way to run a module by name in Python 2.6:
>>> import runpy
>>> runpy.run_module('mypack.mymodule')
run_module returns a dictionary with all created attributes
http://docs.python.org/library/runpy.html?highlight=runpy#runpy.run_module