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


Python ast.PyCF_ONLY_AST方法代码示例

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


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

示例1: _makeAST

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def _makeAST(f):
    # Need to look at the flags used to compile the original function f and
    # pass these same flags to the compile() function. This ensures that
    # syntax-changing __future__ imports like print_function work correctly.
    orig_f_co_flags = f.__code__.co_flags
    # co_flags can contain various internal flags that we can't pass to
    # compile(), so strip them out here
    valid_flags = 0
    for future_feature in __future__.all_feature_names:
        feature = getattr(__future__, future_feature)
        valid_flags |= feature.compiler_flag
    s = inspect.getsource(f)
    s = _dedent(s)
    # use compile instead of ast.parse so that additional flags can be passed
    flags = ast.PyCF_ONLY_AST | (orig_f_co_flags & valid_flags)
    tree = compile(s, filename='<unknown>', mode='exec',
        flags=flags, dont_inherit=True)
    # tree = ast.parse(s)
    tree.sourcefile = inspect.getsourcefile(f)
    tree.lineoffset = inspect.getsourcelines(f)[1] - 1
    return tree 
开发者ID:myhdl,项目名称:myhdl,代码行数:23,代码来源:_util.py

示例2: version

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def version():
    path = 'pypika/__init__.py'
    with open(path, 'r') as file:
        t = compile(file.read(), path, 'exec', ast.PyCF_ONLY_AST)
        for node in (n for n in t.body if isinstance(n, ast.Assign)):
            if len(node.targets) == 1:
                name = node.targets[0]
                if isinstance(name, ast.Name) and \
                      name.id in ('__version__', '__version_info__', 'VERSION'):
                    v = node.value
                    if isinstance(v, ast.Str):
                        return v.s

                    if isinstance(v, ast.Tuple):
                        r = []
                        for e in v.elts:
                            if isinstance(e, ast.Str):
                                r.append(e.s)
                            elif isinstance(e, ast.Num):
                                r.append(str(e.n))
                        return '.'.join(r) 
开发者ID:kayak,项目名称:pypika,代码行数:23,代码来源:setup.py

示例3: get_code_complexity

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def get_code_complexity(code, threshold=7, filename='stdin'):
    try:
        tree = compile(code, filename, "exec", ast.PyCF_ONLY_AST)
    except SyntaxError:
        e = sys.exc_info()[1]
        sys.stderr.write("Unable to parse %s: %s\n" % (filename, e))
        return 0

    complx = []
    McCabeChecker.max_complexity = threshold
    for lineno, offset, text, check in McCabeChecker(tree, filename).run():
        complx.append('%s:%d:1: %s' % (filename, lineno, text))

    if len(complx) == 0:
        return 0
    print('\n'.join(complx))
    return len(complx) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:19,代码来源:mccabe.py

示例4: get_config_comments

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def get_config_comments(func):
    filename = inspect.getfile(func)
    func_body, line_offset = get_function_body(func)
    body_source = dedent_function_body(func_body)
    body_code = compile(body_source, filename, "exec", ast.PyCF_ONLY_AST)
    body_lines = body_source.split("\n")

    variables = {"seed": "the random seed for this experiment"}

    for ast_root in body_code.body:
        for ast_entry in [ast_root] + list(ast.iter_child_nodes(ast_root)):
            if isinstance(ast_entry, ast.Assign):
                # we found an assignment statement
                # go through all targets of the assignment
                # usually a single entry, but can be more for statements like:
                # a = b = 5
                for t in ast_entry.targets:
                    add_doc(t, variables, body_lines)

    return variables 
开发者ID:IDSIA,项目名称:sacred,代码行数:22,代码来源:config_scope.py

示例5: verify_condition

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def verify_condition(condition, variables_and_values):
  """Verifies the |condition| dictionary is in the expected format.
  See verify_ast() for the meaning of |variables_and_values|.
  """
  VALID_INSIDE_CONDITION = ['variables']
  assert isinstance(condition, list), condition
  assert len(condition) == 2, condition
  expr, then = condition

  test_ast = compile(expr, '<condition>', 'eval', ast.PyCF_ONLY_AST)
  verify_ast(test_ast.body, variables_and_values)

  assert isinstance(then, dict), then
  assert set(VALID_INSIDE_CONDITION).issuperset(set(then)), then.keys()
  if not 'variables' in then:
    raise IsolateError('Missing \'variables\' in condition %s' % condition)
  verify_variables(then['variables']) 
开发者ID:luci,项目名称:luci-py,代码行数:19,代码来源:isolate_format.py

示例6: __init__

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def __init__(self, tracer, source, filename, flags):
        # type: (TreeTracerBase, str, str, int) -> None
        # Here the source code is parsed, modified, and compiled
        self.root = compile(source, filename, 'exec', ast.PyCF_ONLY_AST | flags, dont_inherit=True)  # type: ast.Module

        self.nodes = []  # type: List[ast.AST]

        self.set_basic_node_attributes()

        new_root = tracer.parse_extra(self.root, source, filename)
        if new_root is not None:
            self.root = new_root

        self.set_basic_node_attributes()
        self.set_enter_call_nodes()

        new_root = deepcopy(self.root)
        new_root = _NodeVisitor().visit(new_root)

        self.code = compile(new_root, filename, "exec", dont_inherit=True, flags=flags)  # type: CodeType
        self.tracer = tracer
        self.source = source
        self.filename = filename 
开发者ID:alexmojaki,项目名称:executing,代码行数:25,代码来源:tracer.py

示例7: compile_for_aexec

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def compile_for_aexec(
    source, filename="<aexec>", mode="single", dont_imply_dedent=False, local={}
):
    """Return a list of (coroutine object, abstract base tree)."""
    flags = ast.PyCF_ONLY_AST
    if dont_imply_dedent:
        flags |= codeop.PyCF_DONT_IMPLY_DEDENT

    # Avoid a syntax error by wrapping code with `async def`
    indented = "\n".join(line and " " * 4 + line for line in source.split("\n"))
    coroutine = CORO_DEF + "\n" + indented + "\n"
    interactive = compile(coroutine, filename, mode, flags).body[0]

    # Check EOF errors
    try:
        compile(source, filename, mode, flags)
    except SyntaxError as exc:
        if exc.msg == "unexpected EOF while parsing":
            raise

    return [make_tree(statement, filename, mode) for statement in interactive.body] 
开发者ID:vxgmichel,项目名称:aioconsole,代码行数:23,代码来源:execute.py

示例8: test_compile_to_ast

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def test_compile_to_ast(self):
        import ast
        source = Source("x = 4")
        mod = source.compile(flag=ast.PyCF_ONLY_AST)
        assert isinstance(mod, ast.Module)
        compile(mod, "<filename>", "exec") 
开发者ID:pytest-dev,项目名称:py,代码行数:8,代码来源:test_source.py

示例9: get_mccabe_violations_for_file

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def get_mccabe_violations_for_file(filepath, max_complexity):
    code = _read(filepath)
    tree = compile(code, filepath, "exec", ast.PyCF_ONLY_AST)
    visitor = PathGraphingAstVisitor()
    visitor.preorder(tree, visitor)

    violations = []
    for graph in visitor.graphs.values():
        if graph.complexity() >= max_complexity:
            complex_function_name = graph.entity
            if complex_function_name.startswith('If '):
                complex_function_name = 'if __name__ == "__main__"'
            violations.append(complex_function_name)
    return violations 
开发者ID:devmanorg,项目名称:fiasko_bro,代码行数:16,代码来源:code_helpers.py

示例10: run

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def run(path, code=None, params=None, **meta):
        """MCCabe code checking.

        :return list: List of errors.
        """
        tree = compile(code, path, "exec", ast.PyCF_ONLY_AST)

        McCabeChecker.max_complexity = int(params.get('complexity', 10))
        return [
            {'lnum': lineno, 'offset': offset, 'text': text, 'type': McCabeChecker._code}
            for lineno, offset, text, _ in McCabeChecker(tree, path).run()
        ]

#  pylama:ignore=W0212 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:16,代码来源:pylama_mccabe.py

示例11: main

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]
    opar = optparse.OptionParser()
    opar.add_option("-d", "--dot", dest="dot",
                    help="output a graphviz dot file", action="store_true")
    opar.add_option("-m", "--min", dest="threshold",
                    help="minimum complexity for output", type="int",
                    default=1)

    options, args = opar.parse_args(argv)

    code = _read(args[0])
    tree = compile(code, args[0], "exec", ast.PyCF_ONLY_AST)
    visitor = PathGraphingAstVisitor()
    visitor.preorder(tree, visitor)

    if options.dot:
        print('graph {')
        for graph in visitor.graphs.values():
            if (not options.threshold or
                    graph.complexity() >= options.threshold):
                graph.to_dot()
        print('}')
    else:
        for graph in visitor.graphs.values():
            if graph.complexity() >= options.threshold:
                print(graph.name, graph.complexity()) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:30,代码来源:mccabe.py

示例12: get_function_body_code

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def get_function_body_code(func):
    filename = inspect.getfile(func)
    func_body, line_offset = get_function_body(func)
    body_source = dedent_function_body(func_body)
    try:
        body_code = compile(body_source, filename, "exec", ast.PyCF_ONLY_AST)
        body_code = ast.increment_lineno(body_code, n=line_offset)
        body_code = compile(body_code, filename, "exec")
    except SyntaxError as e:
        if e.args[0] == "'return' outside function":
            filename, lineno, _, statement = e.args[1]
            raise SyntaxError(
                "No return statements allowed in ConfigScopes\n"
                "('{}' in File \"{}\", line {})".format(
                    statement.strip(), filename, lineno
                )
            )
        elif e.args[0] == "'yield' outside function":
            filename, lineno, _, statement = e.args[1]
            raise SyntaxError(
                "No yield statements allowed in ConfigScopes\n"
                "('{}' in File \"{}\", line {})".format(
                    statement.strip(), filename, lineno
                )
            )
        else:
            raise
    return body_code 
开发者ID:IDSIA,项目名称:sacred,代码行数:30,代码来源:config_scope.py

示例13: getstatementrange_ast

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def getstatementrange_ast(lineno, source, assertion=False, astnode=None):
    if astnode is None:
        content = str(source)
        # See #4260:
        # don't produce duplicate warnings when compiling source to find ast
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            astnode = compile(content, "source", "exec", _AST_FLAG)

    start, end = get_statement_startend2(lineno, astnode)
    # we need to correct the end:
    # - ast-parsing strips comments
    # - there might be empty lines
    # - we might have lesser indented code blocks at the end
    if end is None:
        end = len(source.lines)

    if end > start + 1:
        # make sure we don't span differently indented code blocks
        # by using the BlockFinder helper used which inspect.getsource() uses itself
        block_finder = inspect.BlockFinder()
        # if we start with an indented line, put blockfinder to "started" mode
        block_finder.started = source.lines[start][0].isspace()
        it = ((x + "\n") for x in source.lines[start:end])
        try:
            for tok in tokenize.generate_tokens(lambda: next(it)):
                block_finder.tokeneater(*tok)
        except (inspect.EndOfBlock, IndentationError):
            end = block_finder.last + start
        except Exception:
            pass

    # the end might still point to a comment or empty line, correct it
    while end:
        line = source.lines[end - 1].lstrip()
        if line.startswith("#") or not line:
            end -= 1
        else:
            break
    return astnode, start, end 
开发者ID:sofia-netsurv,项目名称:python-netsurv,代码行数:42,代码来源:source.py

示例14: test_snippets

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def test_snippets(self):
        for input, output, kind in ((exec_tests, exec_results, "exec"),
                                    (single_tests, single_results, "single"),
                                    (eval_tests, eval_results, "eval")):
            for i, o in itertools.izip(input, output):
                ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
                self.assertEqual(to_tuple(ast_tree), o)
                self._assertTrueorder(ast_tree, (0, 0)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:10,代码来源:test_ast.py

示例15: test_parse

# 需要导入模块: import ast [as 别名]
# 或者: from ast import PyCF_ONLY_AST [as 别名]
def test_parse(self):
        a = ast.parse('foo(1 + 1)')
        b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
        self.assertEqual(ast.dump(a), ast.dump(b)) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:6,代码来源:test_ast.py


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