如何获取Python文件中导入的项目列表

0 投票
1 回答
39 浏览
提问于 2025-04-13 02:16

我想要获取一个文件中导入的项目列表。

举个例子,我有一个文件:

# file1.py
from mod1 import a
from mod2 import b, c

print(a)

我想要一个函数,它接收文件的路径,比如 foo("file1.py"),然后返回以下内容:

{
    "file1.py": [
        "mod1": ["a"],
        "mod2": ["b", "c"]
    ]
}

有没有现成的Python库可以解决我的问题?

你推荐哪个Python库来分析Python代码?

1 个回答

2
{
    "file1.py": [
        "mod1": ["a"],
        "mod2": ["b", "c"]
    ]
}

这是不可能的,因为列表中的项目需要是字典,所以更像是:

{
    "file1.py": [
        {"mod1": ["a"]},
        {"mod2": ["b", "c"]}
    ]
}

import ast

def get_imported_items(file_path):
    with open(file_path, "r") as file:
        tree = ast.parse(file.read(), filename=file_path)

    imports = {}
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            for alias in node.names:
                module_name = alias.name
                if module_name not in imports:
                    imports[module_name] = []
        elif isinstance(node, ast.ImportFrom):
            module_name = node.module
            if module_name not in imports:
                imports[module_name] = []
            for alias in node.names:
                imports[module_name].append(alias.name)

    return {file_path: [{module_name: items} for module_name, items in imports.items()]}

result = get_imported_items("file1.py")
print(result)

这样做就可以了,只需要指定路径就行。

撰写回答