gpt4 book ai didi

python - 为列表中的项目生成一个新线程

转载 作者:行者123 更新时间:2023-12-01 05:21:15 25 4
gpt4 key购买 nike

新手,感谢您花时间查看此内容!

我正在尝试创建一个读取 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()

最佳答案

在这一行中:

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

您正在执行不带参数的 ping() 并将结果返回给 target。这不是线程行为。您需要将其更改为:

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

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

def ping(pingArgs):

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

关于python - 为列表中的项目生成一个新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22304393/

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