[Tutor] First script
Bruce Sass
Bruce Sass <bsass@freenet.edmonton.ab.ca>
Tue, 16 Jan 2001 16:10:12 -0700 (MST)
Hi,
On Tue, 16 Jan 2001, John Precedo wrote:
> Robert L Hinks sent in the following script and asked
> > How would you change it and why?
>
> r = "kill -HUP `ps cax|grep inetd|awk '{print $1}'`" #
> restarts the daemon
> n = "Inetd not restarted"
> w = "Answer needs to be 'yes' or 'no'. Try again!"
>
> yesAnswers = ["yes", "YES", "Y", "y"]
> noAnswers = ["no", "NO", "N", "n"]
> validAnswers = yesAnswers + noAnswers
> answer = ""
>
> answer = raw_input("Do you want to restart the INETD daemon?
> (yes/no): ")
>
> while answer not in validAnswers:
> print w; print
> answer = raw_input("Do you want to restart the INETD
> daemon? (yes/no): ")
>
> if answer in yesAnswers:
> print r
> else:
> print n
I'd want to do this (starting with John's code):
---8<---
import string
def getYNanswer(ystring, nstring, qprompt=""):
"""Get "yes" or "no" interactively.
Returns lowercase answer or ""
"""
yesAnswers = ["yes", "y"]
noAnswers = ["no", "n"]
exitAnswers = ["q", "quit", "e", "exit", "x"]
helpAnswers = ["h", "help", "?"]
validAnswers = yesAnswers + noAnswers + exitAnswers + helpAnswers
answer = ""
while 1:
if answer in yesAnswers:
print ystring
break
elif answer in noAnswers:
print nstring
break
elif answer in exitAnswers:
break
elif answer in helpAnswers:
print "Possible responses are:"
print validAnswers
print "(case is insignificant)."
answer = ""
else:
answer = string.lower(raw_input(qprompt + " (h for help): "))
return answer
r = "kill -HUP `ps cax|grep inetd|awk '{print $1}'`" # restarts the daemon
n = "Inetd not restarted"
prompt = "Do you want to restart the INETD daemon?"
answer = getYNanswer(r, n, prompt)
print "The answer was", answer
--->8--- tested with 1.5.2 and 2.0 ---
or maybe even... class YNAnswer, used like:
inetd = YNAnswer(y_reply, n_reply, prompt)
# ...
if inetd.answer == None:
pass # answer in exitAnswers
elif inetd:
pass # answer in yesAnswers
else
pass # answer in noAnswers
Have fun,
Bruce