与泛滥的api集成-扭曲延迟



我有一个非常简单的脚本,可以监控文件传输进度,将其实际大小与目标进行比较,然后计算其哈希值,与所需的哈希值进行比较,并在一切正常时启动一些额外的东西。

我已经将用于文件传输(wget)的工具替换为depled,它有一个整洁的api可以集成。

与其比较文件进度和哈希,我现在只需要知道什么时候被淹没的人下载完文件。为了实现这一点,我可以根据自己的需要修改这个脚本,但我一直在试图将我的头脑包裹在扭曲的框架上,而这个框架正被淹没。

为了克服它,我从扭曲的延迟文档中获取了一个示例脚本,将一个类封装在它周围,并尝试使用我在这个脚本中使用的相同概念。

现在,我不知道该如何处理reactor对象,因为它基本上是一个无法重新启动的阻塞循环。

这是我正在使用的示例代码:

from twisted.internet import reactor, defer
import time
class DummyDataGetter:
done = False
result = 0
def getDummyData(self, x):
d = defer.Deferred()
# simulate a delayed result by asking the reactor to fire the
# Deferred in 2 seconds time with the result x * 3
reactor.callLater(2, d.callback, x * 3)
return d
def assignResult(self, d):
"""
Data handling function to be added as a callback: handles the
data by printing the result
"""
self.result = d
self.done = True
reactor.stop()
def run(self):
d = self.getDummyData(3)
d.addCallback(self.assignResult)
reactor.run()
getter = DummyDataGetter()
getter.run()
while not getter.done:
time.sleep(0.5)
print getter.result
# then somewhere else I want to get dummy data again
getter = DummyDataGetter()
getter.run() #this throws an exception of type error.ReactorNotRestartable
while not getter.done:
time.sleep(0.5)
print getter.result

我的问题是:

  1. 是否应该在另一个线程中启动reactor以防止它阻塞代码?

  2. 如果是这样的话,我该如何在一个单独的线程中向这个reactor添加更多的回调?只是从我的主线程中做一些类似于reactor.callLater(2, d.callback, x * 3)的事情?

  3. 如果不是,有什么技术可以克服无法在同一过程中启动/停止反应器两次或两次以上的问题?

好吧,我找到的最简单的方法就是简单地使用subprocess.Popen调用一个单独的脚本,将种子的状态和其他任何需要的东西转储到stdout(使用JSON序列化)中,然后通过管道将其传输到调用脚本中。

比扭曲的学习创伤小得多,但当然远非最佳。

最新更新