Setting the correct encoding when piping stdout in Python

后端 未结 10 2429
迷失自我
迷失自我 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:05

    An arguable sanitized version of Craig McQueen's answer.

    import sys, codecs
    class EncodedOut:
        def __init__(self, enc):
            self.enc = enc
            self.stdout = sys.stdout
        def __enter__(self):
            if sys.stdout.encoding is None:
                w = codecs.getwriter(self.enc)
                sys.stdout = w(sys.stdout)
        def __exit__(self, exc_ty, exc_val, tb):
            sys.stdout = self.stdout
    

    Usage:

    with EncodedOut('utf-8'):
        print u'ÅÄÖåäö'
    

提交回复
热议问题