import module from string variable

前端 未结 5 1746
离开以前
离开以前 2020-11-22 07:17

I\'m working on a documentation (personal) for nested matplotlib (MPL) library, which differs from MPL own provided, by interested submodule packages. I\'m writing Python sc

5条回答
  •  無奈伤痛
    2020-11-22 07:39

    spent some time trying to import modules from a list, and this is the thread that got me most of the way there - but I didnt grasp the use of ___import____ -

    so here's how to import a module from a string, and get the same behavior as just import. And try/except the error case, too. :)

      pipmodules = ['pycurl', 'ansible', 'bad_module_no_beer']
      for module in pipmodules:
          try:
              # because we want to import using a variable, do it this way
              module_obj = __import__(module)
              # create a global object containging our module
              globals()[module] = module_obj
          except ImportError:
              sys.stderr.write("ERROR: missing python module: " + module + "\n")
              sys.exit(1)
    

    and yes, for python 2.7> you have other options - but for 2.6<, this works.

提交回复
热议问题