python-3.x - 当我们需要在 exec() 函数中指定数据类型时?
问题描述
我有一段代码使用了 python exec() 函数。数据以数组形式保存在文件中,使用 exec() 时,数据类型指定为字典。我无法退出理解输出是什么
style = dict()
# test.py includes one 10 x 10 array
with open('test.py')as output:
exec(output.read(), style)
解决方案
由于您将空dict()
作为globals
参数传递,exec()
output
因此不会在output.read()
执行时定义。如果您需要打印结果,output.read()
则需要将其中一个globals()
或locals()
作为第二个参数传递给exec
. 它们返回一个字典,其中包含分别在全局和局部范围内可用的对象。新代码可能是:
style = dict()
with open('test.py') as output:
exec("print(output.read())", globals())
或者
style = dict()
with open('test.py') as output:
exec("print(output.read())", locals())
exec 语句的返回值是None
,所以你需要使用 print 来查看输出output.read()
推荐阅读
- google-sheets - 具有多个规则的条件格式 Google 表格
- list - 如何创建会影响子列表的此 prolog 谓词的“深度”版本?
- node.js - 如何比较MongoDB中的字符串是小写还是大写
- javascript - AXIOS PUT 请求返回 200 代码但不更新内容?
- angular - 从未调用过 Ionic 4 服务构造函数-> httpClient http.get 失败
- windows - 将 CMD 输出转换为 CSV 文件
- docker - 惯用的 Makefile 和命令参数
- c# - 如何释放被跟踪的实体?
- xamarin - 使用 MVVMCross 实现 UISearchController
- mysql - 如何从表格中获取最多评论的用户