2011-03-01 109 views
1

民間, 這似乎是一個基本的程序,我不明白這裏出了什麼問題。當運行程序只是等待並且不輸出控制檯上的任何內容時,按下control-c也不會輸出任何內容。請指教。蟒蛇扭曲推遲和getProcessOutputAndValue問題

我的理解如下: (i)Reactor運行並且callLater導致runProgram在'0'秒後被調用。 (ii)runProgram從getProcessOutputAndValue獲得延遲,並且我將Callback和Errback以及reactor.stop()添加爲'Both'回調。

我的期望現在是,當命令執行完成後,必須調用延遲的回調(或失敗後的Errback)。最後,由於指定了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() 

回答

1

如前所述,產量是不必要的。要使用屈服你會改寫runProgram像:

from twisted.internet import defer 

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

我個人倒有明確延期使用粘。一旦你將頭部包裹起來,它就更容易理解,並且與其餘的扭曲更加整潔。

+0

謝謝。選擇你的答案,因爲你給了額外的一點關於如何使用它的收益。 – helpmelearn 2011-03-03 08:07:00

2

你不需要yield - 從getProcessOutputAndValue的返回值已經是一個Deferred

+0

謝謝。我只會選擇其他答案,因爲它具有產量的用法。 – helpmelearn 2011-03-03 08:07:27

+0

當然,不用擔心。 :) – Amber 2011-03-03 17:23:00