如何查看所有当前对象及其直接方法

时间:2013-04-28 05:20:39

标签: python debugging twisted

我在使用twisted 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():

如何有选择地查看最重要的信息,然后进一步继承数据等等?

从扭曲的角度来看,我想知道哪些工厂实例当前处于活动状态以及它与协议的关系

1 个答案:

答案 0 :(得分:1)

但是,如果您真的想要了解如何调试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

而且,如果情况变得更糟 - 你总是可以使用帮助(对象)。

这几乎是让我度过一天的调试方法。如果其他人有一些聪明的想法,不要害羞。