1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
""" This module provides ctypes version of cpython's grp module
"""
from _pwdgrp_cffi import ffi, lib
import _structseq
try: from __pypy__ import builtinify
except ImportError: builtinify = lambda f: f
class struct_group:
__metaclass__ = _structseq.structseqtype
name = "grp.struct_group"
gr_name = _structseq.structseqfield(0)
gr_passwd = _structseq.structseqfield(1)
gr_gid = _structseq.structseqfield(2)
gr_mem = _structseq.structseqfield(3)
def _group_from_gstruct(res):
i = 0
members = []
while res.gr_mem[i]:
members.append(ffi.string(res.gr_mem[i]))
i += 1
return struct_group([
ffi.string(res.gr_name),
ffi.string(res.gr_passwd),
res.gr_gid,
members])
@builtinify
def getgrgid(gid):
res = lib.getgrgid(gid)
if not res:
# XXX maybe check error eventually
raise KeyError(gid)
return _group_from_gstruct(res)
@builtinify
def getgrnam(name):
if not isinstance(name, basestring):
raise TypeError("expected string")
name = str(name)
res = lib.getgrnam(name)
if not res:
raise KeyError("'getgrnam(): name not found: %s'" % name)
return _group_from_gstruct(res)
@builtinify
def getgrall():
lib.setgrent()
lst = []
while 1:
p = lib.getgrent()
if not p:
break
lst.append(_group_from_gstruct(p))
lib.endgrent()
return lst
__all__ = ('struct_group', 'getgrgid', 'getgrnam', 'getgrall')
if __name__ == "__main__":
from os import getgid
gid = getgid()
pw = getgrgid(gid)
print("gid %s: %s" % (pw.gr_gid, pw))
name = pw.gr_name
print("name %r: %s" % (name, getgrnam(name)))
print("All:")
for pw in getgrall():
print(pw)
|