How do you read from stdin in python from a pipe which has no ending

后端 未结 5 1812
春和景丽
春和景丽 2020-12-02 23:35

I\'ve problem to read from Standard input or pipe in python when the pipe is from a \"open\" (do not know right name) file.

I have as example pipetest.py:

5条回答
  •  余生分开走
    2020-12-02 23:39

    For this to work without waiting until the stdin stream ends, you can iter on the readline. I think this is the simplest solution.

    import sys
    k = 0
    try:
       for line in iter(sys.stdin.readline, b''):
          k = k + 1
          print line
    except KeyboardInterrupt:
       sys.stdout.flush()
       pass
    print k
    

提交回复
热议问题