Python 扭曲延迟和 getProcessOutputAndValue 问题

Posted

技术标签:

【中文标题】Python 扭曲延迟和 getProcessOutputAndValue 问题【英文标题】:Python twisted defer and getProcessOutputAndValue question 【发布时间】:2011-03-01 03:35:50 【问题描述】:

各位, 这似乎是一个基本程序,我无法理解这里出了什么问题。运行程序时只是等待并且不会在控制台上输出任何内容,按 control-c 也不会输出任何内容。请指教。

我的理解如下: (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】:

您不需要 yield - getProcessOutputAndValue 的返回值已经是 Deferred

【讨论】:

谢谢。我会选择另一个答案,只是因为它与 yield 有用法。【参考方案2】:

如前所述,yield 在那里是不必要的。要使用 yield 你会重写 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()

我个人会坚持显式延迟使用。一旦你把头绕起来,它就更容易理解,并且与扭曲的其余部分更清晰地集成在一起。

【讨论】:

谢谢。选择你的答案,因为你提供了关于如何使用它的额外信息。

以上是关于Python 扭曲延迟和 getProcessOutputAndValue 问题的主要内容,如果未能解决你的问题,请参考以下文章

扭曲的连接丢失事件

在 WSGI 容器中使用扭曲的词

使用 python 3.8 在 windows 10 上安装 django 频道和扭曲的问题

旁遮普在 python 上安装扭曲运行错误

Python 将 http post body 扭曲转发到 tcp 端口

错误扭曲模块在Python 3.6.3