[Tutor] did I lose the value of record?

Eric L. Howard elh at outreachnetworks.com
Tue Mar 2 12:22:04 EST 2004


At a certain time, now past [Mar.02.2004-05:55:28PM +0100], Janssen at rz.uni-frankfurt.de spake thusly:
> On Tue, 2 Mar 2004, Eric L. Howard wrote:
> 
> [getpwnam with teststring]
> > >>> record  = "elhtest:elh"
> > >>> userhome = pwd.getpwnam(string.split(record, ":")[1])[5]
> > >>> print userhome
> > /home/elh
> 
> [now for real]
> > #!/usr/bin/env python
> >
> > import re, string, pwd
> >
> > listingsfile = open("listings","r")
> > for record in listingsfile.readlines():
> >     if re.search("elhtest", record):
> >         listing = string.split(record, ":")[0]
> >         owner = string.split(record, ":")[1]
> >         ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5]
> >         print "The listing we're found is %s" % listing
> >         print "The owner for this listing is %s" % owner
> >         print "The owner's home dir is %s" % ownerhome
> > listingsfile.close()
> >
> > I get the following:
> >
> > Traceback (most recent call last):
> >   File "./sa_setup.py", line 10, in ?
> >     ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5]
> > KeyError: 'getpwnam(): name not found'
> 
> You very likly have found a user not in password database. Do:
> 
> try: ownerhome = pwd.getpwnam(string.split(record, ":")[1])[5]
> except KeyError: print "ERROR", string.split(record, ":")

I didn't even have to get this far...as soon as I saw the try->except...I
looked at the data again [I knew for a fact that the username should be in
the passwd file] and saw the source of my problem.

> this way you a) find out the bad name b) catch the error.
> 
> BTW: you should do string.split(record, ":") only once. Create a temp
> variable:
> spl = string.split(record, ":") # spl like split
> owner = spl[0]
> 
> or directly:
> owner, home = string.split(record, ":")
> 
> Cleaner code, faster

Cool...thanx.

       ~elh

-- 
Eric L. Howard           e l h @ o u t r e a c h n e t w o r k s . c o m
------------------------------------------------------------------------
www.OutreachNetworks.com                                    313.297.9900
------------------------------------------------------------------------
JabberID: elh at jabber.org                 Advocate of the Theocratic Rule



More information about the Tutor mailing list