我想写一个非 ASCII 字符,比如说→
到标准输出。棘手的部分似乎是我想要连接到该字符串的一些数据是从 json 读取的。考虑以下简单的 json 文档:
{"foo":"bar"}
我包含这个是因为如果我只想打印→
那么似乎只需写一下就足够了:
print("→")
它会在 python2 和 python3 中做正确的事情。
所以我想打印的值foo
和我的非 ASCII 字符一起→
。我发现在 python2 和 python3 中都可以使用的唯一方法是:
getattr(sys.stdout, 'buffer', sys.stdout).write(data["foo"].encode("utf8")+u"→".encode("utf8"))
or
getattr(sys.stdout, 'buffer', sys.stdout).write((data["foo"]+u"→").encode("utf8"))
重要的是不要错过u
在...前面→
因为否则的话UnicodeDecodeError
将被 python2 抛出。
使用print
像这样的函数:
print((data["foo"]+u"→").encode("utf8"), file=(getattr(sys.stdout, 'buffer', sys.stdout)))
似乎不起作用,因为 python3 会抱怨TypeError: 'str' does not support the buffer interface
.
我找到了最好的方法还是有更好的选择?我可以让打印功能起作用吗?