pseudo terminal usage from Python?

Grant Edwards invalid at invalid
Tue Dec 23 21:57:52 CET 2008


On 2008-12-23, skip at pobox.com <skip at pobox.com> wrote:
>     Grant> Are you sure it's not Python buffering its input?  Have you tried
>     Grant> "python -u mympstat.py"?
>
>     >> Nope.  -u unbuffers stdout and stderr, not stdin.  It really must be
>     >> mpstat being uncooperative.
>
>     Grant> That's not what my python man page says:
>
>     Grant>        -u     Force stdin, stdout and stderr to be totally
>     Grant>               unbuffered.  On systems where it matters, also put
>     Grant>               stdin, stdout and stderr in binary mode.
>
>     Grant> That's for 2.5.2, but that's how I remember previous versions
>     Grant> working as well.
>
> I'm still running 2.4.5 at work.  It's -u help:
>
>     -u     : unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x)
>              see man page for details on internal buffering relating to '-u'
>
> Was stdin unbuffering maybe added in 2.5?

Let's do some experiments...

  $ cat echo.py
  import sys

  while 1:
      line = sys.stdin.readline()
      sys.stdout.write(line)
    
  $ (while sleep 1; do date; done) | python2.4 echo.py

[I see a line printed once per second.]

  $ (while sleep 1; do date; done) | python2.5 echo.py

[same as 2.4]

Is python stdin is line-buffered by default?  We'll do a
version that doesn't have newlines in the input stream...

  $ cat echo2.py
  import sys

  while 1:
      sys.stdout.write(sys.stdin.read(1))


  $ (while sleep 1; do echo -n $(date); done) | python2.4 echo2.py

[wait 10-20 seconds -- no output.  When I hit ctrl-C, I see a
all the output.]

  $ (while sleep 1; do echo -n $(date); done) | python2.5 echo2.py

[same as 2.4]

It appears the by default both 2.4 and 2.5 have line-buffered
stdin.

Let's try -u...

  $ (while sleep 1; do echo -n $(date); done) | python2.4 -u echo2.py

[I see output once per second.]

  $ (while sleep 1; do echo -n $(date); done) | python2.5 -u echo2.py

[same as 2.4]

Under Linux, the '-u' option unbuffers stdin in both 2.4 and
2.5.  It just isn't mentioned in the help output or the man
page for 2.4.

-- 
Grant Edwards                   grante             Yow! Will the third world
                                  at               war keep "Bosom Buddies"
                               visi.com            off the air?



More information about the Python-list mailing list