开发者

Run python file -- what function is main?

开发者 https://www.devze.com 2022-12-28 07:59 出处:网络
I have simple python script, \'first.py\': #first.py def firstFunctionEver() : p开发者_运维知识库rint \"hello\"

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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号