In python, if you want to write a script to perform a series of small tasks sequentially, then there is absolutely no need to write a function to contain them. Just put each on a line on its own; or use an expression delimiter like ;
(not really recommended, but you can do is you so desire), likewise:
task1
task2
task3
task4
or
task1; task2; task3; (again **not** really recommended, and certainly not pythonic)
In your case your code could be turned to something like:
print('boo')
print('boo2')
print('boo3')
and it would still act as you expect it to, without the main()
method, as they get evaluated sequentially.
Please note that the reason you might want to create a function for these series of tasks is:
- to present a nice interface (to clients of the code),
- or to encapsulate repeated logic
- There might be more uses, but that's the first I can come up with, and serve to prove my point.
Now, if you feel compelled to write code that resembles the main()
method in other programming languages, then please use the following python idiom (as stated by other users so far):
if __name__ == '__main__':
doSomething()
The above is working as following:
- When you
import
a python module, it gets a string
(usually, the name under which it was imported) assigned as its __name__
attribute.
- When you execute a script directly (by invoking the python vm and passing it the script's name as an argument), the
__name__
attribute is set to __main__
- So when you use the above idiom, you can both use the script as a pluggable module by
import
ing it at will, or just execute it directly to have the series of expressions under the if __name__ == '__main__':
be evaluated directly.
Should you feel the need to dig through more information, my sources were the following:
sudo
to chmod a file you own. - ThiefMaster