Reputation: 175
I am writing a tkinter program and I want to get the input from a textbox and run it as python code. The input from the textbox is python code, my question is how to run is as python code and access its variables.
For example I get this from the textbox:
x = [1, 2, 3]
I want to be able to parse the contents of the textbox from the 'New' window, access the 'x' variable and use it as a python list.
Upvotes: 1
Views: 368
Reputation: 604
For the variable x
you have input data entered in the textbox.
If x
has '[1,2,3]'
(string when given as input to textbox)
You can try this:
exec(x)
The above will execute the python code which takes input as string.
If x
has 'print('hello world')'
, this is how it works:
>>> x = 'print("hello world")'
>>> exec(x)
hello world
Update: While I was framing and uploaded my answer, @acw1668 had commented (no stealing done!)
Upvotes: 3
Reputation: 1337
Of the top of my head, the straight forward way would be to have a class which takes that text input, formats it into a .py file and then calls a sub process running that code. The downside is that these processes probably will not have access to the same data due to different memory addresses.
If you want to have this written code executed in your current process you could dynamically import the written python file in a function. Importing will execute whatever code is outside of functions or classes so when you import the temporary .py file with x = [1, 2]
then the x list should be in this process now.
Upvotes: 2