在python中等待直到满足所需的条件

2024-09-29 00:17:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的程序中,我希望等待status变量的输出为“True”,并且如果status变量为 “True”,我想返回status变量的输出

import subprocess

class MyLibrary(object):

    def execute(self, cmd):
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        out, err = result.communicate()
        return str(out)

    def list(self):
        command = ["<application_command>", "list"]
        status = self.execute(command).__contains__("running")
        <<How to achieve my condition??>>
        return status

test = MyLibrary()
test.list()

Tags: testself程序cmdtrueexecutereturndef
2条回答

试试这个1

import time
def list(self):
    command = ["<application_command>", "list"]
    status = False
    start = time.time()
    while True: # while status is false
        status = "running" in self.execute(command)
        if ((time.time() - start) >= 60) and status:
            return
        if status: # if the status is true
            return status
        else:
            continue

1:从ShadowRanger's comment

看来我自己找到了答案。它工作得很好

def list(self):
    command = ["<application_command>", "list"]
    status = False
    while status is not True:
        status = self.execute(command).__contains__("running")
        if status is True:
            return status
        else:
            continue

希望这种写作风格是好的。如果没有,请征求您的意见

还使用超时选项更新了程序

import subprocess
import time

class MyLibrary(object):
    def execute(self, cmd):
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        out, err = result.communicate()
        return str(out)

    def list(self):
        command = ["<application command>", "list"]
        return self.execute(command)

    def check(self):
        timeout = time.time() + 60
        status = False
        while not status:  # while status is false
            status = "running" in self.list()
            if status or time.time() > timeout:  # if the status is true
                return status
            else:
                continue

相关问题 更多 >