Coverage for pyguymer3/stat.py: 7%
14 statements
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-08 18:47 +0000
« prev ^ index » next coverage.py v7.9.2, created at 2025-07-08 18:47 +0000
1#!/usr/bin/env python3
3# Define function ...
4def stat(
5 fname,
6 /,
7 *,
8 follow_symlinks = True,
9):
10 """
11 This function aims to mimic os.stat() but instead of returning a stat_result
12 object with attributes it returns a dictionary with keys (for more user-
13 friendly serialization to JSON). Influenced by an answer on StackOverflow
14 [1]_.
16 References
17 ----------
18 .. [1] Stackoverflow answer, https://stackoverflow.com/a/58684090
19 """
21 # Import standard modules ...
22 import grp
23 import os
24 import pwd
26 # Stat the file ...
27 info = os.stat(
28 fname,
29 follow_symlinks = follow_symlinks,
30 )
32 # Create a dictionary from the stat_result object ...
33 ans = {}
34 for key in dir(info):
35 if key.startswith("st_"):
36 ans[key] = getattr(info, key)
38 # Add helpful short-hands for user and group information ...
39 if "st_uid" in ans:
40 ans["user"] = pwd.getpwuid(ans["st_uid"]).pw_name
41 if "st_gid" in ans:
42 ans["group"] = grp.getgrgid(ans["st_gid"]).gr_name
44 # Return answer ...
45 return ans