为列表中的项生成新线程

时间:2014-03-10 15:31:42

标签: python multithreading list iteration

新手在这里,谢谢你花时间看看这个!

我正在尝试创建一个读取IP地址列表的脚本,然后为列表中的每个IP地址生成一个新线程。产生新线程的原因是使脚本尽可能快速轻量级。

我遇到的问题是我的脚本需要大约4秒才能完成,它只会ping 12个IP地址'。我希望在不到一秒的时间内ping一系列IP地址,所以如果有人有任何建议或提示,我都会耳朵!

import subprocess
import re
import threading


def get_ips():

        # Fill empty list with IP address 
        ips = []
        with open('C:\Python26\ARPips.prn','r')as f:
            for line in f:
                line = line[:-1]
                if line != "end":
                    ips.append(line)
            return ips

def ping():

    #Ping with "pingArgs" as the arguments
    ping = subprocess.Popen(pingArgs,
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE,
        shell=True)

    #Get and parse output 
    out = ping.communicate()
    out = ''.join((out))
    lost = re.findall(r"Lost = (\d+)", out)
    minimum = re.findall(r"Minimum = (\d+)", out)
    maximum = re.findall(r"Maximum = (\d+)", out)
    avg = re.findall(r"Average = (\d+)", out)
    no =  re.findall(r"Sent = (\d+)", out)

    # Change output to integers
    lost = [int(x) for x in lost]
    minimum = [int(x) for x in minimum]
    maximum = [int(x) for x in maximum]
    avg = [int(x) for x in avg]
    no = [int(x) for x in no]

    # Format output for console
    print "%s \t \t %s \t \t%s \t \t %s \t \t%s" % (no, lost, maximum, minimum, avg)

def main():

    # grab IP address list
    ips = get_ips()

    # Header for output 
    print "Packets \t loss(%) \t Max(ms) \t Min(ms) \t Average(ms)"

    # Global variables for module
    global position, newIP, pingArgs
    position = 0

    # Loop through IP list and spawn new thread for each IP
    for i in ips:
        newIP = ips[position]
        position += 1
        pingArgs = ["ping", "-n", "1", "-l", "1", "-w", "100", newIP]
        t = threading.Thread(target= ping(), args = pingArgs)
        t.start()


if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:2)

在这一行:

t = threading.Thread(target= ping(), args = pingArgs)

您正在执行ping()而没有args并将结果返回到target。这不是线程行为。您需要将其更改为:

t = threading.Thread(target=ping, args=(pingArgs,))

您还需要修改ping()的定义以接受参数:

def ping(pingArgs):

您的代码中还有其他一些问题,例如print中的ping语句(因为线程是异步的,打印到stdout是“非原子的”,您的代码不会按顺序可靠地print打印报表。)。一旦您的代码正常运行,我建议您将其放在codereview上以获得进一步的反馈。