2

I'm trying to import and run a module named dynamically at run time (Python 3.4 / Django 1.7).

I tried:

exec('ds_id = kim_processors.%s.process(%s)' % (function.python_module, model_id))
cursor.execute("""sql""", (ds_id, ))

I get the NameError exception "Exception Value: name 'ds_id' is not defined", yet again, I can see ds_id in the local vars listing:

ds_id   14

I also tried:

exec('import kim_processors.%s as processor_module' % function.python_module)
ds_id = processor_module.process(model_id)

Django reports the NameError exception "Exception Value: name 'processor_module' is not defined". But I can see processor_module listed in localvars, set to the module:

processor_module <module 'kim_processors.someprocessing' from 'C:\\_dev\\kimetrica\\KimSim\\KimSimPrototype\\kimsim_modelbuilder\\kim_processors\\someprocessing.py'>

Don't think it is necessary, but I've also tried passing global() and local() to exec:

exec('import kim_processors.%s as processor_module' % function.python_module, globals(), locals())
exec('ds_id = processor_module.process(%s)' % (model_id), globals(), locals())
dataset_id_parameter = (ds_id, )

And declaring ds_id as global before those statements (also not great but in desperation):

global ds_id
...

Same NameError. Any idea how I can access that module or variable, which is and isn't there?

Chris
  • 5,664
  • 6
  • 44
  • 55
  • Is this in a function? – Martijn Pieters Jan 23 '15 at 13:58
  • The definition of `process(..)` within the module is `def process(model_id): ...`. The value in `ds_id` listed in local vars is correct. (I'm new to Python but assume that is indeed unambiguously a function.) – Chris Jan 23 '15 at 14:00
  • That is indeed a function. There are far better ways to dynamically execute code, however. You can use `importlib` to import modules dynamically, for example. – Martijn Pieters Jan 23 '15 at 14:04
  • Not yet fully sure, but looks like this is working `processor_module = importlib.import_module('kim_processors.%s' % function.python_module)` - huge thanks – Chris Jan 23 '15 at 14:19

0 Answers0