developer tip

디버깅을 위해 생성기 객체를 목록으로 변환

optionbox 2020. 9. 12. 09:46
반응형

디버깅을 위해 생성기 객체를 목록으로 변환 [중복]


이 질문에 이미 답변이 있습니다.

IPython을 사용하여 Python에서 디버깅 할 때 가끔 중단 점에 도달하여 현재 생성자 인 변수를 검사하고 싶습니다. 제가 생각할 수있는 가장 간단한 방법은 목록으로 변환하는 것입니다.하지만 저는 ipdbPython을 처음 접했기 때문에 에서 한 줄로이 작업을 수행하는 쉬운 방법이 무엇인지 명확하지 않습니다 .


list발전기를 부르기 만하면 됩니다.

lst = list(gen)
lst

이것은 더 이상 항목을 반환하지 않는 생성기에 영향을 미칩니다.

또한 list코드 줄을 나열하는 명령과 충돌하므로 IPython에서 직접 호출 할 수 없습니다 .

이 파일에서 테스트되었습니다.

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

실행할 때 :

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

함수 / 변수 / 디버거 이름 충돌을 이스케이프하는 일반적인 방법

디버거 명령이 있습니다 ppp그 의지 printprettyprint그 다음 표현식은.

따라서 다음과 같이 사용할 수 있습니다.

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

또한 exec표현식에 접두사를 붙여서 호출되는 명령 도 있습니다.이 명령 !은 디버거가 표현식을 Python으로 가져 오도록합니다 .

ipdb> !list(g1)
[]

자세한 내용은 help p, help pphelp execwhen in debugger를 참조하십시오 .

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

참고 URL : https://stackoverflow.com/questions/24130745/convert-generator-object-to-list-for-debugging

반응형