How to write a simple shell loop in python?
Saul Spatz
sspatz at kcnet.com
Wed Jan 21 00:12:00 EST 2009
Dietrich Bollmann wrote:
> Hi,
>
> I am trying to write a simple shell loop in Python.
>
> My simple approach works fine - but the first output line after entering
> something is always indented by one blank.
>
> Is there any logic explanation for this?
> How can I get rid of the blank?
> Is there a smarter way to write a simple shell loop which would work
> better?
>
> Thanks, Dietrich
>
>
> Here my approach:
>
> $ python
> Python 2.5.2 (r252:60911, Jan 4 2009, 17:40:26)
> [GCC 4.3.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import sys
>>>> while (1):
> ... print "$ ",
> ... input = sys.stdin.readline()
> ... input = input.strip()
> ... print input
> ... print input
> ... print input
> ...
> $ one
> one
> one
> one
> $ two
> two
> two
> two
> $ three
> three
> three
> three
> $
> Traceback (most recent call last):
> File "<stdin>", line 3, in <module>
> KeyboardInterrupt
>
>
Strange. I don't have an explanation, but experiment shows that if you
change print "$ ", to print "$ " (that is, leave out the comma) then the
leading blank is not printed. This behavior doesn't depend on the
"print input" statement's being in a loop.
By the way, you don't need parens around the loop guard in python:
while 1: (or as I prefer, while True:) work just fine.
Saul
More information about the Python-list
mailing list