【发布时间】:2011-02-02 04:35:00
【问题描述】:
有没有可以和 Perl 的 Data::Dumper 模块一样使用的 Python 模块?
编辑:对不起,我应该更清楚。我主要是在一个用于检查数据而不是持久化的模块之后。
顺便说一句,感谢您的回答。这是一个很棒的网站!
【问题讨论】:
标签: python module object-dumper
有没有可以和 Perl 的 Data::Dumper 模块一样使用的 Python 模块?
编辑:对不起,我应该更清楚。我主要是在一个用于检查数据而不是持久化的模块之后。
顺便说一句,感谢您的回答。这是一个很棒的网站!
【问题讨论】:
标签: python module object-dumper
难道不是所有的答案都忽略了除了列表、字典等基本数据类型的组合之外的任何东西吗?我刚刚在 Python Xlib Window 对象上运行了 pprint 并得到了……<<class 'Xlib.display.Window'> 0x004001fe>……仅此而已。没有数据字段,没有列出方法……有什么可以真正转储对象吗?例如:它的所有属性?
【讨论】:
看到这个并意识到 Python 有一些类似于 Dumper 中的 Data::Dumper 的东西。作者将其描述为
以很好的方式转储 Python 数据结构(包括类实例)- 嵌套,易于阅读的形式。正确处理递归数据结构, 并且有合理的选择来限制转储的范围 简单的深度和如何处理包含的实例的一些规则。
通过 pip 安装它。 Github 存储库位于https://github.com/jric/Dumper.py。
【讨论】:
这是一个简单的解决方案,用于转储由字典、列表或元组组成的嵌套数据(对我来说效果很好):
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
]
【讨论】:
如果你想要比 pprint 更好的东西,但不需要自己滚动,请尝试从 pypi 导入 dumper:
https://github.com/jric/Dumper.py 或
https://github.com/ericholscher/pypi/blob/master/dumper.py
【讨论】:
我需要为 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' ] }
【讨论】:
我也已经使用 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:[
{
“一”:1
}
{
“乙”:2
}
]
}
>>> print(Dumper.dump(pp))
实例::pprint.PrettyPrinter
__dict__ :: {
'_depth':无
'_stream': 文件:: >
'_width':80
'_indent_per_level': 4
}
另外值得一试的是http://salmon-protocol.googlecode.com/svn-history/r24/trunk/salmon-playground/dumper.py它有自己的风格,看起来也很有用。
【讨论】:
对于序列化,有很多选项。
最好的之一是 JSON,它是一种与语言无关的序列化标准。它在 stdlib json 模块中的 2.6 中可用,在此之前在第三方 simplejson 模块中具有相同的 API。
您不想使用marshal,这是相当低级的。如果你想要它提供的东西,你会使用 pickle。
我避免使用 pickle 格式是 Python-only 和不安全的。使用pickle反序列化可以执行任意代码。
pickle,你想使用它的C 实现。 (请import cPickle as pickle。)对于调试,您通常希望查看对象的repr 或使用pprint 模块。
【讨论】:
我认为你会发现最接近的是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'}
【讨论】: