File size: 1,482 Bytes
4fb0bd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import configargparse
import logging
import os


class StoreLoggingLevelAction(configargparse.Action):
    """This class converts string into logging level
    """

    LEVELS = {
        'CRITICAL': logging.CRITICAL,
        'ERROR': logging.ERROR,
        'WARNING': logging.WARNING,
        'INFO': logging.INFO,
        'DEBUG': logging.DEBUG,
        'NOTSET': logging.NOTSET
    }

    CHOICES = list(LEVELS.keys()) + [str(_) for _ in LEVELS.values()]

    def __init__(self, option_strings, dest, help=None, **kwargs):
        super().__init__(option_strings, dest, help=help, **kwargs)

    def __call__(self, parser, namespace, value, option_string=None):
        """This function gets the key 'value' in the LEVELS, or just uses value
        """
        
        level = StoreLoggingLevelAction.LEVELS.get(value, value)
        setattr(namespace, self.dest, level)


class CheckPathAction(configargparse.Action):
    """This class checks file path, if not exits, then create dir(file)
    """

    def __init__(self, option_strings, dest, help=None, **kwargs):
        super().__init__(option_strings, dest, help=help, **kwargs)

    def __call__(self, parser, namespace, value, option_string=None):
        """This function checks file path, if not exits, then create dir(file)
        """
        
        parent_path = os.path.dirname(value)
        if not os.path.exists(parent_path):
            os.makedirs(parent_path)
        setattr(namespace, self.dest, value)