예제 #1
0
파일: log.py 프로젝트: wenhuiwu/CUP
def _fail_handle(msg, e):
    if platforms.is_py2():
        if not isinstance(msg, unicode):
            msg = msg.decode('utf8')
        print('{0}\nerror:{1}'.format(msg, e))
    elif platforms.is_py3():
        print('{0}\nerror:{1}'.format(msg, e))
예제 #2
0
    def _comp_write_keys(cls, valuex, valuey):
        if platforms.is_py2():
            _py_type = [bool, int, float, str, unicode]
        else:
            _py_type = [bool, int, float, str]

        if type(valuex) == type(valuey):
            return 0

        for py_type in _py_type:
            if isinstance(valuex, py_type):
                return -1

        for py_type in _py_type:
            if isinstance(valuey, py_type):
                return 1

        if isinstance(valuex, list) and isinstance(valuey, list):
            try:
                if isinstance(valuex[0], dict) or isinstance(valuex[0], list):
                    return 1
                else:
                    return -1
            # pylint: disable=W0703
            except Exception:
                return -1
            else:
                return -1
        # if isinstance(valuex, list) and isinstance(valuey, str):
        #     return 1
        if isinstance(valuex, dict):
            return 1
        if isinstance(valuey, dict):
            return -1
        return 1
예제 #3
0
파일: oper.py 프로젝트: wenhuiwu/CUP
 def _trans_bytes(data):
     """trans bytes into unicode for python3"""
     if platforms.is_py2():
         return data
     if isinstance(data, bytes):
         try:
             data = bytes.decode(data)
         except Exception:
             data = 'Error to decode result'
     return data
예제 #4
0
파일: log.py 프로젝트: traceofpoem/CUP
 def log_file_func_info(cls, msg, back_trace_len=0):
     """return log traceback info"""
     tempmsg = ' * [%s] [%s:%s] ' % (cls.proc_thd_id(),
                                     cls.get_codefile(2 + back_trace_len),
                                     cls.get_codeline(2 + back_trace_len))
     msg = '{0}{1}'.format(tempmsg, msg)
     if platforms.is_py2():
         if isinstance(msg, unicode):
             return msg
         return msg.decode('utf8')
     return msg
예제 #5
0
파일: conf.py 프로젝트: wenhuiwu/CUP
    def write_conf(self, conf_file, encoding='utf8'):
        """
        write the conf into of the dict into a conf_file

        :param conf_file:
            the file which will be override
        :param encoding:
            'utf8' by default, specify yours if needed
        """
        fhandle = None
        if platforms.is_py2():
            fhandle = _open_codecs(conf_file, 'w', encoding=encoding)
        else:
            fhandle = open(conf_file, 'w', encoding=encoding)
        fhandle.write(self._get_write_string())
        fhandle.close()
예제 #6
0
파일: conf.py 프로젝트: wenhuiwu/CUP
    def write_conf(self, kvs, encoding='utf8'):
        """
        update config items with a dict kvs. Refer to the example above.

        :param kvs:
            ::

                {
                    key : { 'value': value, 'description': 'description'},
                    ......
                }
        """
        self._encoding = encoding
        self._load_items()
        str_xml = self._write_to_conf(kvs)
        fhandle = None
        if platforms.is_py2():
            fhandle = _open_codecs(self._xmlpath, 'w', encoding=encoding)
        else:
            fhandle = open(self._xmlpath, 'w', encoding=encoding)
        fhandle.write(str_xml)
        fhandle.close()
        self._confdict = kvs
예제 #7
0
파일: conf.py 프로젝트: wenhuiwu/CUP
    def _get_input_lines(self, ignore_error, encoding):
        """
        read conf lines
        """
        fhandle = None
        try:
            if platforms.is_py2():
                fhandle = _open_codecs(self._file, 'r', encoding=encoding)
            else:
                fhandle = open(self._file, 'r', encoding=encoding)
        except IOError as error:
            cup.log.error('open file failed:%s, err:%s' % (self._file, error))
            raise IOError(error)
        for line in fhandle.readlines():
            line = line.strip()
            # if it's a blank line or a line with comments only
            if line == '':
                line = '__comments__%s%s' % (self._separator, '\n')
            if line.startswith('#'):
                line = '__comments__%s%s\n' % (self._separator, line)
                continue
            if line.startswith('$include'):
                self._handle_include_syntx(line, ignore_error)
                continue
            # if it's a section
            if line.startswith('['):
                if line.find('#') > 0:
                    line = line[:line.find('#')].strip()
                if not line.endswith(']'):
                    raise LineFormatError('Parse line error, line:\n' + line)
                line = line[1:-1]
                key = line.lstrip('.')
                self._check_groupkey_valid(key)  # check if key is valid
                self._lines.append(line)
                continue
            # key, value = line.split(':', 1)
            key, value = line.split(self._separator, 1)
            key = key.strip()
            value = value.strip(' \t')
            # if remove_comments is True, delete comments in value.

            self._check_key_valid(key)
            if value.startswith('"'):  # if the value is a string
                if not value.endswith('"'):
                    raise ValueFormatError(line)
            else:
                if key != '__comments__':
                    value = self._strip_value(value)
            if value.startswith('"'):
                tmp_value = ''
                # reserve escape in the value string
                escape = False
                for single in value:
                    if escape:
                        if single == '0':
                            tmp_value += '\0'
                        elif single == 'n':
                            tmp_value += '\n'
                        elif single == 'r':
                            tmp_value += '\r'
                        elif single == 't':
                            tmp_value += '\t'
                        elif single == 'v':
                            tmp_value += '\v'
                        elif single == 'a':
                            tmp_value += '\a'
                        elif single == 'b':
                            tmp_value += '\b'
                        elif single == 'd':
                            tmp_value += r'\d'
                        elif single == 'f':
                            tmp_value += '\f'
                        elif single == "'":
                            tmp_value += "'"
                        elif single == '"':
                            tmp_value += '"'
                        elif single == '\\':
                            tmp_value += '\\'
                        else:
                            # raise ValueFormatError(line)
                            pass
                        escape = False
                    elif single == '\\':
                        escape = True
                    else:
                        tmp_value += single
                if escape:
                    raise ValueFormatError(line)
                value = tmp_value
            self._lines.append((key, value))
        fhandle.close()