File: utils.py

package info (click to toggle)
python-easysnmp 0.2.6-1.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 692 kB
  • sloc: ansic: 3,735; python: 1,410; makefile: 161
file content (47 lines) | stat: -rw-r--r-- 1,251 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from __future__ import unicode_literals, absolute_import

import string

from .compat import ub, text_type


def strip_non_printable(value):
    """
    Removes any non-printable characters and adds an indicator to the string
    when binary characters are fonud.

    :param value: the value that you wish to strip
    """
    if value is None:
        return None

    # Filter all non-printable characters
    # (note that we must use join to account for the fact that Python 3
    # returns a generator)
    printable_value = "".join(filter(lambda c: c in string.printable, value))

    if printable_value != value:
        if printable_value:
            printable_value += " "
        printable_value += "(contains binary)"

    return printable_value


def tostr(value):
    """
    Converts any variable to a string or returns None if the variable
    contained None to begin with; this function currently supports None,
    unicode strings, byte strings and numbers.

    :param value: the value you wish to convert to a string
    """

    if value is None:
        return None
    elif isinstance(value, text_type):
        return value
    elif isinstance(value, (int, float)):
        return str(value)
    else:
        return ub(value)