开发者

python import module to work globally

I've got a problem trying to get python to accept an import 'globally'

In a module it needs to import another module depending on another variable but it doesn't seem to import it into all of the module functions if i have it in the start function; for example:

def开发者_如何学Go start():
    selected = "web"
    exec("from gui import " + selected + " as ui")
    log("going to start gui " + selected)
    ui.start()

this works but in the same module:

def close():
    ui.stop()

doesn't work. i don't know what's going on here

Joe


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()


Why do you want to do it this way? Why not use the __import__ builtin? Also, your binding to gui is local to the function start.


You can provide scope of exec with in. Try this:

exec("from gui import " + selected + " as ui") in globals()


You are importing the ui module to the start() function scope only. You should import the module to global scope. To do this you could import the module before the two functions (start and close) or provide global scope to exec() function.

Example: To provide global scope to the exec method.

exec("from gui import " + selected + " as ui") in globals()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜