2014-12-17 2 views
-4

이 오류는 내 블록의 들여 쓰기를 계속하고 있지만, 특히 두 번의 try 절을 실행하고있는 경우에는 그렇게해야 할 곳이 표시되지 않습니다. 두 번째 try 절이 첫 번째 로그와 같이 로그에 인쇄되도록 허용하려고합니다.들여 쓰기 오류 : 들여 쓰기 된 블록이 예상 됨

#!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') 
    for line in f: 

     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!" 
+2

만약'solution_id! = row [2] :'가 참이라면 어떻게 될까요? 선이 실종 된 것 같습니다. – Kevin

+0

IDE 가져 오기 –

+0

명령 arg 인 solution_id가 솔루션 ID (csv 파일에 있음)와 같지 않으면 오류가 발생하여 로그 파일을 채 웁니다. – user3263771

답변

0

else: 
    print row 

무엇 연결된 : 여기에 지금까지 가지고 무엇인가? 그것은 다른 것을 필요로하는 무언가에서 들여 쓰기되어야하지만, 열 1에 있습니다 ...

+1

이것은 대답이 아닌 주석이어야합니다. – MattDMo

+0

'try/except/else' 블록의 일부이므로 문제는 아닙니다. – tdelaney

+0

'else'문제가 수정되었지만 'else'의 마지막 문자에 캐럿이있는 잘못된 구문이 나타납니다. – user3263771

0

두 번째 try 문에서. 당신은하고

for row in f: 
     try:  
      if solution_id != row[2]: 
     except ValueError: 
      logging.error('Solution ID is invalid. Please check the number and try again') 

요구 될 수없는 행동과 if 문 문은 conditinal 후 작업으로 제외를 사용하려고하는 경우

for row in f: 
     try:  
      if solution_id != row[2]: 
       print "row error" 
     except ValueError: 
      logging.error('Solution ID is invalid. Please check the number and try again') 

등 뭔가가있다.

EDIT :: 테스트 할 CVS가 없습니다. 하지만이 코드에서 다른 오류가 발생하지 않습니다 :

#!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') 
    for line in f: 

     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!" 
+0

현재 코드에서 첫 번째 시도 후에 들여 쓰기해야합니다 : f = cvs.read 및 두 번째 시도와 일치하도록 else를 다시 이동합니다. 제외하고 : – grag42