What does `if name == "
Possible Duplicate:
What does <if name ==“ main ”:> do?
I have wrote scripts in Python for quite a while now and I study more of Python as I need it. When reading other people's code I meet if name == "__main__":
construct quite often.
What is it good for?
This allows you to use the same file both as a library (by importing it) or as the starting point for an application.
For example, consider the following file:
# hello.py
def hello(to=__name__):
return "hello, %s" % to
if __name__ == "__main__":
print hello("world")
You can use that code in two ways. For one, you can write a program that imports it. If you import the library, __name__
will be the name of the library and thus the check will fail, and the code will not execute (which is the desired behavior):
#program.py
from hello import hello # this won't cause anything to print
print hello("world")
If you don't want to write this second file, you can directly run your code from the command line with something like:
$ python hello.py
hello, __main__
This behavior all depends on the special variable __name__
which python will set based on whether the library is imported or run directly by the interpreter. If run directly it will be set to __main__
. If imported it will be set to the library name (in this case, hello
).
Often this construct is used to add unit tests to your code. This way, when you write a library you can embed the testing code right in the file without worrying that it will get executed when the library is used in the normal way. When you want to test the library, you don't need any framework because you can just run the library as if it were a program.
See also __main__
in the python documentation (though it's remarkably sparse)
Basically,
There's a distinction between the "main" script file and external files which were imported or referenced in another way. If the script is the "main" script then the special variable __name__
will equal "__main__"
.
You can use this to protect the "execution" code from the classes and variables the script has. This enables you to import a script and use classes and variables without actually running that script's main code if it has any.
链接地址: http://www.djcxy.com/p/9312.html上一篇: 它为什么这样做? 如果
下一篇: “if name ==”是什么