如何格式化python __str__输出

时间:2015-05-21 03:30:18

标签: python python-2.7

我正在开发OpenStack,我看到很多对象都写入了日志文件中的一长串字符串。例如。

vol={'migration_status': None, 'availability_zone': u'nova', 'terminated_at': None, 'updated_at': datetime.datetime(2015, 5, 15, 7, 0, 11), 'provider_geometry': None, 'snapshot_id': None, 'ec2_id': None, 'mountpoint': u'/dev/sdb', 'deleted_at': None, 'id': u'83a5ade7-275e-4ffd-b494-a4c2c9a169d1', 'size': 10L, 'user_id': u'2b5cd66674d24c4f94138002d96f5f96', 'attach_time': u'2015-05-13T06:12:35.749100', 'attached_host': None, 'display_description': None, 'volume_admin_metadata': [<cinder.db.sqlalchemy.models.VolumeAdminMetadata object at 0x7fbd834f52d0>, <cinder.db.sqlalchemy.models.VolumeAdminMetadata object at 0x7fbd834f58d0>], 'encryption_key_id': None, 'project_id': u'9ba90732bdba43dcbd49e111cbe92458', 'launched_at': datetime.datetime(2015, 5, 13, 5, 56, 33), 'scheduled_at': datetime.datetime(2015, 5, 13, 5, 56, 31), 'status': u'available', 'volume_type_id': None, 'deleted': False, 'provider_location': None, 'host': u'controller01', 'source_volid': None, 'provider_auth': None, 'display_name': u'parallel_200_1-my_vol107-umrnk5jchjwo', 'instance_uuid': u'a81b355d-d240-4888-93a1-7e10822a777f', 'bootable': False, 'created_at': datetime.datetime(2015, 5, 13, 5, 56, 31), 'attach_status': u'attached', 'volume_type': None, '_name_id': None, 'volume_metadata': [], 'metadata': {u'readonly': u'False', u'attached_mode': u'rw'}}

我希望有一种方法可以将此输出格式化为类似json的格式,以便更具可读性。类似的东西:

{
  'migration_status': None,
  'availability_zone': u'nova',
  ...
}

我怎么能这样做?

我有一个后续问题。所有答案都涉及建立字典或列表对象。但是如果我在日志文件中的字符串中有以下内容,则会出现错误:

  1. 'volume_admin_metadata':[,] - 错误:语法错误:语法无效(在'&lt;')
  2. 'updated_at':datetime.datetime(2015,5,15,7,0,11) - 错误:NameError:名称'datetime'未定义
  3. “encrypted”:false - 错误:NameError:未定义名称“false”
  4. “source_volid”:null - 错误:NameError:未定义名称“null”
  5. 是否有一些实用程序可以自动处理此语法错误?

2 个答案:

答案 0 :(得分:2)

Python有一个pprint module可以像你描述的那样格式化输出。

>>> import pprint
>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']
>>> stuff.insert(0, stuff[:])
>>> pp = pprint.PrettyPrinter(indent=4)
>>> pp.pprint(stuff)
[   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
    'spam',
    'eggs',
    'lumberjack',
    'knights',
    'ni']

要在__str__方法中使用,pprint.pformat将是最方便的功能。

答案 1 :(得分:1)

pprint外,您还可以尝试json

>>> import json
>>> jhon = {'name': 'Jhon', 'age': 12, 'hobbies': ['football', 'games', 'running'], 'family': {'father': 'David', 'mother': 'Rose'}}
>>> print(json.dumps(jhon, indent=4))
{
    "age": 12, 
    "name": "jhon", 
    "family": {
        "father": "David", 
        "mother": "Rose"
    }, 
    "hobbies": [
        "football", 
        "games", 
        "running"
    ]
}

由于您有类似'updated_at': datetime.datetime(2015, 5, 15, 7, 0, 11)的内容,因此可以使用json.dumps(blabla, indent=4, default=str)