How do you read from stdin?

后端 未结 22 2597
余生分开走
余生分开走 2020-11-21 06:46

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?

22条回答
  •  灰色年华
    2020-11-21 07:34

    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()
    

提交回复
热议问题