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

后端 未结 5 1795
春和景丽
春和景丽 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:58

    while sys.stdin is a file-like object, meaning you can iterate over its lines, it will block until a EOF is inserted.

    The behaviour can be described with the following pseudo-code:

    while True:
        input = ""
        c = stdin.read(1)
        while c is not EOF:
            input += c
            c = stdin.read(1)
        for line in input.split('\n'):
            yield line
    

    this means that, while you can iterate over sys.stdin's lines, you cannot use this approach for the task at hand and you must explicitly call read() or readline()

提交回复
热议问题