[英]Importing Python scripts iteratively from relative directories
I have a script called test.py
, with the following code (I have simplified things significantly): 我有一个名为test.py
的脚本,其中包含以下代码(我已经大大简化了事情):
from foo import Bar
bar = Bar()
result = bar.do_something()
But I don't just have a single script called foo
. 但是我不仅有一个名为foo
脚本。 I have many scripts called foo
, organised in the following directory structure: 我有许多名为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
Each foo.py
has a slightly different implementation of something. 每个foo.py
都略有不同。 And what I want to do with test.py
, is to test all the scripts out, by importing each one and running some tests on it. 我想用test.py
做的是通过导入每个脚本并对其进行一些测试来测试所有脚本。 Below is some code for this (*'s indicate pseudo-code) 下面是一些代码(*表示伪代码)
*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*
How can I do this? 我怎样才能做到这一点? In particular, how can I iteratively import scripts, eg, *import foo.py from this directory*
? 特别是,如何迭代地导入脚本,例如*import foo.py from this directory*
?
I suggest that you change your scripts to create a package for them, as illustrated here . 我建议你改变你的脚本来为他们创建一个包,如图所示这里 。 Then you can simply access each script individually as: 然后,您可以简单地通过以下方式分别访问每个脚本:
import scripts.script_1.foo
or 要么
from scripts.script_1 import foo
Iterative Importing: 迭代导入:
To iterate over the folders and import them, you may use "importlib" library of python. 要遍历文件夹并导入它们,可以使用python的“ importlib”库。 You will need to use "import_module" function from this library . 您将需要使用此库中的 “ import_module”函数。 That being said, you still need to include __init__.py in every directory. 话虽如此,您仍然需要在每个目录中包含__init__.py。 An example of importing a module using this function is illustrated here . 导入使用该功能的模块的一个例子被示出在这里 。
I had to do a couple of different things, but the resulting code snippet looks like this: 我不得不做几件不同的事情,但是生成的代码片段看起来像这样:
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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.