def print_running_variable_name(var):
frame = None
for frame in reversed(inspect.stack()):
if var in frame.frame.f_globals or var in frame.frame.f_locals:
break
if frame is not None:
frame_locals = frame.frame.f_locals
frame_globals = frame.frame.f_globals
for name, value in frame_locals.items():
if value is var:
print(‘Local variable name:‘, name)
return
for name, value in frame_globals.items():
if value is var:
print(‘Global variable name:‘, name)
return
print(‘Variable name not found.‘)
# 示例变量
x = 10
y = 20
# 使用示例
print_running_variable_name(x) # 输出: Global variable name: x
print_running_variable_name(y) # 输出: Global variable name: y
print_running_variable_name(10) # 输出: Variable name not found.
在Python中,变量名是在运行时与变量值进行关联的标识符。要获取正在运行的变量名,可以使用 globals() 或 locals() 函数来检索当前命名空间中的变量,并与变量的值进行比较。以下是一个示例代码,演示如何打印正在运行的变量名:
python
Copy code
def print_running_variable_name(var):
frame = None
for frame in reversed(inspect.stack()):
if var in frame.frame.f_globals or var in frame.frame.f_locals:
break
if frame is not None:
frame_locals = frame.frame.f_locals
frame_globals = frame.frame.f_globals
for name, value in frame_locals.items():
if value is var:
print(‘Local variable name:‘, name)
return
for name, value in frame_globals.items():
if value is var:
print(‘Global variable name:‘, name)
return
print(‘Variable name not found.‘)
# 示例变量
x = 10
y = 20
# 使用示例
print_running_variable_name(x) # 输出: Global variable name: x
print_running_variable_name(y) # 输出: Global variable name: y
print_running_variable_name(10) # 输出: Variable name no