我有一个名为allCut
的脚本,其中包含以下代码(我已经大大简化了事情):
test.py
但是我不仅有一个名为from foo import Bar
bar = Bar()
result = bar.do_something()
的脚本。我有许多名为foo
的脚本,它们按以下目录结构组织:
foo
每个└── project
├── code
│ ├── test.py
└── scripts
├── script_1
└── foo.py
├── script_2
└── foo.py
├── script_3
└── foo.py
├── script_4
└── foo.py
├── script_5
└── foo.py
的实现方式略有不同。我想对foo.py
进行的操作是通过导入每个脚本并对其进行一些测试来测试所有脚本。下面是一些代码(*表示伪代码)
test.py
我该怎么做?特别是,我该如何迭代导入脚本,例如
*Get all script directories*
*For each directory in script directories:*
*import foo.py from this directory*
bar = Bar()
result = bar.do_something()
*Save the result for this directory*
?
答案 0 :(得分:1)
我建议您更改脚本以为其创建一个程序包,如图here所示。然后,您可以简单地通过以下方式分别访问每个脚本:
import scripts.script_1.foo
或
from scripts.script_1 import foo
迭代导入:
要遍历文件夹并导入它们,可以使用python的“ importlib”库。您将需要使用this library中的“ import_module”函数。话虽如此,您仍然需要在每个目录中包含__init__.py。 here说明了使用此功能导入模块的示例。
答案 1 :(得分:1)
我不得不做几件不同的事情,但是生成的代码片段看起来像这样:
import os, sys, importlib
# directory of your script folder
scripts_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))+"/../scripts/")
for root, dirs, files in os.walk(scripts_dir):
# traverse the folder and find ones that has foo.py
if 'foo.py' in files:
sys.path.append(root)
out = importlib.import_module('foo', package=root)
# call the function in foo.py.
#In this case, I assumed there is a function called test
met = getattr(out, 'test')
print(met())
# clean up the path and imported modules
sys.path.remove(root)
del sys.modules['foo']