Setting the correct encoding when piping stdout in Python

后端 未结 10 2428
迷失自我
迷失自我 2020-11-22 01:21

When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:

# -*- co         


        
10条回答
  •  灰色年华
    2020-11-22 01:59

    First, regarding this solution:

    # -*- coding: utf-8 -*-
    print u"åäö".encode('utf-8')
    

    It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone.

    A better solution is to change sys.stdout at the start of your program, to encode with a selected encoding. Here is one solution I found on Python: How is sys.stdout.encoding chosen?, in particular a comment by "toka":

    import sys
    import codecs
    sys.stdout = codecs.getwriter('utf8')(sys.stdout)
    

提交回复
热议问题