After breaking a python program into functions, how do I make one the main function?
This is the biggest newbie question on the planet, but I'm just no开发者_StackOverflowt sure. I've written a bunch of functions that perform some task, and I want a "main" function that will, for example, when I call "someProgram.py", run function1, function2 and quit. I vaguely remember something about "main" but I have no clue.
Python scripts are not collections of functions, but rather collections of statements - function and class definitions are just statements that bind names to function or class objects.
If you put a print statement at the top or middle of your program, it will run normally without being in any function. What this means is that you could just put all the main code at the end of the file and it will run when the script is run. However, if your script is ever imported rather than run directly, that code will also run. This is usually not what you want so you would want to avoid that.
Python provides the __name__
global variable to differentiate when a script is imported and run directly - it is set to the name under which the script runs. If the script is imported, it will be the name of the script file. If it is run directly, it'll be "__main__"
. So, you can put an if __name__ == '__main__':
at the bottom of your program, and everything inside this if block will run only if the script is run directly.
Example.
if __name__ == "__main__":
the_function_I_think_of_as_main()
When a python module is being imported for the first time, it's main block is run. You can distinguish between being run by itself and being imported into another program:
if __name__ == "__main__":
function1()
function2()
else:
# loaded from another module
if __name__ == '__main__':
run_main()
It's the following idiom:
if __name__ == "__main__":
yourfoo()
Also read this.
As I read your question, you're asking about how to define a main function. That actually would be done with something like:
def main():
function1()
function2()
return 0
And then you would put code something like this outside all your main file's functions:
if __name__ == "__main__":
sys.exit(main())
(Of course you need an import sys somewhere for the above to work.)
A (now kind of old, but still relevant) post from Guido tells more.
精彩评论