簡體   English   中英

讀取csv文件中的特定行並檢查輸入是否匹配

[英]Read a specific row in a csv file and check for an input match

我試圖檢查在命令行參數中進行輸入時ID是否匹配。 我希望根據csv文件中的ID檢查輸入。 這是一個示例命令行參數,當一個人想要檢查其文件中的輸入內容時,將使用該參數。 他們需要輸入正確的ID和文件的正確路徑。 id和路徑必須匹配,腳本才能運行。 我的路徑輸入已經正常工作了。

$ 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

我通過添加for循環解決了該問題。 這是我的代碼:

#!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    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM