In one of my packages, I have a cli tool and I use a function to see if there is anything to read on stdin for piping video in to my cli tool.
def stdin_is_readable():
"""
stdin_is readable, detect data on stdin.
"""
readable, _, _ = select.select([sys.stdin], [], [], 0)
return sys.stdin in readable
This works great on Unix and Linux, but apparently fails on Windows.
File "...\threefive\cli.py", line 468, in threefivecli
chk_funk_map()
File "...\threefive\cli.py", line 419, in chk_funk_map
args = chk_stdin(args)
File "...\threefive\cli.py", line 170, in chk_stdin
if stdin_is_readable():
File "...\threefive\cli.py", line 150, in stdin_is_readable
readable, _, _ = select.select([sys.stdin], [], [], 0)
OSError: [WinError 10093] Either the application has not called WSAStartup, or WSAStartup failed
I was raised in a UNIX household, I know nothing about Windows. I am very hesitant to add Windows specific code to my work.
The fix that was suggested looks like this
import os, stat, sys
def stdin_is_readable():
if sys.platform != "win32":
readable, _, _ = select.select([sys.stdin], [], [], 0)
return sys.stdin in readable
try:
fd = sys.stdin.fileno()
except (AttributeError, OSError, ValueError):
return False
if os.isatty(fd):
return False
st = os.fstat(fd)
if stat.S_ISREG(st.st_mode):
return st.st_size > 0
import ctypes, msvcrt
from ctypes import wintypes
avail = wintypes.DWORD(0)
ok = ctypes.windll.kernel32.PeekNamedPipe(
wintypes.HANDLE(msvcrt.get_osfhandle(fd)), None, 0, None, ctypes.byref(avail), None)
return bool(ok) and avail.value > 0
I’m just look for some feedback on the solution.
Is the solution feasible and reasonable?