How to make python 3 print() utf8

前端 未结 2 1916
名媛妹妹
名媛妹妹 2020-11-28 07:32

How can I make python 3 (3.1) print("Some text") to stdout in UTF-8, or how to output raw bytes?

Test.py



        
相关标签:
2条回答
  • 2020-11-28 07:46

    Clarification:

    TestText = "Test - āĀēĒčČ..šŠūŪžŽ" # this not UTF-8...it is a Unicode string in Python 3.X.
    TestText2 = TestText.encode('utf8') # this is a UTF-8-encoded byte string.
    

    To send UTF-8 to stdout regardless of the console's encoding, use the its buffer interface, which accepts bytes:

    import sys
    sys.stdout.buffer.write(TestText2)
    
    0 讨论(0)
  • This is the best I can dope out from the manual, and it's a bit of a dirty hack:

    utf8stdout = open(1, 'w', encoding='utf-8', closefd=False) # fd 1 is stdout
    print(whatever, file=utf8stdout)
    

    It seems like file objects should have a method to change their encoding, but AFAICT there isn't one.

    If you write to utf8stdout and then write to sys.stdout without calling utf8stdout.flush() first, or vice versa, bad things may happen.

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