source = """
x = 1
d = {x: 2}
y = d[x]
c= f + 1
"""
运行这段代码时 c=f+1 会给出错误,因为 f 没有定义,但我也想给出变量列表,它们的值在源字符串中给出
我想要这样的输出
d {1: 2}
d[x] 2
x 1
y 2
{x: 2} {1: 2}
NameError: name 'f' is not defined
您可以使用exec函数执行源代码,然后打印所需变量的值。
source = """
x = 1
d = {x: 2}
y = d[x]
c = f + 1
"""
# Execute the source code
try:
exec(source)
except Exception as e:
print(e)
# Print the values of the desired variables
var_dict = {'d': d, 'x': x, 'y': y, 'f': None}
for var, val in var_dict.items():
print(f"{var} {val}")
if isinstance(val, dict):
print(f"{var}[x] {val[x]}")
要定义所有局部变量而不是硬编码,您可以使用:
import pprint
try:
a = 1
b = 1
c = f + 1
except Exception as e:
local_variables = {k: var for k,var in locals().items() if not k.startswith('_') and not k in ['In', 'Out']}
pprint.pprint(local_variables)
raise e
另一个注意事项:欢迎来到 stack overflow。在提问之前,您应该使用搜索。这已经回答了几次,例如这里: 查看所有定义的变量