这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
当前回答
我需要在一些日志中打印调试信息,无法使用pprint,因为它会破坏它。相反,我这样做了,得到了几乎相同的结果。
DO = DemoObject()
itemDir = DO.__dict__
for i in itemDir:
print '{0} : {1}'.format(i, itemDir[i])
其他回答
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
对于每个挣扎的人
Vars()不返回所有属性。 Dir()不返回属性的值。
下面的代码打印obj的所有属性及其值:
for attr in dir(obj):
try:
print("obj.{} = {}".format(attr, getattr(obj, attr)))
except AttributeError:
print("obj.{} = ?".format(attr))
我需要在一些日志中打印调试信息,无法使用pprint,因为它会破坏它。相反,我这样做了,得到了几乎相同的结果。
DO = DemoObject()
itemDir = DO.__dict__
for i in itemDir:
print '{0} : {1}'.format(i, itemDir[i])
从答案中,可以稍微修改一下,只得到一个对象的“Attributes”,如下所示:
def getAttributes(obj):
from pprint import pprint
from inspect import getmembers
from types import FunctionType
def attributes(obj):
disallowed_names = {
name for name, value in getmembers(type(obj))
if isinstance(value, FunctionType)}
return {
name for name in dir(obj)
if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}
pprint(attributes(obj))
在临时添加此函数时非常有用,并且可以在不修改现有源代码的情况下删除此函数