How to change the stdin and stdout encoding on Python 2

前端 未结 4 1191
無奈伤痛
無奈伤痛 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:21

    A simple code snippet I used, which works for me on ubuntu: python2.7 and python3.6

    from sys import version_info
    if version_info.major == 2:  # for python2
        import codecs
        # for stdin
        UTF8Reader = codecs.getreader('utf8')
        sys.stdin = UTF8Reader(sys.stdin)
        # for stdout
        UTF8Writer = codecs.getwriter('utf8')
        sys.stdout = UTF8Writer(sys.stdout)
    elif version_info.major == 3:  # for python3
        import codecs
        # for stdin
        UTF8Reader = codecs.getreader('utf8')
        sys.stdin = UTF8Reader(sys.stdin.buffer)
        # for stdout
        UTF8Writer = codecs.getwriter('utf8')
        sys.stdout = UTF8Writer(sys.stdout.buffer)
    

提交回复
热议问题