1

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

2
  • 1
    this is incredibly insecure, you should never blindly execute code in this way, not least of which among reasons, because of the behaviour you've just discovered Commented Jul 19, 2022 at 11:53
  • 2
    You can set the globals and locals to empty: exec("yourcode", {}, {}). Or, wrap the exec to a function so that the exec will not modify the global variable. BTW, It is not recommended to use exec in this manner. Commented Jul 19, 2022 at 11:58

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.