__author__="Sergio.Tapia"
__date__ ="$18-10-2010 12:03:29 PM$"
if __name__ == "__main__":
print("Hello")
print(__author__)
Where does it get __main__
and __name__
?
Thanks for the help
__author__="Sergio.Tapia"
__date__ ="$18-10-2010 12:03:29 PM$"
if __name__ == "__main__":
print("Hello")
print(__author__)
Where does it get __main__
and __name__
?
Thanks for the help
The __name__
variable is made available by the runtime. It's the name of the current module, the name under which it was imported. "__main__"
is a string. It's not special, it's just a string. It also happens to be the name of the main script when it is executed.
The if __name__ == "__main__":
mechanism is the common way of doing something when a .py file is executed directly, but not when it is imported as a module.
Python modules can also be run as standalone scripts. As such, code within the if __name__ == "__main__":
block will only run if the module is executed as the "main" file.
Example:
#foo.py
def msg():
print("bar")
if __name__ == "__main__":
msg()
Running this module will output
$ python foo.py
bar
where as importing it will output nothing.
>>> import foo
>>> foo.msg()
bar