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


Python ast.Import方法代码示例

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


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

示例1: get_top_imported_names

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def get_top_imported_names(file: str) -> Set[str]:
    """Collect names imported in given file.

    We only collect top-level names, i.e. `from foo.bar import baz`
    will only add `foo` to the list.
    """
    if not file.endswith(".pyi"):
        return set()
    with open(os.path.join(file), "rb") as f:
        content = f.read()
    parsed = ast.parse(content)
    top_imported = set()
    for node in ast.walk(parsed):
        if isinstance(node, ast.Import):
            for name in node.names:
                top_imported.add(name.name.split('.')[0])
        elif isinstance(node, ast.ImportFrom):
            if node.level > 0:
                # Relative imports always refer to the current package.
                continue
            assert node.module
            top_imported.add(node.module.split('.')[0])
    return top_imported 
开发者ID:python,项目名称:typeshed,代码行数:25,代码来源:migrate_script.py

示例2: _is_relative_import

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def _is_relative_import(module_name, path):
        """Checks if import is relative. Returns True if relative, False if
        absolute, and None if import could not be found."""
        try:
            # Check within the restricted path of a (sub-)package
            imp.find_module(module_name, [path])
        except ImportError:
            pass
        else:
            return True

        try:
            # Check across all of sys.path
            imp.find_module(module_name)
        except ImportError:
            pass
        else:
            return False

        # Module could not be found on system due to:
        # 1. Import that doesn't exist. "Bad import".
        # 2. Since we're only scanning the AST, there's a good chance the
        #    import's inclusion is conditional, and would never be triggered.
        #    For example, an import specific to an OS.
        return None 
开发者ID:pywren,项目名称:pywren-ibm-cloud,代码行数:27,代码来源:module_dependency.py

示例3: _find_imports

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def _find_imports(self, node):
        """Recurses through AST collecting the targets of all import
        statements."""
        if isinstance(node, ast.Import):
            return {self._extract_root_module(alias.name) for alias in node.names}
        elif isinstance(node, ast.ImportFrom):
            # We ignore all imports with levels other than 0. That's because if
            # if level > 0, we know that it's a relative import, and we only
            # care about root modules.
            if node.level == 0:
                return {self._extract_root_module(node.module)}
            else:
                return set()
        elif hasattr(node, 'body') and hasattr(node.body, '__iter__'):
            # Not all bodies are lists (for ex. exec)
            imps = set()
            for child_node in node.body:
                imps.update(self._find_imports(child_node))
            return imps
        else:
            return set() 
开发者ID:pywren,项目名称:pywren-ibm-cloud,代码行数:23,代码来源:module_dependency.py

示例4: _parse_mock_imports

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def _parse_mock_imports(mod_ast, expanded_imports):
  """Parses a module AST node for import statements and resolves them against
  expanded_imports (such as you might get from _expand_mock_imports).

  If an import is not recognized, it is omitted from the returned dictionary.

  Returns a dictionary suitable for eval'ing a statement in mod_ast, with
  symbols from mod_ast's imports resolved to real objects, as per
  expanded_imports.
  """
  ret = {}

  for node in mod_ast.body:
    if isinstance(node, ast.Import):
      for alias in node.names:
        if alias.name in expanded_imports:
          ret[alias.asname or alias.name] = expanded_imports[alias.name]
    elif isinstance(node, ast.ImportFrom):
      if node.level == 0:
        for alias in node.names:
          fullname ='%s.%s' % (node.module, alias.name)
          if fullname in expanded_imports:
            ret[alias.asname or alias.name] = expanded_imports[fullname]

  return ret 
开发者ID:luci,项目名称:recipes-py,代码行数:27,代码来源:cmd.py

示例5: _get_modules

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def _get_modules(self, content) -> Set[str]:
        imports = set()
        tree = ast.parse(content)
        for node in ast.walk(tree):
            if isinstance(node, ast.Import):
                for subnode in node.names:
                    imports.add(subnode.name)
            elif isinstance(node, ast.ImportFrom) and node.level == 0:
                imports.add(node.module)
        modules = set()
        for module in imports:
            if not module:
                continue
            module = module.split('.', maxsplit=1)[0]
            if module in self.stdlib:
                continue
            module = self.aliases.get(module, module)
            modules.add(module)
        return modules 
开发者ID:dephell,项目名称:dephell,代码行数:21,代码来源:imports.py

示例6: visit

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def visit(self, node) -> Any:
        if isinstance(node, ast.Name):
            if isinstance(node.ctx, ast.Load):
                self.loaded.add(node.id)
            elif isinstance(node.ctx, ast.Store):
                self.stored.add(node.id)
        elif isinstance(node, ast.Return):
            self.has_return = True
        # We must keep track of importer name in order to avoid considering as variable
        # names:
        elif isinstance(node, ast.Import):
            self.imported.update([ n.name for n in node.names])
        elif isinstance(node, ast.ImportFrom):
            self.imported.update([ n.name for n in node.names])

        self.generic_visit(node) 
开发者ID:Orange-OpenSource,项目名称:pyDcop,代码行数:18,代码来源:expressionfunction.py

示例7: find_globals

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def find_globals(g, tree):
    """Uses AST to find globals in an ast tree"""
    for child in tree:
        if hasattr(child, 'body') and isinstance(child.body, list):
            find_globals(g, child.body)
        elif isinstance(child, (ast.FunctionDef, ast.ClassDef)):
            g.add(child.name)
            continue
        elif isinstance(child, ast.Assign):
            try:
                g.add(child.targets[0].id)
            except (IndexError, AttributeError):
                pass
        elif isinstance(child, ast.Import):
            g.add(child.names[0].name)
        elif isinstance(child, ast.ImportFrom):
            for name in child.names:
                g_name = name.asname or name.name
                if g_name == '*':
                    continue
                g.add(g_name) 
开发者ID:sivel,项目名称:ansible-testing,代码行数:23,代码来源:utils.py

示例8: _find_blacklist_imports

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def _find_blacklist_imports(self):
        for child in self.ast.body:
            names = []
            if isinstance(child, ast.Import):
                names.extend(child.names)
            elif isinstance(child, ast.TryExcept):
                bodies = child.body
                for handler in child.handlers:
                    bodies.extend(handler.body)
                for grandchild in bodies:
                    if isinstance(grandchild, ast.Import):
                        names.extend(grandchild.names)
            for name in names:
                for blacklist_import, options in BLACKLIST_IMPORTS.items():
                    if re.search(blacklist_import, name.name):
                        msg = options['msg']
                        new_only = options['new_only']
                        if self._is_new_module() and new_only:
                            self.errors.append(msg)
                        elif not new_only:
                            self.errors.append(msg) 
开发者ID:sivel,项目名称:ansible-testing,代码行数:23,代码来源:modules.py

示例9: _find_has_import

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def _find_has_import(self):
        for child in self.ast.body:
            found_try_except_import = False
            found_has = False
            if isinstance(child, ast.TryExcept):
                bodies = child.body
                for handler in child.handlers:
                    bodies.extend(handler.body)
                for grandchild in bodies:
                    if isinstance(grandchild, ast.Import):
                        found_try_except_import = True
                    if isinstance(grandchild, ast.Assign):
                        for target in grandchild.targets:
                            if target.id.lower().startswith('has_'):
                                found_has = True
            if found_try_except_import and not found_has:
                self.warnings.append('Found Try/Except block without HAS_ '
                                     'assginment') 
开发者ID:sivel,项目名称:ansible-testing,代码行数:20,代码来源:modules.py

示例10: get_local_module_reqs

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def get_local_module_reqs(mod):
    tree = ast.parse(inspect.getsource(mod))
    imports = []
    for statement in tree.body:
        if isinstance(statement, ast.Import):
            imports += [(n.name, None) for n in statement.names]
        elif isinstance(statement, ast.ImportFrom):
            if statement.level == 0:
                imp = (statement.module, None)
            else:
                imp = ('.' + statement.module, mod.__package__)
            imports.append(imp)

    result = [import_module(i, p) for i, p in imports]
    if mod.__file__.endswith('__init__.py'):
        # add loaded subpackages
        prefix = mod.__name__ + '.'
        result += [mod for name, mod in sys.modules.items() if name.startswith(prefix)]
    return result 
开发者ID:zyfra,项目名称:ebonite,代码行数:21,代码来源:module.py

示例11: get_dependency_network

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def get_dependency_network(filepath):
	files = get_files(filepath)
	dependencies = {}
	for file in set(files):
		ast = ast.parse(file)
		for node in ast.getChildren()[1].nodes:
			if isinstance(node, ast.Import):
				if file in dependencies:
					dependencies[file].append(node.names[0][0])
				else:
					dependencies[file] = [node.names[0][0]]

			elif isinstance(node, ast.From):
				if file in dependencies:
					dependencies[file].append(node.modname + "/" + node.names[0][0])
	return create_graph(dependencies) 
开发者ID:datactive,项目名称:bigbang,代码行数:18,代码来源:repo_loader.py

示例12: should_trace

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def should_trace(source):
    trace_stmt = None
    deep = False
    for stmt in ast.parse(source).body:
        if isinstance(stmt, ast.Import):
            for alias in stmt.names:
                if alias.name.startswith('birdseye.trace_module'):
                    trace_stmt = stmt
                    if alias.name.endswith('deep'):
                        deep = True

        if isinstance(stmt, ast.ImportFrom) and stmt.module == 'birdseye':
            for alias in stmt.names:
                if alias.name.startswith('trace_module'):
                    trace_stmt = stmt
                    if alias.name.endswith('deep'):
                        deep = True
    return deep, trace_stmt 
开发者ID:alexmojaki,项目名称:executing,代码行数:20,代码来源:import_hook.py

示例13: find_imports

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def find_imports(code):
    """
    Finds the imports in a string of code and returns a list of their package
    names.
    """
    # handle mis-indented input from multi-line strings
    code = dedent(code)

    mod = ast.parse(code)
    imports = set()
    for node in ast.walk(mod):
        if isinstance(node, ast.Import):
            for name in node.names:
                name = name.name
                imports.add(name.split(".")[0])
        elif isinstance(node, ast.ImportFrom):
            name = node.module
            imports.add(name.split(".")[0])
    return list(imports) 
开发者ID:iodide-project,项目名称:pyodide,代码行数:21,代码来源:pyodide.py

示例14: _add_aliases

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def _add_aliases(self, node):
        """
        We delegate to this method instead of using visit_alias() to have
        access to line numbers and to filter imports from __future__.
        """
        assert isinstance(node, (ast.Import, ast.ImportFrom))
        for name_and_alias in node.names:
            # Store only top-level module name ("os.path" -> "os").
            # We can't easily detect when "os.path" is used.
            name = name_and_alias.name.partition(".")[0]
            alias = name_and_alias.asname
            self._define(
                self.defined_imports,
                alias or name,
                node,
                confidence=90,
                ignore=_ignore_import,
            )
            if alias is not None:
                self.used_names.add(name_and_alias.name) 
开发者ID:jendrikseipp,项目名称:vulture,代码行数:22,代码来源:core.py

示例15: onelinerize

# 需要导入模块: import ast [as 别名]
# 或者: from ast import Import [as 别名]
def onelinerize(original):
    # original :: string
    # :: string
    t = ast.parse(original)
    table = symtable.symtable(original, '<string>', 'exec')

    original = original.strip()

    # If there's only one line anyways, be lazy
    if len(original.splitlines()) == 1 and \
       len(t.body) == 1 and \
       type(t.body[0]) in (ast.Delete, ast.Assign, ast.AugAssign, ast.Print,
                           ast.Raise, ast.Assert, ast.Import, ast.ImportFrom,
                           ast.Exec, ast.Global, ast.Expr, ast.Pass):
        return original

    return get_init_code(t, table) 
开发者ID:csvoss,项目名称:onelinerizer,代码行数:19,代码来源:onelinerizer.py


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