scientific-programming-exer.../util/io.py

33 lines
708 B
Python

#!/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