在Python中,为什么要这个东东 __name__ == __main__

One of those nice features of Python, that marks it as a language designed for developers (as opposed to one designed for tool vendors) is the ability to conditionally run some logic if you’re executing a script directly but ignore it if the script is being imported (“included”) by another script.

python 的main 方法是个很有意思的东东,如果你直接执行这个带有main的脚本,它会被调用。但是当这个脚本被import到其他的脚本的时候,main 会被忽略掉。惊奇不惊奇。

Why Does It Work This Way? 要这个东东干啥呢

You might naturally wonder why anybody would want this. Well, sometimes you want to write a .pyfile that can be both used by other programs and modules as a module and can be run as the main program. 

也许你会本能的猜测为什么会有人想要这个,有时候你写一个.py文件,它可以被其他程序和模块调用,有可以作为主程序运行。

  • Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.

  • Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.

  • Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.

猜你喜欢

转载自blog.csdn.net/wangweimic/article/details/88663359