How to use readline interactively?

Carel Fellinger cfelling at iae.nl
Wed Oct 6 18:21:35 EDT 1999


Thomas A. Bryan <tbryan at python.net> 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
>> 
>> 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.

you could also reset the flag that controls this behaviour right after it
has been set by the print statement upon dealing with the trailing comma.

e.g. print "> ",
     sys.stdout.softspace = 0

or you could use a different input scheme with its buildin prompt support
and proper treatment of EOF as a bonus (raises an exception that is:) like:

     s = raw_input("> ")

and as an extra bonus this gets rid of that ugly "\n" thing for you too.


> 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.

an uncaught EofError would be more familiair to you then:)

-- 
groetjes, carel




More information about the Python-list mailing list