Révision 69d17e8b modules/utilities.py

b/modules/utilities.py
20 20
        block_number -= 1
21 21
    all_read_text = b''.join(reversed(blocks))
22 22
    return b'\n'.join(all_read_text.splitlines()[-total_lines_wanted:]).decode()
23

  
24

  
25
def check_bak(file_name):
26
    """Checks if a file already exists and backs it up if so.
27
    @param file_name: file to be checked if exists
28
    """
29
    import os
30
    new_name = file_name
31
    bak_num = 0
32
    while os.path.isdir(new_name) or os.path.isfile(new_name):
33
        bak_num += 1
34
        new_name = new_name.split(".bak")[0] + f".bak{bak_num}"
35
    if bak_num > 0:
36
        os.rename(file_name, new_name)
37
        logger.warning(f"'{file_name}' already present. Backed it up to "
38
                       f"{new_name}")
39

  
40

  
41
def try_command(command, expct_error_types: list, *args, **kwargs):
42
    """Try to run a command and record exceptions (expected and not) on a log.
43

  
44
    @param command: method or function, the command to be executed.
45
    @param expct_error_types: tuple of tuples, every inner tuple is supposed to
46
    contain an exception type (eg. ValueError, TypeError, etc.) to be caught and
47
    a message to print in the log and on the screen explaining the exception.
48
    Error types that are not allow to be called with a custom message as only
49
    error argument are not supported.
50
    The outer tuple encloses all couples of error types and their relative
51
    messages.
52
    *args and **kwargs: arguments and keyword-arguments of the command to be
53
    executed.
54
    When trying to run 'command' with its args and kwargs, if an exception
55
    present on the 'error_types' occurs, its relative error message is recorded
56
    on the log and a same type exception is raised with the custom message.
57
    """
58

  
59
    err = False
60
    try:
61
        return_val = command(*args, **kwargs)
62
    except Exception as e:
63
        for expct_err in expct_error_types:
64
            if isinstance(e, expct_err[0]):
65
                logger.error(expct_err[1])
66
                err = expct_err[0](expct_err[1])
67
                break
68
        else:
69
            logger.exception(unexp_error)
70
            err = e
71
    else:
72
        err = False
73
        return return_val
74
    finally:
75
        if isinstance(err, BaseException):
76
            raise err

Formats disponibles : Unified diff