gpt4 book ai didi

python - 为什么这个 forloop 会跳过列表中的项目?

转载 作者:太空宇宙 更新时间:2023-11-04 10:26:39 26 4
gpt4 key购买 nike

当我运行下面的代码时,它似乎只遍历了列表中所有 worker 列表的一半。然后它跳转到关闭父进程。

我非常困惑,为什么下面的代码没有遍历列表中的所有项目,也许我盯着这个看得太久了,看不出明显的东西?任何帮助将不胜感激。

这是控制台。

Waiting...
[u'worker-1.15579', u'worker-1.15575', u'worker-1.15577', u'worker-1.15570', u'worker-1.15573', u'worker-1.15168', u'worker-1.15170']
The terminate_pid is 15561
Process was SUCCESSFULLY closed.
Process was SUCCESSFULLY closed.
Process was SUCCESSFULLY closed.
no process found with pid 15170
Process was already closed.
Closed terminator window.

下面是代码,

            workers_to_be_restarted = [u'worker-1.14524', u'worker-1.14526', u'worker-1.14518', u'worker-1.14528', u'worker-1.14522']

for item in workers_to_be_restarted:
if this_machine == item.split('.')[0]:
if not terminate_pid:
try:
terminate_pid = psutil.Process(psutil.Process( int(item.split('.')[1]) ).ppid()).ppid()
print "The terminate_pid is {}".format(str(terminate_pid))
except Exception, e:
terminate_pid = None
print e
pass
try:
print "Terminating {}".format(item)
p = psutil.Process( int(item.split('.')[1]) )
p.terminate()
time.sleep(1)
print "Process was SUCCESSFULLY closed."
workers_to_be_restarted.remove( item )
except Exception, e:
print e
time.sleep(1)
print "Process was already closed."
workers_to_be_restarted.remove( item )
pass
try: #THE ABOVE SEEMS TO BE EXITING HERE before looping through all the items!? NOT SURE WHY?
if terminate_pid:
p = psutil.Process( terminate_pid )
p.terminate()
print "Closed terminator window."
worker_restart['restart'] = None
worker_restart['workers_to_be_restarted'] = workers_to_be_restarted

最佳答案

看起来您只是迭代了一部分的原因是 workers_to_be_restarted.remove( item )。这实际上是删除列表中的下一个 项目,而不是您打算删除的项目。例如:

workers_to_be_restarted = [u'worker-1.14524', u'worker-1.14526', u'worker-1.14518', u'worker-1.14528', u'worker-1.14522']
for item in workers_to_be_restarted:
print(item)
workers_to_be_restarted.remove(item)

输出:

worker-1.14524
worker-1.14518
worker-1.14522

如您所见,第二个和第四个 worker 在迭代其他 worker 时被移除。要解决此问题,请复制您的列表并首先对其进行迭代。我会用这样的完整列表切片分配替换您当前的行:

for item in workers_to_be_restarted[:]:

输出:

worker-1.14524
worker-1.14526
worker-1.14518
worker-1.14528
worker-1.14522

关于python - 为什么这个 forloop 会跳过列表中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28989259/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com