Setting the correct encoding when piping stdout in Python

后端 未结 10 2595
迷失自我
迷失自我 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 02:06

    I ran into this problem in a legacy application, and it was difficult to identify where what was printed. I helped myself with this hack:

    # encoding_utf8.py
    import codecs
    import builtins
    
    
    def print_utf8(text, **kwargs):
        print(str(text).encode('utf-8'), **kwargs)
    
    
    def print_utf8(fn):
        def print_fn(*args, **kwargs):
            return fn(str(*args).encode('utf-8'), **kwargs)
        return print_fn
    
    
    builtins.print = print_utf8(print)
    

    On top of my script, test.py:

    import encoding_utf8
    string = 'Axwell Λ Ingrosso'
    print(string)
    

    Note that this changes ALL calls to print to use an encoding, so your console will print this:

    $ python test.py
    b'Axwell \xce\x9b Ingrosso'
    

提交回复
热议问题