我试图检查在命令行参数中输入时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
答案 0 :(得分:0)
我通过添加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