python - Shell pipe working asynchronously -


i thought each processes pipe connected work asynchronously doesn't.

a.py

#!/usr/bin/env python import sys import time line in sys.stdin:     time.sleep(2)     sys.stdout.write(line.upper())     sys.stdout.flush() 

and b.py

#!/usr/bin/env python import sys line in sys.stdin:     sys.stdout.write(line.capitalize())     sys.stdout.flush() 

and test.txt

hello world python 

following code show each lines 1 one 2 seconds.

$ ./a.py < test.txt hello world python 

but following code show entirely 1 time.

$ ./a.py < test.txt | ./b.py hello world python 

it looks shell pipe working synchronously. how can asynchronously?

the problem code that, although expression...

for line in sys.stdin:     # ... 

...is treating sys.stdin iterator, doesn't seem yield values until sys.stdin hits eof, behavior of sys.stdin.readlines().

for first case, hits eof immediately, in second case, has wait a.py terminate, takes 6 seconds.

you'll have rewrite code b.py this...

#!/usr/bin/env python import sys while 1:     line = sys.stdin.readline()     if not line:         break     sys.stdout.write(line.capitalize())     sys.stdout.flush() 

...using readline() call return has whole line, rather waiting eof.

you should make similar change a.py in case want pipe input other text file.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -