Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/318.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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
Python 当无法访问网页时,如何继续执行脚本?_Python_Python 3.x_If Statement_Urllib - Fatal编程技术网

Python 当无法访问网页时,如何继续执行脚本?

Python 当无法访问网页时,如何继续执行脚本?,python,python-3.x,if-statement,urllib,Python,Python 3.x,If Statement,Urllib,需要做的是,如果可以访问10.10.10.2,则程序应退出(),但如果10.10.10.2在10秒内无法访问,将打开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")

需要做的是,如果可以访问10.10.10.2,则程序应
退出()
,但如果10.10.10.2在10秒内无法访问,将打开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
。这会在给定的时间后引发一个URL错误。您可以捕捉到这个错误 带着

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")