Python help

Paul Lussier p.lussier at comcast.net
Thu Feb 5 10:47:56 EST 2004


Hi all,

So, I'm venturing into the world of Python and I find myself as expected,
trying to write python in perl :)

The task I chose to cut my teeth on is rather basic, and could be
written in perl in about 5 minutes.  Of course, the point here is to
learn python, so I didn't.  But I find myself thinking in perl, which
isn't working too well :)

The task is to parse an /etc/group file and spit out the data in LDIF
format for later import to an LDAP server.  For now, I'm happy just
parsing the file and spitting it back out with some minor data massage.

The things I find myself getting stuck on are things like string and list
processing.

Here's what I have so far:

    #!/sw/bin/python

    import os
    import sys

    class gr_struct:             # I found this in the docs and it seems
          pass                   # to work rather well.

    gr_hash = {}
    group = gr_struct()

    fp=open(sys.argv[1], 'r')

    for i in fp:
           i=i.strip("\n")
           line = i.split(':')
           group.name = line[0]  # what I don't quite get is *why* this works
           group.gid = line[2]   # but it certainly beats the dealing
                                 # with nested/anon dictionaries
                                 # (though I think I like
                                 # perl's hashes better

           group.members = line[3].split(',')
           gr_hash = {group.name: group}

    fp.close()    
    skeys = gr_hash.keys()
    string = ''
    for key in skeys:
        members = gr_hash[key].members # why can't I do 
                                       #  gr_hash[key].members.sort()
        members.sort()
        for i in members:              # I would expect to be able use
            if string == '':           # i.join() somehow, but that doesn't
               string = i              # seem to work
            else:
               string += ',' + i
        print key + ":" + gr_hash[key].gid + ":" + string


Obviously a quite rudimentary script, which at this point does nothing
more than re-create the /etc/group file in sorted order and removes
the passwd field.

I'd like to see/hear others ideas on how to write this same script.
I'm most interested in improvements or commentary on why what I did
is either right, wrong, interesting, stupid, etc.

I'm not overly interesting in shell, perl, tcl, or other language solutions
to this problem, since I already know how to write this in the first 3.
(a java or c implementation might be interesting :)

Thanks,

Seeya,
Paul
--
Key fingerprint = 1660 FECC 5D21 D286 F853  E808 BB07 9239 53F1 28EE

	It may look like I'm just sitting here doing nothing,
   but I'm really actively waiting for all my problems to go away.

	 If you're not having fun, you're not doing it right!



More information about the gnhlug-discuss mailing list