How to execute Python program and get the variables using exec()?

前端 未结 1 1577
滥情空心
滥情空心 2021-01-24 01:12

I want to execute a correct Python program using exec() and then get variables and their values after executing. Google says that I should create a dictionary and w

1条回答
  •  孤城傲影
    2021-01-24 01:42

    The code in Python 3 should be:

    exec(code_object, variables)
    

    This syntax is also Python 2 compatible.


    exec(code_object) in variables
    

    would compile and run in Python 3 but do something completely different from Python 2 - it would execute the code_object in current scope; the exec would return None; then the expression None in variables would evaluate False since None is not a key in variables; the result would be dropped - thus neither compile time nor possibly run-time error occurs, except for code_object seeing the wrong scope.

    0 讨论(0)
提交回复
热议问题