pwd.getpw*(), grp.getgr*() and time.{local,gm}time() 
Author Message
 pwd.getpw*(), grp.getgr*() and time.{local,gm}time()

I finally got tired enough of the fact that getpwnam(),
localtime() and stat() returns tuples, so I wrote small wrapper
modules around pwdmodule, grpmodule, timemodule and posixmodule.
They make these functions return objects with attributes.  This I
can now do

    >>> import pwd
    >>> me = pwd.getpwnam("bellman")
    >>> print me.name, me.uid, me.gecos, me.shell
    bellman 236 Thomas Bellman /bin/bash

    >>> import time
    >>> t = time.localtime(time.time())
    >>> print "Time is %02d:%02d:%02d" % (t.hour,t.min,t.sec)
    Time is 18:08:15

and not need to know at what index the gecos field or the hour
field is.  Of course, these objects have __getitem__() and
__getslice__() methods, so old code that expects the tuple return
values still work.

I have implemented this by renaming the original modules to _pwd,
_grp, _time and _posix, and making wrappers in Python.  However,
this didn't work very well with the posix module, since os.py
expects that the module named 'posix' should be present in
sys.builtin_module_names, and I don't know what the best way to
fix this is.  I include the posix.py wrapper anyway.

To implement this, do

    $ mv Module/pwdmodule.c Module/_pwdmodule.c
    $ mv Module/grpmodule.c Module/_grpmodule.c
    $ mv Module/timemodule.c Module/_timemodule.c

apply the following patch, and install the pwd.py, grp.py and
time.py after the patch in the Lib subdirectory.

The patches are agains python 1.4.

I would be very happy if these changes appeared in 1.5, and even
happier if stat(), lstat() and fstat() in the posix module are
changed to.  *Looks beggingly at Guido with puppy-dog eyes*

I will try to fix the documentation too, but I don't have time to
do that today.

----- patch ------------------------------------------------------------
*** Modules/grpmodule.c Tue Oct 14 17:14:18 1997
--- Modules/_grpmodule.c        Tue Oct 14 12:40:16 1997
***************
*** 123,131 ****
        {"getgrall",  grp_getgrall},
        {NULL,          NULL}           /* sentinel */
  };

  void
! initgrp()
  {
!       initmodule("grp", grp_methods);
  }
--- 123,131 ----
        {"getgrall",  grp_getgrall},
        {NULL,          NULL}           /* sentinel */
  };

  void
! init_grp()
  {
!       initmodule("_grp", grp_methods);
  }
*** Modules/pwdmodule.c Tue Oct 14 17:13:57 1997
--- Modules/_pwdmodule.c        Tue Oct 14 12:40:45 1997
***************
*** 112,120 ****
        {"getpwall",  pwd_getpwall},
        {NULL,          NULL}           /* sentinel */
  };

  void
! initpwd()
  {
!       initmodule("pwd", pwd_methods);
  }
--- 112,120 ----
        {"getpwall",  pwd_getpwall},
        {NULL,          NULL}           /* sentinel */
  };

  void
! init_pwd()
  {
!       initmodule("_pwd", pwd_methods);
  }
*** Modules/timemodule.c        Tue Oct 14 17:14:09 1997
--- Modules/_timemodule.c       Tue Oct 14 12:41:00 1997
***************
*** 337,350 ****
                fatal("Can't initialize time module -- dictinsert failed");
        DECREF(v);
  }

  void
! inittime()
  {
        object *m, *d;
!       m = initmodule("time", time_methods);
        d = getmoduledict(m);
  #ifdef HAVE_TZNAME
        tzset();
        ins(d, "timezone", newintobject((long)timezone));
  #ifdef HAVE_ALTZONE
--- 337,350 ----
                fatal("Can't initialize time module -- dictinsert failed");
        DECREF(v);
  }

  void
! init_time()
  {
        object *m, *d;
!       m = initmodule("_time", time_methods);
        d = getmoduledict(m);
  #ifdef HAVE_TZNAME
        tzset();
        ins(d, "timezone", newintobject((long)timezone));
  #ifdef HAVE_ALTZONE
*** Modules/Setup.in.orig       Tue Oct 14 17:16:44 1997
--- Modules/Setup.in    Tue Oct 14 16:06:34 1997
***************
*** 114,134 ****
  cmath cmathmodule.c # -lm # complex math library functions
  math mathmodule.c # -lm # math library functions, e.g. sin()
  regex regexmodule.c regexpr.c # Regular expressions, GNU Emacs style
  strop stropmodule.c   # fast string operations implemented in C
  struct structmodule.c # binary structure packing/unpacking
! time timemodule.c # -lm # time operations and variables
  operator operator.c   # operator.add() and similar goodies

  # Modules with some UNIX dependencies -- on by default:
  # (If you have a really backward UNIX, select and socket may not be
  # supported...)

  fcntl fcntlmodule.c   # fcntl(2) and ioctl(2)
! pwd pwdmodule.c               # pwd(3)
! grp grpmodule.c               # grp(3)
  crypt cryptmodule.c # -lcrypt # crypt(3); needs -lcrypt on some systems
  select selectmodule.c # select(2); not on ancient System V
  socket socketmodule.c # socket(2); not on ancient System V
  errno errnomodule.c   # posix (UNIX) errno values

--- 114,134 ----
  cmath cmathmodule.c # -lm # complex math library functions
  math mathmodule.c # -lm # math library functions, e.g. sin()
  regex regexmodule.c regexpr.c # Regular expressions, GNU Emacs style
  strop stropmodule.c   # fast string operations implemented in C
  struct structmodule.c # binary structure packing/unpacking
! _time _timemodule.c # -lm # time operations and variables
  operator operator.c   # operator.add() and similar goodies

  # Modules with some UNIX dependencies -- on by default:
  # (If you have a really backward UNIX, select and socket may not be
  # supported...)

  fcntl fcntlmodule.c   # fcntl(2) and ioctl(2)
! _pwd _pwdmodule.c             # pwd(3)
! _grp _grpmodule.c             # grp(3)
  crypt cryptmodule.c # -lcrypt # crypt(3); needs -lcrypt on some systems
  select selectmodule.c # select(2); not on ancient System V
  socket socketmodule.c # socket(2); not on ancient System V
  errno errnomodule.c   # posix (UNIX) errno values

----- Lib/pwd.py -------------------------------------------------------
#! /usr/bin/env python

import _pwd

class Pwd:
    def __init__(self, tup):
        self.__l = tup
        self.name = tup[0]
        self.passwd = tup[1]
        self.uid = tup[2]
        self.gid = tup[3]
        self.gecos = tup[4]
        self.dir = tup[5]
        self.shell = tup[6]
    def __getitem__(self, i):
        return self.__l[i]
    def __getslice__(self, start, end):
        return self.__l[start:end]
    def __len__(self):
        return len(self.__l)

def getpwnam(name):
    return Pwd(_pwd.getpwnam(name))

def getpwuid(uid):
    return Pwd(_pwd.getpwuid(uid))

def getpwall():
    return map(Pwd, _pwd.getpwall())

----- Lib/grp.py -------------------------------------------------------
#! /usr/bin/env python

import _grp

class Grp:
    def __init__(self, tup):
        self.__l = tup
        self.name = tup[0]
        self.passwd = tup[1]
        self.gid = tup[2]
        self.mem = tup[3]
    def __getitem__(self, i):
        return self.__l[i]
    def __getslice__(self, start, end):
        return self.__l[start:end]
    def __len__(self):
        return len(self.__l)

def getgrnam(name):
    return Grp(_grp.getgrnam(name))

def getgrgid(gid):
    return Grp(_grp.getgrgid(gid))

def getgrall():
    return map(Grp, _grp.getgrall())

----- Lib/time.py ------------------------------------------------------
#! /usr/bin/env python

if 1:
    from _time import *
    import _time
else:
    # This is only for testing purposes
    import time
    _time = time
    from time import *

class Tm:
    def __init__(self, tup):
        self.__l = tup
        self.year = tup[0]
        self.mon = tup[1]
        self.mday = tup[2]
        self.hour = tup[3]
        self.min = tup[4]
        self.sec = tup[5]
        self.wday = tup[6]
        self.yday = tup[7]
        self.isdst = tup[8]
    def __getitem__(self, i):
        return self.__l[i]
    def __getslice__(self, start, end):
        return self.__l[start:end]
    def __len__(self):
        return len(self.__l)

def _tm_to_tuple(tm):
    try:
        tup = (tm.year, tm.mon, tm.mday, tm.hour, tm.min, tm.sec,
               tm.wday, tm.yday, tm.isdst)
    except AttributeError:
        if type(tm) != type((0,)):
            raise TypeError, "class Tm, "+type(tm).__name__
        if len(tm) != 9:
            raise TypeError, "class Tm, "+str(len(tm))+"-tuple"
        tup = tm
    return tup

def gmtime(secs):
    return Tm(_time.gmtime(secs))

def localtime(secs):
    return Tm(_time.localtime(secs))

def asctime(tm):
    return _time.asctime(_tm_to_tuple(tm))

def mktime(tm):
    return _time.mktime(_tm_to_tuple(tm))

def strftime(format, tm):
    return _time.strftime(format, _tm_to_tuple(tm))

----- Lib/posix.py -----------------------------------------------------
#! /usr/bin/env python

if 1:
    from _posix import *
    import _posix
else:
    # This is only for testing purposes
    import posix
    _posix = posix
    from posix import *

class Stat:
    def __init__(self, tup):
        self.__l = tup
        self.mode = tup[0]
        self.ino = tup[1]
        self.dev = tup[2]
        self.nlink = tup[3]
        self.uid = tup[4]
        self.gid = tup[5]
        self.size = tup[6]
        self.atime = tup[7]
        self.mtime = tup[8]
        self.ctime = tup[9]
    def __getitem__(self, i):
        return self.__l[i]
    def __getslice__(self, start, end):
        return self.__l[start:end]
    def __len__(self):
        return len(self.__l)

def stat(path):
    return Stat(_posix.stat(path))

def lstat(path):
    return Stat(_posix.lstat(path))

def fstat(fd):
    return Stat(_posix.fstat(path))

------------------------------------------------------------------------

--
Thomas Bellman,   Lysator Computer Club,   Link?ping University,  Sweden

 never interrupt the one who is doing it."    ! Make Love -- Nicht Wahr!



Sat, 01 Apr 2000 03:00:00 GMT  
 
 [ 1 post ] 

 Relevant Pages 

1. GMT time vs. local time

2. Is this a bug in Time.gm?

3. date,time,pwd in xlf fortran

4. date,time and pwd from rs6k FORTRAN

5. getting date, time, and pwd

6. Bug in time.c (was Time.times problems)

7. time and scheduling (was: bug report: [ #447945 ] time.time() is not non-decreasing)

8. time zones, daylight saving time, and universal time

9. How to get local system date/time?

10. Local/Module/Global data access at run time

11. Local Versus Standalone Run-time Library

12. Q: How to get local time in milliseconds?

 

 
Powered by phpBB® Forum Software