Hello, is there a possibility or library to convert the following string to a function?
func_str = '''def test(event, x, y, flags, data):
if event == cv2.EVENT_LBUTTONDOWN:
print('LEFT MOUSE BTN DOWN!!!')
if event == cv2.EVENT_RBUTTONDOWN:
print('RIGHT MOUSE BTN DOWN!!!')
if event == cv2.EVENT_MBUTTONDOWN:
print('MIDDLE MOUSE BTN DOWN!!!')'''
Why? Why do you want to write code in strings, rather than just store the code in a file?
Self modifying code, execution of user supplied code, all generally frowned upon as unsafe. Still, people ride barrels over Niagara Falls (not lately).
You are probably looking for the exec() function.
See
this article for instruction and usage.
(May-13-2022, 05:30 PM)mikepy Wrote: [ -> ]Hello, is there a possibility or library to convert the following string to a function?
func_str = '''def test(event, x, y, flags, data):
if event == cv2.EVENT_LBUTTONDOWN:
print('LEFT MOUSE BTN DOWN!!!')
if event == cv2.EVENT_RBUTTONDOWN:
print('RIGHT MOUSE BTN DOWN!!!')
if event == cv2.EVENT_MBUTTONDOWN:
print('MIDDLE MOUSE BTN DOWN!!!')'''
I need this to provide the possibility to the user to write his own callbacks.
(May-13-2022, 05:52 PM)jefsummers Wrote: [ -> ]Self modifying code, execution of user supplied code, all generally frowned upon as unsafe. Still, people ride barrels over Niagara Falls (not lately).
You are probably looking for the exec() function.
See this article for instruction and usage.
The exec function as far as I know executes the function immidiately but I want to save the function in a dictionary as a callback for the cv2 library.
The exec function executes the code. If the code defines a function, exec defines the function. Calling exec with your string will create a new variable named "test" which is assigned to reference the new function.
Why didn't you just try that instead of offering a rebuttal?
exec('''def test(event, x, y, flags, data):
if event == 1:
print('LEFT MOUSE BTN DOWN!!!')
if event == 2:
print('RIGHT MOUSE BTN DOWN!!!')
if event == 3:
print('MIDDLE MOUSE BTN DOWN!!!')''')
test(2, 0, 0, 0, 0)
Output:
RIGHT MOUSE BTN DOWN!!!
(May-13-2022, 06:08 PM)mikepy Wrote: [ -> ]but I want to save the function in a dictionary as a callback for the cv2 library.
Why don't you do that then? You know functions are first-class in Python, right?
exec('''def test(event, x, y, flags, data):
if event == 1:
print('LEFT MOUSE BTN DOWN!!!')
if event == 2:
print('RIGHT MOUSE BTN DOWN!!!')
if event == 3:
print('MIDDLE MOUSE BTN DOWN!!!')''')
functions = {"test":test}
functions["test"](3, 0, 0, 0, 0)
Output:
MIDDLE MOUSE BTN DOWN!!!
Thank you guys I will try your solutions!!!
EDIT:
After trying both of your solutions it works like a charm. Thank you very much :).