I\'m trying to do some of the code golf challenges, but they all require the input to be taken from stdin
. How do I get that in Python?
Read from sys.stdin
, but to read binary data on Windows, you need to be extra careful, because sys.stdin
there is opened in text mode and it will corrupt \r\n
replacing them with \n
.
The solution is to set mode to binary if Windows + Python 2 is detected, and on Python 3 use sys.stdin.buffer
.
import sys
PY3K = sys.version_info >= (3, 0)
if PY3K:
source = sys.stdin.buffer
else:
# Python 2 on Windows opens sys.stdin in text mode, and
# binary data that read from it becomes corrupted on \r\n
if sys.platform == "win32":
# set sys.stdin to binary mode
import os, msvcrt
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
source = sys.stdin
b = source.read()