我创建了以下功能:(缩进可能不是示例中的完美)
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=5nb=7nsum=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
所以,我知道我应该在字典中获取此输出,但是,代码中动态执行的内容也是字典,我相信问题与之相关。
P.S:一些背景信息是变量和数学操作来自XML文件,需要处理,结果应保留在Python脚本中以进行进一步处理。
你们能为此提供帮助吗?
预先感谢。
问:
eri
exec()
的第三个参数是一个词典,用于查找局部变量,而不是函数的正常局部变量。因此,您需要向其添加profile_info_per_sec
,以便exec()
可以找到该变量。
varprint_res = { 'profile_info_per_sec': profile_info_per_sec }