2012-09-11 50 views
1

如何在Windows 7上使用Python獲取一個或多個網卡的%使用率?我嘗試使用psutil庫,但它只返回傳輸的數據。如何在Windows 7上使用Python獲取網卡的%使用率

我想獲得的網卡列表和它們的用法

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

通過比較傳輸的數據量和/或將其與最大容量進行比較來推導出它。 –

回答

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 

把這段代碼用一粒鹽,編程新手(一個星期)。也沒有錯誤處理。

哦,我的輸出是低於,我的LAN卡沒有被使用。

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% 
相關問題