我了解如果您当前正在迭代该列表,则无法从列表中删除元素。然后我要做的是将我不想删除的列表中的元素复制到另一个列表,然后用新列表替换原始列表。这是我的相关代码:
while len(tokenList) > 0:
# loop through the tokenList list
# reset the updated token list and the remove flag
updatedTokenList = []
removeFlag = False
for token in tokenList:
completionHash = aciServer.checkTaskForCompletion(token)
# If the completion hash is not the empty hash, parse the information
if completionHash != {}:
# if we find that a task has completed, remove it from the list
if completionHash['Status'] == 'FINISHED' and completionHash['Error'] == '':
# The task completed successfully, remove the token from the list
removeFlag = True
elif completionHash['Status'] == 'RUNNING' and completionHash['Error'] == '':
# The task must still be running
print('Task ' + completionHash['Type'] + ' ' + token + ' has been running for ' + completionHash['Runtime'] + ' seconds.')
elif completionHash['Status'] == 'queued':
# The task is in the queue
print('Task ' + completionHash['Type'] + ' ' + token + ' is queued in position ' + completionHash['QueuePosition'])
elif completionHash['Status'] == 'not_found':
# Did not find a task with this token, possible the task hasn't been added yet
print(completionHash['Error'])
# if the task is still running, no change to the token list will have occured
else:
# This is probably because the server got rid of the token after the task completed
print('Completion hash is empty, something went wrong.')
tokenListError.append(token)
removeFlag = True
if not removeFlag:
print('appending token to updatedTokenList')
updatedTokenList.append(token)
print('length of tokenList after removal loop: ' + str(len(updatedTokenList)))
# wait some time, proportional to the number of tasks left
checkInterval = len(updatedTokenList) * checkIntervalMultiplier
print('Waiting ' + str(checkInterval) + ' seconds before checking again...')
print('Tokens remaining: ' + str(len(updatedTokenList)))
# replace the original token list with the updated token list
tokenList = updatedTokenList
# wait a while based on how many tokens remain
time.sleep(checkInterval)
所以这一切的重点是用新列表更新 tokenList。每次循环,新任务都会完成,它们不应该被添加到 updatedTokenList 中。剩余的任务令牌将替换原始令牌列表。
这不起作用。在我第一次通过时,即使尚未完成任何任务,它也不会向 updatedTokenList 添加任何令牌。我无法弄清楚我做错了什么。有什么建议么?