1

如何使用 Python 在 Windows 7 上获得一个或多个网卡的使用百分比?我尝试使用 psutil 库,但它只返回传输的数据。

我想获取网卡列表及其使用情况

Network card 1 - 1%
Network card 2 - 0%
Network card 3 - 5%
4

1 回答 1

0

您无法获得百分比,但您可以获得发送和接收的字节数,安装psutil,导入 psutil 和 re (正则表达式模块)。请参阅下面的示例代码,了解我是如何做到的。

import psutil # http://code.google.com/p/psutil/
import re # Regular expression

#Percentage function
def percentage(part, whole):
        return 100 * float(part)/float(whole)

if __name__ == '__main__':

    #Retrieve all stats for all Network Cards using psutil
    Stats = psutil.net_io_counters(pernic=True)

    #Just showing printed values for Stats, useful for new coders :)
    for key, val in Stats.items():
        print key, val


    #Filter Starts, convert to string for use with Regular expression
    LanString = str(Stats['Local Area Connection'])
    WirelessString = str(Stats['Wireless Network Connection'])

    #Regular expression pattern that collects values between = character and , character
    pattern = re.compile("\=(.*?)\,") 

    #Find all values matching the pattern
    LanResult = re.findall(pattern, LanString)
    WirelessResult = re.findall(pattern, WirelessString)

    #Select values bytes_sent + bytes_recieved, convert to integers, add together
    LanSumUsage = int(LanResult[0]) + int(LanResult[1])
    WirelessSumUsage = int(WirelessResult[0]) + int(WirelessResult[1])

    #Calculate and print percentages
    TotalUsage = LanSumUsage + WirelessSumUsage
    LanCardPercentage = percentage(LanSumUsage, TotalUsage)
    WirelessCardPercentage = percentage(WirelessSumUsage, TotalUsage)
    print("\nLan Card: %d%%") % LanCardPercentage
    print("Wireless Card: %d%%") % WirelessCardPercentage

对这段代码持保留态度,这是编程新手(一周后)。也没有错误处理。

哦,我的输出在下面,我的网卡没有被使用。

Wireless Network Connection iostat(bytes_sent=801853517, bytes_recv=2106217519, packets_sent=4655581, packets_recv=6351113, errin=0, errout=0, dropin=0, dropout=0)
isatap.{10384343-0618-4406-B3D9-DA096A39B0DC} iostat(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0)
Teredo Tunneling Pseudo-Interface iostat(bytes_sent=3358183, bytes_recv=27088294, packets_sent=40579, packets_recv=33727, errin=0, errout=1474, dropin=0, dropout=0)
Local Area Connection iostat(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0)
Loopback Pseudo-Interface 1 iostat(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0)
isatap.{109E44C6-1D07-4E41-A7EA-FCFF2284A1DB} iostat(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0)

Lan Card: 0%
Wireless Card: 100%
于 2012-09-12T02:23:18.427 回答