13 lines
536 B
Python
13 lines
536 B
Python
import os
|
|
import stat
|
|
|
|
|
|
def read(path: str) -> str:
|
|
"""path's text, or "" for anything but a regular file: a FIFO would hang the hook and a device such as /dev/zero would flood it."""
|
|
try:
|
|
# O_NONBLOCK opens a FIFO without waiting for a writer; fstat then judges the file opened, not one swapped in after a stat.
|
|
with open(os.open(path, os.O_RDONLY | os.O_NONBLOCK), encoding="utf-8") as opened:
|
|
return opened.read() if stat.S_ISREG(os.fstat(opened.fileno()).st_mode) else ""
|
|
except (OSError, UnicodeDecodeError):
|
|
return ""
|