Skip to main content

process_dirs

Process liveness and private-directory helpers for per-process cache directories.

A cache directory named after the process that made it (its pid and create time) can be judged orphaned once that process is gone. These helpers decide that, check a directory is private to this user before anything is stored in it, and remove a directory without following symlinks.

Module​

Functions​

directory_bytes​

def directory_bytes(directory: Path) ‑> int:

Return the total size of the regular files under directory.

Symlinks are not followed, and errors are ignored.

Arguments

  • directory: The directory to measure.

Returns The total size in bytes; 0 if directory cannot be read.

ensure_private_directory​

def ensure_private_directory(directory: Path) ‑> None:

Raise unless directory is a real directory private to this user.

Arguments

  • directory: The directory to check. A symlink is not followed.

Raises

  • NotADirectoryError: If directory is a symlink or not a directory.
  • PermissionError: On POSIX, if directory is not owned by this user or its mode is not 0700.
  • OSError: If directory cannot be inspected.

owner_is_gone​

def owner_is_gone(pid: int, created_ms: int) ‑> bool:

Return whether the process that made a directory has exited.

The process is the same one only if pid is alive with a create time within CREATE_TIME_TOLERANCE_MS of created_ms; a different create time means the pid was reused.

Arguments

  • pid: The pid recorded in the directory's name.
  • created_ms: The create time, in milliseconds, recorded in its name.

Returns True when no such process exists or the pid belongs to another process. False when the process is live, cannot be inspected (AccessDenied), or anything else goes wrong, so nothing is deleted on a guess.

process_create_ms​

def process_create_ms(pid: int | None = None) ‑> int:

Return a process's create time in milliseconds.

Arguments

  • pid: The process to ask about; None is this process.

Returns The create time, in whole milliseconds since the epoch.

Raises

  • psutil.Error: If the process cannot be inspected.

remove_directory​

def remove_directory(path: Path) ‑> None:

Remove path if it is a real directory, retrying briefly for Windows locks.

Anything else (a symlink, a file, nothing) is left alone. A directory that another process removes first is done; one it is still removing (a file vanishes mid-removal) is retried, so the directory does not stay half-removed. Never raises.

Arguments

  • path: The directory to remove.

root_is_insecure​

def root_is_insecure(root: Path) ‑> bool:

Return whether an existing root cannot be trusted to hold cache directories.

A symlink or a non-directory is never trusted. On POSIX a root owned by another user, or writable by its group or others, is not either. A root that does not exist is not insecure.

Arguments

  • root: The candidate root.

Returns True when root exists and is not private to this user.