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

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


当前回答

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

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

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

其他回答

转储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?

Pprint包含一个“漂亮的打印机”,用于生成令人满意的数据结构表示。格式化程序生成的数据结构表示可以被解释器正确解析,并且易于人类阅读。如果可能的话,输出将保持在单行上,并在跨多行分割时缩进。

你可以使用"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

为什么不简单点呢:

for key,value in obj.__dict__.iteritems():
    print key,value

要打印对象的当前状态,你可以:

>>> obj # in an interpreter

or

print repr(obj) # in a script

or

print obj

为你的类定义__str__或__repr__方法。来自Python文档:

__repr__(self)由repr()内置函数调用,由字符串调用 转换(反引号)到 计算“官方”字符串 对象的表示。如果有的话 可能,这看起来像a 有效的Python表达式 方法重新创建对象 相同的值(给定一个合适的 环境)。如果不可能, 形式为“<…一些有用的 描述……应该返回>。 返回值必须为字符串 对象。如果一个类定义了repr() 但不是__str__(),则__repr__()是 也用于“非正式”字符串 实例的表示 班级是必需的。这是典型的 用于调试,所以很重要 这个表示是 信息丰富且明确。 __str__(self)由str()内置函数调用,由print函数调用 语句来计算“非正式的” 对象的字符串表示形式。 这与__repr__()不同 它不必是一个有效的Python 表达:比较方便还是 可以使用简洁的表示 代替。返回值必须为a 字符串对象。