这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
这里我要找的是PHP的print_r函数。
这样我就可以通过查看有问题的对象的状态来调试脚本。
当前回答
试试beeprint吧。
它不仅可以帮助你打印对象变量,还可以帮助你输出漂亮的结果,就像这样:
class(NormalClassNewStyle):
dicts: {
},
lists: [],
static_props: 1,
tupl: (1, 2)
其他回答
你可以使用"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
from pprint import pprint
def print_r(the_object):
print ("CLASS: ", the_object.__class__.__name__, " (BASE CLASS: ", the_object.__class__.__bases__,")")
pprint(vars(the_object))
如果你想在一个复杂的数据结构中看到所有的值,那么可以这样做:
from pprint import pprint
pprint(my_var)
其中my_var是您感兴趣的变量。当我使用pprint(vars(my_var))时,我什么都没有得到,这里的其他答案没有帮助,或者方法看起来不必要的长。顺便说一下,在我的特殊情况下,我正在检查的代码有一个字典的字典。
值得指出的是,对于一些自定义类,您可能只会得到一个无用的<someobject。0x7f739267f400>类型的输出。在这种情况下,你可能不得不实现一个__str__方法,或尝试一些其他的解决方案。
我还发现,在我获得这种对象类型输出的一个实例中,vars()显示了我想要的结果。因此,覆盖这两种情况的更好解决方案是分别尝试两种情况。但是使用vars()有时会抛出异常,例如,TypeError: vars()参数必须具有__dict__属性。
我仍然希望找到一些简单的,在所有场景下都可以工作的东西,而不需要第三方库。
您可以尝试Flask调试工具栏。 https://pypi.python.org/pypi/Flask-DebugToolbar
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
app = Flask(__name__)
# the toolbar is only enabled in debug mode:
app.debug = True
# set a 'SECRET_KEY' to enable the Flask session cookies
app.config['SECRET_KEY'] = '<replace with a secret key>'
toolbar = DebugToolbarExtension(app)
这个项目修改pprint以显示所有对象字段值,它忽略对象__repr__成员函数,它还递归到嵌套对象。它与python3一起工作,参见https://github.com/MoserMichael/pprintex 你可以通过pip: pip install printex安装它