[Tutor] First script
John Precedo
johnp@reportlab.com
Tue, 16 Jan 2001 20:16:29 -0000
Robert L Hinks sent in the following script and asked
> How would you change it and why?
OK, before I go any further, I'd better say that I'm pretty
much a Python beginner myself...
but since I have written more than one script, I thought I'd
try and "improve" this one :o)
[remarks/header trimmed out for brevity]
>
> 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!"
>
> answer = " "
>
> query = raw_input("Do you want to restart the INETD
daemon? (yes/no): ")
>
> answer = query
>
> if len(answer) > 2:
> print r
> elif len(answer) < 2:
> print w
> else:
> print n
You've been quite clever using 'len(answer)' as a decider
for what you want to do. But what happens if the user
(mis)types 'ye'? Or types 'noo'? Sticky keys can be a real
pain!
My version uses a while loop, so instead of just telling
them to try again, you give them a chance to try again. (It
saves them typing in the filename again :o)
Oh, and I didn't see the logic in using 'query' as a
temporary variable - why not just put the reply straight
into answer?
Well, this I'd how I'd implement it:
[ - - - - - - - - START OF SNIPPET - - - - - - - - ]
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
[ - - - - - - - - END OF SNIPPET - - - - - - - - ]
Strictly speaking, pre-defining answer like that isn't
necessary - or at least my test program works OK without it.
But I'd rather have it in there and be safe :o)
Anyway, I hope some of this helped.
--
John Precedo (johnp@reportlab.com)
Junior Developer, Reportlab, Inc