Python: assign a list to a function - python

Is there a way to assign a list based on a variable env and pass the result to function? I am passing a variable called env, which could be UPE, DEV, PRD for example. Based on the result, I want to assign the list respectively to the functions below. What would be the best approach?
UPE=['SERVER1','SERVER2','SERVER3','SERVER4']
DEV=['ServerA','ServerB']
PRD=['SERVER1','SERVER2','SERVER3','SERVER4']
if os.path.isfile('/myfile/' + configFile):
config_parser = ConfigParser()
config_parser.read('/myfile/' + configFile)
if actions == "start":
startOVD('start',UPE[3]) //I want pass the result of env setup variable
#ans = raw_input("Would you like to start OVD, MSAS,OAG : y | n : ")
if env == 'UPE':
startMSAS('start',UPE[0])
startOAG('start',UPE[1])
startOHS('start',UPE[2])
for section_name in sorted(config_parser.sections(), reverse=True):
adminURL = config_parser.get(section_name, 'ADMIN_URL')
adminUsername = config_parser.get(section_name, 'ADMIN_USER')
adminPassword = config_parser.get(section_name, 'ADMIN_PASS')
adminHost = config_parser.get(section_name, 'NM_HOST')
domainName = config_parser.get(section_name, 'DOMAIN_NAME')
domainDir = config_parser.get(section_name, 'DOMAIN_DIR')
admPort = adminURL[-4:]
printHeader('Initiating Starting Sequence')
startAdmin('start', adminHost, domainDir, domainName, admPort)
showServerStatus('start', adminUsername, adminPassword, adminURL)
if actions == "stop":
for section_name in (config_parser.sections()):
adminURL = config_parser.get(section_name, 'ADMIN_URL')
adminUsername = config_parser.get(section_name, 'ADMIN_USER')
adminPassword = config_parser.get(section_name, 'ADMIN_PASS')
adminHost = config_parser.get(section_name, 'NM_HOST')
domainName = config_parser.get(section_name, 'DOMAIN_NAME')
domainDir = config_parser.get(section_name, 'DOMAIN_DIR')
admPort = adminURL[-4:]
printHeader('Initiating Stopping Sequence')
showServerStatus('stop', adminUsername, adminPassword, adminURL)
stopAdmin(adminHost, domainDir, domainName, admPort)
if env == 'UPE':
stopMSAS('stop',UPE[0])
stopOAG('stop',UPE[1])
stopOHS('stop',UPE[2])
stopOVD('stop',UPE[3])

I would organize this by setting up a list of callbacks.
from functools import partial
start_funcs = [partial(startOVD 'start',UPE[3])
if env == 'UPE':
start_funcs.extend([partial(startMSAS, 'start', UPE[0]),
partial(startOAG, 'start', UPE[1])])
start_funcs.append(partial(startOHS, 'start', UPE[2]))
Add similar logic for the cases when env has a different value. In the end, you'll just iterate over start_funcs and call each function in order.
if actions == "start":
for f in start_funcs:
f()
# ...

Related

text files are empty after I run my script

TL;DR
When I run my program it deletes all my txt file data, I do not understand why.
I'm making a waypoint editor/saver for my robot arm, and this program is meant to allow me to choose from a 'set' which is just a txt file, and then change or set a new point in that 'set' and it works to an extent. when I run the program I can enter a point, change values and save them, and if I choose to set another point my old point is still there, and if I end the program I can check the txt file and it has all the values. the problem is when I rerun the program, even if I don't get past the first input command, and I stop it immediately it will clear all my text files, and I haven't even chosen witch txt file to edit, I understand that it will run all imported modules when I run the program, but none of those subprograms were giving me grief in my other version of my robot arm control system so I am at a loss as to what I'm doing wrong, I've been at this problem for 2 days now and haven't gotten anywhere. I apologize for my total lack of commenting, I'm trying to work on that but I was excited to make this program and got carried away.
from machine import Pin, PWM, ADC, I2C
from time import sleep
import Move
from pico_i2c_lcd import I2cLcd
def EDITMODE():
analog_value = machine.ADC(28)
i2c = I2C(0, sda=Pin(0), scl =Pin(1), freq=400000)
I2C_ADDR = i2c.scan()[0]
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
stv=0
base = PWM(Pin(18))
base.freq(50)
lcdt = 1
j2 = PWM(Pin(19))
j2.freq(50)
j3 = PWM(Pin(20))
j3.freq(50)
claw = PWM(Pin(21))
claw.freq(50)
buttonmove = 20000
b1 = Pin(2, Pin.IN, Pin.PULL_DOWN)
b2 = Pin(3, Pin.IN, Pin.PULL_DOWN)
b3= Pin(4, Pin.IN, Pin.PULL_DOWN)
b4= Pin(5, Pin.IN, Pin.PULL_DOWN)
b5= Pin(6, Pin.IN, Pin.PULL_DOWN)
b6= Pin(7, Pin.IN, Pin.PULL_DOWN)
b7= Pin(8, Pin.IN, Pin.PULL_DOWN)
b8= Pin(9, Pin.IN, Pin.PULL_DOWN)
b9= Pin(10, Pin.IN, Pin.PULL_DOWN)
b10= Pin(11, Pin.IN, Pin.PULL_DOWN)
b11= Pin(12, Pin.IN, Pin.PULL_DOWN)
b12= Pin(13, Pin.IN, Pin.PULL_DOWN)
bshift= Pin(14, Pin.IN, Pin.PULL_DOWN)
l1led = Pin(16, Pin.OUT)
l2led= Pin(17, Pin.OUT)
global gha
gha = 0
buttonmove = 5000
j1v =1222500
j4v =1282500
j2v =1312500
j3v=1762500
break1 = 0
while True:
if break1 ==1:
break
#decides which waypoint to edit
eprog = int(input('Which Set would you like to edit (1-5) '))
if eprog == 1:
curentprogram = 'Prog1.txt'
elif eprog == 2:
curentprogram = 'Prog2.txt'
elif eprog == 3:
curentprogram = 'Prog3.txt'
elif eprog == 4:
curentprogram = 'Prog4.txt'
elif eprog == 5:
curentprogram = 'Prog5.txt'
file = open(curentprogram, "r")
WPL = file.readlines()
file.close()
x = len(WPL)
print(WPL)
print('There are ', str(x/6), ' Waypoints currently set')
epoint1 = int(input('Which waypoint would you like to set? '))
epoint = (epoint1*6)
if epoint >0:
epoint = epoint+1
print('Move robot to desired position then save waypoint')
sleepvalue = 0
while True:
b1v = b1.value()
b2v = b2.value()
b3v = b3.value()
b4v = b4.value()
b5v = b5.value()
b6v = b6.value()
b7v = b12.value()
b8v = b11.value()
b9v = b10.value()
b10v = b9.value()
b11v = b8.value()
b12v = b7.value()
shiftb = bshift.value()
if shiftb == 1:
l2led(0)
if b1v ==1:
j1v = j1v+buttonmove
if b12v ==1:
j1v = j1v-buttonmove
if b2v ==1:
j2v = j2v+buttonmove
if b11v ==1:
j2v = j2v-buttonmove
if b3v ==1:
j4v = j4v - buttonmove
if b10v ==1:
j4v = j4v + buttonmove
if b4v ==1:
j3v = j3v+buttonmove
if b9v ==1:
j3v = j3v-buttonmove
else:
l2led(1)
if b6v == 1:
sleepvalue = sleepvalue+1
print('sleep time =', sleepvalue)
sleep(.5)
if b7v == 1:
sleepvalue = sleepvalue-1
if sleepvalue < 0:
sleepvalue = 0
print('sleep time =', sleepvalue)
sleep(.5)
if b1v == 1:
print(epoint, x)
if epoint+.01 > (x/6):
print('value not written, new waypoint value = ', str((x/6)+1))
WPL.append(j1v)
WPL.append(j2v)
WPL.append(j3v)
WPL.append(j4v)
WPL.append(x/6)
WPL.append(sleepvalue)
else:
print('Saving Point')
print(epoint)
epoint = int(epoint)
WPL[epoint] = j1v
WPL[epoint+1] = j2v
WPL[epoint+2] = j3v
WPL[epoint+3] = j4v
WPL[epoint+4] = (epoint/6)
WPL[epoint+5] = sleepvalue
print(WPL)
file = open(curentprogram, 'w')
file.write('')
file.close
file = open(curentprogram, 'a')
print(WPL)
for item in WPL:
print(item, 'bannana')
file.write((str(item))+'\n')
file.close()
restart = input('would you like to set another point? (y/n) ')
if restart == 'n' or restart == 'N':
return
else:
break
sleep(.025)
print(j1v, j2v, j3v, j4v)
#base.duty_ns(int(j1v))
#j2.duty_ns(int(j2v))
#j3.duty_ns(int(j3v))
#claw.duty_ns(int(j4v))
if __name__ == '__main__':
print('hello')
EDITMODE()
The issue comes from the following line:
file = open(curentprogram, 'w')
When appending data to a file, you must use mode a for append. Otherwise, when using w, if a file with that name exists, it is removed.
According to the documentation:
[...] mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end.
EDIT
Since I cannot run your code, I would suggest you to start with a simpler script and start building up yours from there. For instance, lets some.txt be a text file with he following content:
$ cat some.txt
foo
Then you can experiment with the following code:
with open('some.txt', 'r') as file:
lines = file.readlines()
print(lines)
# this prints: ['foo\n']
with open('some.txt', 'w') as file:
file.write('')
with open('some.txt', 'a') as file:
file.write('bar\n')
then:
$ cat some.txt
bar
So, this logic seems to work fine. From here, try to see what you are doing and how it might affect the i/o operations.

Python Json value overwritten by last value

lista =
[{Identity: joe,
summary:[
{distance: 1, time:2, status: idle},
{distance:2, time:5, status: moving}],
{unit: imperial}]
I can pull the data easily and put in pandas. The issue is, if an identity has multiple instances of, say idle, it takes the last value, instead of summing together.
my code...
zdrivershours = {}
zdistance = {}
zstophours = {}
For driver in resp:
driverid[driver['AssetID']] = driver['AssetName']
for value in [driver['SegmentSummary']]:
for value in value:
if value['SegmentType'] == 'Motion':
zdriverhours[driver['AssetID']] = round(value['Time']/3600,2)
if value['SegmentType'] == 'Stop':
zstophours[driver['AssetID']] = round(value['IdleTime']/3600,2)
zdistance[driver['AssetID']] = value['Distance']
To obtain the summatory of distance for every driver replace:
zdistance[driver['AssetID']] = value['Distance']
by
if driver['AssetID'] in zdistance:
zdistance[driver['AssetID']] = zdistance[driver['AssetID']] + value['Distance']
else:
zdistance[driver['AssetID']] = value['Distance']

Combobox in tkinter not giving correct .get() value

This so weird, like i am trying to use if statement and the selection in combobox to do some specific command and when combobox value is selected to 'full_name' (part of elif) they return an messagebox, that is supposed to be showed only when the first if statement is executed but according to the conditions its supposed to return the elif part but it returns the if part. Is there a mistake in my code? If the Q is unclear please try referring the code or lemme knw :) Thanks in advance.
CODE:
def sp_patient():
#Creating window
sp_pat = Toplevel(update)
sp_pat.title('Choose Patient')
def search():
#Assigning variable to .get()
a = drops.get()
if a == 'id' or 'emirate_id' or 'email_adress' or 'gender' or 'DOB' or 'blood_grp' or 'COVID_test':
#Establishing connection
con = mysql.connect(host='***', user='nihaalnz',
password='****', database='nihaalnztrying')
# Making SQL command
c = con.cursor()
c.execute(f"SELECT * FROM patient_infos where `{a}` = '{e_1.get()}'")
# Executing and saving SQL command
records = c.fetchall()
if records == []:
messagebox.showinfo('Does not exist!','Sorry such patient does not exist')
else:
#Creating window
result_win = Toplevel(sp_pat)
result_win.title('Search result')
index=0
for index,x in enumerate(records):
num=0
for y in x:
lookup_label = Label(result_win,text=y)
lookup_label.grid(row=index+1,column=num)
num += 1
#Closing connection
con.close()
#Creating column header and exit button
l_1 = Label(result_win,text='ID',font=font_text)
l_2 = Label(result_win,text='Full Name',font=font_text)
l_3 = Label(result_win,text='Phone no.',font=font_text)
l_4 = Label(result_win,text='Emirates ID',font=font_text)
l_5 = Label(result_win,text='Email addr.',font=font_text)
l_6 = Label(result_win,text='Gender',font=font_text)
l_7 = Label(result_win,text='DOB',font=font_text)
l_8 = Label(result_win,text='Nationality',font=font_text)
l_9 = Label(result_win,text='Blood group',font=font_text)
l_10 = Label(result_win,text='COVID test',font=font_text)
l_11 = Label(result_win,text='Emergency no.',font=font_text)
btn_ext = Button(result_win,text='Exit',font=font_text,command=result_win.destroy,borderwidth=2,fg='#eb4d4b')
#Placing it in screen
l_1.grid(row=0,column=0,padx=20)
l_2.grid(row=0,column=1,padx=20)
l_3.grid(row=0,column=2,padx=20)
l_4.grid(row=0,column=3,padx=20)
l_5.grid(row=0,column=4,padx=20)
l_6.grid(row=0,column=5,padx=20)
l_7.grid(row=0,column=6,padx=20)
l_8.grid(row=0,column=7,padx=20)
l_9.grid(row=0,column=8,padx=20)
l_10.grid(row=0,column=9,padx=20)
l_11.grid(row=0,column=10,padx=20)
btn_ext.grid(row=index+2,columnspan=11,ipadx=240,sticky=E+W)
elif a == 'full_name' or 'ph_no' or 'nationality' or 'emergency_no':
#Creating window
result_win = Toplevel(sp_pat)
result_win.title('Search result')
#Establishing connection
con = mysql.connect(host='****', user='nihaalnz',
password='*****', database='nihaalnztrying')
# Making SQL command
c = con.cursor()
c.execute(f"SELECT * FROM patient_infos where `{a}` regexp '{e_1.get()}'")
# Executing and saving SQL command
records = c.fetchall()
index=0
for index,x in enumerate(records):
num=0
for y in x:
lookup_label = Label(result_win,text=y)
lookup_label.grid(row=index+1,column=num)
num += 1
#Closing connection
con.close()
#Creating column headers and exit button
l_1 = Label(result_win,text='ID',font=font_text)
l_2 = Label(result_win,text='Full Name',font=font_text)
l_3 = Label(result_win,text='Phone no.',font=font_text)
l_4 = Label(result_win,text='Emirates ID',font=font_text)
l_5 = Label(result_win,text='Email addr.',font=font_text)
l_6 = Label(result_win,text='Gender',font=font_text)
l_7 = Label(result_win,text='DOB',font=font_text)
l_8 = Label(result_win,text='Nationality',font=font_text)
l_9 = Label(result_win,text='Blood group',font=font_text)
l_10 = Label(result_win,text='COVID test',font=font_text)
l_11 = Label(result_win,text='Emergency no.',font=font_text)
btn_ext = Button(result_win,text='Exit',font=font_text,command=result_win.destroy,borderwidth=2,fg='#eb4d4b')
#Placing it on screen
l_1.grid(row=0,column=0,padx=20)
l_2.grid(row=0,column=1,padx=20)
l_3.grid(row=0,column=2,padx=20)
l_4.grid(row=0,column=3,padx=20)
l_5.grid(row=0,column=4,padx=20)
l_6.grid(row=0,column=5,padx=20)
l_7.grid(row=0,column=6,padx=20)
l_8.grid(row=0,column=7,padx=20)
l_9.grid(row=0,column=8,padx=20)
l_10.grid(row=0,column=9,padx=20)
l_11.grid(row=0,column=10,padx=20)
btn_ext.grid(row=index+2,columnspan=11,ipadx=240,sticky=E+W)
elif a == 'Search by...':
#Error message
messagebox.showinfo('No choice given','Please choose a valid option to search by...')
#Defining dropdown and entry box
drops = ttk.Combobox(sp_pat,value=['Search by...','id','full_name','ph_no','emirate_id','email_addr','gender','DOB','nationality','blood_grp','COVID_test','emergency_no'],state='readonly')
print(drops.get())
drops.current(0)
e_1 = Entry(sp_pat)
#Defining Labels and search button
l_sch = Label(sp_pat,text='Search',font=Font(size='20'))
l_id = Label(sp_pat,text='Enter',font=font_text)
bt_db = Button(sp_pat,text='Search',command=search)
#Placing it in screen
drops.grid(row=1,columnspan=3,ipady=5,padx=5,pady=10)
e_1.grid(row=2,column=1,ipady=5,padx=5,pady=5)
l_id.grid(row=2,column=0,padx=5,pady=5)
bt_db.grid(row=3,columnspan=2,padx=5,pady=5,sticky=E+W)
l_sch.grid(row=0,columnspan=2,sticky=E+W,padx=10,pady=10)
The problem is this line:
if a == 'id' or 'emirate_id' or...
This statement always return True. It is evaluating whether a=="id" or emirate_id is True, and a non-empty string always returns True.
You can be explicit and use:
if a == 'id' or a == 'emirate_id' or ...
Or better yet, use keyword in:
if a in ("id", "emirate_id",...)

Parsing Security Matrix Spreadsheet - NoneType is not Iterable

Trying to Nest no's and yes's with their respective applications and services.
That way when a request comes in for a specific zone to zone sequence, a check can be run against this logic to verify accepted requests.
I have tried calling Decision_List[Zone_Name][yes_no].update and i tried ,append when it was a list type and not a dict but there is no update method ?
Base_Sheet = range(5, sh.ncols)
Column_Rows = range(1, sh.nrows)
for colnum in Base_Sheet:
Zone_Name = sh.col_values(colnum)[0]
Zone_App_Header = {sh.col_values(4)[0]:{}}
Zone_Svc_Header = {sh.col_values(3)[0]:{}}
Zone_Proto_Header = {sh.col_values(2)[0]:{}}
Zone_DestPort_Header = {sh.col_values(1)[0]: {}}
Zone_SrcPort_Header = {sh.col_values(0)[0]: {}}
Decision_List = {Zone_Name:{}}
for rows in Column_Rows:
app_object = sh.col_values(4)[rows]
svc_object = sh.col_values(3)[rows]
proto_object = sh.col_values(3)[rows]
dst_object = sh.col_values(2)[rows]
src_object = sh.col_values(1)[rows]
yes_no = sh.col_values(colnum)[rows]
if yes_no not in Decision_List[Zone_Name]:
Decision_List[Zone_Name][yes_no] = [app_object]
else:
Decision_List[Zone_Name]=[yes_no].append(app_object)
I would like it present info as follows
Decision_List{Zone_Name:{yes:[ssh, ssl, soap], no:
[web-browsing,facebook]}}
I would still like to know why i couldnt call the append method on that specific yes_no key whos value was a list.
But in the mean time, i made a work around of sorts. I created a set as the key and gave the yes_no as the value. this will allow me to pair many no type values with the keys being a set of the application, port, service, etc.. and then i can search for yes values and create additional dicts out of them for logic.
Any better ideas out there i am all ears.
for rownum in range(0, sh.nrows):
#row_val is all the values in the row of cell.index[rownum] as determined by rownum
row_val = sh.row_values(rownum)
col_val = sh.col_values(rownum)
print rownum, col_val[0], col_val[1: CoR]
header.append({col_val[0]: col_val[1: CoR]})
print header[0]['Start Port']
dec_tree = {}
count = 1
Base_Sheet = range(5, sh.ncols)
Column_Rows = range(1, sh.nrows)
for colnum in Base_Sheet:
Zone_Name = sh.col_values(colnum)[0]
Zone_App_Header = {sh.col_values(4)[0]:{}}
Zone_Svc_Header = {sh.col_values(3)[0]:{}}
Zone_Proto_Header = {sh.col_values(2)[0]:{}}
Zone_DestPort_Header = {sh.col_values(1)[0]: {}}
Zone_SrcPort_Header = {sh.col_values(0)[0]: {}}
Decision_List = {Zone_Name:{}}
for rows in Column_Rows:
app_object = sh.col_values(4)[rows]
svc_object = sh.col_values(3)[rows]
proto_object = sh.col_values(3)[rows]
dst_object = sh.col_values(2)[rows]
src_object = sh.col_values(1)[rows]
yes_no = sh.col_values(colnum)[rows]
for rule_name in Decision_List.iterkeys():
Decision_List[Zone_Name][(app_object, svc_object, proto_object)]= yes_no
Thanks again.
I think still a better way is to use collections.defaultdict
In this manner it will ensure that i am able to append to the specific yes_no as i had originally intended.
for colnum in Base_Sheet:
Zone_Name = sh.col_values(colnum)[0]
Zone_App_Header = {sh.col_values(4)[0]:{}}
Zone_Svc_Header = {sh.col_values(3)[0]:{}}
Zone_Proto_Header = {sh.col_values(2)[0]:{}}
Zone_DestPort_Header = {sh.col_values(1)[0]: {}}
Zone_SrcPort_Header = {sh.col_values(0)[0]: {}}
Decision_List = {Zone_Name:defaultdict(list)}
for rows in Column_Rows:
app_object = sh.col_values(4)[rows]
svc_object = sh.col_values(3)[rows]
proto_object = sh.col_values(2)[rows]
dst_object = sh.col_values(1)[rows]
src_object = sh.col_values(0)[rows]
yes_no = sh.col_values(colnum)[rows]
if yes_no not in Decision_List[Zone_Name]:
Decision_List[Zone_Name][yes_no]= [app_object, svc_object, proto_object, dst_object, src_object]
else:
Decision_List[Zone_Name][yes_no].append([(app_object, svc_object, proto_object,dst_object, src_object)])
This allows me to then set the values as a set and append them as needed

Trying to avoid creating numerous variables in python

I am new to python and I have a lot of variables I will be using in this script. These variables are being used to grab data from each column in an uploaded file. I have added variables for each object type and I have about 12 more object types to add. Isn't there a better way I can do this? I have the file it's grabbing data from here:
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
Here is the script I have so far.
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]
If the values are in the same order every time, you could consider populating a list that you then could loop over, instead of doing it one by one.
For the "target" portion of your script, you could nest another loop for range(3, 46) as well, and pass the index to your list instead of manually for every number from 3 to 46.
Why do you do this?
for line in current_file:
for row in current_file:
If the first row is a header row and you're skipping it on purpose, you can use a DictReader instead.
It doesn't look like you'll be able to do much to clean this up, but you could factor out each "section" into its own function:
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()
Behind the scenes all the member names of an object are stored in a dict. You can access this dict with vars(obj) or obj.__dict__. You can then use the update method of the dict to add a set of names to your object.
eg.
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)

Categories

Resources