【问题标题】:when we need to specify the data type in exec() function?当我们需要在 exec() 函数中指定数据类型时?
【发布时间】:2020-07-09 04:36:16
【问题描述】:

我有一段代码使用了 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.x exec


    【解决方案1】:

    由于您将空的dict() 作为globals 参数传递给exec(),所以在执行output.read() 时不会定义output。如果您需要打印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() 的输出

    【讨论】:

    • 那么,当我们使用 dict() 作为数据类型时,我在 test.py 中的内容将被打印为字典而不是数组(原始数据类型)?
    猜你喜欢
    • 2013-05-28
    • 1970-01-01
    • 2013-10-18
    • 1970-01-01
    • 2015-10-23
    • 2012-05-02
    • 2020-09-22
    • 1970-01-01
    相关资源
    最近更新 更多