除ValueError之外的语法无效

时间:2014-12-17 06:39:17

标签: python

我一直在这里得到这个无效的语法错误:除了ValueError:它在'except'之后给我一个克拉。我想知道我是否需要排队'excepts',但我尝试了,我仍然有相同的语法错误。我的代码出了什么问题?

这是我的代码:

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 FileNotFoundError:
    logging.error('No such file or directory. Please try again')   
    for line in f:
        #process (line) 

        for row in f:     
            if solution_id != row[2]:
                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 个答案:

答案 0 :(得分:3)

每个except子句必须与try子句相关联。您的代码中包含的代码不是。

答案 1 :(得分: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