Python显然没有将控制返回while循环
我有一个基于MySQLdb游标的while循环,在这个循环中,我需要根据if语句中的一些条件移动到下一个迭代。经过清理的代码如下所示:Python显然没有将控制返回while循环,python,mysql,mysql-python,Python,Mysql,Mysql Python,我有一个基于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(locatio
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
while cur.fetchone() is not None:
#your code
此代码的行为不符合预期。运行时,如果它命中与文件\u计数匹配的目录=1
条件下,循环似乎再次运行,而不前进到下一行。除非我误解了continue
的用法,否则我认为它应该有效地退出循环的迭代并移到下一行
我遗漏了什么?您认为
继续
将移动到下一个迭代是正确的
但是,在任何迭代中都不会修改任何内容。
您的语句行在中不是None
,而从不更改。它要么总是正确的,要么总是错误的
您可能希望执行以下操作:
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
while cur.fetchone() is not None:
#your code
或者更好:
while cur.fetchone():
#your code
您需要获取下一行,而不是“继续”:
row=cur.fetchone()您确定cont
与True或False不同吗?例如,没有?(例如,你的logger.info()调用真的记录了消息吗?)也许我很敏感,但我不明白为什么这会被否决:-/@FrankSchmitt yes我确信cont
的值是由函数query\u yes\u no
设置的,这听起来是一个很好的解决方案-如果我这样做,大概我也需要继续?i、 e.cur.fetchone()
然后continue
这非常有效,感谢您使用现有代码,并添加了cur.fetchone()
和continue
,如我之前的评论所述。不,在这种情况下您不需要“continue”。在最后一条语句之后,循环仍将继续,即再次执行while表达式。很抱歉,我确实需要continue
,但这是因为在我的实际代码中,while循环中有更多内容,我只是为了简洁而进行了编辑。但是谢谢你的澄清!谢谢你的解释:)