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?

1

3 Answers 3

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

Read more at the docs here.

Sign up to request clarification or add additional context in comments.

Comments

10
if __name__ == '__main__':
    firstFunctionEver()

1 Comment

What is __name__ and when is it __main__? Please explain and provide references.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.