代码之家  ›  专栏  ›  技术社区  ›  Rob Wells

有一个Python等价于Perl的Data::Dumper吗?

  •  36
  • Rob Wells  · 技术社区  · 14 年前

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

    顺便说一句,谢谢你的回答。这是一个很棒的网站!

    9 回复  |  直到 5 年前
        1
  •  33
  •   jjfine    14 年前

    Dumper有两个主要用途:数据持久性和调试/检查对象。据我所知,没有任何东西能像Data::Dumper那样工作。

    我用 pickle 用于数据持久性。

    我用 pprint

        2
  •  8
  •   JimB    14 年前

    我想你能找到的最接近的就是 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'}
    
        3
  •  6
  •   Juho Vepsäläinen    14 年前
        4
  •  4
  •   Saurabh Hirani    13 年前

    我也已经使用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 它有自己的风格,似乎也很有用。

        5
  •  4
  •   mdiehl13 Ahhhhbisto    5 年前

    蟒蛇2

    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)
    

    蟒蛇3

     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
    ]
    
        6
  •  3
  •   Mike Graham    14 年前
    • 对于序列化,有许多选项。

      • 其中最好的一种是JSON,它是一种与语言无关的序列化标准。它在stdlib的2.6版本中提供 json 在第三方中使用相同的API simplejson

      • 您不想使用 marshal

      • 我避免使用pickle,因为它的格式仅限于Python,而且不安全。使用pickle反序列化可以执行任意代码。

        • 如果你用了 pickle ,则要使用其C实现(做 import cPickle as pickle .)
    • 对于调试,通常需要查看对象的 repr 使用 pprint

        7
  •  1
  •   Damon    12 年前

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

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

        8
  •  1
  •   Mario Kirov    6 年前

    我需要为API请求返回类似Perl的dump,所以我想到了这个方法,它不能将输出格式化为漂亮的,但对我来说是一个完美的工作。

    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' ] }
    
        10
  •  0
  •   sevenr    5 年前

    看到这一点并意识到Python中有类似于Data::Dumper的东西 Dumper . 作者将其描述为

    嵌套,易于阅读的形式。正确处理递归数据结构, 简单的深度和一些如何处理包含实例的规则。

    https://github.com/jric/Dumper.py .

        11
  •  0
  •   psprint    4 年前

    <<class 'Xlib.display.Window'> 0x004001fe> 这就是全部。没有数据字段,没有列出的方法有什么可以 真实的 倾倒物品?例如:所有的 ?