当管道来自"打开"(不知道正确的名称)文件时,我有问题从python中的标准输入或管道读取.
我有例如 pipetest.py:
import sys
import time
k = 0
try:
for line in sys.stdin:
k = k + 1
print line
except KeyboardInterrupt:
sys.stdout.flush()
pass
print k
Run Code Online (Sandbox Code Playgroud)
我运行了一段时间后继续输出和Ctrl + c的程序
$ ping 127.0.0.1 | python pipetest.py
^C0
Run Code Online (Sandbox Code Playgroud)
我没有输出.但如果我通过一个普通的文件,它的工作原理.
$ ping 127.0.0.1 > testfile.txt
Run Code Online (Sandbox Code Playgroud)
一段时间后,这将以Ctrl + c结束
$ cat testfile.txt | python pipetest.py
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.017 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.015 ms
64 bytes from 127.0.0.1: …Run Code Online (Sandbox Code Playgroud)