On this page
  1. pwd
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Resolving a File Owner's Username from os.stat()
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

pwd

Prev: pty | Up: stdlib_module | Next: py_compile
Rel: os, io, time, argparse, getopt
Ref: docs.python.org — pwd
Tags: #public #python3 #stdlib


Import

import pwd

Overview

Unix-only interface to the POSIX user account database via getpwuid(), getpwnam(), and getpwall(). Use pwd on macOS/Linux to resolve numeric UIDs from os.stat().st_uid into usernames, home directories, or login shells.

Quick Start

import os
import sys

if sys.platform != "win32":
    import pwd

    entry = pwd.getpwuid(os.getuid())
    assert entry.pw_uid == os.getuid()
    assert isinstance(entry.pw_name, str) and isinstance(entry.pw_dir, str)

Implementation Walkthrough

1. Resolving a File Owner's Username from os.stat()

Pair pwd.getpwuid() with stat / pathlib to display human-readable file ownership:

import os
import pwd

def file_owner(path: str) -> str:
    uid = os.stat(path).st_uid
    try:
        return pwd.getpwuid(uid).pw_name
    except KeyError:
        return str(uid)

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes