当前位置: 首页>>代码示例>>Python>>正文


Python ast.literal_eval方法代码示例

本文整理汇总了Python中ast.literal_eval方法的典型用法代码示例。如果您正苦于以下问题:Python ast.literal_eval方法的具体用法?Python ast.literal_eval怎么用?Python ast.literal_eval使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ast的用法示例。


在下文中一共展示了ast.literal_eval方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: cfg_from_list

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def cfg_from_list(cfg_list):
  """Set config keys via list (e.g., from command line)."""
  from ast import literal_eval
  assert len(cfg_list) % 2 == 0
  for k, v in zip(cfg_list[0::2], cfg_list[1::2]):
    key_list = k.split('.')
    d = __C
    for subkey in key_list[:-1]:
      assert subkey in d
      d = d[subkey]
    subkey = key_list[-1]
    assert subkey in d
    try:
      value = literal_eval(v)
    except:
      # handle the case when v is a string literal
      value = v
    assert type(value) == type(d[subkey]), \
      'type {} does not match original type {}'.format(
        type(value), type(d[subkey]))
    d[subkey] = value 
开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:23,代码来源:config.py

示例2: format_file

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def format_file(path):
    """Format a file (path) using the available formatters."""
    root_path = os.environ.get('CIOCHECK_PROJECT_ROOT')
    check = ast.literal_eval(os.environ.get('CIOCHECK_CHECK'))
    check_multi_formatters = [f for f in MULTI_FORMATTERS if f.name in check]

    results = {}

    for formatter in check_multi_formatters:
        paths = filter_files([path], formatter.extensions)
        if paths:
            formatter.cmd_root = root_path
            result = formatter.format_task(path)
            if result:
                results[formatter.name] = result
    return results 
开发者ID:ContinuumIO,项目名称:ciocheck,代码行数:18,代码来源:format_task.py

示例3: set_config

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def set_config(self, request):
        uid = await self.check_user(request)
        if uid is None:
            return web.Response(status=401)
        data = await request.json()
        mid, key, value = int(data["mid"]), data["key"], data["value"]
        mod = self.client_data[uid][0].modules[mid]
        if value:
            try:
                value = ast.literal_eval(value)
            except (ValueError, SyntaxError):
                pass
            self.client_data[uid][2].setdefault(mod.__module__, {}).setdefault("__config__", {})[key] = value
        else:
            try:
                del self.client_data[uid][2].setdefault(mod.__module__, {}).setdefault("__config__", {})[key]
            except KeyError:
                pass
        self.client_data[uid][0].send_config_one(mod, self.client_data[uid][2], skip_hook=True)
        self.client_data[uid][2].save()
        return web.Response() 
开发者ID:friendly-telegram,项目名称:friendly-telegram,代码行数:23,代码来源:config.py

示例4: custom_command

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def custom_command(self, client, args, message):
        if len(args) < 1:
            await utils.answer(message, self.strings["what_client_command"])
            return
        cmd = getattr(client, args[0], None)
        if not callable(cmd):
            await utils.answer(message, self.strings["bad_client_command"])
            return
        fargs = []
        for arg in args[1:]:
            try:
                fargs.append(ast.literal_eval(arg))
            except (ValueError, SyntaxError):
                fargs.append(arg)
        logger.debug(fargs)
        await cmd(*fargs) 
开发者ID:friendly-telegram,项目名称:friendly-telegram,代码行数:18,代码来源:remote.py

示例5: writesummary

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def writesummary(self):
    """ Write summary file """

    for section in summaryfile.sections():
      for option in summaryfile.options(section):
        summaryfile.set(section, option, str(self.summary[section][option]))
    of = open(config['files']['summaryfile'],'w')
    summaryfile.write(of)
    of.close()

#  def writehour(self, data):
#    hoursummaryfile=open('/media/75cc9171-4331-4f88-ac3f-0278d132fae9/hoursummary','a')
#    hoursummaryfile.write(data)
#    hoursummaryfile.close()
#    logsummary.set('alltime', 'maxvoltages') = round(max(literal_eval(logsummary.get('currentday','maxvoltages')),literal_eval(logsummary.get(),2)
#    logsummary.set('alltime', 'minvoltages') = round(min(literal_eval(logsummary.get('currentday','minvoltages')),batdata.batvoltsav[8]),2)
#    logsummary.set('alltime', 'ah') = round(max(literal_eval(logsummary.get('currentday','ah'))[1], batdata.soc/1000),2)
#    logsummary.set('alltime', 'ah') = round(min(literal_eval(logsummary.get('currentday','ah'))[0], batdata.soc/1000),2)
#    logsummary.set('alltime', 'current') = round(max(literal_eval(logsummary.get('alltime','current'))[1], batdata.currentav[-3]/1000),2)
#    logsummary.set('alltime', 'current') = round(min(literal_eval(logsummary.get('alltime','current'))[0], batdata.currentav[-3]/1000),2) 
开发者ID:simat,项目名称:BatteryMonitor,代码行数:22,代码来源:summary.py

示例6: _convert_property_type

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def _convert_property_type(value):
        """Converts the string value in a boolean, integer or string

        :param value: string value
        :returns: boolean, integer or string value
        """
        if value in ('true', 'True'):
            return True
        elif value in ('false', 'False'):
            return False
        elif str(value).startswith('{') and str(value).endswith('}'):
            return ast.literal_eval(value)
        else:
            try:
                return int(value)
            except ValueError:
                return value 
开发者ID:Telefonica,项目名称:toolium,代码行数:19,代码来源:config_driver.py

示例7: post

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def post(self, request, *args, **kwargs):
        response = super(TokenView, self).post(request, *args, **kwargs)
        content = ast.literal_eval(response.content.decode("utf-8"))
        if response.status_code == 200 and 'access_token' in content:
            if not TokenView._is_jwt_config_set():
                logger.warning(
                    'Missing JWT configuration, skipping token build')
            else:
                try:
                    content['access_token_jwt'] = self._get_access_token_jwt(
                        request, content)
                    try:
                        content = bytes(json.dumps(content), 'utf-8')
                    except TypeError:
                        content = bytes(json.dumps(content).encode("utf-8"))
                    response.content = content
                except MissingIdAttribute:
                    response.status_code = 400
                    response.content = json.dumps({
                        "error": "invalid_request",
                        "error_description": "App not configured correctly. "
                                             "Please set JWT_ID_ATTRIBUTE.",
                    })
        return response 
开发者ID:Humanitec,项目名称:django-oauth-toolkit-jwt,代码行数:26,代码来源:views.py

示例8: native_concat

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def native_concat(nodes):
    """Return a native Python type from the list of compiled nodes. If the
    result is a single node, its value is returned. Otherwise, the nodes are
    concatenated as strings. If the result can be parsed with
    :func:`ast.literal_eval`, the parsed value is returned. Otherwise, the
    string is returned.
    """
    head = list(islice(nodes, 2))

    if not head:
        return None

    if len(head) == 1:
        out = head[0]
    else:
        out = u''.join([text_type(v) for v in chain(head, nodes)])

    try:
        return literal_eval(out)
    except (ValueError, SyntaxError, MemoryError):
        return out 
开发者ID:remg427,项目名称:misp42splunk,代码行数:23,代码来源:nativetypes.py

示例9: _get_constant

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def _get_constant(name):
    """Read a __magic__ constant from qutebrowser/__init__.py.

    We don't import qutebrowser here because it can go wrong for multiple
    reasons. Instead we use re/ast to get the value directly from the source
    file.

    Args:
        name: The name of the argument to get.

    Return:
        The value of the argument.
    """
    field_re = re.compile(r'__{}__\s+=\s+(.*)'.format(re.escape(name)))
    path = os.path.join(BASEDIR, 'qutebrowser', '__init__.py')
    line = field_re.search(read_file(path)).group(1)
    value = ast.literal_eval(line)
    return value 
开发者ID:qutebrowser,项目名称:qutebrowser,代码行数:20,代码来源:setup.py

示例10: cfg_from_list

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def cfg_from_list(cfg_list):
    """Set config keys via list (e.g., from command line)."""
    from ast import literal_eval
    assert len(cfg_list) % 2 == 0
    for k, v in zip(cfg_list[0::2], cfg_list[1::2]):
        key_list = k.split('.')
        d = __C
        for subkey in key_list[:-1]:
            assert subkey in d.keys()
            d = d[subkey]
        subkey = key_list[-1]
        assert subkey in d.keys()
        try:
            value = literal_eval(v)
        except:
            # handle the case when v is a string literal
            value = v
        assert type(value) == type(d[subkey]), \
            'type {} does not match original type {}'.format(
            type(value), type(d[subkey]))
        d[subkey] = value 
开发者ID:chrischoy,项目名称:3D-R2N2,代码行数:23,代码来源:config.py

示例11: load_secrets_file

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def load_secrets_file(config_dict: dict) -> dict:
    from string import Template
    import ast

    gn_env = os.getenv(ENV_KEY_ENVIRONMENT)
    secrets_path = os.getenv(ENV_KEY_SECRETS)
    if secrets_path is None:
        secrets_path = 'secrets/%s.yaml' % gn_env

    logger.debug('loading secrets file "%s"' % secrets_path)

    # first substitute environment variables, which holds precedence over the yaml config (if it exists)
    template = Template(str(config_dict))
    template = template.safe_substitute(os.environ)

    if os.path.isfile(secrets_path):
        try:
            secrets = yaml.safe_load(open(secrets_path))
        except Exception as e:
            raise RuntimeError("Failed to open secrets configuration {0}: {1}".format(secrets_path, str(e)))
        template = Template(template)
        template = template.safe_substitute(secrets)

    return ast.literal_eval(template) 
开发者ID:thenetcircle,项目名称:dino,代码行数:26,代码来源:environ.py

示例12: load_secrets_file

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def load_secrets_file(config_dict: dict) -> dict:
    from string import Template
    import ast

    secrets_path = dino_home + '/secrets/%s.yaml' % dino_env

    # first substitute environment variables, which holds precedence over the yaml config (if it exists)
    template = Template(str(config_dict))
    template = template.safe_substitute(os.environ)

    if os.path.isfile(secrets_path):
        try:
            secrets = yaml.safe_load(open(secrets_path))
        except Exception as e:
            raise RuntimeError("Failed to open secrets configuration {0}: {1}".format(secrets_path, str(e)))
        template = Template(template)
        template = template.safe_substitute(secrets)

    return ast.literal_eval(template) 
开发者ID:thenetcircle,项目名称:dino,代码行数:21,代码来源:count_users_in_rooms.py

示例13: check_docstring_missing

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def check_docstring_missing(self, definition, docstring):
        """D10{0,1,2,3}: Public definitions should have docstrings.

        All modules should normally have docstrings.  [...] all functions and
        classes exported by a module should also have docstrings. Public
        methods (including the __init__ constructor) should also have
        docstrings.

        Note: Public (exported) definitions are either those with names listed
              in __all__ variable (if present), or those that do not start
              with a single underscore.

        """
        if (not docstring and definition.is_public or
                docstring and is_blank(ast.literal_eval(docstring))):
            codes = {Module: violations.D100,
                     Class: violations.D101,
                     NestedClass: violations.D106,
                     Method: (lambda: violations.D105() if definition.is_magic
                              else (violations.D107() if definition.is_init
                              else violations.D102())),
                     Function: violations.D103,
                     NestedFunction: violations.D103,
                     Package: violations.D104}
            return codes[type(definition)]() 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:27,代码来源:checker.py

示例14: check_blank_after_summary

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def check_blank_after_summary(self, definition, docstring):
        """D205: Put one blank line between summary line and description.

        Multi-line docstrings consist of a summary line just like a one-line
        docstring, followed by a blank line, followed by a more elaborate
        description. The summary line may be used by automatic indexing tools;
        it is important that it fits on one line and is separated from the
        rest of the docstring by a blank line.

        """
        if docstring:
            lines = ast.literal_eval(docstring).strip().split('\n')
            if len(lines) > 1:
                post_summary_blanks = list(map(is_blank, lines[1:]))
                blanks_count = sum(takewhile(bool, post_summary_blanks))
                if blanks_count != 1:
                    return violations.D205(blanks_count) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:19,代码来源:checker.py

示例15: check_triple_double_quotes

# 需要导入模块: import ast [as 别名]
# 或者: from ast import literal_eval [as 别名]
def check_triple_double_quotes(self, definition, docstring):
        r'''D300: Use """triple double quotes""".

        For consistency, always use """triple double quotes""" around
        docstrings. Use r"""raw triple double quotes""" if you use any
        backslashes in your docstrings. For Unicode docstrings, use
        u"""Unicode triple-quoted strings""".

        Note: Exception to this is made if the docstring contains
              """ quotes in its body.

        '''
        if docstring:
            if '"""' in ast.literal_eval(docstring):
                # Allow ''' quotes if docstring contains """, because
                # otherwise """ quotes could not be expressed inside
                # docstring. Not in PEP 257.
                regex = re(r"[uU]?[rR]?'''[^'].*")
            else:
                regex = re(r'[uU]?[rR]?"""[^"].*')

            if not regex.match(docstring):
                illegal_matcher = re(r"""[uU]?[rR]?("+|'+).*""")
                illegal_quotes = illegal_matcher.match(docstring).group(1)
                return violations.D300(illegal_quotes) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:27,代码来源:checker.py


注:本文中的ast.literal_eval方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。