That's really high-level: bits of beautiful python

Rocco Moretti roccomoretti at hotpop.com
Tue Feb 21 15:14:24 EST 2006


Max wrote:

> But today we were discussing the problem of running externally-provided 
> code (e.g. add-on modules). Neither of us knew how to do it in C, though 
> I suggested using DLLs. However, I quickly installed python on his 
> laptop and coded this:
> 
> exec "import %s as ext_mod" % raw_input("Module: ")
> ext_mod.do()

Be careful with this - its fine for developer only use, but I'd avoid it 
in production code. You leave the possibility for hackers to try to 
import the module named 'os; os.system('rm -rf /'); import', or other 
such deviousness.

Probably a better version:

ext_mod_name = raw_input("Module: ")
ext_mod = __import__(ext_mod_name, globals(), locals(), ['__dict__'])
ext_mod.do()

But granted, it's less cool than the original.

P.S. The ", globals(), locals(), ['__dict__']" is there so that the 
proper thing is done when you provide the code with a dotted module name.



More information about the Python-list mailing list