Continue语句应使用下一项重新开始循环,但是当我的代码中发生异常时,for循环会退出。
def Update():
numberRemoved = 0
for conn in connections:
print("Starting for loop")
try:
print("First one")
conn.send("up?".encode())
reply = conn.recv(1024)
if reply.decode().strip() != "yes":
print("Recieved reply but clients response was different from expected...")
except ConnectionResetError:
print("It's down")
connections.remove(conn)
print("Removed the connection")
numberRemoved += 1
continue
此代码遍历套接字连接列表,并检查客户端是否仍在运行,但是即使有继续语句,每次发生异常时,for循环也会停止。我该如何解决? 谢谢!
答案 0 :(得分:1)
您从迭代的列表中删除内容。这使python感到困惑-不要这样做。您需要防止所有可能的异常-您只能捕获一种类型,其他所有类型都将终止程序。
修复,以便在遇到问题时进行修改,或者:
记住要删除的内容的代码:
def Update(connections):
to_be_removed = []
for conn in connections:
print("Starting for loop")
try:
print("First one") # not only the first one, every one is printing first one
conn.send("up?".encode())
reply = conn.recv(1024)
if reply.decode().strip() != "yes":
print("Response was different from expected...")
except ConnectionResetError: # other errors will kill your program
print("It's down")
to_be_removed.append(conn)
# there is no need to put a continue into your except block, because there
# is no code after the except block that belongs into the loop and
# has to be skipped if the exception happens - continue is superflous
# remove items from list after iterating it
for conn in to_be_removed:
connections.remove(conn)
如果您有[1,2,3,4]
的列表并在其上循环:
k = [1,2,3,4]
for i in k:
print(i,k)
k.remove(i)
print(k)
你得到
(1, [1, 2, 3, 4]) # i is 1, the 1st number in k
[2, 3, 4] # 1 is removed, continuing with 2nd element of list
(3, [2, 3, 4]) # list got modified, 3 is the 2nd element
[2, 4] # 3 is removed, continuing with 3rd element of list
# oh wait - no 3rd element - cool - we are done