I wrote a small script. It’s designed to search the python directory for all available modules (whether they are installed or not), then it is supposed to check what modules are currently loaded, then it offers an option to dynamically load a module of your choice. The latter using __import__() because I am passing a string to it – (this is where I am having a problem – but I’ll get back to it shortly)…then it gives the option to “browse” the module for all its classes, functions, etc. (using dir([module name]) …).
The problem:
When the module is loaded dynamically – it is embedded in a try/except statement – if it succeeds it reports that the “module is loaded” and if it fails it reports…duh…”Failed to load…”
If you type the name of a module, for example a module named “uu”, it says “loaded”. So I know it is loading – however, when I go back and call the function that checks all of the LOADED modules – it is blank (using sys.modules)
I am thinking that python is loading the module into a temporary place which is not sys.modules because when I exit out of the script and check sys.modules it is not there.
Nascent_Notes, nice script!
I tried loading
uu(command 3) and printing the list of loaded modules (command 2) and they both seem to work fine.However, if I try to “browse the module” (command 4), I get the following error:
Try running
You should get
NameError: name 'uu' is not defined.So it appears that although
__import__successfully imports theuumodule,it does not add
uuto the global namespace — the moduleuucan not beaccessed by the variable name
uu. It can be accessed throughsys.moduleshowever:Therefore, change
to
Not only is using
raw_inputmuch safer thaninput(the user will not be able to execute unexpected/malicious commands), but alsoraw_inputdoes what you want here.On a minor note, you could also change
to the more pythonic
Edit:
sys.modules is a dict (short for dictionary). Dicts are like telephone books — you give it a name (better known as a “key”) and it returns a phone number (or more generally, a “value”).
In the case of sys.modules, the keys are module names (strings). The values are the module objects themselves.
You access the values in the dict using bracket notation. So
uuis just a string, butsys.modules['uu']is the moduleuu.You can read the full story on dicts here: http://docs.python.org/tutorial/datastructures.html#dictionaries