Read STDIN as bytes rather than a string

Jason Friedman jason at powerpull.net
Mon Jun 18 19:49:37 EDT 2012


> sys.stdin wraps a buffered reader which itself wraps a raw file reader.
>
>>>> sys.stdin
> <_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>
>>>> sys.stdin.buffer
> <_io.BufferedReader name='<stdin>'>
>>>> sys.stdin.buffer.raw
> <_io.FileIO name='<stdin>' mode='rb'>
>
> You should read from sys.stdin.buffer unless you really need the bare
> metal.
>

Thank you, and just to close the loop:

$ cat ~/my-input.py
#!/opt/python/bin/python3
import sys
print(sys.stdin.buffer.read())

$ echo hello | ~/my-input.py
b'hello\n'



More information about the Python-list mailing list