source

디버깅을 위해 제너레이터 개체를 목록으로 변환

ittop 2023. 7. 16. 17:55
반응형

디버깅을 위해 제너레이터 개체를 목록으로 변환

IPython을 사용하여 Python에서 디버깅할 때 때때로 중단점에 도달하여 현재 생성기인 변수를 조사하려고 합니다.제가 생각할 수 있는 가장 간단한 방법은 목록으로 변환하는 것입니다. 하지만 저는 이것을 한 줄로 하는 쉬운 방법이 무엇인지 잘 모르겠습니다.ipdb파이썬이 너무 생소해서요.

간단히 전화하기list발전기에서.

lst = list(gen)
lst

이는 제너레이터에 영향을 미쳐 더 이상의 항목을 반환하지 않습니다.

또한 직접 전화할 수 없습니다.listIPython에서 코드 라인을 나열하는 명령과 충돌하기 때문입니다.

이 파일에서 테스트됨:

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.

함수/변수/디버거 이름 충돌을 피하기 위한 일반적인 방법

디버거 명령이 있습니다.p그리고.pp그 의지print그리고.prettyprint그들 뒤에 오는 모든 표현.

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

$ 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식 앞에 다음을 추가하여 호출되는 명령!이는 디버거가 사용자의 표현을 파이썬 표현으로 사용하도록 강제합니다.

ipdb> !list(g1)
[]

자세한 내용은 다음을 참조하십시오.help p,help pp그리고.help exec디버거에 있을 때.

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

반응형