我以为每个进程管道连接的工作是异步的,但事实并非如此。Shell管道异步工作
a.py
#!/usr/bin/env python
import sys
import time
for line in sys.stdin:
time.sleep(2)
sys.stdout.write(line.upper())
sys.stdout.flush()
和b.py
#!/usr/bin/env python
import sys
for line in sys.stdin:
sys.stdout.write(line.capitalize())
sys.stdout.flush()
和test.txt的
hello
world
python
以下代码显示每行一个一个由2秒。
$ ./a.py < test.txt
HELLO
WORLD
PYTHON
但下面的代码完全显示了一次。
$ ./a.py < test.txt | ./b.py
Hello
World
Python
看起来管壳是同步工作的。我怎样才能异步?
感谢您的回答。我在http://stackoverflow.com/a/7608205/395425中找到了类似的线程。在python2.7中,“for”语句正在等待EOF,但python3.3不会等待。 –
我后来发现,python 2.x“for sys.stdin中的行”不会等到EOF。它似乎在缓冲。 –