Python continue 显然没有将控制返回给 while 循环
Python continue apparently not returning control to while loop
我有一个基于 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
的用法,否则我认为它应该有效地退出循环迭代并移至下一行。
我错过了什么?
你是正确的 continue
将移动到下一个迭代。
但是,您没有在任何迭代中修改任何内容。
你的声明 row is not None
,在你的 while
中永远不会改变。它要么始终为真,要么始终为假。
你可能想做这样的事情:
while cur.fetchone() is not None:
#your code
或者更好:
while cur.fetchone():
#your code
而不是 'continue' 您需要获取下一行:
行 = cur.fetchone()
我有一个基于 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
的用法,否则我认为它应该有效地退出循环迭代并移至下一行。
我错过了什么?
你是正确的 continue
将移动到下一个迭代。
但是,您没有在任何迭代中修改任何内容。
你的声明 row is not None
,在你的 while
中永远不会改变。它要么始终为真,要么始终为假。
你可能想做这样的事情:
while cur.fetchone() is not None:
#your code
或者更好:
while cur.fetchone():
#your code
而不是 'continue' 您需要获取下一行: 行 = cur.fetchone()