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

2024-04-27 23:08:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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:无法将字符串转换为浮点:“192.168.1.99”

我的任务是将结果打印到列表中,并使用matplotlib在饼图中显示活动ip地址与非活动ip地址的百分比。不确定如何在此处获得要在饼图中显示的活动或非活动结果。我还想允许用户将结果保存到一个文本文件作为是或否选项,而不是结果自动写入一个文件,因为这个程序是目前设置的。我是否会在程序中使用另一个嵌套的if-else语句,如果answer=y或yes,则完成写入,如果answer=no返回或中断


Tags: import程序ipforlabelsmatplotlibosmain