如何执行python程序并使用exec()获取变量? [英] How to execute Python program and get the variables using exec()?

查看:489
本文介绍了如何执行python程序并使用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_objectexec将返回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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆