[Swlug] if __name__ == '__main__':

Rhys Sage rhys_sage at yahoo.com
Sat Feb 26 14:44:39 UTC 2022


I'm working with an existing Python program and I've looked at the online information as to what "if __name__ == '__main__':" is supposed to do. It seems a very weird and verbose way of doing anything. I'm hoping somebody can help me break that down a bit so I can understand it better.
I get == as being the same as.
Where __name__ and __main__ come from is a little puzzling.
What exactly is __main__ and why does it need __ surrounding it. Same for __name__?
The code it's extracted from is this...
if __name__ == '__main__':    ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)  # Open Serial port    try:        while True:            line = readString()            lines = line.split(",")            if checksum(line):                if lines[0] == "GPRMC":                    printRMC(lines)                    pass                elif lines[0] == "GPGGA":                    printGGA(lines)                    pass                elif lines[0] == "GPGSA":                    # printGSA(lines)                    pass                elif lines[0] == "GPGSV":                    # printGSV(lines)                    pass                elif lines[0] == "GPGLL":                    printGLL(lines)                    pass                elif lines[0] == "GPVTG":                    printVTG(lines)                    pass                else:                    print("\n\nUnknown type:", lines[0], "\n\n")    except KeyboardInterrupt:        print('Exiting Script')

Rhys Sage
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.lug.org.uk/pipermail/swlug/attachments/20220226/8b33fa39/attachment.htm>


More information about the Swlug mailing list