def network_load(interface='eth0', measure_interval=1, suffix='B/s', si_prefix=False): '''Return the network load. Uses the ``psutil`` module if available for multi-platform compatibility, falls back to reading :file:`/sys/class/net/{interface}/statistics/{rx,tx}_bytes`. :param str interface: network interface to measure :param float measure_interval: interval used to measure the network load (in seconds) :param str suffix: string appended to each load string :param bool si_prefix: use SI prefix, e.g. MB instead of MiB ''' import time from powerline.lib import humanize_bytes def get_bytes(): try: import psutil io_counters = psutil.network_io_counters(pernic=True) if_io = io_counters.get(interface) if not if_io: return None return (if_io.bytes_recv, if_io.bytes_sent) except ImportError: try: with open('/sys/class/net/{interface}/statistics/rx_bytes'.format(interface=interface), 'rb') as file_obj: rx = int(file_obj.read()) with open('/sys/class/net/{interface}/statistics/tx_bytes'.format(interface=interface), 'rb') as file_obj: tx = int(file_obj.read()) return (rx, tx) except IOError: return None b1 = get_bytes() if b1 is None: return None time.sleep(measure_interval) b2 = get_bytes() return '⬇ {rx_diff} ⬆ {tx_diff}'.format( rx_diff=humanize_bytes((b2[0] - b1[0]) / measure_interval, suffix, si_prefix).rjust(8), tx_diff=humanize_bytes((b2[1] - b1[1]) / measure_interval, suffix, si_prefix).rjust(8), )
def test_humanize_bytes(self): self.assertEqual(humanize_bytes(0), '0 B') self.assertEqual(humanize_bytes(1), '1 B') self.assertEqual(humanize_bytes(1, suffix='bit'), '1 bit') self.assertEqual(humanize_bytes(1000, si_prefix=True), '1 kB') self.assertEqual(humanize_bytes(1024, si_prefix=True), '1 kB') self.assertEqual(humanize_bytes(1000000000, si_prefix=True), '1.00 GB') self.assertEqual(humanize_bytes(1000000000, si_prefix=False), '953.7 MiB')
def file_size(segment_info, suffix='B', binary_prefix=False): '''Return file size. :param str suffix: string appended to the file size :param bool binary_prefix: use binary prefix, e.g. MiB instead of MB :return: file size or None if the file isn't saved or if the size is too big to fit in a number ''' file_name = segment_info['buffer'].name file_size = vim_funcs['getfsize'](file_name) if file_size < 0: return None return humanize_bytes(file_size, suffix, binary_prefix)
def file_size(segment_info, suffix='B', si_prefix=False): '''Return file size. :param str suffix: string appended to the file size :param bool si_prefix: use SI prefix, e.g. MB instead of MiB :return: file size or None if the file isn't saved or if the size is too big to fit in a number ''' file_name = segment_info['buffer'].name if not file_name: return None try: file_size = os.stat(file_name).st_size except: return None return humanize_bytes(file_size, suffix, si_prefix)