import from user input?

Christian Tismer tismer at appliedbiometrics.com
Fri Apr 9 10:17:27 EDT 1999


Gaetan Corneau wrote:
> 
> Hello,
> 
> I want to import modules at runtime, and get the module name from the user.
> Is that possible? How?

There is more than one way.
The obvious one is to execute a generated statement
in the correct environment, as in

>>> import string
>>> modname=string.strip(raw_input("which module do you want to import today?"))
>>> exec "import "+modname
>>> re # what I typed
<module 're' from 'D:\Python\Lib\re.pyc'>
>>> 

But if you want to be less open to users who might type bad things
like "sys ; sys.exit()",
this version might be easier to handle:

>>> globals()[modname] = __import__(modname)

The advantage is that the builtin function __import__ is a function
which requires a module name as a string parameter.
No necessity to check for bad input, but by a try...except ImportError
clause
if the module isn't found.

> Another question: is there a function to copy/move entire directory trees?

There is a walk function in os.path which makes it
an easy exercise to write such a function.

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaiserin-Augusta-Allee 101   :    *Starship* http://starship.python.net
10553 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     we're tired of banana software - shipped green, ripens at home




More information about the Python-list mailing list