我创建的字典不是我想要的输出,我不知道我的代码有什么问题。
代码如下:
hostInfoDict = {
'192.168.247.62': {80: 'http', 8080: 'http-proxy'},
'192.168.247.64': {80: 'http', 8080: 'http-proxy'},
'192.168.247.74': {80: 'http', 8080: 'http-proxy'}
}
for host, hostInfo in hostInfoDict.items():
httpHostStatusDict = {}
for port in hostInfo.keys():
urls = 'http://' + host + ":" + str(port) + '/thredds/catalog.html'
#print(urls)
try:
r = requests.get(urls, timeout=0.5, allow_redirects=False)
#print(urls, r.status_code)
except requests.exceptions.HTTPError:
"""An HTTP error occurred."""
pass
except requests.exceptions.ConnectionError:
"""A Connection error occurred."""
pass
except requests.exceptions.Timeout:
"""
The request timed out while trying to connect to the remote server.
Requests that produced this error are safe to retry.
"""
pass
except requests.exceptions.RequestException:
"""
There was an ambiguous exception that occurred while handling your request.
"""
pass
try:
if urls not in httpHostStatusDict:
httpHostStatusDict[urls] = str(r.status_code)
except:
pass
print(httpHostStatusDict)
以上代码的输出如下所示。它们是分开的,而不是整个字典。
{'http://192.168.247.62:80/thredds/catalog.html': '200', 'http://192.168.247.62:8080/thredds/catalog.html': '200'}
{'http://192.168.247.64:80/thredds/catalog.html': '404', 'http://192.168.247.64:8080/thredds/catalog.html': '404'}
{'http://192.168.247.74:80/thredds/catalog.html': '200', 'http://192.168.247.74:8080/thredds/catalog.html': '200'}
预期输出为
{
{'http://192.168.247.62:80/thredds/catalog.html': '200'},
{'http://192.168.247.62:8080/thredds/catalog.html': '200'},
{'http://192.168.247.64:80/thredds/catalog.html': '404'},
{'http://192.168.247.64:8080/thredds/catalog.html': '404'},
{'http://192.168.247.74:80/thredds/catalog.html': '200'},
{'http://192.168.247.74:8080/thredds/catalog.html': '200'}
}
这是一个Python REQUEST项目:)我认为这是一个代码问题,因此我认为您不需要安装该库。 感谢您的帮助。
答案 0 :(得分:1)
您应该在第一个for循环之前放置httpHostStatusDict = {},并在整个第一个for循环之后打印。