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


Python _ast.Call方法代码示例

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


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

示例1: run

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import Call [as 别名]
def run(self, node, input_state):
    result_state = input_state.copy()
    block = node.data

    constraints = self.cfg.block_constraints

    for stmt in block.statements:
      native = stmt.native
      if isinstance(native, _ast.Assign) or isinstance(native, _ast.AugAssign):
        self.transfer_assign(result_state, native, stmt.start_bytecode_index)

      elif isinstance(native, _ast.Expr):
        value = native.value
        logger.debug("Stmt kind: %s", type(value))
        if isinstance(value, _ast.Call):
          self.transfer_call(result_state, native, stmt.start_bytecode_index)
      else:
        logger.error("Unknown stmt: %s", dump_native_ast(native))

    return result_state


  # Assign: a <- b 
开发者ID:neuroo,项目名称:equip,代码行数:25,代码来源:types.py

示例2: setup_py

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import Call [as 别名]
def setup_py(location: str) -> dict:
    """Returns back any configuration info we are able to determine from a setup.py file"""
    setup_config = {}
    try:
        with open(location) as setup_py_file:
            for node in ast.walk(ast.parse(setup_py_file.read())):
                if (
                    type(node) == _ast.Call
                    and type(getattr(node, "func", None)) == _ast.Name
                    and node.func.id == "setup"  # type: ignore
                ):
                    for keyword in node.keywords:  # type: ignore
                        if keyword.arg == "packages":
                            setup_config["modules"] = ast.literal_eval(keyword.value)
                            break
                    break
    except Exception as error:
        warnings.warn(f"Error ({error}) occurred trying to parse setup.py file: {location}")

    return setup_config 
开发者ID:timothycrosley,项目名称:portray,代码行数:22,代码来源:config.py

示例3: visit_Call

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import Call [as 别名]
def visit_Call( self, node ):
    # TODO: specially handle self.visit( node.func ) if attr
    #       currently not visiting at all!
    args     = [self.visit(x) for x in node.args]
    keywords = [self.visit(x) for x in node.keywords]
    if node.starargs:
      starargs = [self.visit(x) for x in node.starargs]
    else:
      starargs = None
    if node.kwargs:
      kwargs = [self.visit(x) for x in node.kwargs]
    else:
      kwargs = None

    return _ast.Call(func=node.func,
                     args=args,
                     keyword=keywords,
                     starargs=starargs,
                     kwargs=kwargs) 
开发者ID:cornell-brg,项目名称:pymtl,代码行数:21,代码来源:cpp.py

示例4: NAME

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import Call [as 别名]
def NAME(self, node):
        """
        Handle occurrence of Name (which can be a load/store/delete access.)
        """
        # Locate the name in locals / function / globals scopes.
        if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
            self.handleNodeLoad(node)
            if (node.id == 'locals' and isinstance(self.scope, FunctionScope)
                    and isinstance(node.parent, ast.Call)):
                # we are doing locals() call in current scope
                self.scope.usesLocals = True
        elif isinstance(node.ctx, (ast.Store, ast.AugStore)):
            self.handleNodeStore(node)
        elif isinstance(node.ctx, ast.Del):
            self.handleNodeDelete(node)
        else:
            # must be a Param context -- this only happens for names in function
            # arguments, but these aren't dispatched through here
            raise RuntimeError("Got impossible expression context: %r" % (node.ctx,)) 
开发者ID:zrzka,项目名称:blackmamba,代码行数:21,代码来源:checker.py

示例5: visit_call

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import Call [as 别名]
def visit_call(self, node: _ast.Call):  # func, args, keywords
        func = self._run(node.func)
        args = [self._run(x) for x in node.args]
        keywords = {x.arg: self._run(x.value) for x in node.keywords}
        return func(*args, **keywords) 
开发者ID:item4,项目名称:yui,代码行数:7,代码来源:calc.py

示例6: get_rules

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import Call [as 别名]
def get_rules():
	
	with open(PARSER_FILE) as f:
		src = f.read()
	
	rules = collections.OrderedDict()
	for node in ast.parse(src).body:
		
		if not isinstance(node, _ast.FunctionDef):
			continue
		
		if not node.decorator_list:
			continue
		
		assert len(node.decorator_list) == 1
		decorator = node.decorator_list[0]
		if not isinstance(decorator, _ast.Call):
			continue
		
		func = decorator.func
		if not isinstance(func, _ast.Attribute):
			continue
		
		assert func.attr == 'production'
		ln = decorator.args[0].s
		name, match = ln.split(' : ', 1)
		rules.setdefault(name, []).append(tuple(match.split()))
	
	return rules 
开发者ID:djc,项目名称:runa,代码行数:31,代码来源:grammar.py

示例7: make_call

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import Call [as 别名]
def make_call(i, bytecode):
    op = bytecode[i][2]

    def get_call_arg_length(op, arg):
      na = arg & 0xff         # num args
      nk = (arg >> 8) & 0xff  # num keywords
      return na, nk, na + 2 * nk + CALL_EXTRA_ARG_OFFSET[op]

    has_var, has_kw = 0, 0
    if op in (CALL_FUNCTION_VAR, CALL_FUNCTION_VAR_KW): has_var = 1
    if op in (CALL_FUNCTION_KW, CALL_FUNCTION_VAR_KW): has_kw = 1

    op, arg = bytecode[i][2], bytecode[i][3]
    num_args, num_keywords, offset = get_call_arg_length(op, arg)

    func, args, keywords, starargs, kwargs = None, None, None, None, None

    if has_kw > 0:
      i, kwargs = Statement.make_expr(i - 1, bytecode)

    if has_var > 0:
      i, starargs = Statement.make_expr(i - 1, bytecode)

    # Handle keywords
    if num_keywords > 0:
      keywords = []
      while num_keywords > 0:
        i, kw_value = Statement.make_expr(i - 1, bytecode)
        i, kw_name = Statement.make_expr(i - 1, bytecode)
        keywords.insert(0, _ast.keyword(kw_name, kw_value))
        num_keywords -= 1

    finger = i - 1

    if num_args > 0:
      n = num_args - 1
      args = [None] * num_args
      for k in range(num_args):
        cur_stack = 0
        loc_bytecode = []
        is_first = True
        while True:
          op, arg = bytecode[finger][2], bytecode[finger][3]
          pop, push = get_stack_effect(op, arg)
          cur_stack -= (pop - push) if not is_first else pop
          is_first = False
          loc_bytecode.insert(0, bytecode[finger])
          if cur_stack == 0:
            break
          finger -= 1
        _, args[n] = Statement.make_expr(len(loc_bytecode) - 1, loc_bytecode)
        n -= 1
        finger -= 1

    _, func = Statement.make_expr(finger, bytecode)

    call = _ast.Call(func, args, keywords, starargs, kwargs)
    logger.debug("\n%s", dump(call))
    return finger, call 
开发者ID:neuroo,项目名称:equip,代码行数:61,代码来源:stmt.py

示例8: parse_source_file

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import Call [as 别名]
def parse_source_file(file_name):
  """
  Parses the AST of Python file for lines containing
  references to the argparse module.

  returns the collection of ast objects found.

  Example client code:

    1. parser = ArgumentParser(desc="My help Message")
    2. parser.add_argument('filename', help="Name of the file to load")
    3. parser.add_argument('-f', '--format', help='Format of output \nOptions: ['md', 'html']
    4. args = parser.parse_args()

  Variables:
    * nodes 									Primary syntax tree object
    *	argparse_assignments   	The assignment of the ArgumentParser (line 1 in example code)
    * add_arg_assignments     Calls to add_argument() (lines 2-3 in example code)
    * parser_var_name					The instance variable of the ArgumentParser (line 1 in example code)
    * ast_source							The curated collection of all parser related nodes in the client code
  """

  nodes = ast.parse(_openfile(file_name))

  module_imports = get_nodes_by_instance_type(nodes, _ast.Import)
  specific_imports = get_nodes_by_instance_type(nodes, _ast.ImportFrom)

  assignment_objs = get_nodes_by_instance_type(nodes, _ast.Assign)
  call_objects = get_nodes_by_instance_type(nodes, _ast.Call)

  argparse_assignments = get_nodes_by_containing_attr(assignment_objs, 'ArgumentParser')
  add_arg_assignments  = get_nodes_by_containing_attr(call_objects, 'add_argument')
  parse_args_assignment = get_nodes_by_containing_attr(call_objects, 'parse_args')

  ast_argparse_source = chain(
    module_imports,
    specific_imports,
    argparse_assignments,
    add_arg_assignments
    # parse_args_assignment
  )
  return ast_argparse_source 
开发者ID:lrq3000,项目名称:pyFileFixity,代码行数:44,代码来源:source_parser.py

示例9: visit_For

# 需要导入模块: import _ast [as 别名]
# 或者: from _ast import Call [as 别名]
def visit_For( self, node ):
    self.generic_visit( node )

    if not ( isinstance( node.iter,      _ast.Call ) and
             isinstance( node.iter.func, _ast.Name ) and
             node.iter.func.id in ['range', 'xrange'] ):
      raise VerilogTranslationError(
        'For loops are only translatable when using range or xrange!\n'
        'Please use "for i in range(...)/xrange(...)".',
        node.lineno
      )

    call = node.iter

    if   len( call.args ) == 1:
      start = _ast.Num( n=0 )
      stop  = call.args[0]
      step  = _ast.Num( n=1 )
    elif len( call.args ) == 2:
      start = call.args[0]
      stop  = call.args[1]
      step  = _ast.Num( n=1 ) # TODO: should be an expression
    elif len( call.args ) == 3:
      start = call.args[0]
      stop  = call.args[1]
      step  = call.args[2]
    else:
      raise VerilogTranslationError(
        'An invalid number of arguments provided to (x)range function!\n',
        node.lineno
      )

    # Must know if the step is negative or positive in order to set the
    # correct bound check. This is because of Python's range behavior.
    try:
      if   hasattr( step, '_object' ): step_val = step._object
      elif hasattr( step, 'n'       ): step_val = step.n
      assert step_val != 0
    except (UnboundLocalError,AssertionError):
      raise VerilogTranslationError(
        'An error occurred when translating a "for loop"!\n'
        'The "step" parameter to range must be a constant integer value != 0!',
        node.lineno
      )

    node.iter       = _ast.Slice( lower=start, upper=stop, step=step )
    node.iter.lt_gt = '<' if step_val > 0 else '>'

    return node

#-------------------------------------------------------------------------
# ConstantToSlice
#------------------------------------------------------------------------- 
开发者ID:cornell-brg,项目名称:pymtl,代码行数:55,代码来源:visitors.py


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