1

我正在用扭曲的 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 触发之前查看哪些类的实例是活动的。

我正在检查这个打印一个类的所有实例

使用此代码

import gc
for obj in gc.get_objects():

我怎样才能有选择地查看最上面的信息,然后进一步继承数据等等?

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

4

1 回答 1

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,它实际上可以“实时”戳和刺激事物。 在此处查看有关 TwistedConch 的详细信息

或者..

另一个技巧是添加一个' del(self)'函数到你的对象,当对象被垃圾收集器清理时打印出一些东西(当它被删除/超出范围时)

或者..

你也可以玩pdb,或者如果你喜欢 ncurses pudb很棒。查看这个问题,了解一些使用 pdb 的绝妙技巧。启动-python-调试器-自动出错

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

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

于 2013-04-28T07:42:54.520 回答