Importing/reloading modules

  • Thread starter OKB (not okblacke)
  • Start date
O

OKB (not okblacke)

I'm fooling around with some MUD server code, and I want to add a
"reload" command that will let MUD wizards reload the server modules,
so that changes to the MUD parser and such can be effected without
having to shut down and restart the server.

Now, what I want to do at the top of my main module, instead of
just "import somemodule", is something like this:

try:
reload(somemodule)
except NameError:
import somemodule

. . . so that it imports the module if it's just starting up, and
reloads it otherwise. The problem is that I want to be able to call
this code multiple times, so I can call it from the "reload" command.
I can't figure out how to do this appropriately.

If I put the try/except in a function, it doesn't import the
module name into the global namespace, so that's no good. I could, of
course, import the modules normally and write a separate function that
reloads them, but then if I decided to import another module or remove
one, I'd have to change both pieces of code.

What I want is to get one piece of code that imports modules, or
reloads them if they're already imported, and I need to be able to
call this code like a function, from anywhere in my program. (There
are also "from foo import bar" statements that I need to re-execute
along with the reloads.) Something like:

importFunc():
from foo import bar # except import it into the global namespace
try:
reload(baz)
except NameError:
import baz # except import it into the global namespace

Someone suggested that I fiddle with __import__, but I'm not sure
exactly what to do, or if this is the best approach. The
documentation seems to suggest that simply doing __import__
('somemodule', globals(), globals()) won't actually stick the module
name into the global namespace -- is there some way to make this
happen, though?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top