Why python IDLE and console produce different results

I am writing a simple Python script to translate Chinese punctuation into English.

import codecs, sys

def trcn():
    tr = lambda x: x.translate(str.maketrans(""",。!?;:、()【】『』「」﹁﹂""‘’《》~¥…—×""", """,.!?;:,()[][][][]""''<>~$^-*"""))
    out = codecs.getwriter('utf-8')(sys.stdout)
    for line in sys.stdin:
        out.write(tr(line))

if __name__ == '__main__':
    if not len(sys.argv) == 1:
        print("usage:\n\t{0} STDIN STDOUT".format(sys.argv[0]))
        sys.exit(-1)
    trcn()
    sys.exit(0)

But something is wrong with UNICODE . I can’t convey it. Msg error:

Traceback (most recent call last):
  File "trcn.py", line 13, in <module>
    trcn()
  File "trcn.py", line 7, in trcn
    out.write(tr(line))
  File "C:\Python31\Lib\codecs.py", line 356, in write
    self.stream.write(data)
TypeError: must be str, not bytes

After that, I test out.write () in IDLE and Console. They gave different results. I do not know why.

In IDLE

Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import sys,codecs
>>> out = codecs.getwriter('utf-8')(sys.stdout)
>>> out.write('hello')
hello
>>>

In console

Python 3.1.2 (r312:79149, Mar 21 2010, 00:41:52) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys,codecs
>>> out = codecs.getwriter('utf-8')(sys.stdout)
>>> out.write('hello')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python31\Lib\codecs.py", line 356, in write
    self.stream.write(data)
TypeError: must be str, not bytes
>>>

Platform: Windows XP EN

+3
source share
3 answers

Your encoded output exits the encoder in bytes and therefore should be passed to sys.stdout.buffer:

out = codecs.getwriter('utf-8')(sys.stdout.buffer)

, - IDLE , . , IDLE sys.stdout (, .buffer, ).

+6

IDLE stdout . , -, , , stdout .

Unicode, sys.stdout.buffer.

+1

, utf-8. python . python.

-1

Source: https://habr.com/ru/post/1782877/


All Articles