python 3.0, how to make print() output unicode?

前端 未结 5 1658
猫巷女王i
猫巷女王i 2020-11-28 15:49

I\'m working in WinXP 5.1.2600, writing a Python application involving Chinese pinyin, which has involved me in endless Unicode problems. Switching to Python 3.0 has solved

相关标签:
5条回答
  • 2020-11-28 16:09

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

    0 讨论(0)
  • 2020-11-28 16:10

    Here's a dirty hack:

    # works
    import os
    os.system("chcp 65001 &")
    print("юникод")
    

    However everything breaks it:

    • simple muting first line already breaks it:

      # doesn't work
      import os
      os.system("chcp 65001 >nul &")
      print("юникод")
      
    • checking for OS type breaks it:

      # doesn't work
      import os
      if os.name == "nt":
          os.system("chcp 65001 &")
      
      print("юникод")
      
    • it doesn't even works under if block:

      # doesn't work
      import os
      if os.name == "nt":
          os.system("chcp 65001 &")
          print("юникод")
      

    But one can print with cmd's echo:

    # works
    import os
    os.system("chcp 65001 & echo {0}".format("юникод"))
    

    and here's a simple way to make this cross-platform:

    # works
    
    import os
    
    def simple_cross_platrofm_print(obj):
        if os.name == "nt":
            os.system("chcp 65001 >nul & echo {0}".format(obj))
        else:
            print(obj)
    
    simple_cross_platrofm_print("юникод")
    

    but the window's echo trailing empty line can't be suppressed.

    0 讨论(0)
  • 2020-11-28 16:28

    Check out the question and answer here, I think they have some valuable clues. Specifically, note the setdefaultencoding in the sys module, but also the fact that you probably shouldn't use it.

    0 讨论(0)
  • 2020-11-28 16:30

    The Windows command prompt (cmd.exe) cannot display the Unicode characters you are using, even though Python is handling it in a correct manner internally. You need to use IDLE, Cygwin, or another program that can display Unicode correctly.

    See this thread for a full explanation: http://www.nabble.com/unable-to-print-Unicode-characters-in-Python-3-td21670662.html

    0 讨论(0)
  • 2020-11-28 16:33

    The problem of displaying Unicode charaters in Python in Windows is known. There is no official solution yet. The right thing to do is to use winapi function WriteConsoleW. It is nontrivial to build a working solution as there are other related issues. However, I have developed a package which tries to fix Python regarding this issue. See https://github.com/Drekin/win-unicode-console. You can also read there a deeper explanation of the problem. The package is also on pypi (https://pypi.python.org/pypi/win_unicode_console) and can be installed using pip.

    0 讨论(0)
提交回复
热议问题