我有以下Python 2.7代码:
def getGateway():
""" Use the configuration to determine valid gateway
If more GWs are present, one will be chosen by random.choice
"""
localServer = ThisLocalServer(log=LOG)
gw=localServer.getRandomAgentGateway()
print "See if its a string %s - %s" % (gw,type(gw))
candidate = "gw"
response = os.system("ping -c 1 " + candidate)
if response == 0:
print candidate, 'is up!'
return gw
else:
print candidate, 'is down we need a new gatewuy'
用例如下: 我的软件使用getRandomAgentGateway确定IP。不幸的是,它不像我想要的那样智能,有时结果是无法访问的IP。我想构建一个ping检查,它将: A)使用已经内置的getRandomAgentGateway获取一个IP(列表中只有两个) B)Ping IP C)确保该IP是可达的,如果是 - 提供可达的IP,中断循环并执行"返回gw"如果不是 - 留在循环中并调用" getRandomAgentGateway()"再次找到可达的IP
我无法修改getRandomAgentGateway,所以我想在这里构建ping检查。任何帮助将受到高度赞赏。
答案 0 :(得分:0)
您的逻辑中似乎有错误。
candidate = "gw"
似乎做错了。你需要的可能是
if isinstance(gw,str):
# do whatever
实际上,为什么getRandomAgentGateway会返回其他答案而不是str?
最后,为了实现这一点,你可能应该尝试不止一次,写下类似的东西:
def teste():
max_number_of_tries = 2
current_try = 0
while current_try < max_number_of_tries:
gw=getRandomAgentGateway()
if isinstance(gw,str):
response = os.system("ping " + gw)
if response == 0:
print( gw, 'is up!')
return gw
else:
print( gw, 'is down we need a new gatewuy, trying again')
current_try += 1
print ( "Too much tries" )