如何将python3中数学运算的exec输出分配给字典?

2024-10-01 19:31:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了以下函数:(示例中的缩进可能不完美)

def TestFunction():
    profile_info_per_sec = {}

    profile_info_per_sec['DB CPU(s):'] = 1

(snipped)
    l, g = locals().copy(), globals().copy()

    print ('------- 1.0 Just Printing the Value -------')
    varprint = 'print(' + 'float(' + str(finalvar) + '))'
    print ('1.0 To Be Executed: ', varprint)
    exec (varprint)
    print (locals() == l, globals() == g)
    print ('*******')

    print ('------- 2.0 Just Printing the Value -------')
    varprint = 'x=' + 'float(' + str(finalvar) + ')\nprint(x)'
    print ('2.0 To Be Executed: ', varprint)
    exec (varprint)
    print (locals() == l, globals() == g)
    print ('*******')

    print ('------- 2.1 Just Printing the Value -------')
    varprint = 'a=5\nb=7\nsum=a+b'
    print ('2.1 To Be Executed: ', varprint)
    varprint_res = {}
    exec (varprint,{},varprint_res)
    print (varprint_res)
    print (locals() == l, globals() == g)
    print ('*******')

这将产生以下输出:

------- 1.0 Just Printing the Value -------
1.0 To Be Executed:  print(float(profile_info_per_sec['DB CPU(s):']))
1.0
False True
*******
------- 2.0 Just Printing the Value -------
2.0 To Be Executed:  x=float(profile_info_per_sec['DB CPU(s):'])
print(x)
1.0
False True
*******
------- 2.1 Just Printing the Value -------
2.1 To Be Executed:  a=5
b=7
sum=a+b
{'a': 5, 'b': 7, 'sum': 12}
False True
*******

但是,当我尝试添加下面的代码时,这已经不起作用了

 print ('------- 3.0 Capturing Value -------')
 varprint = 'x=' + 'float(' + str(finalvar) + ')\nx=x+x'
 varprint_res = {}
 print ('3.0 To Be Executed: ', varprint)
 exec (varprint,{},varprint_res)

输出错误为:

------- 3.0 Capturing Value -------
3.0 To Be Executed:  x=float(profile_info_per_sec['DB CPU(s):'])
x=x+x
Traceback (most recent call last):
  File "XmlTestCase.py", line 111, in <module>
    TestFunction()
  File "XmlTestCase.py", line 70, in TestFunction
    exec (varprint,{},varprint_res)
  File "<string>", line 1, in <module>
NameError: name 'profile_info_per_sec' is not defined

所以,我知道我应该在一个字典中得到它的输出,然而,在代码中动态执行的也是一个字典,我相信问题与它有关

注意:一些背景信息是这个变量和数学运算来自一个XML文件,需要进行处理,结果应该保留在python脚本中以便进一步处理

你们能帮个忙吗

提前谢谢

谨致问候

埃里


Tags: thetoinfovalueressecbefloat
1条回答
网友
1楼 · 发布于 2024-10-01 19:31:18

exec()的第三个参数是一个字典,用于查找局部变量,而不是函数的普通局部变量。所以您需要向它添加profile_info_per_sec,这样exec()就可以找到那个变量

varprint_res = { 'profile_info_per_sec': profile_info_per_sec }

相关问题 更多 >

    热门问题