需要做的是,如果10.10.10.2是可访问的,则程序应为exit()
,但如果在10秒内无法访问10.10.10.2,则192.168.100.5将被打开,程序将继续。。。
有人能举一个小例子说明如何做到这一点吗?
import urllib.request
import eventlet
from xml.dom import minidom
import urllib.request
preflash = urllib.request.urlopen("http://10.10.10.2").getcode()
correct = urllib.request.urlopen("http://192.168.100.5").getcode()
print(100*"#")
#eventlet.monkey_patch()
#with eventlet.Timeout(10):
if True:
print("Web page status code:",preflash)
print("Web page is reachable")
else:
print("Web page status code:", correct)
print("Web page is reachable")
url_str = 'http://192.168.100.2/globals.xml'
# open webpage and read values
xml_str = urllib.request.urlopen(url_str).read()
# Parses XML doc to String for Terminal output
xmldoc = minidom.parseString(xml_str)
# Finding the neccassary Set points/ Sollwerte from the xmldoc
# prints the order_number from the xmldoc
order_number = xmldoc.getElementsByTagName('order_number')
print("The Order number of the current device is:", order_number[0].firstChild.nodeValue)
print(100*"-")
使用timeout
参数调用urlopen
。这会在给定时间后引发URLError。您可以捕获此错误尝试一下。。。除了块
import urllib
try:
preflash = urllib.request.urlopen("http://10.10.10.2", timeout=10).getcode()
print("Web page status code:", preflash)
print("Web page is reachable")
except urllib.error.URLError:
correct = urllib.request.urlopen("http://192.168.100.5").getcode()
print("Web page status code:", correct)
print("Web page is reachable")