How to change the stdin and stdout encoding on Python 2

前端 未结 4 1193
無奈伤痛
無奈伤痛 2020-12-10 01:48

I\'m using Windows and Linux machines for the same project. The default encoding for stdin on Windows is cp1252, and on Linux it is utf-8.

I would like to change eve

4条回答
  •  温柔的废话
    2020-12-10 02:25

    This is an old question, but just for reference.

    To read UTF-8 from stdin, use:

    UTF8Reader = codecs.getreader('utf8')
    sys.stdin = UTF8Reader(sys.stdin)
    
    # Then, e.g.:
    for _ in sys.stdin:
        print _.strip()
    

    To write UTF-8 to stdout, use:

    UTF8Writer = codecs.getwriter('utf8')
    sys.stdout = UTF8Writer(sys.stdout)
    
    # Then, e.g.:
    print 'Anything'
    

提交回复
热议问题