Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

After breaking a python program into functions, how do I make one the main function?

Tags:

python

This is the biggest newbie question on the planet, but I'm just not 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.

like image 875
Mark Avatar asked Jan 24 '10 03:01

Mark


1 Answers

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()
like image 103
Max Shawabkeh Avatar answered Oct 13 '22 00:10

Max Shawabkeh