我有一个长期运行的任务,必须由外部代码指导。但是外部代码需要一些关于这个任务的信息。这是我的自制示例:
def longtask(self):
yield self.get_step_length(1)
for x in self.perform_step(1):
...
yield x.id
yield self.get_step_length(2)
for x in self.perform_step(2):
...
yield x.value
...
# call site
generator = self.longtask()
step1len = generator.Next()
step1pb = ProgressBar('Step 1', step1len)
# pull only step 1 items
for index, id in itertools.izip(xrange(0, step1len), generator):
step1pb.update(index)
...do something with id
step2len = generator.Next()
step2pb = ProgressBar('Step 2', step1len)
# pull only step 1 items
for index, value in itertools.izip(xrange(0, step1len), generator):
step2pb.update(index)
... do something other with value
在python中使用如此复杂的生成器协议是否正确,或者我需要重构这段代码?