Setting the correct encoding when piping stdout in Python

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

    You may want to try changing the environment variable "PYTHONIOENCODING" to "utf_8". I have written a page on my ordeal with this problem.

    Tl;dr of the blog post:

    import sys, locale, os
    print(sys.stdout.encoding)
    print(sys.stdout.isatty())
    print(locale.getpreferredencoding())
    print(sys.getfilesystemencoding())
    print(os.environ["PYTHONIOENCODING"])
    print(chr(246), chr(9786), chr(9787))
    

    gives you

    utf_8
    False
    ANSI_X3.4-1968
    ascii
    utf_8
    ö ☺ ☻
    

提交回复
热议问题