[Tutor] did I lose the value of record?

Michael Janssen Janssen at rz.uni-frankfurt.de
Tue Mar 2 11:55:28 EST 2004


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, ":")

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

Michael




More information about the Tutor mailing list