문제

그래서 제가 여기서 찾고 있는 것은 PHP와 같은 것입니다. print_r 기능.이는 문제의 개체 상태를 확인하여 스크립트를 디버깅할 수 있도록 하기 위한 것입니다.

도움이 되었습니까?

해결책

당신은 정말로 두 가지 다른 것들을 섞고 있습니다.

사용 dir(), vars() 아니면 그 inspect 관심있는 것을 얻기위한 모듈 (나는 사용한다. __builtins__ 예로서; 대신 객체를 사용할 수 있습니다).

>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__

그 사전을 인쇄하지만 당신이 좋아하는 멋진.

>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...

또는

>>> from pprint import pprint
>>> pprint(l)
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'DeprecationWarning',
...

>>> pprint(d, indent=2)
{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
  'AssertionError': <type 'exceptions.AssertionError'>,
  'AttributeError': <type 'exceptions.AttributeError'>,
...
  '_': [ 'ArithmeticError',
         'AssertionError',
         'AttributeError',
         'BaseException',
         'DeprecationWarning',
...

Pretty Printing은 대화식 디버거에서 명령으로 사용할 수 있습니다.

(Pdb) pp vars()
{'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
                  'AssertionError': <type 'exceptions.AssertionError'>,
                  'AttributeError': <type 'exceptions.AttributeError'>,
                  'BaseException': <type 'exceptions.BaseException'>,
                  'BufferError': <type 'exceptions.BufferError'>,
                  ...
                  'zip': <built-in function zip>},
 '__file__': 'pass.py',
 '__name__': '__main__'}

다른 팁

당신은 원합니다 vars() 혼합 pprint():

from pprint import pprint
pprint(vars(your_object))
def dump(obj):
  for attr in dir(obj):
    print("obj.%s = %r" % (attr, getattr(obj, attr)))

저자의 선호도에 따라 예외 처리, 국가/특수 문자 인쇄, 중첩 된 물체 등으로 되풀이되는 것과 같은 것들을 추가하는 많은 3 자 기능이 있습니다. 그러나 그들은 모두 기본적으로 이것으로 끓습니다.

멍청이 언급되었지만 속성의 이름 만 제공합니다. 당신이 그들의 가치를 원한다면 __dict__를 시도하십시오.

class O:
   def __init__ (self):
      self.value = 3

o = O()

출력은 다음과 같습니다.

>>> o.__dict__

{'value': 3}

객체의 현재 상태를 인쇄하려면 다음과 같습니다.

>>> obj # in an interpreter

또는

print repr(obj) # in a script

또는

print obj

수업에 대해 정의합니다 __str__ 또는 __repr__ 행동 양식. 로부터 파이썬 문서:

__repr__(self) 전화에 repr() 내장 함수 및 문자열 변환 (리버스 따옴표)에 의해 개체의 "공식"문자열 표현을 계산합니다. 가능하다면, 이것은 동일한 값 (적절한 환경이 주어진)을 가진 물체를 재현하는 데 사용될 수있는 유효한 파이썬 표현식처럼 보일 것입니다. 이것이 불가능한 경우, "<... 유용한 설명 ...>"양식의 문자열을 반환해야합니다. 리턴 값은 문자열 객체 여야합니다. 수업이 정의 된 경우 repr() 하지만 __str__(), 그 다음에 __repr__() 해당 클래스의 인스턴스의 "비공식적"문자열 표현이 필요할 때도 사용됩니다. 이것은 일반적으로 디버깅에 사용되므로 표현이 정보가 풍부하고 모호하지 않은 것이 중요합니다.

__str__(self) 전화에 str() 내장 함수 및 인쇄 문에 의해 객체의 "비공식"문자열 표현을 계산합니다. 이것은 다릅니다 __repr__() 유효한 파이썬 표현식 일 필요는 없다는 점에서 대신 더 편리하거나 간결한 표현이 사용될 수 있습니다. 리턴 값은 문자열 객체 여야합니다.

"dir ()"함수를 사용하여이를 수행 할 수 있습니다.

>>> import sys
>>> dir(sys)
['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo
t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder
, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'
 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault
ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he
version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_
ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit
, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption
', 'winver']
>>>

또 다른 유용한 기능은 도움입니다.

>>> help(sys)
Help on built-in module sys:

NAME
    sys

FILE
    (built-in)

MODULE DOCS
    http://www.python.org/doc/current/lib/module-sys.html

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.

    Dynamic objects:

    argv -- command line arguments; argv[0] is the script pathname if known

확인해 볼 가치가 있을 것 같습니다.

Perl의 Data::Dumper와 동등한 Python이 있습니까?

내 추천은 이렇습니다.

https://gist.github.com/1071857

Perl에는 개체 데이터를 Perl 소스 코드로 다시 변환하는 Data::Dumper라는 모듈이 있습니다(주의:코드를 소스로 다시 변환하지 않으며 거의 ​​항상 출력에서 ​​객체 메서드 함수를 원하지 않습니다.이는 지속성을 위해 사용될 수 있지만 일반적인 목적은 디버깅입니다.

표준 Python pprint가 달성하지 못하는 여러 가지가 있습니다. 특히 개체의 인스턴스를 볼 때 내림차순을 멈추고 개체의 내부 16진수 포인터를 제공합니다(에러, 해당 포인터는 많이 사용되지 않습니다). 방법).간단히 말해서 Python은 이 훌륭한 객체 지향 패러다임에 관한 것이지만 기본 제공되는 도구는 객체가 아닌 다른 작업을 위해 설계되었습니다.

Perl Data::Dumper를 사용하면 원하는 깊이를 제어할 수 있으며 순환 링크 구조도 감지할 수 있습니다(정말 중요합니다).이 프로세스는 근본적으로 Perl에서 달성하기가 더 쉽습니다. 객체에는 축복 이상의 특별한 마법이 없기 때문입니다(보편적으로 잘 정의된 프로세스).

대부분의 경우 사용 __dict__ 또는 dir() 원하는 정보를 얻을 수 있습니다. 더 자세한 내용이 필요한 경우 표준 라이브러리에는 다음이 포함됩니다. 검사 모듈은 인상적인 세부 사항을 얻을 수 있습니다. 실제 정보 중 일부는 다음과 같습니다.

  • 기능 및 메소드 매개 변수의 이름
  • 클래스 계층
  • 함수/클래스 개체 구현의 소스 코드
  • 프레임 객체에서 로컬 변수

"내 객체가 어떤 속성 값을 가지고 있습니까?"를 찾고 있다면 dir() 그리고 __dict__ 아마도 충분할 것입니다. 현재 임의의 객체의 현재 상태를 파헤 치려고한다면 (파이썬에서는 거의 모든 것이 객체라는 점을 명심하십시오). inspect 고려할 가치가 있습니다.

메타 프로 그램 예제 마법으로 물체를 덤프하십시오:

$ cat dump.py
#!/usr/bin/python
import sys
if len(sys.argv) > 2:
    module, metaklass  = sys.argv[1:3]
    m = __import__(module, globals(), locals(), [metaklass])
    __metaclass__ = getattr(m, metaklass)

class Data:
    def __init__(self):
        self.num = 38
        self.lst = ['a','b','c']
        self.str = 'spam'
    dumps   = lambda self: repr(self)
    __str__ = lambda self: self.dumps()

data = Data()
print data

논쟁없이 :

$ python dump.py
<__main__.Data instance at 0x00A052D8>

와 함께 gnosis utils:

$ python dump.py gnosis.magic MetaXMLPickler
<?xml version="1.0"?>
<!DOCTYPE PyObject SYSTEM "PyObjects.dtd">
<PyObject module="__main__" class="Data" id="11038416">
<attr name="lst" type="list" id="11196136" >
  <item type="string" value="a" />
  <item type="string" value="b" />
  <item type="string" value="c" />
</attr>
<attr name="num" type="numeric" value="38" />
<attr name="str" type="string" value="spam" />
</PyObject>

약간 구식이지만 여전히 작동합니다.

디버깅을 위해 이것을 사용하고 있고 모든 것을 재귀적인 덤프를 원한다면, 수업이 좋을 필요가 있기 때문에 허용 된 대답은 불만족 스럽습니다. __str__ 이미 구현. 그렇지 않다면, 이것은 훨씬 더 잘 작동합니다.

import json
print(json.dumps(YOUR_OBJECT, 
                 default=lambda obj: vars(obj),
                 indent=1))

이것은 모든 객체 내용을 재귀 적으로 JSON 또는 Yaml Indented 형식으로 인쇄합니다.

import jsonpickle # pip install jsonpickle
import json
import yaml # pip install pyyaml

serialized = jsonpickle.encode(obj, max_depth=2) # max_depth is optional
print json.dumps(json.loads(serialized), indent=4)
print yaml.dump(yaml.load(serialized), indent=4)

사용하는 것이 좋습니다 help(your_object).

help(dir)

 If called without an argument, return the names in the current scope.
 Else, return an alphabetized list of names comprising (some of) the attributes
 of the given object, and of attributes reachable from it.
 If the object supplies a method named __dir__, it will be used; otherwise
 the default dir() logic is used and returns:
 for a module object: the module's attributes.
 for a class object:  its attributes, and recursively the attributes
 of its bases.
 for any other object: its attributes, its class's attributes, and
 recursively the attributes of its class's base classes.

help(vars)

Without arguments, equivalent to locals().
With an argument, equivalent to object.__dict__.

디버그 정보를 일부 로그로 인쇄해야했고 PPRINT를 사용할 수 없었습니다. 대신 나는 이것을했고 거의 같은 일을 얻었습니다.

DO = DemoObject()

itemDir = DO.__dict__

for i in itemDir:
    print '{0}  :  {1}'.format(i, itemDir[i])

"myObject"를 덤프하려면 :

from bson import json_util
import json

print(json.dumps(myObject, default=json_util.default, sort_keys=True, indent=4, separators=(',', ': ')))

vars () 및 dir ()를 시도했습니다. 둘 다 내가 찾고 있던 것에 실패했습니다. vars ()는 객체에 __dict__가 없기 때문에 작동하지 않았다 (예외. 타입 자 : vars () 인수는 __dict__ 속성이 있어야한다). Dir ()는 내가 찾고 있던 것이 아니 었습니다. 그것은 단지 필드 이름 목록 일뿐입니다. 값이나 객체 구조를 제공하지 않습니다.

json.dumps ()는 default = json_util.default없이 대부분의 객체에서 작동한다고 생각하지만 객체에 DateTime 필드가있어 표준 JSON SERIALIZER가 실패했습니다. 보다 Python에서 "DateTime.dateTime JSON SERIALIZABLE"을 극복하는 방법?

from pprint import pprint

def print_r(the_object):
    print ("CLASS: ", the_object.__class__.__name__, " (BASE CLASS: ", the_object.__class__.__bases__,")")
    pprint(vars(the_object))

노력하다 PRETTY

from ppretty import ppretty


class A(object):
    s = 5

    def __init__(self):
        self._p = 8

    @property
    def foo(self):
        return range(10)


print ppretty(A(), show_protected=True, show_static=True, show_properties=True)

산출:

__main__.A(_p = 8, foo = [0, 1, ..., 8, 9], s = 5)

pprint 데이터 구조의 미적으로 유쾌한 표현을 생성하기위한 "예쁜 프린터"가 포함되어 있습니다. Formatter는 통역사가 올바르게 구문 분석 할 수있는 데이터 구조의 표현을 생성하며 인간이 읽기 쉽습니다. 출력은 가능하면 한 줄로 유지되며 여러 줄에 분리 될 때 들여 쓰기됩니다.

간단한 점 : 왜 :

for key,value in obj.__dict__.iteritems():
    print key,value

나는 pprint 만 언급하는 답을 발전시켰다. 분명히, 당신이 모든 것을보고 싶다면 가치 복잡한 데이터 구조에서 다음과 같은 작업을 수행하십시오.

from pprint import pprint
pprint(my_var)

어디에 my_var 관심있는 변수입니다. pprint (vars (my_var))를 사용했을 때 나는 아무것도 얻지 못했고, 여기서 다른 답변은 도움이되지 않았거나 그 방법이 불필요하게 길어 보였다. 그건 그렇고, 내 특별한 경우, 내가 검사하고 있던 코드에는 사전 사전이있었습니다.

일부 사용자 정의 클래스를 사용하면 도움이되지 않는 사람으로 끝날 수 있다는 점을 지적 할 가치가 있습니다. <someobject.ExampleClass object at 0x7f739267f400> 종류의 출력. 이 경우 구현해야 할 수도 있습니다. __str__ 방법 또는 다른 솔루션을 시도하십시오. 나는 여전히 타사 라이브러리없이 모든 시나리오에서 작동하는 단순한 것을 찾고 싶습니다.

단지 시도 신지.

인쇄 객체 변수뿐만 아니라 다음과 같은 아름다운 출력도 도움이됩니다.

class(NormalClassNewStyle):
  dicts: {
  },
  lists: [],
  static_props: 1,
  tupl: (1, 2)

모두에게 어려움을 겪고 있습니다

  • vars() 모든 속성을 반환하지는 않습니다.
  • dir() 속성의 값을 반환하지 않습니다.

다음 코드는 인쇄합니다 모두 의 속성 obj 그들의 가치로 :

for attr in dir(obj):
        try:
            print("obj.{} = {}".format(attr, getattr(obj, attr)))
        except AttributeError:
            print("obj.{} = ?".format(attr))

플라스크 디버그 도구 모음을 사용해 볼 수 있습니다.
https://pypi.python.org/pypi/flask-debugtoolbar

from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__)

# the toolbar is only enabled in debug mode:
app.debug = True

# set a 'SECRET_KEY' to enable the Flask session cookies
app.config['SECRET_KEY'] = '<replace with a secret key>'

toolbar = DebugToolbarExtension(app)

나는 Python Object 내장 유형으로 작업하는 것을 좋아합니다 열쇠 또는 가치.

방법이나 변수에 관계없이 속성의 경우 :

o.keys()

해당 속성의 값 :

o.values()
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top