Setting the correct encoding when piping stdout in Python

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

    I could "automate" it with a call to:

    def __fix_io_encoding(last_resort_default='UTF-8'):
      import sys
      if [x for x in (sys.stdin,sys.stdout,sys.stderr) if x.encoding is None] :
          import os
          defEnc = None
          if defEnc is None :
            try:
              import locale
              defEnc = locale.getpreferredencoding()
            except: pass
          if defEnc is None :
            try: defEnc = sys.getfilesystemencoding()
            except: pass
          if defEnc is None :
            try: defEnc = sys.stdin.encoding
            except: pass
          if defEnc is None :
            defEnc = last_resort_default
          os.environ['PYTHONIOENCODING'] = os.environ.get("PYTHONIOENCODING",defEnc)
          os.execvpe(sys.argv[0],sys.argv,os.environ)
    __fix_io_encoding() ; del __fix_io_encoding
    

    Yes, it's possible to get an infinite loop here if this "setenv" fails.

提交回复
热议问题