當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。