File: utils.py

package info (click to toggle)
python-ezsnmp 1.1.0-2.1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 11,280 kB
  • sloc: cpp: 3,746; python: 1,987; javascript: 1,110; makefile: 17; sh: 12
file content (58 lines) | stat: -rw-r--r-- 1,548 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
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/env python3

from __future__ import unicode_literals, absolute_import
from typing import Optional, Union

import ipaddress
import string


def strip_non_printable(value: Optional[str]) -> Optional[str]:
    """
    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: Union[str, int, float, None]) -> Optional[str]:
    """
    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, str):
        return value
    elif isinstance(value, (int, float)):
        return str(value)
    else:
        return value


def is_hostname_ipv6(hostname: str) -> bool:
    try:
        ipaddress.IPv6Address(hostname)
    except ipaddress.AddressValueError:
        return False
    else:
        return True