Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
which code works?
#1
don't cheat and try to run these. the question applies to Python version 2 or 2.7 or 2.7.whatever. which of these works right (for a useful definition of "right"?

catlines1.py:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
for line in sys.stdin:
    print('line =',repr(line))
    sys.stdout.flush()
catlines2.py:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
while True:
    line=sys.stdin.readline()
    print('line =',repr(line))
    sys.stdout.flush()
if you are going to try these, try piping in the ping command like ping -c 6 127.0.0.1|python2 catlines1.py or ping -c 6 127.0.0.1|python2 catlines2.py and see what happens. the -c 6 option for ping limits it to just 6 pings.
Skaaaaaperen........
Quote
#2
Without running them (but looking at the doc a little bit...) each one has positive and a negative point:

First one will wait until the stdin buffer is closed and then will report all the lines. I do not know if playing with the buffer sizes can solve this.

Second one will write each line as soon as a newline is in the buffer... but when the stdin is finished will continue writing "line = r''" until you hit Ctrl-C. This can be solved with:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
while True:
    line=sys.stdin.readline()
    if not line:
        break
    print('line =',repr(line))
    sys.stdout.flush()
As readline will return '' only if the stream is at end of file (and maybe if you use size=0, I have not tried it)

Do I get some extra points for this? Big Grin
Quote
#3
you do get plenty of points. but they are virtual. what if a line of input is an empty line for the 2nd one? what document says the first one will wait? what about using os.read for both of these? or limiting them to python3?
Skaaaaaperen........
Quote
#4
I look at the doc for readline, to check in which cases returns an empty string...
That the first part hangs until the stdin is closed I discovered some time ago, trying to understand why one script that in theory was monitoring the output of a really slow fortran program was not reporting anything through the zeromq socket.
I took me a week to stop having nightmares with the router/dealer schemas.
Quote
#5
looks like i will need to use os.read() or wait for python2.EoL.
Skaaaaaperen........
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Any interesting works in progress? mpd 5 492 Dec-15-2017, 09:34 PM
Last Post: wavic
  Can't understand how it works wavic 3 903 Dec-08-2017, 05:12 PM
Last Post: Larz60+

Forum Jump:


Users browsing this thread: 1 Guest(s)