【问题标题】:Python continue apparently not returning control to while loopPython continue 显然没有将控制权返回给 while 循环
【发布时间】:2016-03-08 10:06:36
【问题描述】:

我有一个基于 MySQLdb 游标的 while 循环,我需要根据 if 语句中的某些条件移动到下一次迭代。净化后的代码如下所示:

    row = cur.fetchone()

    while row is not None: 
      unique_id = row[0] 
      mac = row[1] 
      url = row[2]

      location = old_path + unique_id 

      os.chdir(location)
      file_count = 0
      for file in os.listdir(location): 
        if file.startswith('phone.') and file.endswith('.cfg'):
            file_count = file_count + 1

      if file_count != 1: 
        userprompt = 'Multiple phone.MAC.RANDOM.cfg files detected continue?'
        cont = query_yes_no(userprompt) # prompt user on what to do next - abort or continue
        if cont == False:
          debugmsg = 'User requested abort - aborting'
          print debugmsg
          logger.info(debugmsg)
          sys.exit()
        elif cont == True:
            debugmsg = 'Moving to next on user request'
            logger.info(debugmsg)
            continue

此代码的行为与预期不符。运行时,如果它遇到与file_count !=1 条件匹配的目录,则循环似乎会再次运行,而不会前进到下一行。除非我误解了 continue 的用法,否则我认为它应该有效地退出循环的迭代并移至下一行。

我错过了什么?

【问题讨论】:

  • 您确定cont 与True 或False 不同吗?例如。没有任何? (即您的 logger.info() 调用是否真的记录了消息?)
  • 也许我很敏感,但我不明白为什么这被否决了? :-/
  • @FrankSchmitt 是的,我确信 cont 的值是由函数 query_yes_no 设置的

标签: python mysql mysql-python


【解决方案1】:

您需要获取下一行,而不是“继续”: row = cur.fetchone()

【讨论】:

  • 这听起来是个不错的解决方案——如果我这样做,大概我也需要继续吗?即cur.fetchone() 然后continue
  • 这工作得很好,谢谢,使用现有的代码,加上我之前评论中提到的cur.fetchone()continue
  • 不,在这种情况下您不需要“继续”。在最后一条语句之后,循环将继续,即再次执行 while 表达式。
  • 抱歉,我确实需要 continue,但这是因为在我的 实际 代码中,while 循环中有更多内容,我只是为了简洁而进行了编辑。但是感谢您的澄清!
【解决方案2】:

continue 将移至下一次迭代是正确的。

但是,您不会在任何迭代中修改任何内容。 您在while 中的声明row is not None 永远不会改变。它要么总是对的,要么总是错的。

你可能想做这样的事情:

while cur.fetchone() is not None: 
  #your code

或者更好:

while cur.fetchone(): 
  #your code

【讨论】:

  • 感谢您的解释:)
猜你喜欢
  • 2017-03-30
  • 2016-01-21
  • 2014-03-25
  • 2018-08-10
  • 2014-01-17
  • 1970-01-01
  • 2015-12-13
  • 2016-01-31
  • 2022-08-22
相关资源
最近更新 更多