handle wrong stdin streams

This commit is contained in:
scito
2022-12-24 04:19:43 +01:00
parent bc329e24d5
commit c2d7c905ff
2 changed files with 58 additions and 2 deletions

View File

@@ -140,12 +140,15 @@ def extract_otps(args):
def get_lines_from_file(filename):
lines = read_lines_from_text_file(filename)
if lines != None:
if are_bytes(lines):
abort('\nBinary input was given in stdin, please use = instead of -.')
elif lines:
return lines
# could not process text file, try reading as image
return convert_img_to_line(filename)
def read_lines_from_text_file(filename):
if filename != '=':
check_file_exists(filename)
@@ -169,6 +172,7 @@ def read_lines_from_text_file(filename):
finally:
finput.close()
def convert_img_to_line(filename):
if filename != '-':
try:
@@ -180,7 +184,10 @@ def convert_img_to_line(filename):
except AttributeError:
# Workaround for pytest, since pytest cannot monkeypatch sys.stdin.buffer
stdin = sys.stdin.read()
array = frombuffer(stdin, dtype='uint8')
try:
array = frombuffer(stdin, dtype='uint8')
except TypeError as e:
abort('\nERROR: Cannot read binary stdin buffer. Exception: {}'.format(str(e)))
image = imdecode(array, IMREAD_UNCHANGED)
if image is None:
@@ -384,6 +391,16 @@ def check_file_exists(filename):
abort('\nERROR: Input file provided is non-existent or not a file.'
'\ninput file: {}'.format(filename))
def are_bytes(lines):
if lines and len(lines) > 0:
try:
lines[0].startswith('#')
return False
except (UnicodeDecodeError, AttributeError, TypeError):
return True
def eprint(*args, **kwargs):
'''Print to stderr.'''
print(*args, file=sys.stderr, **kwargs)