Python扭曲的defer和getProcessOutputAndValue问题
各位, 这似乎是一个基本程序,我无法理解这里出了什么问题。运行时,程序只是等待,不会在控制台上输出任何内容,按 control-c 也不会输出任何内容。请指教。
我的理解如下: (i) Reactor 运行并且 callLater 导致 runProgram 在“0”秒后被调用。 (ii) runProgram 从 getProcessOutputAndValue 获得延迟返回,我添加 Callback 和 Errback 以及reactor.stop() 作为“两个”回调。
我现在的期望是,当命令执行完成时,必须调用延迟的回调(或失败时的错误回调)。最后,由于指定了 addBoth,因此应该调用reactor.stop()来停止反应器。
from twisted.internet.utils import getProcessOutputAndValue
from twisted.internet import reactor
def printResult(result):
print u'Result is %s' % result
def printError(reason):
print u'Error is %s' % reason
def stopReactor(r):
print u'Stopping reactor'
reactor.stop()
print u'Reactor stopped'
def runProgram():
command = ['lrt']
d = yield getProcessOutputAndValue('echo', command)
d.addCallback(printResult)
d.addErrback(printError)
d.addBoth(stopReactor)
reactor.callLater(0, runProgram)
reactor.run()
Folks,
This seems like a basic program and I cannot understand what is going wrong here. When run the program just waits and does not output anything on console, pressing control-c does not output anything either. Please advise.
My understanding is as follows:
(i) Reactor is run and callLater causes runProgram to be called after '0' seconds.
(ii) runProgram gets a deferred back from getProcessOutputAndValue, and I add Callback and Errback as well as reactor.stop() as 'Both' callbacks.
My expectation now is, the deferred's Callback (or Errback upon failure) must be called when the command execution is done. Finally, since addBoth is specified, the reactor.stop() should be called which stops the reactor.
from twisted.internet.utils import getProcessOutputAndValue
from twisted.internet import reactor
def printResult(result):
print u'Result is %s' % result
def printError(reason):
print u'Error is %s' % reason
def stopReactor(r):
print u'Stopping reactor'
reactor.stop()
print u'Reactor stopped'
def runProgram():
command = ['lrt']
d = yield getProcessOutputAndValue('echo', command)
d.addCallback(printResult)
d.addErrback(printError)
d.addBoth(stopReactor)
reactor.callLater(0, runProgram)
reactor.run()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要
yield
-getProcessOutputAndValue
的返回值已经是Deferred
。You don't need the
yield
- the return value fromgetProcessOutputAndValue
is already aDeferred
.正如已经指出的那样,产量在那里是不必要的。要使用yield,您需要重写runProgram,如下所示:
就我个人而言,我会坚持显式延迟使用。一旦你理解了它,它就更容易理解,并且与扭曲的其余部分更清晰地结合在一起。
As has already been stated yield is unnecessary there. To use yield you'd rewrite runProgram like:
Personally I'd stick with the explicit deferred usage. Once you wrap your head around it is easier to understand and integrates more cleanly with the rest of twisted.