Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python2.7中轮询最大等待时间,除非条件为_Python_Python 2.7_Wait_Polling - Fatal编程技术网

在Python2.7中轮询最大等待时间,除非条件为

在Python2.7中轮询最大等待时间,除非条件为,python,python-2.7,wait,polling,Python,Python 2.7,Wait,Polling,我有一个函数,它执行shell命令在机器上部署服务器。此函数采用以下参数: 目录路径 命令 服务器端口 等待时间 现在,一旦从目录路径内执行命令,函数time.sleeps直到等待时间,然后检查在服务器端口上侦听的进程 虽然这种方法是有效的,但它确实为命令s浪费了大量时间,因为它启动所用的时间远远小于等待时间 我计划创建一个服务生,它将等待最长的等待时间,但会定期小间隔轮询服务器端口。如果在等待时间结束之前发现了进程,我希望函数仅从该点安全返回,并且在结束之前不会阻止进程 我不知道如何进行同

我有一个函数,它执行shell命令在机器上部署服务器。此函数采用以下参数:

  • 目录路径
  • 命令
  • 服务器端口
  • 等待时间
现在,一旦从
目录路径
内执行
命令
,函数
time.sleep
s直到
等待时间
,然后检查在
服务器端口
上侦听的进程

虽然这种方法是有效的,但它确实为
命令
s浪费了大量时间,因为它启动所用的时间远远小于
等待时间

我计划创建一个服务生,它将等待最长的
等待时间
,但会定期小间隔轮询
服务器端口
。如果在
等待时间结束之前发现了进程,我希望函数仅从该点安全返回,并且在结束之前不会阻止进程

我不知道如何进行同样的工作。我能想到的最接近的方法是创建一个poll对象(使用
select.poll
),但是一个示例(或者一个包,如果有的话)会对我有很大帮助

我当前的功能类似于:

run_local_command(
    ['nohup', start_command, ">>", logfile, '2>>', errfile, '&'],
    explanation="Starting server",
    target_dir=target_dir
)
time.sleep(wait_time)
# Get the PIDs listening to the specific port
processes = [
    p for p in psutil.net_connections(kind='inet')
    if p.laddr[1] == port and p.status == 'LISTEN'
]
logger.debug("Logged following processes for the service port: %s", processes)
pids = [x.pid for x in processes if x.pid is not None]

我通常用来等待条件满足或超时的是一个小函数,如下所示:

def wait_condition(condition, timeout=5.0, granularity=0.3, time_factory=time):
    end_time = time.time() + timeout   # compute the maximal end time
    status = condition()               # first condition check, no need to wait if condition already True
    while not status and time.time() < end_time:    # loop until the condition is false and timeout not exhausted
        time.sleep(granularity)        # release CPU cycles
        status = condition()           # check condition
    return status                      # at the end, be nice and return the final condition status : True = condition satisfied, False = timeout occurred.
def port_opened():
    return [p for p in psutil.net_connections(kind='inet') if p.laddr[1] == port and p.status == 'LISTEN']    # assuming that an empty list is False in python

似乎是一个简单的方法。。。不知道为什么我会跳入@hjpotter92链接的答案可以用来等待多个条件的实现,您的问题似乎只有一个停止条件,在这种情况下,这是一个好原则:)