为什么pythonidle和Console会产生不同的结果
我写了一个简单的Python脚本将中文标点翻译成英文为什么pythonidle和Console会产生不同的结果,python,Python,我写了一个简单的Python脚本将中文标点翻译成英文 import codecs, sys def trcn(): tr = lambda x: x.translate(str.maketrans(""",。!?;:、()【】『』「」﹁﹂“”‘’《》~¥…—×""", """,.!?;:,()[][][][]""''<>~$^-*""")) out = codecs.getwriter('utf-8')(sys.stdout) for line in sys
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)
在控制台中
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
>>>
Python 3.1.2(r312:79149,2010年3月21日,00:41:52)[MSC v.1500 32位(英特尔)]上的
win32
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>导入系统、编解码器
>>>out=codecs.getwriter('utf-8')(sys.stdout)
>>>出去。写(‘你好’)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
写入文件“C:\Python31\Lib\codecs.py”,第356行
self.stream.write(数据)
TypeError:必须是str,而不是bytes
>>>
平台:Windows XP EN您的编码输出将以字节形式从编码器中输出,因此必须将其传递到
sys.stdout.buffer
:
out = codecs.getwriter('utf-8')(sys.stdout.buffer)
我不完全清楚为什么您的代码在空闲和控制台中的行为不同,但上面的内容可能会有所帮助。也许IDLE的
sys.stdout
实际上需要字节而不是字符(希望它有一个.buffer
也需要字节)。很明显,控制台的编码不是utf-8。在控制台中调用python时,可以将编码指定为可选参数。只需在python文档中查找它。IDLE将标准输出重定向到它自己的GUI输出。它显然接受字节和字符串,而普通标准输出不接受
要么将其解码为Unicode,要么将其打印到sys.stdout.buffer。谢谢。我曾经假设编解码器的输出是unicode字符串,而不是字节。现在已经很清楚了。谢谢!这两天我都快发疯了。我在尝试“out=codecdes.getwriter('utf-8')(sys.stdout)”,它可以在Linux上工作,但在Windows上不行(甚至在cygwin中也不行)
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
>>>
out = codecs.getwriter('utf-8')(sys.stdout.buffer)