Evaluate my first python script, please

Tim Wintle tim.wintle at teamrubber.com
Fri Mar 5 17:07:22 CET 2010


On Fri, 2010-03-05 at 07:53 -0800, Pete Emerson wrote:
> Thanks for your response, further questions inline.
> 
> On Mar 4, 11:07 am, Tim Wintle <tim.win... at teamrubber.com> wrote:
> > On Thu, 2010-03-04 at 10:39 -0800, Pete Emerson wrote:
> > > I am looking for advice along the lines of "an easier way to do this"
> > > or "a more python way" (I'm sure that's asking for trouble!) or
> > > "people commonly do this instead" or "here's a slick trick" or "oh,
> > > interesting, here's my version to do the same thing".
> >
> > (1) I would wrap it all in a function
> >
> > def main():
> >     # your code here
> >
> > if __name__ == "__main__":
> >     main()
> 
> Is this purely aesthetic reasons, or will I appreciate this when I
> write my own modules, or something else?

It's for when you reuse this code. 

Consider it's in "mymodule.py" (so run with ./mymodule.py) - if you then
make a "tests.py" (for example) you can "import mymodule" without it
automatically running your code.

re-writing it

def main(args):
    #your code

if __name__ == "__main__":
    main(sys.argv[1:])

would obviously be more sensible for actually writing tests.


> > ... or you could replace whole section between the for loop and
> > hosts.append with:
> >
> >     if sorted(hostname.split(".")) == sorted(sys.argv[1:]):
> >         host.append(hostname)
> 
> This doesn't actually work, because I'm not looking for a one to one
> mapping of args to sections of hostname, but rather a subset. So
> passing in 'prod sfo' would register a match for '001.webapp.prod.sfo'.

Ah - good point - I guess the the set intersection technique someone
else mentioned is best in that case.

Tim




More information about the Python-list mailing list