开发者

Python twisted defer and getProcessOutputAndValue question

开发者 https://www.devze.com 2023-02-14 13:21 出处:网络
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 any

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开发者_如何学C) 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()


You don't need the yield - the return value from getProcessOutputAndValue is already a Deferred.


As has already been stated yield is unnecessary there. To use yield you'd rewrite runProgram like:

from twisted.internet import defer

@defer.inlineCallbacks
def runProgram():
    command = ['lrt']
    try:
        result = yield getProcessOutputAndValue('echo', command)
        printResult(result)
    except e:
        printError(e)
        stopReactor()

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号