REALLY need help with iterating a list.

infidel saint.infidel at gmail.com
Mon Jun 11 14:59:36 EDT 2007


On Jun 11, 11:30 am, Radamand <radam... at gmail.com> wrote:
>     This has been driving me buggy for 2 days, i need to be able to
> iterate a list of items until none are left, without regard to which
> items are removed. I'll put the relevant portions of code below,
> please forgive my attrocious naming conventions.
>     Basically i'm trying to spin up some subprocesses that will ping a
> group of servers and then wait until all of them have completed (good
> or bad), store the ping result and the return code, and move on.
>     The problem comes in the second block, when i try to iterate the
> list of servers and remove the ones that are finished, for some reason
> Python appears to re-index the list when I remove an item and the next
> step through the loop it cant find the item its expecting because the
> indexes have changed.
>     Any assistance would be appreciated...
>
> =============================================================================
> for server in serverlist:
>     ping[server] = subprocess.Popen("ping -c 1 " + str(server) + " 5",
> shell=True, stdout=subprocess.PIPE)
>
> while len(serverlist) > 0:
>     for server in serverlist:
>         if ping[server].returncode==None:
>             ping[server].poll()
>         else:
>             pingresult[server] = ping[server].stdout.read()
>             pingreturncode[server] = ping[server].returncode
>             serverlist.remove(server)

How about something like this?

while serverlist:
    server = serverlist.pop(0)
    pinger = ping[server]
    if pinger.returncode==None:
        pinger.poll()
        serverlist.append(server)
    else:
        pingresult[server] = pinger.stdout.read()
        pingreturncode[server] = pinger.returncode

Basic idea:  as long as there are servers in the list, pop the first
one out of the list, see if it's done, and if it isn't, put it back on
the end of the list.




More information about the Python-list mailing list