python中的time.sleep无法正常工作,但会立即退出

时间:2019-04-18 12:16:22

标签: python

我正在executeScript中的Nifi中使用下面的代码,并添加了time.sleep以增加代码延迟,以便它在一段时间后尝试,但是这无法按预期工作。它不需等待就一次接一个地打印日志

 class ModJSON(StreamCallback):
        def __init__(self):
            pass

        def process(self, inputStream, outputStream):
            text = IOUtils.toString(inputStream, StandardCharsets.UTF_8)
            obj = json.loads(text)
            response = self._updateelasticsearch(timestamp, flowID, elasticSearchURL, indexName)
            log.error("response : " + response)
            flowcounter = 1

            while (response.find('"updated":1') == -1 & flowcounter < 35):
                flowcounter += 1
                time.sleep(50)
                response = self._updateelasticsearch(timestamp, flowID, elasticSearchURL, indexName)

            flowcounter = 0
            outputStream.write(bytearray(json.dumps(response, indent=4).encode('utf-8')))

        def _updateelasticsearch(self, timestamp, flowID, elasticSearchURL, indexName):
            try:
                #update code
            return rest_response

        def _validateIfExist(self, flowid, elasticSearchURL, indexName) :
            #validatecode

            if record_count > 0:
                return True
            else :
                return False


    flowFile = session.get()
    if (flowFile != None):
        flowFile = session.write(flowFile, ModJSON())
        session.transfer(flowFile, REL_SUCCESS)
        session.commit()

1 个答案:

答案 0 :(得分:2)

我怀疑您的while循环从未被输入。

while (response.find('"updated":1') == -1 & flowcounter < 35):
                                          ^ problem

按位&运算符的行为不同于布尔值and运算符。 &的优先级与and的优先级不同,因此可以产生令人惊讶的结果:

>>> 1 == 1 & 2 == 2
False

类似地,表达式response.find('"updated":1') == -1 & flowcounter < 35仅在response.find('"updated":1') == (-1 & flowcounter)(-1 & flowcounter) < 35时计算为True。当(-1 & flowcounter)为正时,flowcounter永远不等于-1,因此,当response.find('"updated":1')返回-1时,您的条件永远不会成功。

如果您只是想将条件中的子句逻辑上链接在一起,请使用and

while (response.find('"updated":1') == -1 and flowcounter < 35):