Я пытаюсь проверить соответствие идентификатора, когда ввод выполняется в аргументе командной строки. Я хочу, чтобы входные данные проверялись на идентификатор, который находится в файле 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
Вы пробовали использовать модуль 'csv'? – ryanpattison
Нет, я не импортирую его уже. – user3263771
Почему бы не прочитать в [csv module] (https://docs.python.org/2/library/csv.html) в документах и не дать ему пойти? * Затем * отправьте свой код и вопрос, если у вас возникнут проблемы. Вы узнали бы намного больше. – ryanpattison