2015-01-06 39 views
0

我是python的新手,我將在此腳本中使用很多變量。這些變量正用於從上載文件中的每列中獲取數據。我爲每個對象類型添加了變量,並且我添加了約12個以上的對象類型。沒有更好的方法可以做到這一點嗎?我有它從這裏抓取數據的文件:試圖避免在python中創建大量變量

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] 
+1

如何使用字典將對象存儲爲具有特定鍵的值? (例如'{'var1':obj1,'var2':obj2,...}') – Kasramvd

+0

謝謝,這是另一個選項,我會看看。 – bayernmunich

回答

0

如果值是相同的順序每一次,你可以考慮填充列表,然後你可以遍歷,而不是做一個接一個。

您的腳本的「目標」部分,你可以嵌套另一個循環for range(3, 46)以及和指數手工傳遞到您的列表,而不是從3每到46

+0

謝謝!我會去做。我只需要看看訂單是否會以任何方式改變。 – bayernmunich

+0

如果排序不同,您可以使用字典和比較鍵。 – MeetTitan

+0

@bayernmunich,我也認爲你的'else'語句在你的'try'塊之後是多餘的。 – MeetTitan

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() 
+0

好的,謝謝。我認爲將每個部分放入它自己的函數中可能是最好的選擇,尤其是因爲我沒有試圖用硬編碼數據填充它。 – bayernmunich

0

幕後所有成員對象的名稱存儲在dict中。您可以通過vars(obj)obj.__dict__訪問此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) 
+0

我可以創建一個類,這將有助於分隔值,即使它們在同一列中。 – bayernmunich

+0

該類並不意味着如何分離數據,而是如何使用字典填充對象上的名稱。但是,將數據分成三個單獨的字符串來保存每個不同類型對象所需的數據是個不錯的主意。 – Dunes