繁体   English   中英

从相对目录迭代导入Python脚本

[英]Importing Python scripts iteratively from relative directories

我有一个名为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*

我怎样才能做到这一点? 特别是,如何迭代地导入脚本,例如*import foo.py from this directory*

我建议你改变你的脚本来为他们创建一个包,如图所示这里 然后,您可以简单地通过以下方式分别访问每个脚本:

import scripts.script_1.foo

要么

from scripts.script_1 import foo

迭代导入:

要遍历文件夹并导入它们,可以使用python的“ importlib”库。 您将需要使用此库中的 “ import_module”函数。 话虽如此,您仍然需要在每个目录中包含__init__.py。 导入使用该功能的模块的一个例子被示出在这里

我不得不做几件不同的事情,但是生成的代码片段看起来像这样:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM