当使用'with open'时,Python脚本只读取最后一行。

我正在使用 pyzabbix 模块通过 Zabbix API 查询一些数据。脚本正在读取我使用-f开关指定的文本文件,并且应该返回每一行数据或主机不存在,但当我运行它时,它只返回文本文件的最后一行。

示例数据文件是:。

server1
server2

它只会返回:

host server2 exist, hostid : 4517, group: [u'Servergroup1', u'Servergroup2']

我的代码是:

import optparse
import sys
import traceback
from getpass import getpass
from core import ZabbixAPI

def get_options():
    usage = "usage: %prog [options]"
    OptionParser = optparse.OptionParser
    parser = OptionParser(usage)

    parser.add_option("-s","--server",action="store",type="string",\
        dest="server",help="(REQUIRED)Zabbix Server URL.")
    parser.add_option("-u", "--username", action="store", type="string",\
        dest="username",help="(REQUIRED)Username (Will prompt if not given).")
    parser.add_option("-p", "--password", action="store", type="string",\
        dest="password",help="(REQUIRED)Password (Will prompt if not given).")
    parser.add_option("-H","--hostname",action="store",type="string",\
        dest="hostname",help="(REQUIRED)hostname for hosts.")
    parser.add_option("-f","--file",dest="filename",\
        metavar="FILE",help="Load values from input file. Specify - for standard input Each line of file contains whitespace delimited: <hostname>")

    options,args = parser.parse_args()

    if not options.server:
        options.server = raw_input('server http:')

    if not options.username:
        options.username = raw_input('Username:')

    if not options.password:
        options.password = getpass()

    return options, args

def errmsg(msg):
    sys.stderr.write(msg + "\n")
    sys.exit(-1)

if __name__ == "__main__":
    options, args = get_options()

    zapi = ZabbixAPI(options.server,options.username, options.password)

    hostname = options.hostname
    file = options.filename

    if file:
        with open(file,"r") as f:
            host_list = f.readlines()
        for hostname in host_list:
            hostname = hostname.rstrip()
        try:
                    hostinfo = zapi.host.get({"filter":{"host":hostname},"output":"hostid", "selectGroups": "extend", "selectParentTemplates": ["templateid","name"]})[0]
                    hostid = hostinfo["hostid"]
                    host_group_list = []
                    host_template_list = []
                    for l in hostinfo["groups"]:
                        host_group_list.append(l["name"])
                    for t in hostinfo["parentTemplates"]:
                        host_template_list.append(t["name"])
                    #print "host %s exist, hostid : %s, group: %s, template: %s " % (hostname, hostid, host_group_list, host_template_list)
                    print "host %s exist, hostid : %s, group: %s" % (hostname, hostid, host_group_list)
        except:
                    print "host not exist: %s" %hostname
    else:
        try:
            hostinfo = zapi.host.get({"filter":{"host":hostname},"output":"hostid", "selectGroups": "extend", "selectParentTemplates": ["templateid","name"]})[0]
            hostid = hostinfo["hostid"]
            host_group_list = []
            host_template_list = []
            for l in hostinfo["groups"]:
                host_group_list.append(l["name"])
            for t in hostinfo["parentTemplates"]:
                host_template_list.append(t["name"])
            print "host %s exist, hostid : %s, group: %s, template: %s " % (hostname, hostid, host_group_list, host_template_list)
        except:
            print "host not exist: %s" %hostname

解决方案:

你的尝试块的缩进程度不正确。你的 try 块的缩进级别不正确。

        for hostname in host_list:
            hostname = hostname.rstrip()
        try:
                    ...
        except:
                    print "host not exist: %s" %hostname

应该是


    for hostname in host_list:
        hostname = hostname.rstrip()
        try:
                ...
        except:
                print "host not exist: %s" %hostname

给TA打赏
共{{data.count}}人
人已打赏
未分类

根据之前查询的结果,在MySQL中运行不同的SELECT命令。

2022-9-8 8:15:35

未分类

如何在退出conda环境时添加删除update包?

2022-9-8 8:15:37

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索