Skip to main content
 首页 » 编程设计

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

2024年10月01日7tuyile006

我正在尝试在 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: 主要执行:

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 

请帮助我确定问题所在。提前致谢。

请您参考如下方法:

使用 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'}