函数中的exec函数不起作用(python 3.5)

时间:2017-10-16 15:48:21

标签: python json python-3.5

我正在尝试在python中编写一个动态程序(根据标签解析json文件),我正在使用Python exec函数来做到这一点。但是当exec语句处于函数中时,程序失败了。

跑1: 执行函数:

import json
from pandas.io.json import json_normalize
import sys
def param(dfile):
    aString = "['widget']['image']~['widget']['window']~['widget']['text']"
    for nd_part in aString.split('~'):
        exec("temp = %s%s"%(dfile,nd_part))
        print(temp)
if __name__ == "__main__":
    dfile = json.load(open("sample_json.json"))
    str_list = param(dfile)

JSON数据:sample_json.json

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": {
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}

错误:

Traceback (most recent call last):
  File "sample_test_json.py", line 12, in <module>
    str_list = param(dfile)
  File "sample_test_json.py", line 9, in param
    print(temp)
NameError: name 'temp' is not defined

跑2: EXEC主要:

import json
from pandas.io.json import json_normalize
import sys
if __name__ == "__main__":
    dfile = json.load(open("sample_json.json"))
    aString = "['widget']['image']~['widget']['window']~['widget']['text']"
    for nd_part in aString.split('~'):
        exec("temp = %s%s"%(dfile,nd_part))
        print(temp)

JSON数据:sample_json.json(与上面相同的数据)

输出:无错误(按预期结果)

{'hOffset': 250, 'vOffset': 250, 'name': 'sun1', 'alignment': 'center', 'src': 'Images/Sun.png'}
{'width': 500, 'height': 500, 'name': 'main_window', 'title': 'Sample Konfabulator Widget'}
{'data': 'Click Here', 'hOffset': 250, 'vOffset': 100, 'size': 36, 'style': 'bold', 'onMouseUp': 'sun1.opacity = (sun1.opacity / 100) * 90;', 'name': 'text1', 'alignment': 'center'}

运行3: 我试过eval并试着从这篇文章中格式化字符串。 How to return value from exec in function?

import json
from pandas.io.json import json_normalize
import sys
def param(dfile):
    aString = "['widget']['image']~['widget']['window']~['widget']['text']"
    for nd_part in aString.split('~'):
        exec('temp = "{}""{}"'.format(dfile,nd_part))
        print(temp)
if __name__ == "__main__":
    dfile = json.load(open("sample_json.json"))
    str_list = param(dfile)

错误:

Traceback (most recent call last):
  File "sample_test_json.py", line 12, in <module>
    str_list = param(dfile)
  File "sample_test_json.py", line 9, in param
    print(temp)
NameError: name 'temp' is not defined

请帮我确定问题。提前谢谢。

1 个答案:

答案 0 :(得分:2)

使用Eval()我得到的结果我已经完成了。在下面发布答案。但我仍然不确定为什么exec()不起作用。

import json
from pandas.io.json import json_normalize
import sys
def param(dfile):
    aString = "['widget']['image']~['widget']['window']~['widget']['text']"
    for nd_part in aString.split('~'):
        s = '{0}{1}'.format('dfile',nd_part)
        temp = eval(s)
        print(temp)
if __name__ == "__main__":
    dfile = json.load(open("sample_json.json"))
    str_list = param(dfile)

结果:

{'src': 'Images/Sun.png', 'alignment': 'center', 'vOffset': 250, 'name': 'sun1', 'hOffset': 250}
{'title': 'Sample Konfabulator Widget', 'height': 500, 'width': 500, 'name': 'main_window'}
{'alignment': 'center', 'onMouseUp': 'sun1.opacity = (sun1.opacity / 100) * 90;', 'data': 'Click Here', 'hOffset': 250, 'size': 36, 'vOffset': 100, 'name': 'text1', 'style': 'bold'}