【问题标题】:How to debug Protocol.dataReceived in Twisted如何在 Twisted 中调试 Protocol.dataReceived
【发布时间】:2016-08-30 15:22:28
【问题描述】:

我是twisted 新手,在twisted.internet.protocol.Protocol 对象的dataReceived 方法中调试我的代码时遇到了麻烦。

给定一些这样的代码

class Printer(Protocol):
    def dataReceived(self, data):
        print data # Works perfectly
        print toto # should trigger some error since "toto" is not defined
...
response.deliverBody(Printer())

我找不到在dataReceived 上添加Errback 的方法。有办法吗?另一种调试其行为的方法?

提前感谢您的帮助。

【问题讨论】:

    标签: python asynchronous twisted


    【解决方案1】:

    您无法直接从dataReceived 捕获错误,因为该函数不是deferred 用户通常可以控制的。您只能在 deferred 对象上调用 addErrback。以下是如何捕获错误的示例:

    from twisted.internet.protocol import Protocol
    from twisted.internet.defer import Deferred
    
    class Printer(Protocol):
        def dataReceived(self, data):
            d = Deferred()
            d.addCallback(self.display_data)
            d.addErrback(self.error_func)
            d.callback(data)
    
        def display_data(self, data):
            print(data)
            print(toto)    # this will raise NameError error
    
        def error_func(self, error):
            print('[!] Whoops here is the error: {0}'.format(error))
    

    dataReceived 函数中创建了一个deferred,它将打印data 和无效的toto 变量。 errorback 函数(即self.error_func())被链接起来以捕获display_data() 中发生的错误。您应该非常努力地避免 dataReceived 函数本身出现错误。这并不总是可能的,但应该尝试。希望这会有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多