是否有与Perl的Data :: Dumper等效的Python?

时间:2010-03-29 19:09:49

标签: python module object-dumper

是否有一个Python模块可以像Perl的Data::Dumper模块一样使用?

编辑:抱歉,我应该更清楚了。我主要是在检查数据而不是持久化的模块之后。

BTW感谢您的回答。这是一个很棒的网站!

11 个答案:

答案 0 :(得分:28)

Data :: Dumper有两个主要用途:数据持久性和调试/检查对象。据我所知,没有任何东西可以与Data :: Dumper完全相同。

我使用pickle来保持数据持久性。

我使用pprint直观地检查我的对象/ debug。

答案 1 :(得分:5)

我认为最接近的是pprint模块。

>>> l = [1, 2, 3, 4]
>>> l.append(l)
>>> d = {1: l, 2: 'this is a string'}
>>> print d
{1: [1, 2, 3, 4, [...]], 2: 'this is a string'}

>>> pprint.pprint(d)
{1: [1, 2, 3, 4, <Recursion on list with id=47898714920216>],
 2: 'this is a string'}

答案 2 :(得分:4)

可能有两种选择:picklemarshalshelve

答案 3 :(得分:3)

  • 对于序列化,有很多选项。

    • 最好的一个是JSON,它是一个与语言无关的序列化标准。它在stdlib json模块中以2.6提供,之前在第三方simplejson模块中使用相同的API。

    • 您不想使用marshal,这是相当低级别的。如果你想要它提供的东西,你会使用泡菜。

    • 我避免使用pickle,格式只有Python且不安全。使用pickle反序列化可以执行任意代码。

      • 如果您确实使用了pickle,则需要使用其C实现。 (做import cPickle as pickle。)
  • 要进行调试,您通常需要查看对象的repr或使用pprint模块。

答案 4 :(得分:3)

这是一个简单的解决方案,用于转储由字典,列表或元组组成的嵌套数据(对我来说效果很好):

<强> Python2

def printStruct(struc, indent=0):
  if isinstance(struc, dict):
    print '  '*indent+'{'
    for key,val in struc.iteritems():
      if isinstance(val, (dict, list, tuple)):
        print '  '*(indent+1) + str(key) + '=> '
        printStruct(val, indent+2)
      else:
        print '  '*(indent+1) + str(key) + '=> ' + str(val)
    print '  '*indent+'}'
  elif isinstance(struc, list):
    print '  '*indent + '['
    for item in struc:
      printStruct(item, indent+1)
    print '  '*indent + ']'
  elif isinstance(struc, tuple):
    print '  '*indent + '('
    for item in struc:
      printStruct(item, indent+1)
    print '  '*indent + ')'
  else: print '  '*indent + str(struc)

<强> Python3

 def printStruct(struc, indent=0):
   if isinstance(struc, dict):
     print ('  '*indent+'{')
     for key,val in struc.items():
       if isinstance(val, (dict, list, tuple)):
         print ('  '*(indent+1) + str(key) + '=> ')
         printStruct(val, indent+2)
       else:
         print ('  '*(indent+1) + str(key) + '=> ' + str(val))
     print ('  '*indent+'}')
   elif isinstance(struc, list):
     print ('  '*indent + '[')
     for item in struc:
       printStruct(item, indent+1)
     print ('  '*indent + ']')
   elif isinstance(struc, tuple):
     print ('  '*indent + '(')
     for item in struc:
       printStruct(item, indent+1)
     print ('  '*indent + ')')
   else: print ('  '*indent + str(struc))

在工作中看到它:

>>> d = [{'a1':1, 'a2':2, 'a3':3}, [1,2,3], [{'b1':1, 'b2':2}, {'c1':1}], 'd1', 'd2', 'd3']
>>> printStruct(d)
[
  {
    a1=> 1
    a3=> 3
    a2=> 2
  }
  [
    1
    2
    3
  ]
  [
    {
      b1=> 1
      b2=> 2
    }
    {
      c1=> 1
    }
  ]
  d1
  d2
  d3
]

答案 5 :(得分:2)

我也一直在使用Data :: Dumper很长一段时间,并已经习惯了显示格式良好的复杂数据结构。如上所述的pprint做得相当不错,但我不太喜欢它的格式化风格。加上pprint不允许你检查Data :: Dumper之类的对象:

在网上搜索并发现了这些:

https://gist.github.com/1071857#file_dumper.pyamazon

>>> y = { 1: [1,2,3], 2: [{'a':1},{'b':2}]}

>>> pp = pprint.PrettyPrinter(indent = 4)
>>> pp.pprint(y)
{   1: [1, 2, 3], 2: [{   'a': 1}, {   'b': 2}]}

>>> print(Dumper.dump(y)) # Dumper is the python module in the above link
{
    1: [
        1 
        2 
        3
    ] 
    2: [
        {
            'a': 1
        } 
        {
            'b': 2
        }
    ]
}
>>> print(Dumper.dump(pp))
instance::pprint.PrettyPrinter
    __dict__ :: {
        '_depth': None 
        '_stream': file:: > 
        '_width': 80 
        '_indent_per_level': 4
    }

另外值得一试的是http://salmon-protocol.googlecode.com/svn-history/r24/trunk/salmon-playground/dumper.py它有自己的风格,看起来也很有用。

答案 6 :(得分:1)

就检查你的对象而言,我发现这是一个有用的等效数据:Dumper:

https://salmon-protocol.googlecode.com/svn-history/r24/trunk/salmon-playground/dumper.py

它可以处理unicode字符串。

答案 7 :(得分:1)

如果您想要比pprint更好的功能,但又不需要自己动手,请尝试从pypi导入dumper:
https://github.com/jric/Dumper.pyhttps://github.com/ericholscher/pypi/blob/master/dumper.py

答案 8 :(得分:0)

我需要为API请求返回类似Perl的转储,所以我想出了这一点,它不会将输出格式化为漂亮,但对我来说却是完美的工作。

from decimal import Decimal
from datetime import datetime, date

def dump(self, obj):

    if obj is None:
        return "undef"

    if isinstance(obj, dict):
        return self.dump_dict(obj)

    if isinstance(obj, (list, tuple)):
        return self.dump_list(obj)

    if isinstance(obj, Decimal):
        return "'{:.05f}'".format(obj)
        # ... or handle it your way

    if isinstance(obj, (datetime, date)):
        return "'{}'".format(obj.isoformat(
            sep=' ',
            timespec='milliseconds'))
        # ... or handle it your way

    return "'{}'".format(obj)

def dump_dict(self, obj):
    result = []
    for key, val in obj.items():
        result.append(' => '.join((self.dump(key), self.dump(val))))

    return ' '.join(('{', ', '.join(result), '}'))

def dump_list(self, obj):
    result = []
    for val in obj:
        result.append(self.dump(val))

    return ' '.join(('[', ', '.join(result), ']'))



Using the above:

    example_dict = {'a': 'example1', 'b': 'example2', 'c': [1, 2, 3, 'asd'], 'd': [{'g': 'something1', 'e': 'something2'}, {'z': 'something1'}]}

    print(dump(example_dict))

will ouput:

    { 'b' => 'example2', 'a' => 'example1', 'd' => [ { 'g' => 'something1', 'e' => 'something2' }, { 'z' => 'something1' } ], 'c' => [ '1', '2', '3', 'asd' ] }

答案 9 :(得分:0)

看到这一点,并意识到Python具有类似于Dumper中的Data :: Dumper的功能。作者将其描述为

  

将Python数据结构(包括类实例)很好地转储为-   嵌套的,易于阅读的表格。正确处理递归数据结构,   并有合理的选择来限制转储的范围   简单的深度以及一些有关如何处理包含的实例的规则。

通过pip安装它。 Github仓库位于https://github.com/jric/Dumper.py

答案 10 :(得分:0)

是不是所有答案都忽略了转储,而不是列表,字典等基本数据类型的组合?我刚刚在Python Xlib Window对象上运行了pprint,然后得到了10…就这样。没有数据字段,没有列出方法...对象的真实转储有什么东西吗?例如:所有其属性