开发者

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?


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()


If you import something it's not main. You need to run it from the menu or as an argument when you start 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()


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


Regarding the execfile mentioned by taleinat.

Python 3.5 deprecated execfile instead following method is suggested.

Removed execfile(). Instead of execfile(fn) use exec(open(fn).read()).

PS:I could not comment on taleinat's solution because of lack of reputation points in stackoverflow.


EDIT: Updated this old answer since execfile was removed in Python 3.

With Python 2

Use execfile (i.e. execfile(file_path)) instead of using import.

With Python 3

Use the runpy module as suggested in Carles Barrobés's answer.

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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜