2014-12-15 3 views
0

Я пытаюсь проверить соответствие идентификатора, когда ввод выполняется в аргументе командной строки. Я хочу, чтобы входные данные проверялись на идентификатор, который находится в файле csv. Вот пример аргумента командной строки, который вводится, когда человек хочет проверить свой файл на входы. Им нужно ввести правильный идентификатор и правильный путь к их файлу. Идентификатор и путь должны совпадать для запуска сценария. У меня уже есть входной путь.Прочитайте определенную строку в файле csv и проверьте соответствие ввода

$ python filename.py CA-BB-CD /etc/pathtofile/myfile.csv 

Action Object Type   ID 
Add  Service   CA-BB-CC 
Add  Service Team  CA-BB-CC 
Modify Host Team  CA-BB-CC 
Modify Service Team  CA-BB-CC 

То, что я в моем коде прямо сейчас:

#!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, input_id, input_file = argv 

#set up logging to file 
logging.basicConfig(level=logging.DEBUG, 
       format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', 
       datefmt='%a, %d %b %Y %H:%M:%S', 
       filename='/etc/pathtofile/mydirectory/logs/mylog.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/mypath/ingestion/objectItems.cfg') 
config.read('/etc/mypath/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() 

def input_id(r): 
    r.read() 


# place an exception for incorrect path 
try: 
    current_file = open(input_file) 
    print_all(current_file) 

    current_input = open(input_file(row[3])) 
    input_id(current_input) 

#list exceptions 
except IOError: 
    print("No such file or directory. Please try again") 
#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') 
except IOError: 
print("Undefined action found") 
#logging warning 
logging.warning('Undefined action found') 
close 
+0

Вы пробовали использовать модуль 'csv'? – ryanpattison

+0

Нет, я не импортирую его уже. – user3263771

+0

Почему бы не прочитать в [csv module] (https://docs.python.org/2/library/csv.html) в документах и ​​не дать ему пойти? * Затем * отправьте свой код и вопрос, если у вас возникнут проблемы. Вы узнали бы намного больше. – ryanpattison

ответ

0

Я исправил проблему, добавив цикл. Это мой код:

#!usr/bin/python 


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

#creating time stamp and returning as a string to add to solution id log name 
def timeIzNow(): 
    full = time.strftime(" %Y-%m-%d %H:%M:%S") 

    return full 

#set up logging to file 
LOG_FILENAME = solution_id + timeIzNow() 
logging.basicConfig(level=logging.DEBUG, 
        format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s %(process)d', 
        datefmt='%d %b %Y %H:%M:%S', 
        filename=LOG_FILENAME, 
       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 


try: 
    f = csv.reader(open(input_file, "rb")) 
except: 
    logging.error('No such file or directory. Please try again') 
else: 
    try: 
     for row in f:    
      if solution_id != row[2]: 
       print "Solution ID is invalid. Pleae check the number and try again" 
    except ValueError: 
       logging.error('Solution ID is invalid. Please check the number and try again') 
    else: 
     print row  







finally: 
    print "all error checks done!" 

# let's do add update delete. that way we don't have to do a conversion in the script from modify to update 
# uSE THE CODE THAT i'M USING TO VALIDATE  
Смежные вопросы