无法对pprint输出进行编码/解码 [英] Unable to encode/decode pprint output

查看:154
本文介绍了无法对pprint输出进行编码/解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是基于那个的副作用。

This question is based on a side-effect of that one.

我的 .py 文件都有# - * - 编码:utf-8 - * - 编码定义在第一行,像我的 api.py

My .py files are all have # -*- coding: utf-8 -*- encoding definer on the first line, like my api.py

正如我提到的相关问题,我使用 HttpResponse 返回api文档。由于我通过以下方式定义编码:

As I mention on the related question, I use HttpResponse to return the api documentation. Since I defined encoding by:

HttpResponse(cy_content, content_type='text/plain; charset=utf-8')

一切都OK,当我打电话给我的API服务时,除了字符串之外,没有编码问题由pprint编写的字典

Everything is ok, and when I call my API service, there are no encoding problems except the string formed from a dictionary by pprint

由于我在我的dict中使用了一些值中的土耳其字符,所以pprint将它们转换为 unichr 等价物,如:

Since I am using Turkish characters in some values in my dict, pprint converts them to unichr equivalents, like:

API_STATUS = {
    1: 'müşteri',
    2: 'some other status message'
}

my_str = 'Here is the documentation part that contains Turkish chars like işüğçö'
my_str += pprint.pformat(API_STATUS, indent=4, width=1)
return HttpRespopnse(my_str, content_type='text/plain; charset=utf-8')

我的纯文本输出如下:

Here is the documentation part that contains Turkish chars like işüğçö

{
    1: 'm\xc3\xbc\xc5\x9fteri',
    2: 'some other status message'
}

我尝试将pprint输出解码或编码为不同的编码,没有成功...克服这个问题的最佳做法是什么

I try to decode or encode pprint output to different encodings, with no success... What is the best practice to overcome this problem

推荐答案

pprint 似乎使用 repr 默认情况下,您可以通过覆盖 PrettyPrinter来解决此问题。格式

pprint appears to use repr by default, you can work around this by overriding PrettyPrinter.format:

# coding=utf8

import pprint

class MyPrettyPrinter(pprint.PrettyPrinter):
    def format(self, object, context, maxlevels, level):
        if isinstance(object, unicode):
            return (object.encode('utf8'), True, False)
        return pprint.PrettyPrinter.format(self, object, context, maxlevels, level)


d = {'foo': u'işüğçö'}

pprint.pprint(d)              # {'foo': u'i\u015f\xfc\u011f\xe7\xf6'}
MyPrettyPrinter().pprint(d)   # {'foo': işüğçö}

这篇关于无法对pprint输出进行编码/解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆