Run python file -- what function is main?
I have simple python script, 'first.py':
#first.py
def firstFunctionEver() :
p开发者_运维知识库rint "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?
if __name__ == "__main__":
firstFunctionEver()
Read more at the docs here.
if __name__ == '__main__':
firstFunctionEver()
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
精彩评论