如何在python中打印变量名? [英] How can you print a variable name in python?

查看:1175
本文介绍了如何在python中打印变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个名为的变量选项它等于2.我如何访问变量的名称?相当于

 在[53]:namestr(选择)
输出[53]:'choice'

用于制作字典。有一个很好的方法,我只是错过了。



编辑:



因此这样做。我正在运行一些数据分析的东西,我在这个程序中调用多个参数,我想在运行时调整或不调整。我读取了最后一次运行中使用的.config文件中使用的参数,形式为

  filename 
no_sig_resonance.dat

mass_peak
700

选择
1,2,3

当提示输入值时,显示以前使用的值,空字符串输入将使用以前使用的值。



我的问题是因为当写入字典时,这些值已被扫描。如果需要一个参数,我运行 get_param ,它访问该文件并找到该参数。



我想我会一起阅读。 config 文件一起解决问题,并从中生成一个字典。我原来避免了...我不再记得的原因完美的情况来更新我的代码!

解决方案

如果你坚持,这里是一些可怕的基于检查的解决方案。 b
$ b

  import inspect,re 

def varname(p):
for inspect.getframeinfo(inspect。 currentframe()。f_back)[3]:
m = re.search(r'\bvarname\s * \(\s *([A-Za-z _] [A-Za-z0-如果m $
返回m.group(1)

如果__name__ =='__main__':
spam = 42
打印varname(垃圾邮件)

我希望它会激励你重新评估您遇到的问题,并寻找另一种方法。


Say I have a variable named choice it is equal to 2. How would I access the name of the variable? Something equivalent to

In [53]: namestr(choice)
Out[53]: 'choice'

for use in making a dictionary. There's a good way to do this and I'm just missing it.

EDIT:

The reason to do this is thus. I am running some data analysis stuff where I call the program with multiple parameters that I would like to tweak, or not tweak, at runtime. I read in the parameters I used in the last run from a .config file formated as

filename
no_sig_resonance.dat

mass_peak
700

choice
1,2,3

When prompted for values, the previously used is displayed and an empty string input will use the previously used value.

My question comes about because when it comes to writing the dictionary that these values have been scanned into. If a parameter is needed I run get_param which accesses the file and finds the parameter.

I think I will avoid the problem all together by reading the .config file once and producing a dictionary from that. I avoided that originally for... reasons I no longer remember. Perfect situation to update my code!

解决方案

If you insist, here is some horrible inspect-based solution.

import inspect, re

def varname(p):
  for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
    m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
    if m:
      return m.group(1)

if __name__ == '__main__':
  spam = 42
  print varname(spam)

I hope it will inspire you to reevaluate the problem you have and look for another approach.

这篇关于如何在python中打印变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆