【发布时间】:2017-12-29 22:42:24
【问题描述】:
我目前正在tornado 框架上使用python3(仍然是初学者)进行开发,并且我有一个想在后台运行的功能。更准确地说,该函数的任务是下载一个大文件(逐块),并且可能在每个块下载后做更多的事情。但调用函数不应等待下载函数完成,而应继续执行。
这里有一些代码示例:
@gen.coroutine
def dosomethingfunc(self, env):
print("Do something")
self.downloadfunc(file_url, target_path) #I don't want to wait here
print("Do something else")
@gen.coroutine
def downloadfunc(self, file_url, target_path):
response = urllib.request.urlopen(file_url)
CHUNK = 16 * 1024
with open(target_path, 'wb') as f:
while True:
chunk = response.read(CHUNK)
if not chunk:
break
f.write(chunk)
time.sleep(0.1) #do something after a chunk is downloaded - sleep only as example
我已在 stackoverflow https://stackoverflow.com/a/25083098/2492068 上阅读此答案并尝试使用它。
实际上,我想如果我使用@gen.coroutine 但不使用yield,dosomethingfunc 会继续,而无需等待downloadfunc 完成。但实际上行为是相同的(有或没有yield) - "Do something else" 只会在downloadfunc 完成下载后打印。
我在这里缺少什么?
【问题讨论】:
标签: python parallel-processing tornado coroutine