python导入模块全局工作

Joe*_*son 1 python import module

我试图让python接受'全局'导入时遇到了问题

在一个模块中,它需要根据另一个变量导入另一个模块,但是如果我在start函数中有它,它似乎不会将它导入到所有模块函数中; 例如:

def start():
    selected = "web"
    exec("from gui import " + selected + " as ui")
    log("going to start gui " + selected)
    ui.start()
Run Code Online (Sandbox Code Playgroud)

这工作但在同一模块中:

def close():
    ui.stop()
Run Code Online (Sandbox Code Playgroud)

不起作用.我不知道这里发生了什么

小智 8

import gui
ui = None

def start():
  selected = "web"
  log("going to start gui " + selected)
  global ui
  __import__("gui.%s" % selected) # if you're importing a submodule that
                                  # may not have been imported yet
  ui = getattr(gui, selected)
  ui.start()
Run Code Online (Sandbox Code Playgroud)