The following code creates a dictionary and prints it at regular intervals:
import bpy
import json
class ModalTimerOperator(bpy.types.Operator):
"""Operator which runs its self from a timer"""
bl_idname = "wm.modal_timer_operator"
bl_label = "Modal Timer Operator"
_timer = None
def modal(self, context, event):
if event.type in {'RIGHTMOUSE', 'ESC'}:
self.cancel(context)
return {'CANCELLED'}
if event.type == 'TIMER':
dict = {"a":4}
msg = 'testDict = '+json.dumps(dict)+'\n'
msg += 'list = ["a","b","c"]\n'
msg += 'def printTestFunc(num1,num2):\n'
msg += ' print(num1)\n'
msg += ' print(num2)\n'
msg += 'for i in range(5):\n'
msg += ' [printTestFunc(0,testDict[key]) for key in list if key in testDict]\n'
exec(msg)
return {'PASS_THROUGH'}
def execute(self, context):
wm = context.window_manager
self._timer = wm.event_timer_add(0.1, window=context.window)
wm.modal_handler_add(self)
return {'RUNNING_MODAL'}
def cancel(self, context):
wm = context.window_manager
wm.event_timer_remove(self._timer)
def register():
bpy.utils.register_class(ModalTimerOperator)
def unregister():
bpy.utils.unregister_class(ModalTimerOperator)
if __name__ == "__main__":
register()
# test call
bpy.ops.wm.modal_timer_operator()
Unfortunately, it returns the following error:
line 28, in modal File "", line 7, in File "", line 7, in NameError: name 'testDict' is not defined
However, when I write the following code using Python without using Blender's ModalOperator there is no error:
import json
dict = {"a":4}
msg = 'testDict = '+json.dumps(dict)+'\n'
msg += 'list = ["a","b","c"]\n'
msg += 'def printTestFunc(num1,num2):\n'
msg += ' print(num1)\n'
msg += ' print(num2)\n'
msg += 'for i in range(5):\n'
msg += ' [printTestFunc(0,testDict[key]) for key in list if key in testDict]\n'
exec(msg)
I think this is a Modal Operator specific trouble. Why does this happen?
exec()
in the first place? Is there any specific reason why you can't simply call a function and pass the the json data as an argument? $\endgroup$exec()
in this sample. $\endgroup$