简体   繁体   English

python和子目录的动态导入

[英]python and dynamic imports of sub directories

I have a data structure that looks like this in python 2.7 我有一个在python 2.7中看起来像这样的数据结构

myfile.py
--parsers
  --folder1
    file1.py
         def filemethod(data=None)
            pass

Under the folder parsers, I can add many subfolders 在文件夹解析器下,我可以添加许多子文件夹

I will always know then name of the function I want to call however 但我总是会知道我想要调用的函数的名称

How do I do an import the parser directory so I can find the methods in each of the sub directory and accessible from myfile.py. 如何导入解析器目录,以便在每个子目录中找到方法,并可从myfile.py访问。 I use getattr to convert a name to a function object. 我使用getattr将名称转换为函数对象。 This is necessary because I get the name of the function to call from a remote call to a redis queue. 这是必要的,因为我得到了从远程调用到redis队列调用的函数的名称。

import ??????
methodToCall = getattr('filemethod', 'file1')
methodToCall(data)

A good way to do dynamic imports is using imp.load_source() : 执行动态导入的好方法是使用imp.load_source()

import imp
module = imp.load_source( 'mymodule', module_full_path )

in your case it will be something like: 在你的情况下,它将是这样的:

module = imp.load_source( 'file1', '.\parsers\file1.py')
methodToCall = getattr( module, 'filemethod' )
methodToCall( data )

Make sure you replace 'file1' and '.\\parsers\\file1.py' with your desired module name and the correct path to its source file. 确保将'file1''.\\parsers\\file1.py'替换为所需的模块名称及其源文件的正确路径。

Another way is to first import the subdirectories from parsers/__init__.py . 另一种方法是首先从parsers/__init__.py导入子目录。

parsers/__init__.py : parsers/__init__.py

import folder1
import folder2
...

then: 然后:

import parsers
foldername = 'folder1'  # for example
mod = getattr(parsers, foldername)
methodToCall = getattr(mod, 'filemethod')
methodToCall(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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