我对如何纠正以下问题感到有点迷茫。 当xxxx计数器达到15时,我希望脚本停止,这很好。 但是,当其中一个try语句出错时,我只希望它转到oldlist中的下一个url,而不是像现在一样停止脚本。
我阅读了有关此内容以及可能更好地包含While语句的文档,但我不知道该怎么做才能让它像我想要的那样工作。它实际上是一个更大的循环,但只是在下面进行了简化。
system:Python 2.7上的IDLE。* x64
xxxx = 0
oldlist = [lost of stuff]
newlist = [lots of stuff]
otherlist = [lots of stuff]
for url in oldlist:
found = False
if xxxx == 15:
break
for item in newlist:
if something:
if something:
found = True
for items in otherlist:
if something:
found = False
if found == True:
xxxx +=1
try:
something
except Exception as thing: #catch em all
print "1st Error"
break #should go to the next url
try:
something
except Exception as morethings: #catch em all
print "2nd Error"
break #should go to the next url
这实际上是不好的蟒蛇? 应该更像是:
while xxxx != 15:
for url in oldlist:
found = False
for item in newlist:
if something:
if something:
found = True
for items in otherlist:
if something:
found = False
while found == True:
xxxx +=1
while True:
try:
something
except Exception as thing: #catch em all
print "1st Error"
break
try:
something
except Exception as morethings: #catch em all
print "2nd Error"
break
答案 0 :(得分:2)
如果我理解您的问题,则需要continue
语句,而不是break
语句。
答案 1 :(得分:0)
您应该使用except
块中的continue
statement而不是break
来继续for
循环中的下一个项目(如果有)。
try:
something
except Exception as thing:
print "1st Error"
continue # go to the next url
除此之外,你的第一个代码块看起来还不错。但是,您可能希望在 try/excepts
之后递增计数器,否则也会计算您遇到异常并跳到下一次迭代的情况。但也许这正是你想要的。
你的第二个代码块在语义上不等同,恕我直言也差得多。这个循环将始终通过整个for
循环然后从while
循环中断 - 或者如果少于15个'良好'网址,则甚至再次通过for
循环在里面。此外,两个内部while
循环都是无限循环(第一个循环,第二个循环,除非你有异常并且突破它)。