Home > Back-end >  Executing external python code without changing original variables
Executing external python code without changing original variables

Time:07-19

When I execute external python code using the exec() method:

i = 0
exec("i = 99\nprint(i)")
print(i)

Output:
99
99

The code I'm executing changes the variable i in my original program. What alternative way of executing external python code can I use to hinder this? Consider that the code I'm executing is given to me as a string, and I have no control over it or its variable names.

Desired Output when executing the same code:
99
0

CodePudding user response:

Although I recognize the insecurity of this approach, HALF9000 provided an approach in the comments that suits my needs. Setting global and local variables to empty in the exec method solves my problem:

i = 0
exec("i = 99\nprint(i)",{},{})
print(i)

Output:
99
0

CodePudding user response:

You code:

i = 0       #i=0
exec("i = 99\nprint(i)")     #i=99
print(i)                     #i=99

Output:
99
99

Execute line by line:

New Code:

exec("i = 99\nprint(i)")            #i=99
i = 0                               #i=0
print(i)                            #i=0  

Output:
99
0

Explanation: Python executes code line by line, in your code, you declare 0 then update value 99 then print 2 times if you want to desire output then you can initialize 99 and print it first then after that you can initialize 0.

  • Related