这里我要找的是PHP的print_r函数。

这样我就可以通过查看有问题的对象的状态来调试脚本。


当前回答

你实际上是把两种不同的东西混合在一起。

使用dir(), vars()或inspect模块来获取您感兴趣的内容(我使用__builtins__作为示例;你可以用任何物体代替)。

>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__

随你喜欢,把那本词典打印出来吧:

>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...

or

>>> from pprint import pprint
>>> pprint(l)
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'DeprecationWarning',
...

>>> pprint(d, indent=2)
{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
  'AssertionError': <type 'exceptions.AssertionError'>,
  'AttributeError': <type 'exceptions.AttributeError'>,
...
  '_': [ 'ArithmeticError',
         'AssertionError',
         'AttributeError',
         'BaseException',
         'DeprecationWarning',
...

Pretty print也可以在交互式调试器中作为命令使用:

(Pdb) pp vars()
{'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
                  'AssertionError': <type 'exceptions.AssertionError'>,
                  'AttributeError': <type 'exceptions.AttributeError'>,
                  'BaseException': <type 'exceptions.BaseException'>,
                  'BufferError': <type 'exceptions.BufferError'>,
                  ...
                  'zip': <built-in function zip>},
 '__file__': 'pass.py',
 '__name__': '__main__'}

其他回答

虽然有很多好的答案,这里有一个一行程序,可以给出属性和值:

(str(vars(config)).split(",")[1:])

其中'config'是有问题的对象。我列出这作为一个单独的答案,因为我只是想简单地打印对象的相关值(包括__main等),而不使用循环或漂亮的打印,没有找到一个方便的答案。

在大多数情况下,使用__dict__或dir()将获得你想要的信息。如果您碰巧需要更多的细节,标准库包括inspect模块,它允许您获得一些令人印象深刻的细节。一些真正宝贵的信息包括:

函数和方法参数的名称 类层次结构 实现一个函数/类对象的源代码 帧对象的局部变量

如果你只是在寻找“我的对象有哪些属性值?”,那么dir()和__dict__可能就足够了。如果您真的想深入研究任意对象的当前状态(请记住,在python中几乎所有东西都是对象),那么inspect值得考虑。

转储myObject:

from bson import json_util
import json

print(json.dumps(myObject, default=json_util.default, sort_keys=True, indent=4, separators=(',', ': ')))

我尝试了vars()和dir();都没有达到我的期望。Vars()不起作用,因为对象没有__dict__(异常。vars()参数必须具有__dict__属性)。dir()不是我要找的:它只是一个字段名称的列表,没有给出值或对象结构。

我认为json.dumps()将适用于大多数对象,没有default=json_util.default,但我在对象中有一个datetime字段,因此标准json序列化器失败。参见如何克服“约会时间”。datetime不是JSON序列化”在python?

我建议使用help(your_object)。

帮助(dir)

如果不带参数调用,则返回当前作用域中的名称。 否则,返回由(部分)属性组成的名称按字母顺序排列的列表 给定对象的属性。 如果对象提供了一个名为__dir__的方法,则将使用它;否则 使用默认的dir()逻辑并返回: 对于模块对象:模块的属性。 对于类对象:它的属性和递归的属性 它的碱基。 对于任何其他对象:它的属性,它的类的属性和 递归地获取其类的基类的属性。

帮助(变量)

不带参数,相当于locals()。 带有一个参数,等价于object.__dict__。

试试beeprint吧。

它不仅可以帮助你打印对象变量,还可以帮助你输出漂亮的结果,就像这样:

class(NormalClassNewStyle):
  dicts: {
  },
  lists: [],
  static_props: 1,
  tupl: (1, 2)