我正在尝试创建一个辅助函数来读取文件并模拟单元测试的所有导入。我必须阅读文件与导入,因为我在 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 statements”的最佳方法
有道理?我知道我可以逐行读取文件,但我希望有一种更简洁/简洁的方式。
如果您有任何问题,请告诉我。