Avoiding a SyntaxError when giving no input
Skip Montanaro
skip at pobox.com
Wed Jan 16 09:19:44 EST 2002
Heiko> I got a python script here that takes strings with the input() -
Heiko> function. Now, if I dont enter anything, and just press enter,
Heiko> python exits with a SyntaxError. How can I force python to just
Heiko> ask again for a value? I tried it with exception handling, but
Heiko> that doesnt seem to work with SyntaxError.
You may not want to call input() directly. It is, in effect:
def input(prompt):
return eval(raw_input(prompt))
Instead, you might want to use raw_input and check responses before calling
eval:
while 1:
ans = raw_input(prompt)
if not validate_input(ans):
print "invalid input:", repr(ans)
else:
result = eval(ans)
break
The validate_input function would catch empty strings, dangerous stuff,
etc. You might want to call eval() with explicit globals and locals args as
well to minimize potential for damaging input.
--
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)
More information about the Python-list
mailing list