一位朋友上周问我如何枚举或列出程序/函数/等中的所有变量.出于调试的目的(基本上获取所有内容的快照,以便您可以查看设置了哪些变量,或者是否设置了它们).我环顾四周,找到了一个比较好的Python方法:
#!/usr/bin/python foo1 = "Hello world" foo2 = "bar" foo3 = {"1":"a", "2":"b"} foo4 = "1+1" for name in dir(): myvalue = eval(name) print name, "is", type(name), "and is equal to ", myvalue
这将输出如下内容:
__builtins__ isand is equal to __doc__ is and is equal to None __file__ is and is equal to ./foo.py __name__ is and is equal to __main__ foo1 is and is equal to Hello world foo2 is and is equal to bar foo3 is and is equal to {'1': 'a', '2': 'b'} foo4 is and is equal to 1+1
到目前为止,我已经在PHP中找到了部分方法(由链接文本提供),但它只列出了所有变量及其类型,而不是内容:
getIterator(); $iterator->valid(); $iterator->next()) { echo $iterator->key() . ' => ' . $iterator->current() . '
'; } ?>
所以我把它告诉你:你如何用你最喜欢的语言列出所有变量及其内容?
由VonC编辑:我建议这个问题遵循一点点" 代码挑战 " 的精神.
如果您不同意,只需编辑并删除标签和链接即可.
在python中,使用返回包含所有本地绑定的字典的locals,因此,避免使用eval:
>>> foo1 = "Hello world" >>> foo2 = "bar" >>> foo3 = {"1":"a", ... "2":"b"} >>> foo4 = "1+1" >>> import pprint >>> pprint.pprint(locals()) {'__builtins__':, '__doc__': None, '__name__': '__main__', 'foo1': 'Hello world', 'foo2': 'bar', 'foo3': {'1': 'a', '2': 'b'}, 'foo4': '1+1', 'pprint': }
这就是Ruby中的样子:
#!/usr/bin/env ruby foo1 = 'Hello world' foo2 = 'bar' foo3 = { '1' => 'a', '2' => 'b' } foo4 = '1+1' b = binding local_variables.each do |var| puts "#{var} is #{var.class} and is equal to #{b.local_variable_get(var).inspect}" end
哪个会输出
foo1 is String and is equal to "Hello world" foo2 is String and is equal to "bar" foo3 is String and is equal to {"1"=>"a", "2"=>"b"} foo4 is String and is equal to "1+1"
但是,您不是要输出变量引用的对象类型而不是用于表示变量标识符的类型吗?IOW,类型foo3
应该是Hash
(或dict
)而不是String
,对吧?在这种情况下,代码将是
#!/usr/bin/env ruby foo1 = 'Hello world' foo2 = 'bar' foo3 = { '1' => 'a', '2' => 'b' } foo4 = '1+1' b = binding local_variables.each do |var| val = b.local_variable_get(var) puts "#{var} is #{val.class} and is equal to #{val.inspect}" end
结果是
foo1 is String and is equal to "Hello world" foo2 is String and is equal to "bar" foo3 is Hash and is equal to {"1"=>"a", "2"=>"b"} foo4 is String and is equal to "1+1"
在PHP中你可以这样做:
$defined = get_defined_vars(); foreach($defined as $varName => $varValue){ echo "$varName is of type ".gettype($varValue)." and has value $varValue
"; }
在Lua中,基本数据结构是表,甚至全局环境_G也是一个表.所以,一个简单的枚举就可以了.
for k,v in pairs(_G) do print(k..' is '..type(v)..' and is equal to '..tostring(v)) end
IPython的:
whos
你也可以向你的朋友推荐Spyder,它显示那些与Matlab非常相似的变量,并提供逐行调试的GUI.
击:
set
免责声明:不是我最喜欢的语言!
一个完全递归的PHP单行程序:
print_r(get_defined_vars());