Python wait until data is in sys.stdin

后端 未结 9 1298
隐瞒了意图╮
隐瞒了意图╮ 2020-12-15 23:00

my problem is the following:

My pythons script receives data via sys.stdin, but it needs to wait until new data is available on sys.stdin.

As described in th

9条回答
  •  盖世英雄少女心
    2020-12-15 23:29

    The following should just work.

    import sys
    for line in sys.stdin:
        # whatever
    

    Rationale:

    The code will iterate over lines in stdin as they come in. If the stream is still open, but there isn't a complete line then the loop will hang until either a newline character is encountered (and the whole line returned) or the stream is closed (and the whatever is left in the buffer is returned).

    Once the stream has been closed, no more data can be written to or read from stdin. Period.

    The reason that your code was overloading your cpu is that once the stdin has been closed any subsequent attempts to iterate over stdin will return immediately without doing anything. In essence your code was equivalent to the following.

    for line in sys.stdin:
        # do something
    
    while 1:
        pass # infinite loop, very CPU intensive
    

    Maybe it would be useful if you posted how you were writing data to stdin.

    EDIT:

    Python will (for the purposes of for loops, iterators and readlines() consider a stream closed when it encounters an EOF character. You can ask python to read more data after this, but you cannot use any of the previous methods. The python man page recommends using

    import sys
    while True:
        line = sys.stdin.readline()
        # do something with line
    

    When an EOF character is encountered readline will return an empty string. The next call to readline will function as normal if the stream is still open. You can test this out yourself by running the command in a terminal. Pressing ctrl+D will cause a terminal to write the EOF character to stdin. This will cause the first program in this post to terminate, but the last program will continue to read data until the stream is actually closed. The last program should not 100% your CPU as readline will wait until there is data to return rather than returning an empty string.

    I only have the problem of a busy loop when I try readline from an actual file. But when reading from stdin, readline happily blocks.

提交回复
热议问题