Help with __name__ == '__main__'

Erlend J. Leiknes nookieNO_SP_AM at online.no
Mon May 13 17:46:58 EDT 2002


if __name__ == '__main__': is a method to avoid the code to be executed if
its imported as a module.

You could simply just remove the """ if __name__ == '__main__': """, but
then you cannot use your code as a module without adding it back (unless you
want it to be executed upon import.

"Manuel" <magni2k at uni.de> wrote in message
news:mailman.1021276643.10462.python-list at python.org...
> Hi, Thanks a lot for the help from Skip Montanaro and Andreas Jung!
>
> But now a new question. This is the complete code and I am not able to
call
> the function so, that it only prints out e.g. the gethost list. How can I
> handle this in __name__ == '__main__'! Or is there another possibility to
> handle this more elegant or simpler? Thanks for help and hints!
> The function call should be in this type:
> python filelist.py serverlist.txt
> and optional:  python filelist.py serverlist.txt gethost
> or  python filelist.py serverlist.txt getprotocol getpath
>
> Thanks for help and hints!
>
>
> filelist.py
> import sys, string, urlparse
>
> class ListFile:
>
>   def __init__(self, filename):
>       self.file = open(filename, 'r')
>
>
>
>   def __getitem__(self, i):
>       line = self.file.readline()
>       if line:
>           return line
>       else:
>           raise IndexError
>
>   def __getattr__(self, name):
>       return getattr(self.file, name)
>
>   def getall(self):
>       for line in self.file:
>           parseurl = urlparse.urlparse(line)
>           getprotocol = parseurl[0]
>           gethost = parseurl[1]
>           getpath = parseurl[2]
>           print getprotocol, gethost, getpath,
>
>   def getprotocol(self):
>       for line in self.file:
>           parseurl = urlparse.urlparse(line)
>           getprotocol = parseurl[0]
>           print getprotocol
>
>   def gethost(self):
>       for line in self.file:
>           parseurl = urlparse.urlparse(line)
>           gethost = parseurl[1]
>           print gethost
>
>   def getpath(self):
>       for line in self.file:
>           parseurl = urlparse.urlparse(line)
>           getpath = parseurl[2]
>           print getpath,
>
> if __name__ == '__main__':
>   line = ListFile(sys.argv[1])
>   line.getall()
>   line.getall()
>   line.getprotocol()
>   line.gethost()
>   line.getpath()
>
>
>
>





More information about the Python-list mailing list