Initial Util Package

This commit is contained in:
2018-10-24 16:53:41 +02:00
parent d14a16f94c
commit 567a95a2b2
4 changed files with 79 additions and 0 deletions

0
util/__init__.py Normal file
View File

32
util/io.py Normal file
View File

@@ -0,0 +1,32 @@
#!/usr/bin/python3
"""
Input/Output utilities.
"""
import sys
def readvalue(msg, type_, emsg=None, fin=sys.stdin, fout=sys.stdout):
"""
Basically uses ``input(msg)`` until it has been able to convert
the input to ``type_``. Prints the error message ``emsg``
if supplied, else the type error message.
Reads from ``fin`` and writes to ``fout``. They default to ``sys.stdin``
and ``sys.stdout``.
"""
x = None
while(x is None):
print(msg, file=fout, flush=True, end="")
x_raw = fin.readline()
try:
# Remove the trailing \n.
x = type_(x_raw[:-1])
except ValueError as e:
if(emsg):
print(emsg, file=fout, flush=True)
else:
print(str(e), file=fout, flush=True)
return x