[여기에 선호하는 언어] 프로그램의 모든 변수를 열거하거나 나열합니다.
친구가 지난주에 프로그램 / 함수 등의 모든 변수를 열거하거나 나열하는 방법을 물었습니다. 디버깅 목적으로 (본질적으로 모든 변수의 스냅 샷을 가져 와서 어떤 변수가 설정되어 있는지 또는 설정되어 있는지 확인할 수 있습니다). 나는 약간 둘러 보았고 Python에 비교적 좋은 방법을 찾았습니다.
#! / usr / bin / python foo1 = "Hello world" foo2 = "바" foo3 = { "1": "a", "2": "b"} foo4 = "1 + 1" dir ()의 이름 : myvalue = eval (이름) print name, "is", type (name), "and is equal to", myvalue
다음과 같이 출력됩니다.
__builtins__는 <type 'str'>이고 <module '__builtin __'(내장)>과 같습니다. __doc__는 <type 'str'>이고 None과 같습니다. __file__은 <type 'str'>이고 ./foo.py와 같습니다. __name__은 <type 'str'>이고 __main__과 같습니다. foo1은 <type 'str'>이고 Hello world와 같습니다. foo2는 <type 'str'>이고 bar와 같습니다. foo3은 <type 'str'>이고 { '1': 'a', '2': 'b'}와 같습니다. foo4는 <type 'str'>이고 1 + 1과 같습니다.
지금까지 PHP에서 부분적인 방법을 찾았 지만 ( 링크 텍스트 제공 ) 내용이 아닌 모든 변수와 유형 만 나열합니다.
<? php // 몇 가지 변수 생성 $ bar = 'foo'; $ foo = '바'; // 새 배열 객체 생성 $ arrayObj = new ArrayObject (get_defined_vars ()); // 배열 객체와 에코 변수 및 값을 반복합니다. for ($ iterator = $ arrayObj-> getIterator (); $ iterator-> valid (); $ iterator-> next ()) { echo $ iterator-> key (). '=>'. $ iterator-> current (). '<br />'; } ?>
그래서 나는 그것을 당신에게 넣습니다 : 당신은 당신이 좋아하는 언어로 모든 변수와 그 내용을 어떻게 나열합니까?
VonC 편집 :이 질문은 약간의 " 코드 도전 " 정신을 따른 다고 제안합니다 .
동의하지 않으면 태그와 링크를 편집하고 제거하십시오.
파이썬에서는 모든 로컬 바인딩을 포함하는 사전을 반환하는 로컬을 사용하여 eval을 피합니다.
>>> foo1 = "Hello world"
>>> foo2 = "bar"
>>> foo3 = {"1":"a",
... "2":"b"}
>>> foo4 = "1+1"
>>> import pprint
>>> pprint.pprint(locals())
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__name__': '__main__',
'foo1': 'Hello world',
'foo2': 'bar',
'foo3': {'1': 'a', '2': 'b'},
'foo4': '1+1',
'pprint': <module 'pprint' from '/usr/lib/python2.5/pprint.pyc'>}
루비 에서는 다음과 같습니다 .
#!/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은 문자열이고 "Hello world"와 같습니다. foo2는 문자열이고 "bar"와 같습니다. foo3은 문자열이고 { "1"=> "a", "2"=> "b"}와 같습니다. foo4는 문자열이고 "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은 문자열이고 "Hello world"와 같습니다. foo2는 문자열이고 "bar"와 같습니다. foo3은 해시이고 { "1"=> "a", "2"=> "b"}와 같습니다. foo4는 문자열이고 "1 + 1"과 같습니다.
PHP에서는 다음과 같이 할 수 있습니다.
$defined = get_defined_vars();
foreach($defined as $varName => $varValue){
echo "$varName is of type ".gettype($varValue)." and has value $varValue <br>";
}
Lua에서 기본 데이터 구조는 테이블 이며 글로벌 환경 _G도 테이블입니다. 따라서 간단한 열거가 트릭을 수행합니다.
for k,v in pairs(_G) do
print(k..' is '..type(v)..' and is equal to '..tostring(v))
end
IPython :
whos
또한 Matlab과 매우 유사한 변수를 표시하고 줄 단위 디버깅을위한 GUI를 제공하는 Spyder 를 친구에게 추천 할 수 있습니다 .
세게 때리다:
set
면책 조항 : 내가 좋아하는 언어가 아닙니다!
완전히 재귀적인 PHP 한 줄 :
print_r(get_defined_vars());
먼저 디버거를 사용합니다. 예를 들어 Visual Studio에는 원하는 모든 변수 등을 표시하는 "Locals"및 "Watch"창이 있으며 모든 수준으로 완전히 확장 할 수 있습니다.
C #에서는 메서드 변수를 매우 쉽게 얻을 수 없지만 (컴파일러에 의해 제거되는 경우가 많음) 리플렉션을 통해 필드 등에 액세스 할 수 있습니다.
static class Program { // formatted for minimal vertical space
static object foo1 = "Hello world", foo2 = "bar",
foo3 = new[] { 1, 2, 3 }, foo4;
static void Main() {
foreach (var field in typeof(Program).GetFields(
BindingFlags.Static | BindingFlags.NonPublic)) {
var val = field.GetValue(null);
if (val == null) {
Console.WriteLine("{0} is null", field.Name);
} else {
Console.WriteLine("{0} ({1}) = {2}",
field.Name, val.GetType().Name, val);
}
}
}
}
Perl. my
로컬을 처리 하지 않고 쓸모없는 참조를 필터링하지 않지만 패키지 범위의 모든 것을 볼 수 있습니다.
my %env = %{__PACKAGE__ . '::'};
while (($a, $b) = each %env) {
print "\$$a = $$b\n";
print "\@$a = (@$b)\n";
print "%$a = (@{[%$b]})\n";
print "*$a = $b\n";
}
Matlab :
who
자바에서 문제는 C #과 비슷할 것입니다. 더 자세한 모드에서만 (I know, I KNOW ;) Java is verbose ... you make it already clear;) )
Refection을 통해 개체 필드에 액세스 할 수 있지만 메서드 로컬 변수에 쉽게 액세스 할 수 없습니다. 따라서 다음은 정적 분석 코드가 아니라 런타임 디버깅 전용입니다.
package test;
import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;
/**
*
* @author <a href="https://stackoverflow.com/users/6309/vonc">VonC</a>
*/
public class DisplayVars
{
private static int field1 = 1;
private static String field2 = "~2~";
private boolean isField = false;
/**
* @param args
*/
public static void main(final String[] args)
{
final Field[] someFields = DisplayVars.class.getDeclaredFields();
try
{
displayFields(someFields);
} catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
/**
* @param someFields
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
@SuppressWarnings("unchecked")
public static void displayFields(final Field[] someFields)
throws IllegalAccessException
{
DisplayVars anObject = new DisplayVars();
Object res = null;
for (int ifields = 0; ifields < someFields.length; ifields++)
{
final Field aField = someFields[ifields];
AccessController.doPrivileged(new PrivilegedAction() {
public Object run()
{
aField.setAccessible(true);
return null; // nothing to return
}
});
res = aField.get(anObject);
if (res != null)
{
System.out.println(aField.getName() + ": " + res.toString());
} else
{
System.out.println(aField.getName() + ": null");
}
}
}
}
R 언어에서
ls()
작업 메모리에서 모든 개체를 제거하려면
rm(list=ls(all=TRUE))
In REBOL, all variables live inside a context of type object!
. There's a global context, and every function has its own implicit local context. You can create new contexts explicitly by creating a new object!
(or using the context
function). This is different from traditional languages because variables (called "words" in REBOL) carry a reference to their context around with them, even when they have left the "scope" in which they were defined.
So, the bottom line is that, given a context, we can list the variables it defines. We'll use Ladislav Mecir's context-words?
function.
context-words?: func [ ctx [object!] ] [ bind first ctx ctx ]
Now we can list all the words defined in the global context. (There are a lot of them.)
probe context-words? system/words
We can also write a function that then lists the variables it defines.
enumerable: func [a b c /local x y z] [
probe context-words? bind? 'a
]
What we can't do in REBOL, as far as I know, is walk up the context tree, although the interpreter seems to be able to do this perfectly well when it decides how to bind words to their contexts. I think this is because the context tree (i.e., scope) may have one "shape" at the time a word is bound but quite another at the time it's evaluated.
Quick and dirty JavaScript solution if you have FireBug installed (or another browser with console.log). If you don't, you'll have to change console.log to document.write, and run in at as an inline script at the end of your . Change MAX_DEPTH to how many levels of recursion you want (be careful!).
(function() {
var MAX_DEPTH = 0;
function printObj(name, o, depth) {
console.log(name + " type: '"+typeof o+"' value: " + o);
if(typeof o == "function" || depth >= MAX_DEPTH) return;
for(var c in o) {
printObj(name+"."+c, o[c], depth+1);
}
}
for(var o in window) {
printObj(o, window[o], 0);
}
})();
Common Lisp:
(do-all-symbols (x) (print x))
To also show all bound values:
(do-all-symbols (x) (print x) (when (boundp x) (print (symbol-value x))))
This is a long list, and not particularly useful. I would really use the integrated debugger.
Here's an idea for oo-languages.
First you need something like toString() in Java to print meaningful contents. Second - you have to restrict yourself to one object-hierarchy. In the constructor of the root-object (like Any in Eiffel), your register the instance upon creation in some kind of global list. During destruction, you deregister (be sure to use some data structure that allows fast insert / search / removal). Any time during program execution, you can walk through this data-structure and print all objects registered there.
Due to it's structure, Eiffel might be very good for this purpose. Other Languages have problems with objects that are not user-defined (e.g. the jdk-classes). In Java it might be possible to create your own Object-class using some open-source jdk.
'code' 카테고리의 다른 글
Java 임시 파일은 언제 삭제됩니까? (0) | 2020.10.14 |
---|---|
application.yml은 환경 변수를 지원합니까? (0) | 2020.10.14 |
생성 된 XML에서 'standalone =“yes”'제거 (0) | 2020.10.13 |
파일을 byte []로 변환하는 안정적인 방법 (0) | 2020.10.13 |
UIImageView-할당 된 이미지의 파일 이름을 얻는 방법은 무엇입니까? (0) | 2020.10.13 |