试图避免在python中创建大量变量

时间:2015-01-06 22:02:54

标签: python

我是python的新手,我将在这个脚本中使用很多变量。这些变量用于从上载文件中的每列中获取数据。我为每个对象类型添加了变量,我还要添加12个以上的对象类型。难道我有更好的方法可以做到这一点吗?我有文件,它从这里抓取数据:

Action  Object  Solution ID hostgroup_name  alias
Add Host Group  ISD-CR  ISD-CR_database ISD-CR Database
Add Service ISD-CR  ISD-CR_database 
Update  Service Group   ISD-CR      ISD-CR Database
Delete  Service ISD-CR  ISD-CR_database 

这是我到目前为止的脚本。

from pynag import Model
from pynag.Parsers import config 
def addObject():

            # Add hostgroup object
            hg = Model.Hostgroup()

            hg.set_filename('/etc/nagios/objects/solution1/{0}.cfg'.format(target_hostgroup_name))

            # Adding all attributes to allow any to be added if needed
            hg.hostgroup_name = target_hostgroup_name
            hg.alias = target_alias
            hg.members = target_members
            hg.hostgroup_members = target_hostgroup_members
            hg.notes = target_notes
            hg.notes_url = target_notes_url
            hg.action_url = target_action_url

            # Save
            hg.save()

            print "hostgroup added"

            # Add service object
            s = Model.Service()

            s.set_filename('/etc/nagios/objects/solution1/{0}.cfg'.format(target_hostgroup_name))

            # Adding all attributes to allow any to be added if needed
            s.host_name = target_host_name
            s.hostgroup_name = target_hostgroup_name
            s.service_description = target_service_description
            s.display_name = target_display_name
            s.servicegroups = target_servicegroups
            s.is_volatile = target_is_volatile
            s.check_command = target_check_command
            s.initial_state = target_initial_state
            s.max_check_attempts = target_max_check_attempts
            s.check_interval = target_check_interval
            s.retry_interval = target_retry_interval
            s.active_checks_enabled = target_active_checks_enabled
            s.passive_checks_enabled = target_passive_checks_enabled
            s.check_period = target_check_period
            s.obsess_over_service = target_obsess_over_service
            s.check_freshness = target_check_freshness
            s.freshness_threshold = target_freshness_threshold
            s.event_handler = target_event_handler
            s.event_handler_enabled = target_event_handler_enabled
            s.low_flap_threshold = target_low_flap_threshold
            s.high_flap_threshold = target_high_flap_threshold
            s.flap_detection_enabled = target_flap_detection_enabled
            s.flap_detection_options = target_flap_detection_options
            s.process_perf_data = target_process_perf_data
            s.retain_status_information = target_retain_status_information
            s.retain_nonstatus_information = target_retain_nonstatus_information
            s.notification_interval = target_notification_interval
            s.first_notification_delay = target_first_notification_delay
            s.notification_period = target_notification_period 
            s.notification_options = target_notification_options
            s.notification_enabled = target_notifications_enabled
            s.contacts = target_contacts
            s.contact_groups = target_contact_groups
            s.stalking_options = target_stalking_options
            s.notes = target_notes
            s.notes_url = target_notes_url
            s.action_url = target_action_url
            s.icon_image = target_icon_image
            s.icon_image_alt = target_icon_image_alt

            # Save
            s.save()

            print "service added"

            # Add servicegroup object
            sg = Model.Servicegroup()

            sg.set_filename('/etc/nagios/objects/solution1/{0}.cfg'.format(target_hostgroup_name))

            # Adding all attributes to allow any to be added if needed
            sg.servicegroup_name = target_servicegroup_name
            sg.alias = target_alias
            sg.members = target_members
            sg.servicegroup_members = target_servicegroup_members
            sg.notes = target_notes
            sg.notes_url = target_notes_url
            sg.action_url = '/etc/nagios/objects/solution1/{0}.cfg'.format(target_hostgroup_name)

            # Save        
            sg.save()

            print "service group added"

try:
        current_file = csv.reader(open(input_file, "rb"), delimiter='\t')
    except:  
        logging.error('No such file or directory. Please try again')
    else:
        for line in current_file:        
            for row in current_file:

                target_hostgroup_name = row[3]
                target_alias = row[4]
                target_members = row[5]
                target_hostgroup_members = row[6]
                target_notes = row[7]
                target_notes_url = row[8]
                target_action_url = row[9]
                target_host_name = row[10]
                target_service_description = row[11]
                target_display_name = row[12]
                target_servicegroups = row[13]
                target_is_volatile = row[14]
                target_check_command = row[15]
                target_initial_state = row[16]
                target_max_check_attempts = row[17]
                target_check_interval = row[18]
                target_retry_interval = row[19]
                target_active_checks_enabled = row[20]
                target_passive_checks_enabled = row[21]
                target_check_period = row[22]
                target_obsess_over_service = row[23]
                target_check_freshness = row[24]
                target_freshness_threshold = row[25]
                target_event_handler = row[26]
                target_event_handler_enabled = row[27]
                target_low_flap_threshold = row[28]
                target_high_flap_threshold = row[29]
                target_flap_detection_enabled = row[30]
                target_flap_detection_options = row[31]
                target_process_perf_data = row[32]
                target_retain_status_information = row[33]
                target_retain_nonstatus_information = row[34]
                target_notification_interval = row[35]
                target_first_notification_delay = row[36]
                target_notification_period = row[37]
                target_notification_options = row[38]
                target_notifications_enabled = row[39]
                target_contacts = row[40]
                target_contact_groups = row[41]
                target_stalking_options = row[42]
                target_icon_image = row[43]
                target_icon_image_alt = row[44]
                target_servicegroup_name = row[45]
                target_servicegroup_members = row[46]

3 个答案:

答案 0 :(得分:0)

如果值每次都以相同的顺序排列,您可以考虑填充一个然后可以循环的列表,而不是逐个执行。

对于脚本的“目标”部分,您也可以嵌套另一个循环for range(3, 46),并将索引传递到列表,而不是手动传递从3到46的每个数字。

答案 1 :(得分:0)

你为什么这样做?

for line in current_file:
    for row in current_file:

如果第一行是标题行并且您故意跳过它,则可以改为使用DictReader

看起来你并没有能够做很多事情来清理它,但是你可以把每个"部分分解出去"进入自己的职能:

def save_hostgroup(name, alias, members, hostgroup_members, notes, notes_url, action_url):
    hg = Model.Hostgroup()
    hg.set_filename('/etc/nagios/objects/solution1/{0}.cfg'.format(target_hostgroup_name))

    # Adding all attributes to allow any to be added if needed
    hg.hostgroup_name = target_hostgroup_name
    hg.alias = target_alias
    hg.members = target_members
    hg.hostgroup_members = target_hostgroup_members
    hg.notes = target_notes
    hg.notes_url = target_notes_url
    hg.action_url = target_action_url

    hg.save()

答案 2 :(得分:0)

在幕后,对象的所有成员名称都存储在dict中。您可以使用dictvars(obj)访问此obj.__dict__。然后,您可以使用dict的更新方法为对象添加一组名称。

例如

class SomeClass:
    def __str__(self):
        return "SomeClass({})".format(
            ", ".join(
                "{}={!r}".format(key, value) 
                    for key, value in self.__dict__.items()
            )
        )
    __repr__ = __str__

target_names = ['var_a', 'var_b', 'var_c']
target_values = [1, 2, 3]

target = dict(zip(target_names, target_values))
assert target == {'var_a': 1, 'var_b': 2, 'var_c': 3}

s = SomeClass()
vars(s).update(target)

assert hasattr(s, 'var_a')
assert s.var_a == 1
print(s) # prints SomeClass(var_c=3, var_a=1, var_b=2)
相关问题