Initial Util Package
This commit is contained in:
0
util/__init__.py
Normal file
0
util/__init__.py
Normal file
32
util/io.py
Normal file
32
util/io.py
Normal 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
|
Reference in New Issue
Block a user