Why does it do this ? if
Possible Duplicate:
What does <if name ==“ main ”:> do?
Consider this code:
if __name__ == '__main__':
import pdb
pdb.run("interact()n")
What does the following line mean?
if(__name__=='__main__')
I fainted.
This will be true if this module is being run as a standalone program. That way, something can act either as a module imported by another program, or a standalone program, but only execute the code in the if
statement if executed as a program.
__name__
is a variable automatically set in an executing python program. If you import
your module from another program, __name__
will be set to the name of the module. If you run your program directly, __name__
will be set to __main__
.
Therefore, if you want some things to happen only if you're running your program from the command line and not when imported (eg. unit tests for a library), you can use the
if __name__ == "__main__":
# will run only if module directly run
print "I am being run directly"
else:
# will run only if module imported
print "I am being imported"
trick. It's a common Python idiom.
That is a check to see if you are directly running the script or if it is included in a library.
When you run a python script like this:
python myScript.py
It sends a parameter, telling you to run the programs first method, which is widely called "main", so when __name__
is __main__
you know that the program was executed from a command line or double clicked.
上一篇: 我不明白Python的主要区块。 那个东西是什么?
下一篇: 它为什么这样做? 如果