【问题标题】:Indentation Error: expected an indented block缩进错误:需要一个缩进块
【发布时间】:2015-02-16 10:37:24
【问题描述】:

我不断收到这个错误,告诉我要缩进我的块,但我看不出我需要在哪里这样做,特别是如果我正在运行两个 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!"

【问题讨论】:

  • 如果if solution_id != row[2]: 为真,会发生什么?你好像少了一行。
  • 获得一个 IDE,它会告诉你
  • 如果 solution_id 是一个命令 arg,不等于解决方案 id,它在一个 csv 文件中,那么一个错误将被踢出并为它创建一个日志文件。
  • 你给了我们 83 行代码,没有提到哪一行有问题。 Python 会准确地告诉您哪一行存在缩进问题,并且很容易看出这是因为您有一个 if 语句,而它的正上方没有正文。

标签: python csv


【解决方案1】:

什么是

else:
  print row

连接到?它应该从需要 else 的东西缩进,但它在第 1 列中......

【讨论】:

  • 这应该是评论,而不是答案
  • 它是try/except/else 块的一部分,所以不是问题。
  • 我修复了 'else' 的问题,但我现在得到一个无效的语法,'else' 的最后一个字母上的克拉数
【解决方案2】:

在第二个 try 语句中。你有没有任何动作的 if 语句

    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') 

需要有类似的东西

    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') 

if 语句试图使用 except 作为条件后的动作。

编辑:: 我没有 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!"

【讨论】:

  • 现在在当前代码中,您需要在第一次尝试后缩进:f=cvs.read 并将 else 移回以与第二次尝试一致;除了:
猜你喜欢
  • 1970-01-01
  • 2016-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多