简体   繁体   English

Python脚本必须将函数定义为main吗?

[英]Must Python script define a function as main?

Must/should a Python script have a main() function? Python脚本必须/应该有main()函数吗? For example is it ok to replace 例如,可以替换

if __name__ == '__main__':
  main()

with

if __name__ == '__main__':
  entryPoint()

(or some other meaningful name) (或其他一些有意义的名字)

Using a function named main() is just a convention. 使用名为main()的函数只是一种约定。 You can give it any name you want to. 你可以给它任何你想要的名字。

Testing for the module name is just a nice trick to prevent code running when your code is not being executed as the __main__ module (ie not when imported as the script Python started with, but imported as a module). 当代码没有作为__main__模块执行时,测试模块名称只是防止代码运行的一个很好的技巧 (即不是在Python开始时导入,而是作为模块导入时)。 You can run any code you like under that if test. if测试,您可以运行任何您喜欢的代码。

Using a function in that case helps keep the global namespace of your module uncluttered by shunting names into a local namespace instead. 在这种情况下使用函数有助于通过将名称分流到本地名称空间来保持模块的全局名称空间不整洁。 Naming that function main() is commonplace, but not a requirement. 命名函数main()是常见的,但不是必需的。

No, a Python script doesn't have to have a main() function. 不,Python脚本不必具有main()函数。 It is just following conventions because the function that you put under the if __name__ == '__main__': statement is the function that really does all of the work for your script, so it is the main function. 它只是遵循约定,因为您放在if __name__ == '__main__':语句下的函数是真正完成脚本所有工作的函数,因此它是主函数。 If there really is function name that would make the program easier to read and clearer, then you can instead use that function name. 如果确实有函数名称可以使程序更容易阅读和更清楚,那么您可以改为使用该函数名称。

In fact, you don't even need the if __name__ == '__main__': part, but it is a good practice, not just a convention. 事实上,你甚至不需要 if __name__ == '__main__': part,但这是一个很好的做法,而不仅仅是一个约定。 It will just prevent the main() function or whatever else you would like to call it from running when you import the file as a module. 当您将文件作为模块导入时,它将阻止main()函数或您想要运行的任何其他函数。 If you won't be importing the script, you probably don't need it, but it is still a good practice. 如果你不想导入脚本,你可能不需要它,但它仍然是一个很好的做法。 For more on that and why it does what it does, see What does if __name__ == "__main__": do? 有关它的更多信息以及它为什么会这样做 ,请参阅if __name__ ==“__ main__”会怎么样?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM