[英]how can I extract Average in this each ping result and store in file
Here I can ping each IP but am not able to extract the Average of the result.在这里,我可以 ping 每个 IP,但无法提取结果的平均值。 Can anyone help, please?有人可以帮忙吗?
import subprocess
import threading
ip_list = []
def ping(host):
ip_list.append(host+ ' '+ str((subprocess.run('ping '+host +' -n 1').returncode)))
with open(r'input.txt', "r") as input_file:
hosts = input_file.read()
hosts_list =hosts.split('\n')
num_threads = 1
number = 0
while number< len(hosts_list):
for i in range(num_threads):
t = threading.Thread(target=ping, args=(hosts_list[number+i],))
t.start()
t.join()
number = number +1
After doing some research I found out that using subprocess.run and then getting the returncode you dont get the output but only the return code so usually 0 for a successfull run with no error.在做了一些研究之后,我发现使用 subprocess.run 然后获取返回码,你不会得到输出,而只有返回码,所以通常 0 表示成功运行且没有错误。 If you want to get the output of the process you have to use subprocess.Popen and then communicate.如果你想获得进程的输出,你必须使用 subprocess.Popen 然后进行通信。 Then if you only want the average you have to do some string manipulation with the output to only get the number after "Average".然后,如果您只想要平均值,则必须对输出进行一些字符串操作,以便仅获得“平均值”之后的数字。 Here's an exemple:这是一个例子:
def ping(host):
output = subprocess.Popen(["ping", host, "-n", "1"], stdout=subprocess.PIPE).communicate()[0]
words = str(output).split(sep=" ")
average = words[words.index("Average")+2].split("ms")[0]
ip_list.append(host+ ' '+ average)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.