为列表中的项生成新线程

1 投票
1 回答
618 浏览
提问于 2025-04-17 21:39

我是个新手,非常感谢你们花时间来看这个!

我正在尝试写一个脚本,这个脚本会读取一串IP地址,然后为每个IP地址创建一个新的线程。创建新线程的原因是为了让这个脚本运行得更快、更轻便。

我遇到的问题是,我的脚本完成大约需要4秒钟,而它只会对12个IP地址进行ping操作。我希望能在一秒钟内对一系列IP地址进行ping,所以如果有人有建议或技巧,我非常乐意听取!

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 个回答

2

在这一行:

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

你在这里调用了 ping(),没有传任何参数,然后把结果返回给 target。这样做并不是线程处理的方式。你需要把它改成:

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

你还需要修改 ping() 的定义,让它可以接受参数:

def ping(pingArgs):

你的代码里还有其他一些问题,比如在 ping 里的 print 语句(因为线程是异步的,而打印到标准输出不是“原子”的,所以你的代码不能保证 print 语句的顺序输出)。一旦你的代码能正常工作,我建议把它放到 codereview 上,获取一些进一步的反馈。

撰写回答