跨命名空间动态加载python模块

时间:2018-07-12 18:17:14

标签: python module

我的目录结构是

solution
- classes
  - setup.py
  - parser.py
- driver.py  

setup.py的内容

from __future__ import print_function
import sys
from importlib import import_module
import subprocess
import sys
import imp
import os

class Setup(object):
    def __init__(self,packages=["yaml", "jinja2", "cryptography"], *args):
        self.packages = packages
        if len(args) > 0:
            self.packages.extend(args)
        print(self.packages)

    def _install(self,package):
        subprocess.call([sys.executable, "-m", "pip", "install", package])

    def _global_imports(self, modulename, shortname=None, asfunction=False):
        print("Module being imported is {}".format(modulename))
        if shortname is None:
            shortname = modulename
        if asfunction is False:
            globals()[shortname] = import_module(modulename)
        else:        
            globals()[shortname] = eval(modulename + "." + shortname)

    def import_packages(self):
        for item in self.packages:
            try:
                imp.find_module(item)
                found = True
            except ImportError as e:
                found = False
                self._install(item)

            self._global_imports(item)

parser.py的内容

import os
import copy
from classes.certgen import *
from classes.setup import *

s = Setup()
s.import_packages()

class Parser(object):
    def __init__(self, templatefile, paramsfile):
        assert os.path.isfile(templatefile), "Template file not provided/does not exist"
        self.templatefile = templatefile
        assert os.path.isfile(paramsfile), "Parameter file not provided/does not exist"
        self.paramsfile = paramsfile

    def load_paramsfile(self):
        paramsdict = None
        with open(self.paramsfile, 'r') as stream:
            try:
                paramsdict = yaml.load(stream)
                print(params)
            except yaml.YAMLError as exc:
                print(exc)

        return paramsdict

driver.py的内容

from classes.parser import *
import sys

template="../sometemplate.j2"
params="../parameters.yaml"

p = Parser(template,params)

r = p.load_paramsfile()

执行驱动程序代码时,出现以下错误:

    Traceback (most recent call last):
  File "driver.py", line 10, in <module>
    r = p.load_paramsfile()
  File "/home/new/solution/classes/parser.py", line 22, in load_paramsfile
    except yaml.YAMLError as exc:
NameError: global name 'yaml' is not defined

我的理解是,当我在setup.py中将其添加到全局变量时,它将在parser.py中可用...我看到我的理解可能在全局变量中受命名空间限制。那么,如何实现使用setup.py之类的类来动态导入每个命名空间所需的模块?

赞赏这方面的任何指针/帮助

0 个答案:

没有答案