helpers.py 3.26 KB
Newer Older
Mario Hock's avatar
Mario Hock committed
1
#!/usr/bin/env python3
2
3
# -*- coding:utf-8 -*-

Mario Hock's avatar
Mario Hock committed
4
5
6
7
8
9
10
11
12
# Copyright (c) 2014,
# Karlsruhe Institute of Technology, Institute of Telematics
#
# This code is provided under the BSD 2-Clause License.
# Please refer to the LICENSE.txt file for further information.
#
# Author: Mario Hock


13
import os
Mario Hock's avatar
Mario Hock committed
14
import netifaces
15
import operator
16
import psutil
Mario Hock's avatar
Mario Hock committed
17
18
19
20
21
22
23
24
25
26

def get_nics():
    return netifaces.interfaces()

def get_nic_speeds():
    ret = dict()

    for nic in get_nics():
        try:
            with open("/sys/class/net/" + nic + "/speed", "r") as f:
Mario Hock's avatar
Mario Hock committed
27
                speed = int( f.read().strip() ) * 1000 * 1000
Mario Hock's avatar
Mario Hock committed
28
29
30
31
32
33
34

            ret[nic] = speed
        except OSError:
            speed = 0

    return ret

Mario Hock's avatar
Mario Hock committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

def split_proprtionally(text, weights, size=0, fill=" "):
    """
    Split a string proportional to a given weight-distribution.

    If a |size| is specified, that string is filled with |fill| at the end to match that length.
    (NOTE: len(fill) must be 1)
    """

    if ( size > 0 ):
        ## Fill text with spaces.
        if ( len(text) < size ):
            text += fill * (size-len(text))
        ## Truncate text if it's too long.
        elif ( len(text) > size ):
            text = text[size]
    else:
        size = len(text)

    # sum of all weights
    total_weights = float( sum(weights) )

    ## Calculate an int for each weight so that they sum appropriately to |size|.
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
    float_lengths = [ (w / total_weights)*size for w in weights ]
    weighted_lengths = [ int(round( f )) for f in float_lengths ]

    ## Compensate rounding-related inconsistencies.
        # XXX I hope this actually does what's supposed to do...
        # (Increase/decrease the fields with the biggest rounding differences in order to fit the size)
    diff = size - sum(weighted_lengths)
    while( diff != 0 ):
        sign = -1 if diff < 0 else 1

        ## Calculate index where the rounding produced the biggest difference.
        #    (On equality, the latter one wins.)
        max_diff = 0
        index_of_max_diff = None
        for i in range( len(weighted_lengths) ):
            cur_diff = ( float_lengths[i] - weighted_lengths[i] ) * sign

            if ( cur_diff >= max_diff ):
                max_diff = cur_diff
                index_of_max_diff = i

        ## Increase the just found index by 1.
        weighted_lengths[i] += sign
        diff -= sign

    assert( sum(weighted_lengths) == size )
Mario Hock's avatar
Mario Hock committed
84
85
86
87
88
89
90
91
92
93
94



    ## * split *
    ret = list()
    last_pos = 0
    for pos in weighted_lengths:
        ret.append( text[last_pos:last_pos + pos] )
        last_pos += pos

    return ret
95
96
97
98
99
100


def get_sysinfo():
    #uname = os.uname()
    #input_fields = ("sysname", "nodename", "release", "version", "machine")

101
    output_fields = ("sysname", "hostname", "kernel", "version", "machine", "memory")
102
103
104
105

    ret = dict()
    for out_field, value in zip(output_fields, os.uname()):
        ret[out_field] = value
106
    ret["memory"] = psutil.virtual_memory().total
107
    return ret
108
109


110
111
112
113
114
115
116
117
118
119
120
121
122
123
def sort_named_tuple(data, skip=None):
    """
    Sort a named tuple by its values.

    With |skip| a value can be specified that is excluded from the result.
    """

    d = data._asdict()

    # NOTE: Possible improvement: Accept a list in skip?
    if ( skip ):
        del d[skip]

    return sorted( d.items() , key=operator.itemgetter(1), reverse=True)