如何执行python程序并使用exec()获取变量? [英] How to execute Python program and get the variables using exec()?
问题描述
我想使用exec()
执行正确的Python程序,然后在执行后获取变量及其值. Google说我应该创建一个字典,然后在其中写入执行结果:exec(code_object)
在变量中.但不幸的是,Python 3中没有.
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 write the result of execution there: exec(code_object)
in variables. But unfortunately that doesn't in Python 3.
推荐答案
Python 3中的代码应为:
The code in Python 3 should be:
exec(code_object, variables)
此语法也是 Python 2兼容.
exec(code_object) in variables
可以编译并在Python 3中运行,但做一些与Python 2完全不同的事情-它会在当前范围内执行code_object
; exec
将返回None
;然后,由于None
不是variables
中的键,因此表达式None in variables
将对False
求值;结果将被删除-因此,除了code_object
看到错误的作用域之外,不会发生编译时或运行时错误.
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.
这篇关于如何执行python程序并使用exec()获取变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!