Python, Unicode, and the Windows console

前端 未结 13 2110
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 04:38

When I try to print a Unicode string in a Windows console, I get a UnicodeEncodeError: \'charmap\' codec can\'t encode character .... error. I assume this is b

13条回答
  •  温柔的废话
    2020-11-21 05:11

    Like Giampaolo Rodolà's answer, but even more dirty: I really, really intend to spend a long time (soon) understanding the whole subject of encodings and how they apply to Windoze consoles,

    For the moment I just wanted sthg which would mean my program would NOT CRASH, and which I understood ... and also which didn't involve importing too many exotic modules (in particular I'm using Jython, so half the time a Python module turns out not in fact to be available).

    def pr(s):
        try:
            print(s)
        except UnicodeEncodeError:
            for c in s:
                try:
                    print( c, end='')
                except UnicodeEncodeError:
                    print( '?', end='')
    

    NB "pr" is shorter to type than "print" (and quite a bit shorter to type than "safeprint")...!

提交回复
热议问题