如何重置收益率并停止迭代

时间:2019-08-11 18:16:52

标签: python generator

我正在遇到有关发电机的一些问题。我有1000个元素的列表。我想一一阅读单个项目并进行一些操作。该操作类似于将某些特定值进行比较。如果我可以从列表中找到该值,那么我想停止迭代并再次重置收益。

我在寻找功能来重置发生器中的__next__指针。另外,我还必须在运行时FN_SOVLS中创建100个对象。

class FN_SOV1S:

    def __init__(self,elementlist,idxNo):
        self._elementlist = elementlist
        self._idxNo =idxNo
        setup()
        process()


    def setup(self):
        try:
            self.df = pd.read_excel(r'D:\OPCUA\Working_VF1.xls', sheet_name='Valve1S')
            for tag,col in self.readcmd():
                if col==4:
                    self.cmd = tag

                if col == 5:
                    self.openFB = tag

                if col == 6:
                    self.clsFB = tag

                if col == 7:
                    self.delaytime = tag

        except Exception as e:
            log_exception(e)



    def process(self):

        for tagname,tagvalue in self.searchValueBytag():
            if tagname == self.cmd:
                if tagvalue == 1:
                    sleep(self.delaytime)
                    gen.writegeneral.writenodevalue(self.openFB,1)
                    gen.writegeneral.writenodevalue(self.clsFB,0)

                else:
                    gen.writegeneral.writenodevalue(self.openFB, 0)
                    gen.writegeneral.writenodevalue(self.clsFB, 1)


    def searchValueBytag(self):
        n = 0
        while n < len(self._elementlist):
            tagname, tagvalue = self._elementlist[n]
            yield tagname, tagvalue
            n =+ 1

要重置生成器功能的条件是:

 for tagname,tagvalue in self.searchValueBytag():
            if tagname == self.cmd:

2 个答案:

答案 0 :(得分:1)

您不能“重置”正在运行的发电机。

可以做的是在使用生成器的break循环中for

之后,您可以再次调用searchValueBytag重新创建生成器。

答案 1 :(得分:0)

我不完全理解您的问题,但是希望可以有所帮助。这将使用一个标志,该标志将继续重新启动生成器,直到不再找到self.cmd值。

很明显,这与您的代码不同,要使其正常工作还需要更多代码,但是您可以轻松地使用此标志来重置生成器

def generator():
    # arbitrary length
    length = 100
    n = 0

    while n < length:
        yield n
        n += 1

# create a complete flag that is only true when the end of the iteration is reached
complete = False

# keep trying until complete is true
while not complete:

    # restarts the generator by making a new one
    g = generator()

    # keeps going until 'break'
    while True:
        # try/catch because next returns error when the end of the generator is reached
        # when the end is reached we know that to turn complete to true
        try:
            # get the next val in the iterator
            value = next(g)

            # if value is the reset flag, then break out of while loop and restart generator
            if value == RESET_FLAG:
                break
        except:
            # StopIteration exeption received, job finished
            complete = True
            break
    def generator():
        length = 100
        n = 0

        while n < length:
           yield n
           n += 1