How to use readline interactively?

Thomas A. Bryan tbryan at python.net
Tue Oct 5 19:38:28 EDT 1999


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
> 
> What's wrong with it is that there is always a spare space 
> at the beginning of the first line of output after the prompt:
> 
> I want to get rid of that space before Hello.

You could use sys.stdout.write() in one or both places.

I've never run into this problem before, but if you use 

print "whatever", 
#followed by a bunch of python
print "second thing"

there will be a space between "whatever" and "second thing".
That is, it appears that a space is added to "second thing" 
before it is printed.  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
You're just getting confused because the user's input (and carriage
return)
separates the two print statements.

I'm not sure how it's implemented, but it appears that calling
sys.stdout.write() between calls to print will kill that space.

For example, 

import sys
print "Ready?"
print "eins",
print "zwei",
print "drei",
sys.stdout.write("interruption")
print "vier",
print "Done"

$ python test.py
Ready?
eins zwei dreiinterruptionvier Done
$

---Tom

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.




More information about the Python-list mailing list