Search code examples
pythonvariablesexeceval

How do i assign a variable to a eval / exec value?


is it possible to assign a variable to a exec / eval value? this is what i tried

def execute ():
    run_wn = tk.Tk() 
    des1 = tk.Label(run_wn, text = "------------------------------").pack()
    run_value = exec(cmd.get("1.0", "end"))
    value = tk.Label(run_wn, text = run_value)
    des2 = tk.Label(run_wn, text = "------------------------------").pack()
    run_wn.mainloop
bt = tk.Button(wn, text = "run", command = execute).pack()

the cmd is a text box.. when i execute this code then it does not return anything in the run screen. it prints it is there any way you can asign a value to a exec / eval value and and use it as text in a Label??

this is just a experimental project..

help will be very appreciated!!

thanks


Solution

  • exec takes two other positional arguments, dictionaries for globals and locals, so you could exec like this to capture results in a dict:

    In [1]: ns = {}
    In [2]: exec("p = 1 + 2", globals(), ns)
    
    In [3]: ns
    Out[3]: {'p': 3}
    

    Exec'ing untrusted code is dangerous. Don't do it if you're mixing user input into the commands unless you really know what you're doing.