exec function in a function is not working(python 3.5)

泄露秘密 提交于 2020-04-11 18:06:26

问题


I am trying to write a dynamic program(to parse json files based on their tags) in python and i am using Python exec function to do that. But the program is failing when exec statement is in a function.

RUN 1: Exec in a 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 = %s%s"%(dfile,nd_part))
        print(temp)
if __name__ == "__main__":
    dfile = json.load(open("sample_json.json"))
    str_list = param(dfile)

JSON Data: 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;"
    }
}}

Error:

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

RUN 2: EXEC in main:

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 Data: sample_json.json(same data as above)

Output: No error(Result as expected)

{'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'}

RUN 3: I tried eval and tried formatting the string from this post. 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)

Error:

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

Please help me in identifying the issue. Thanks in advance.


回答1:


Using Eval() i am getting the result i exepcted. Posting answer below. But still i am not sure why exec() is not working.

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)

Result:

{'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'}


来源:https://stackoverflow.com/questions/46774217/exec-function-in-a-function-is-not-workingpython-3-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!