Python从py模块读取所有import语句的简便方法

时间:2012-01-25 18:51:57

标签: python python-2.7 mox

我正在尝试创建一个帮助函数来读取文件并模拟单元测试的所有导入。我必须阅读文件vs import,因为我在python路径上没有这些东西。

示例代码:


#module.py
import com.stackoverflow.question
from com.stackoverflow.util import test_func
from com.stackoverflow.util import TestClass

#magic helper: what i want
magic = process('<path_to>/module.py')
for module in magic.modules_as_strings():
    #todo  would have to recuirsively add each path
    # so i would first create com, then com.stackoverflow, etc
    setattr(self, module, StubModules(module)
for obj in magic.sink:
    #these would be "from"  from x import Y
    #its basically just creating self.Y = object
    setattr(self, object)

上面是模拟代码,我真的在寻找将文件标记为“from / import语句”的最佳方法

那有道理吗?我知道我可以逐行阅读文件,但我希望能有一种更干净/简洁的方式。

如果您有任何问题,请与我们联系。

1 个答案:

答案 0 :(得分:11)

使用AST模块,非常简单:

import ast
from collections import namedtuple

Import = namedtuple("Import", ["module", "name", "alias"])

def get_imports(path):
    with open(path) as fh:        
       root = ast.parse(fh.read(), path)

    for node in ast.iter_child_nodes(root):
        if isinstance(node, ast.Import):
            module = []
        elif isinstance(node, ast.ImportFrom):  
            module = node.module.split('.')
        else:
            continue

        for n in node.names:
            yield Import(module, n.name.split('.'), n.asname)

对于这样的模块:

from coco import bunny
from coco.bungy import carrot
from meta import teta
from rocket import spaceship as sp
import bingo
import com.stackoverflow
import motorbike as car
import module1, module2

s="a random variable"

def func():
    """And a function"""

输出结果为:

>>> for imp in get_imports("/path/to/file.py"): print imp
Import(module=['coco'], name=['bunny'], alias=None)
Import(module=['coco', 'bungy'], name=['carrot'], alias=None)
Import(module=['meta'], name=['teta'], alias=None)
Import(module=['rocket'], name=['spaceship'], alias='sp')
Import(module=[], name=['bingo'], alias=None)
Import(module=[], name=['com', 'stackoverflow'], alias=None)
Import(module=[], name=['motorbike'], alias='car')
Import(module=[], name=['module1'], alias=None)
Import(module=[], name=['module2'], alias=None)