LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   convert while(<>) from perl to python (https://www.linuxquestions.org/questions/programming-9/convert-while-from-perl-to-python-434496/)

bardinjw 04-12-2006 10:41 AM

convert while(<>) from perl to python
 
i have a perl script that the basic structure of which is:

Code:

$| = 1;
while (<>); {
    print;
}

I'm trying to get the equivalent funtionality in python.

Code:

import sys
while sys.stdin:
    print sys.stdin.readline()

this works the same at the command line (except ctrl+d doesn't exit), but breaks when it's in a pipe. i'm not sure if it's the stdin or stdout that's the problem.

the script needs to get a single line off the pipeline in, process it, then pipe it back out.

ioerror 04-13-2006 06:41 AM

Code:

while sys.stdin:
This doesn't do what you probably think! sys.stdin is an open file object, so it is always "true" (unless you close it). Python won't automatically read from sys.stdin the way Perl does with (<>).

Try something like this:

Code:

for line in sys.stdin.readlines():
        # do whatever...
        print line

or maybe this

Code:

while 1:
        line = sys.stdin.readline().strip()
        if not line:
                break
        # do whatever ....
        print line


bardinjw 04-13-2006 08:21 AM

thanks ioerror

i've been doing a little more work on this
this is run as a child process, sits and waits for input on its stdin, and returns a string
Code:

read = stdin.readline
line = read()[:-1]

while line:
        if SOMETHING:
                sys.stdout.write('STRING')
                sys.stdout.flush()
        else:
                sys.stdout.write('ANOTHER STRING')
                sys.stdout.flush()
        line = read()[:-1]

It Works!
I needed to flush the output buffers, maybe this is equivalent to
"$| = 1"
in perl.

"while 1" works as well, but it won't exit gracefully when it needs to. "while line" exits in a SIGQUIT or eof.

please post any recomendations, or comments. i'm just trying to figure out the efficiencies and interactions of these little programs.


All times are GMT -5. The time now is 05:52 AM.