Python while循环不退出,为什么?

时间:2014-09-15 17:20:54

标签: python

以下功能等待直到构建RackSpace服务器。之后它返回该服务器对象:

def _wait_for_server(cloud_server, server):
    while server.status != 'ACTIVE':
        sleep(30)
        s = cloud_server.servers.get(server.id)
        print '%s: %s (%s%%)' % (s.id, s.status, s.progress)

    return server

至少它应该如此!相反,当服务器状态达到Active时,while循环继续运行并且永不退出。为什么会这样?

以下是显示上述代码的终端输出:

7cbadf1b-1090-40d5-9437-9869ca392b5a: BUILD (10%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: BUILD (10%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: BUILD (10%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: BUILD (10%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: BUILD (40%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: BUILD (40%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: BUILD (40%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: BUILD (40%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: BUILD (70%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: BUILD (80%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: ACTIVE (100%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: ACTIVE (100%)
7cbadf1b-1090-40d5-9437-9869ca392b5a: ACTIVE (100%)
... runs until the end of time or my laptop battery runs out

2 个答案:

答案 0 :(得分:1)

在循环中,变量server永远不会更新。您应该添加break语句以从循环中退出:

def _wait_for_server(cloud_server, server):
    while True:
        sleep(30)
        s = cloud_server.servers.get(server.id)
        print '%s: %s (%s%%)' % (s.id, s.status, s.progress)
        if s.status == 'ACTIVE':
            break

    return server

或更新server而不是s

def _wait_for_server(cloud_server, server):
    while server.status != 'ACTIVE':
        sleep(30)
        server = cloud_server.servers.get(server.id)
        print '%s: %s (%s%%)' % (server.id, server.status, server.progress)

    return server

答案 1 :(得分:1)

我怀疑" s"和"服务器"变量有不同的值。您正在从网络中检索s,但从不对服务器执行任何操作。 我敢打赌,如果你把

server = s

在那里,它将开始工作。