GNOME可以用的最小的网络指示器
#!/usr/bin/python # -*- coding: utf-8 -*- """ Created on Tue Nov 11 21:26:17 2014 @author: terry """ import pygtk pygtk.require('2.0') import sys import os import shutil import json import time from threading import Thread, Event import subprocess import psutil as ps import copy import re import gtk gtk.gdk.threads_init() import appindicator import logging class StatusUpdateIndicator(Thread): B_UNITS = ['', 'KB', 'MB', 'GB', 'TB'] interval = 2 def __init__(self): Thread.__init__(self) self.isRunning = True self.last = ps.cpu_times() self.last_net_usage = [0, 0] # (up, down) self.network_indicator = appindicator.Indicator ("indicator-sysmonitor", "sysmonitor", appindicator.CATEGORY_APPLICATION_STATUS) self.network_indicator.set_status (appindicator.STATUS_ACTIVE) self.network_indicator.set_icon("gnome-netstatus-idle") self.network_indicator.set_label("Init...") # create a menu self.menu = gtk.Menu() image = gtk.ImageMenuItem(gtk.STOCK_QUIT) image.connect("activate", self.quit) image.show() self.menu.append(image) self.menu.show() self.network_indicator.set_menu(self.menu) def bytes_to_human(self,bytes_): unit = 0 while bytes_ > 1024: unit += 1 bytes_ /= 1024 return '{}{}'.format(int(bytes_), self.B_UNITS[unit]) def update(self): """It returns the bytes sent and recieved in bytes/second""" current = [0, 0] for _, iostat in ps.network_io_counters(pernic=True).items(): current[0] += iostat.bytes_recv current[1] += iostat.bytes_sent dummy = copy.deepcopy(current) current[0] -= self.last_net_usage[0] current[1] -= self.last_net_usage[1] self.last_net_usage = dummy current[0] /= self.interval current[1] /= self.interval if current[0] == 0 and current[1] == 0: self.network_indicator.set_icon("gnome-netstatus-idle") elif current[0] > 0 and current[1] == 0: self.network_indicator.set_icon("gnome-netstatus-rx") elif current[0] == 0 and current[1] > 0: self.network_indicator.set_icon("gnome-netstatus-tx") else: self.network_indicator.set_icon("gnome-netstatus-txrx") traffic = '{}/s | {}/s'.format(self.bytes_to_human(current[1]), self.bytes_to_human(current[0])) # print traffic self.network_indicator.set_label(traffic) def run(self): """It is the main loop.""" while self.isRunning: self.update() time.sleep(self.interval) def quit(self, widget, data=None): self.isRunning = False gtk.main_quit() def main(): gtk.main() return 0 if __name__ == "__main__": indicator = StatusUpdateIndicator() indicator.setDaemon(True) indicator.start() main() #network_indicator = appindicator.Indicator("indicator-sysmonitor", # "sysmonitor", # appindicator.CATEGORY_SYSTEM_SERVICES) #network_indicator.set_status(appindicator.STATUS_ACTIVE) #network_indicator.set_label("Init...") #network_indicator.set_icon("gnome-netstatus-idle") # #updater = StatusUpdater(network_indicator)