python 3: reading bytes from stdin pipe with readahead

前端 未结 3 1792
长情又很酷
长情又很酷 2021-01-11 18:08

i want to read bytes. sys.stdin is opened in textmode, yet it has a buffer that can be used to read bytes: sys.stdin.buffer.

my problem is

3条回答
  •  日久生厌
    2021-01-11 18:45

    Try this:

    import sys
    
    ssb = sys.stdin.buffer.read(1)
    if ssb == b'h':
        print(ssb+sys.stdin.buffer.read())
    

    Echo a string:

    a@fuhq:~$ echo 'hi' | python3 buf_test.py 
    b'hi\n'
    

    Redirect a file:

    a@fuhq:~$ cat hi.text
    hi
    a@fuhq:~$ python3 buf_test.py   <  hi.text
    b'hi\n'
    

提交回复
热议问题