How to use readline interactively?
John Farrell
jfarrell at mincom.com
Wed Oct 6 00:03:11 EDT 1999
"Thomas A. Bryan" wrote:
> John Farrell wrote:
> > import sys
> > while 1:
> > print "> ",
> > s = sys.stdin.readline()
> > if s[-1] == '\n': s = s[:-1]
> > if len(s) == 0: break
> > print "Hello " + s
> You could use sys.stdout.write() in one or both places.
>
> What you're seeing is the comma from the line
> print "> ",
> It is output as a space at the front of your
> print "Hello" + s
Of course, that makes sense. Thank you for explaining it.
> P.S. I'm sure you're just posting a code fragement, but I
> used EOF to get out of the while loop (like any good Python
> programmer :), and the code snippet died with an uncaught
> IndexError exception.
That's a habit I never got into, but I do remember spending hours
trying to handle EOF in C or maybe Pascal when I was at Uni. I guess
that's why I never got into the habit, because it broke my programs :-).
I find it mildly distressing that the user can arbitrarily tell the
program that it's not getting any more input, it would be kinder to
just hit Ctrl-Break and put the poor thing out of its misery.
The revised code snippet is:
import sys
while 1:
sys.stdout.write("> ")
s = sys.stdin.readline()
if len(s) > 0 and s[-1] == '\n': s = s[:-1]
if len(s) == 0: break
sys.stdout.write("Hello " + s + '\n')
which works just like I want it to, and will even handle EOF. I seem
to remember already doing this in my proper app.
John
More information about the Python-list
mailing list