0

Okay I went over the csv module and updated my code. I have the csv in place and the file is being read but my input value is not giving me an error like it should when the wrong one is put in. Here is what I have now:

#!usr/bin/python


from subprocess import *
import sys
import ConfigParser
import os
import csv
import getopt
import time
import datetime
import logging
from sys import argv
script, solution_id, input_file = argv

#set up logging to file
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%d %b %Y %H:%M:%S',
                    filename='/etc/nagios/ingestion/logs/catch.log',
                    filemode='w')
# defining a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# setting a format which is simpler for console use
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
# telling the handler to use this format
console.setFormatter(formatter)
# adding the handler to the root logger
logging.getLogger('').addHandler(console)

#set up configuration Parser
config = ConfigParser.RawConfigParser()
config.read('/etc/nagios/ingestion/objectItems.cfg')
config.read('/etc/nagios/ingestion/action.cfg')

#get objects
objects = config.get('Objects', 'objects')

#get actions
actions = config.get('Actions', 'actions')

#if no object is found, run error
assert(sys.argv[1] != None), "object does not exist"
#logging debug 
#logging.debug('object does not exist')

#Get inputs and check value and path to file
def print_all(f):
    f.read()

# place an exception for incorrect path
try:
    current_file = csv.reader(open(input_file, "rb"))
    for row in current_file: solution_id = row[2]
    if solution_id != row[2]:
        print "invalid solution id"

#list exceptions  
except IOError:
    #logging error
    logging.error('No such file or directory. Please try again')


except IOError:
    print("Solution id is invalid. Please check the number and try again")
    #logging error
    logging.error('Solution id is invalid. Please check the number and try again')     
1
  • You have two except IOError clauses for the same try. Only the first one will fire. Is this a typo, or is that in your real code? Commented Dec 15, 2014 at 20:00

2 Answers 2

1

Looking at the last parts of your code, I see a number of probems - or potential ones

# place an exception for incorrect path
try:
    current_file = csv.reader(open(input_file, "rb"))

Did you mean to open the file as a binary one? I thnk you want "rt"

    for row in current_file: solution_id = row[2]

This last line reads through the file, extracting row[2] from each line. The result is that solution_id will only have the value from the final row in the file. It will also be undefined on the next statement if the file was empty (i.e. loop never executed)

    if solution_id != row[2]:
        print "invalid solution id"

#list exceptions  
except IOError:
    #logging error
    logging.error('No such file or directory. Please try again')

Now you have a second except IOError. As far as I know, if IOError is raised within the try clause, only the first exception handler will fire. So you will never see the Solution id is invalid message. Did you mean to raise (and catch) a different exception in the body of the try?

except IOError:
    print("Solution id is invalid. Please check the number and try again")
    #logging error
    logging.error('Solution id is invalid. Please check the number and try again') 
Sign up to request clarification or add additional context in comments.

1 Comment

Yes in this instance I need to raise two exceptions, one for an invalid file and the other for an invalid solution id
0

I'm not totally sure what your question is. But in your code you have

#if no object is found, run error
assert(sys.argv[1] != None), "object does not exist"

If you specify something on the command line (following the script name) then sys.argv[1] will most definitely be something, not None; it'll be a string. Shouldn't your test be against some string match that's read from the config or similar?

Alternatively, if you want to test whether there IS something on the command line, use len():

if len(argv) < 2:
    print('Bad usage, you need to state the solution_id ' +
          'and input_file on the commandline') 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.