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

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


当前回答

我喜欢使用python对象内置类型、键或值。

对于属性,不管它们是方法还是变量:

o.keys()

对于这些属性的值:

o.values()

其他回答

如果你想在一个复杂的数据结构中看到所有的值,那么可以这样做:

from pprint import pprint
pprint(my_var)

其中my_var是您感兴趣的变量。当我使用pprint(vars(my_var))时,我什么都没有得到,这里的其他答案没有帮助,或者方法看起来不必要的长。顺便说一下,在我的特殊情况下,我正在检查的代码有一个字典的字典。

值得指出的是,对于一些自定义类,您可能只会得到一个无用的<someobject。0x7f739267f400>类型的输出。在这种情况下,你可能不得不实现一个__str__方法,或尝试一些其他的解决方案。

我还发现,在我获得这种对象类型输出的一个实例中,vars()显示了我想要的结果。因此,覆盖这两种情况的更好解决方案是分别尝试两种情况。但是使用vars()有时会抛出异常,例如,TypeError: vars()参数必须具有__dict__属性。

我仍然希望找到一些简单的,在所有场景下都可以工作的东西,而不需要第三方库。

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

使用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__'}

我没有测试过性能,但我相信这是在Python中以列表形式枚举任何对象的属性/属性/键的最快方法。

# If core==False, ignore __k__ entries
def obj_props(obj, core=False) -> list:
    assert not obj is None, f"obj must not be null (None)"
    _props = []
    _use_dir=False
    def _add(p):
        if not core and p.find('__') == 0: return
        _props.append(p)
    if hasattr(obj, '__dict__'): 
        for p in obj.__dict__.keys(): _add(p)
    elif hasattr(obj, '__slots__'):
        for p in obj.__slots__: _add(p)
    elif hasattr(obj, 'keys'):
        try:
            for p in obj.keys(): _add(p)
        except Exception as ex:
            _props = []
            _use_dir = True
    else:
        _use_dir = True
    if _use_dir:
        # fall back to slow and steady
        for p in dir(obj):
            if not core and p.find('__') == 0: continue
            v = getattr(obj, p)
            v_t = type(v).__name__
            if v_t in ('function', 'method', 'builtin_function_or_method', 'method-wrapper'): continue
            _props.append(p)

    return _props

上面应该适用于常规的python对象(使用__dict__),使用插槽的对象(__slots__),甚至适用于像对象一样的字典。

大多数其他示例使用dir(obj),它将枚举对象的所有方法和属性,如果您只需要它的属性,则会对性能造成影响。

你可以使用"dir()"函数来做到这一点。

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo
t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder
, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'
 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault
ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he
version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_
ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit
, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption
', 'winver']
>>>

另一个有用的功能是帮助。

>>> help(sys)
Help on built-in module sys:

NAME
    sys

FILE
    (built-in)

MODULE DOCS
    http://www.python.org/doc/current/lib/module-sys.html

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.

    Dynamic objects:

    argv -- command line arguments; argv[0] is the script pathname if known

如果你用它来调试,你只是想递归转储所有的东西,接受的答案是不令人满意的,因为它要求你的类已经有良好的__str__实现。如果不是这样的话,这样做会更好:

import json
print(json.dumps(YOUR_OBJECT, 
                 default=lambda obj: vars(obj),
                 indent=1))