Duplicate of:
What doesif __name__== "__main__"do?
Consider this code:
if __name__ == '__main__':
import pdb
pdb.run("interact()\n")
What does the following line mean?
if(__name__==开发者_C百科'__main__')
I fainted.
__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.
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.
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.
He has written a python module, intended to be used via import.
If the module is passed to the interpreter as the main python script, the code you quote will run. This will invoke the interact() method under the python debugger.
加载中,请稍侯......
精彩评论