如何避免 python 中的 yield 命令每次都抛出异常?

How to avoid yield command in python throws exceptions every time?

我正在使用 Twisted Klein 开发异步 Web 服务。部分代码如下:

@inlineCallbacks
def test(input1): 
    try:
        result = yield function(input1)
        print result
        returnValue(result)
    except:
        returnValue("None")
        pass

我将此 test 函数作为我的网络服务的一部分,每次我从 returns "None" 中的其他函数调用 test 函数时。但是,在服务器屏幕上它打印出我想要的正确结果(try 中的 print result 行被正确执行,只是 returnValue(result) 没有被使用)。我对异步编码不是很熟悉,但是除了 yield 之外,还有什么我应该注意尝试的吗?谢谢。

首先,你永远不应该有一个空洞的 except 子句。 (也有例外,但一般来说还是抓具体错误比较好。)

其次,来自 returnValue:

上扭曲的文档

Note: this is currently implemented by raising an exception derived from BaseException. You might want to change any 'except:' clauses to an 'except Exception:' clause so as not to catch this exception.

Also: while this function currently will work when called from within arbitrary functions called from within the generator, do not rely upon this behavior.

发生的事情是你的正确结果正在打印,然后你调用 returnValue,这会引发异常,导致你的代码 return None

twisted docs