我想創建一個幫助函數來讀取文件並模擬出單元測試的所有導入。我不得不讀取文件與導入,因爲我沒有這些東西在python路徑。Python簡單的方法來讀取py模塊中的所有導入語句
示例代碼:
#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)
以上是模擬代碼,我真的找最好的辦法只有記號化的 「從/ import語句」
文件這有道理嗎?我知道我可以逐行讀取文件,但我希望能夠採用更簡潔,更簡潔的方式。
讓我知道如果您有任何問題。
您可以加入一個例子輸出魔法調用(數據結構)? – GaretJax
對不起,我錯過了這一點,但我只是期待字符串完全限定的模塊,所以像a.b.c.module_name。我正要標記它.. – Nix
我希望我的解決方案也能工作。你總是可以去掉不必要的部分。 – GaretJax