76

What's a good way to find the uid/gid for a given username or groupname using Python? I need to set file ownership with os.chown and need the integer ids instead of the alphabetic.

[Quick note]: getpwnam works great but is not available on windows, so here's some code that creates stubs to allow you to run the same code on windows and unix.

try:
    from pwd import getpwnam
except:
    getpwnam = lambda x: (0,0,0)
    os.chown = lambda x, y, z: True
    os.chmod = lambda x, y: True
    os.fchown = os.chown
    os.fchmod = os.chmod
Parand
  • 102,950
  • 48
  • 151
  • 186
  • possible duplicate of [Python script to list users and groups](http://stackoverflow.com/questions/421618/python-script-to-list-users-and-groups) – chown Oct 14 '11 at 15:59

1 Answers1

114

Use the pwd and grp modules:

from pwd import getpwnam  

print getpwnam('someuser')[2]
# or
print getpwnam('someuser').pw_uid
print grp.getgrnam('somegroup')[2]
gerardw
  • 5,822
  • 46
  • 39
dfa
  • 114,442
  • 31
  • 189
  • 228