简体   繁体   English

如何在每个 ping 结果中提取平均值并存储在文件中

[英]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.

相关问题 Python:如何从文件中平均 Ping 时间 - Python: How to Average Ping Times From File 我正在尝试编写 python 脚本,它 ping n 个服务器并将结果存储在与 ex ping 8.8.8.8 &gt;&gt;c:\\result.txt 相同的文本文件中 - I am trying to write python script which ping n number of server and store result in text file same as ex ping 8.8.8.8 >>c:\result.txt 如何在 BeautifulSoap 中提取结果字符串? - How can I extract the result string in BeautifulSoap? 如何在元组列表中找到每个相似条目的平均值? - How can I find the average of each similar entry in a list of tuples? 如何找到序列中每个交付的平均分数? - How can I find the average score of each delivery within a sequence? 如何从 a.txt 文件中提取数据并将其存储在 2 个单独的变量中? - How can i extract data from a .txt file and store it in 2 separate variables? 我有一个csv文件,我想将csv文件的每一行提取到不同的csv文件中。 我怎样才能做到这一点? - I have a csv file and i want to extract each row of csv file into different csv file . how can i do that? 如何将python脚本的结果存储到新的csv文件中? - How can I store the result of my python script into a new csv file? 如何将 python 字典的每个键值对存储在 json 文件中的单独行上? - How can I store each key-value pair of my python dictionary on a separate line in json file? 如何提取整个表格并将其存储在 CSV 文件中? - How do I extract entire table and store it in CSV file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM