Python Forum
which code works? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: which code works? (/thread-10910.html)



which code works? - Skaperen - Jun-13-2018

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 [font=Courier New, Courier, monospace]ping -c 6 127.0.0.1|python2 catlines1.py[/font] 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.


RE: which code works? - killerrex - Jun-13-2018

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


RE: which code works? - Skaperen - Jun-14-2018

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?


RE: which code works? - killerrex - Jun-14-2018

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.


RE: which code works? - Skaperen - Jun-15-2018

looks like i will need to use os.read() or wait for python2.EoL.