17

I have simple python script, 'first.py':

#first.py
def firstFunctionEver() :
    print "hello"

firstFunctionEver()

I want to call this script using : python first.py and have it call the firstFunctionEver(). But, the script is ugly -- what function can I put the call to firstFunctionEver() in and have it run when the script is loaded?

atp
  • 30,132
  • 47
  • 125
  • 187

3 Answers3

40
if __name__ == "__main__":
    firstFunctionEver()

Read more at the docs here.

Steve Tjoa
  • 59,122
  • 18
  • 90
  • 101
10
if __name__ == '__main__':
    firstFunctionEver()
Ken
  • 334
  • 2
  • 8
  • What is `__name__` and when is it `__main__`? Please explain and provide references. – agf Apr 14 '12 at 01:03
0

I know that you explicitly said you want to call your script using python first.py. However you could consider calling your script in different way without even changing any code.

Let's say your project structure is of the form first_pckg/first.py. You can rename your first.py to __main__.py. Also include a __init__.py empty file to mark the directory as a python package. You can then simply call your package like this:

$ python -m first_pckg
hello
renatodamas
  • 16,555
  • 8
  • 30
  • 51