首页 > 解决方案 > 当我们需要在 exec() 函数中指定数据类型时?

问题描述

我有一段代码使用了 python exec() 函数。数据以数组形式保存在文件中,使用 exec() 时,数据类型指定为字典。我无法退出理解输出是什么

style = dict()
# test.py includes one 10 x 10 array 
with open('test.py')as output:
    exec(output.read(), style)

标签: python-3.xexec

解决方案


由于您将空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()


推荐阅读