如何使用matplotlib在饼图中绘制IP地址列表并将信息保存到文本文件

时间:2019-11-24 20:20:21

标签: python python-3.x matplotlib

到目前为止,我正在运行的代码如下:

import subprocess
import os
import matplotlib.pyplot as plt
def Main ():
    ipaddress = open('ipaddress.txt', 'a')
    with open(os.devnull, "wb") as limbo:
        for n in range(1, 100):
            ip="192.168.1.{0}".format(n)
            result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
                stdout=limbo, stderr=limbo).wait()
            if result:
                print (ip + " inactive")
                ipaddress.write(ip + ' inactive')
            else:
                print (ip + " active")
                ipaddress.write(ip + ' Acive')
    ip = ip.split('\n')
    ip = [float(f) for f in ip]
    slice_labels = ['Active', 'Inactive']
    # Create a pie chart from the values.
    plt.pie(ip, labels=slice_labels)
    # Add a title.
    plt.title('IP address activity')
    # Display the pie chart.
    plt.show()
Main()

运行该程序时,出现ValueError:无法将字符串转换为float:'192.168.1.99'

我的任务是将结果打印到列表中,并使用matplotlib在饼图中显示活动IP地址与无效IP地址的百分比。不知道该怎么做才能使结果显示在活动或不活动的饼图中。我还希望允许用户将结果保存为文本文件,是“是”或“否”选项,而不是将结果自动写入文件,因为当前已设置此程序。我是否只在程序中使用另一个嵌套的if-else语句,如果answer = y或yes,则完成写入,如果answer = no return or break?

0 个答案:

没有答案