首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >主机服务字典分类

主机服务字典分类
EN

Stack Overflow用户
提问于 2018-08-22 10:05:36
回答 1查看 22关注 0票数 0

我创建的字典不是我想要的输出,我不知道我的代码有什么问题。

代码如下:

代码语言:javascript
复制
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)

上述代码的输出如下所示。它们是分开的,而不是整个字典。

代码语言:javascript
复制
{'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'}

预期输出为

代码语言:javascript
复制
{
 {'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请求项目:)我认为这是一个代码问题,所以我不认为你需要安装库。你的帮助是我的谢意。

EN

回答 1

Stack Overflow用户

发布于 2018-08-22 10:13:50

您应该将httpHostStatusDict = {}放在第一个for循环之前,而print应该放在整个第一个for代码之后。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51958953

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档