[Tutor] Input
Ricardo Aráoz
ricaraoz at gmail.com
Tue Jan 15 23:30:45 CET 2008
Last week someone had an issue with raw_input() and how to get input for
a number. So I remembered my CP/M times and got to think of a little
function I had there. The function is lost and my time is scarce but I
made a little effort and here you have the results. It has loads of room
for improvement and probably a few bugs but it's a starting point, and
it should guarantee that you get the input you need.
You just define your mask and the functions checks the input
accordingly, it returns a string.
You might improve it by displaying the mask, e.g. for mask = '9999.99'
you might see in the screen ____.__ or for mask = '999-AAA::9999' you'd
see ___-___::___ so the user will know the format of what's expected of
him, also a beep on incorrect entry might prove nice.
HTH
-----------------------------------------------------------------------
import msvcrt
_validChars = {
'X' :
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
, '9' : '1234567890'
, '-' : '-1234567890'
, 'A' :
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
, '!' : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'}
_validKeys = _validChars.keys()
def maskInput(mask, separators = True) :
lmask = list(mask)
lmask.reverse()
usedMask = []
retInput = ''
c = ''
maskChar = lmask.pop()
try :
while maskChar not in _validKeys :
if separators :
retInput += maskChar
msvcrt.putch(maskChar)
maskChar = lmask.pop()
except IndexError : pass
c = msvcrt.getch()
while c != chr(13) :
if maskChar and maskChar not in _validKeys and c in
_validChars[lmask[-1]] :
if separators :
retInput += maskChar
msvcrt.putch(maskChar)
usedMask.append(maskChar)
maskChar = lmask.pop()
if usedMask and c == '\b' :
try :
if maskChar :
lmask.append(maskChar)
maskChar = usedMask.pop()
retInput = retInput[:-1]
msvcrt.putch(c)
msvcrt.putch(' ')
msvcrt.putch(c)
while usedMask[-1] not in _validKeys :
if maskChar :
lmask.append(maskChar)
maskChar = usedMask.pop()
if separators :
retInput = retInput[:-1]
msvcrt.putch(c)
msvcrt.putch(' ')
msvcrt.putch(c)
except IndexError : pass
elif maskChar and c in _validChars[maskChar] :
retInput += c
msvcrt.putch(c)
try :
usedMask.append(maskChar)
maskChar = lmask.pop()
# while maskChar not in _validKeys :
except IndexError :
maskChar = ''
c = msvcrt.getch()
return retInput
if __name__ == '__main__' :
invar = maskInput('-9999.99')
print
print invar
------------------------------------------------------------------------
More information about the Tutor
mailing list