Running a script with exec, how does one "backup" python process global state in its entirety and restores it afterwards?
code example:
import os
print(os.getcwd())
a = 8
print(a)
exec_scope = {}
exec("""
import os
os.chdir('../new place')
a = 9
print(a)
""", exec_scope)
print(os.getcwd())
print(a)
output:
C:\original place
8
9
C:\new place
8
The goal is to exec non-malicious code without having any global side-effect by backing up the current state and undoing any changes that may occur legitimately during the exec of the external (but safe) script.
This question was changes because the original wording would be interpreted that there is a need to protect against malicious code and that is not the focus. The assumption is that the external code is completely safe and holds not ill intentions but may affect the global state of the process for legitimate reasons and this effect was decided is undesirable.
So the goal of the question is to find the easiest/fastest/simplest way to undo any changes to the global state that can be undone.