主函数奇怪的缩进块错误

时间:2013-10-19 16:23:05

标签: python

我的错误

  File "controller.py", line 26
    try:
      ^
IndentationError: expected an indented block

我的代码:

def main():
    config=ConfigParser.ConfigParser()
    config.readfp(open("settings.cfg"),"r")
    for site in config.sections():
       # ipdb.set_trace()
        settings=dict(config.items(site))
        with open('shoes.txt') as fp: <--new code trying to add
            for category, url in csv.reader(fp):  <--new code trying to add
            #ipdb.set_trace()
            #print url,category
            try: <--line 26

出于某种原因,我得到了错误,我不确定如何解决它,你可以帮助我吗?

我有一个旧的工作正常:

def main():
    config=ConfigParser.ConfigParser()
    config.readfp(open("settings.cfg"),"r")
    for site in config.sections():
       # ipdb.set_trace()
        settings=dict(config.items(site))
        for (url,category) in zip(settings['url'].split(","),settings['category'].split(",")):
            #ipdb.set_trace()
            #print url,category
            try:
... more code

2 个答案:

答案 0 :(得分:2)

我认为try不应该是for循环的一部分

def main():
    config=ConfigParser.ConfigParser()
    config.readfp(open("settings.cfg"),"r")
    for site in config.sections():
       # ipdb.set_trace()
        settings=dict(config.items(site))
        with open('shoes.txt') as fp: <--new code trying to add
            for category, url in csv.reader(fp):  <--new code trying to add
                pass
            #ipdb.set_trace()
            #print url,category
            try: <--line 26

在python中无法使用空块,“for”语句有一个空块。只需添加“通行证”(在这种情况下无效)。

其他变体,似乎符合预期的行为:

def main():
    config=ConfigParser.ConfigParser()
    config.readfp(open("settings.cfg"),"r")
    for site in config.sections():
       # ipdb.set_trace()
        settings=dict(config.items(site))
        with open('shoes.txt') as fp: <--new code trying to add
            for category, url in csv.reader(fp):  <--new code trying to add
                #ipdb.set_trace()
                #print url,category
                try: <--line 26

答案 1 :(得分:1)

修改

我现在重写了我的帖子,我知道你的问题是什么......

你的旧代码工作的原因是它在for循环中有一些东西,即try / except块。但新代码却没有(评论不计算在内)。

要解决您的问题,请确保您的缩进很好,并在for循环中添加一些东西。您的代码可能应如下所示:

def main():
    config=ConfigParser.ConfigParser()
    config.readfp(open("settings.cfg"),"r")
    for site in config.sections():
        # ipdb.set_trace()
        settings=dict(config.items(site))
        with open('shoes.txt') as fp: <--new code trying to add
            for category, url in csv.reader(fp):  <--new code trying to add
                #ipdb.set_trace()
                #print url,category
                try:
                    ...