我正在用扭曲的Python查看本教程。 https://github.com/jdavisp3/twisted-intro/blob/master/twisted-client-3/get-poetry.py
def get_poetry(host, port, callback):
"""
Download a poem from the given host and port and invoke
callback(poem)
when the poem is complete.
"""
from twisted.internet import reactor
factory = PoetryClientFactory(callback)#I am interested in checking the instances alive here
reactor.connectTCP(host, port, factory)
def poetry_main():
addresses = parse_args()
from twisted.internet import reactor
poems = []
def got_poem(poem):
poems.append(poem)
if len(poems) == len(addresses):
reactor.stop()
for address in addresses:
host, port = address
get_poetry(host, port, got_poem)
reactor.run()
for poem in poems:
print poem
if __name__ == '__main__':
poetry_main()
我以前从未真正调试过Python。
我想看看在reactor.stop 触发之前哪些类的实例还活着。
我正在检查这个Printing all instances of a class
使用此代码
import gc
for obj in gc.get_objects():
如何有选择地查看最上面的信息以及进一步继承的数据等?
从一个扭曲的角度来看,我想看看哪些工厂实例当前处于事件状态以及它与协议(protocol)有何关系
最佳答案
但是,如果您真的只是想了解一下如何调试 Python,请查看“dir(obj)”,它将列出对象的所有属性和方法。
class Blah(object):
pass
b = Blah()
for x in dir(b):
try:
print getattr(b,x,False)
except Exception, e:
print x,e
将产生:
<class '__main__.Blah'>
<method-wrapper '__delattr__' of Blah object at 0x1028ba490>
{}
None
<built-in method __format__ of Blah object at 0x1028ba490>
<method-wrapper '__getattribute__' of Blah object at 0x1028ba490>
<method-wrapper '__hash__' of Blah object at 0x1028ba490>
<method-wrapper '__init__' of Blah object at 0x1028ba490>
__main__
<built-in method __new__ of type object at 0x10276a4e0>
<built-in method __reduce__ of Blah object at 0x1028ba490>
<built-in method __reduce_ex__ of Blah object at 0x1028ba490>
<method-wrapper '__repr__' of Blah object at 0x1028ba490>
<method-wrapper '__setattr__' of Blah object at 0x1028ba490>
<built-in method __sizeof__ of Blah object at 0x1028ba490>
<method-wrapper '__str__' of Blah object at 0x1028ba490>
<built-in method __subclasshook__ of type object at 0x7fd522c6e490>
现在,您的情况可能会因 objc 等内容而有所不同 - 因为它是围绕进行共享库调用的一个薄 Python 包装器。它们不会有文档字符串,或者在某些情况下,如果函数查找是针对共享库的延迟查找,则响应“dir”。但是,你永远不知道。
大多数时候,当涉及到 objc 的东西时,我只是深入研究它们的源代码,以弄清楚当挖掘污垢的正常方法不起作用时它们是如何做的。
说到普通方法:
Twisted 的一个巧妙功能,您还可以提供可访问 telnet 或 SSH 的交互式 Python shell,它实际上可以“实时”地戳戳和刺激事物。 Check here for details on TwistedConch .
或者..
另一个技巧是向对象添加一个“del(self)”函数,当对象被垃圾收集器清理时(当对象被删除/超出范围时),该函数会打印出一些内容
或者..
您还可以玩 pdb ,或者如果您喜欢 ncurses pudb太棒了。查看这个问题,了解使用 pdb 的一些巧妙技巧。 starting-python-debugger-automatically-on-error
而且,如果情况变得更糟 - 您可以随时使用 help(object)。
这些几乎就是让我度过这一天的调试方法。如果其他人有一些聪明的想法,请不要害羞。
关于python - 如何查看当前所有对象及其直接方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16259891/