Python에서 스파이더를 사용하여 효율적으로 디버그하려면 어떻게해야합니까?
저는 Python을 좋아하고 Spyder를 좋아하지만 Spyder로 디버깅하는 것은 끔찍합니다!
- 중단 점을 넣을 때마다 두 개의 버튼을 눌러야합니다. 먼저 디버그 버튼을 누른 다음 계속 버튼 (첫 번째 줄에서 자동으로 일시 중지됨)을 눌러야합니다.
- 또한 자동 완성 기능이있는 표준 iPython 콘솔을 사용하는 대신 쓰레기 인 형편없는 ipdb >> 콘솔이 있습니다.
- 최악의 것은 버그가 무엇인지 알아 내기 위해 인쇄물이나 간단한 평가를 써도이 콘솔이 매우 자주 멈춘다는 것입니다. 이것은 matlab보다 훨씬 나쁩니다.
- 마지막으로 ipdb >> 콘솔 내에서 함수를 호출하고 그 안에 중단 점을 넣으면 거기서 멈추지 않습니다. 디버깅을 시작하기 전에 중단 점을 넣어야하는 것 같습니다 (ctrl + F5).
해결책이 있거나 파이썬 스크립트와 함수를 디버깅하는 방법을 알려 주실 수 있습니까?
Windows 8.1 64 비트에서 Anaconda를 새로 설치하고 있습니다.
( Spyder dev 여기 ) 우리는 Spyder의 디버깅 경험이 이상적이지 않다는 것을 알고 있습니다. 지금 우리가 제공하는 것은 표준 Python 디버거와 매우 유사하지만, 과학자가 디버거에 대해 기대하는 것에 더 가까운 것을 제공하기 위해 다음 메이저 버전에서 개선하기 위해 노력하고 있습니다 (간단히 말하면 일반 IPython 콘솔). 현재 중단 점에서 변수를 검사하고 플로팅합니다).
이제 포인트에 대해 :
사실입니다. 사용자가 실행 버튼을 누르고 현재 파일에 중단 점이 있으면 Spyder가 디버그 모드로 들어가 첫 번째 중단 점이 충족 될 때까지 프로그램을 실행하도록 개선하려고합니다.
ipdb
IPython 디버거 콘솔입니다. 안타깝게도 IPython 아키텍처의 제한으로 인해 매우 제한적입니다 (코드 완성 및 화살표로 기록 검색 없음). 또한ipdb
일반pdb
콘솔 또는 일반 콘솔 에서 임의의 Python 코드를 실행할 수 없습니다 . 실행할 수있는 명령ipdb
은 그help
안에 있는 명령을 평가할 때 읽을 수있는 것 입니다.내가 말했듯이 임의의 Python 코드를 평가할 수 없기 때문입니다.
Python / IPython 콘솔과 동기화되도록 편집기에 새 중단 점을 입력해야합니다.
디버깅 워크 플로
실제로 파이썬 디버거pdb
와 ipdb
( pdb
모듈을 사용하여 액세스 할 수있는) 다른 통합을 사용하고 있음을 이해해야합니다 ipdb
. 이 사소한 예제가 더 잘 사용하는 데 도움이되기를 바랍니다.
이 코드를 디버그하려고한다고 가정합니다.
def Waiting_fun(): #1 line number one
for i in range(100): #2
pass #3
#4
def New_sum(lista, to_s = False): #5
result = 0 #6
print 1 #7
for i in lista: #8
print "summed" #9
result +=i #10
Waiting_fun() #11
if to_s: #12
result = str(result)
return result
a = New_sum([1,4,5,7,8])
b = New_sum([1,4],1)
c = 456
d = New_sum([6,8,9],1)
final_result = a*b*c*d
Out: Type error
iPython % debug를 사용한 빠른 첫 디버깅
%debug
내가 제일 먼저하는 일은 iPython에서 magic 명령을 사용하여 pdb를 호출 %debug
하는 것 %pdb
입니다..
%debug
> /home/opdate/Desktop/test.py(23)<module>()
19 a = New_sum([1,4,5,7,8])
20 b = New_sum([1,4],1)
21 c = 456
22 d = New_sum([6,8,9],1)
---> 23 final_result = a*b*c*d
점심을 먹으면 pdb
. 공식 문서 에서 모든 명령을 찾 거나 명령 h
을 사용하여 표시 할 수 있습니다. 이 단계에서 내가 사용하는 유일한 명령은 다음과 같습니다.
p
: 지정한 변수를 인쇄합니다.pp
: 예쁜 프린트args
: 함수 내부에 있으면 인수를 인쇄합니다.pp locals()
: 모든 변수를 인쇄하는 데 유용 할 수 있지만 대부분의 경우 엉망입니다!!
에 나열된 명령과 충돌하지 않으려면 사용하십시오.h
whatis
variable_name : type (variable_name)과 동일u
: 스택 추적에서 현재 프레임을 한 수준 위로 이동합니다 (이전 프레임으로).d
: 스택 추적에서 현재 프레임을 한 수준 아래로 이동합니다 (최신 프레임으로).q
: 완료되면 q를 사용하여 종료 할 수 있습니다.
우리의 경우 :
ipdb> pp a,b,c,d
(25, '5', 456, '23')
또는 ipdb> !a,b,c,d
(Esclamation 표시와 첫 번째 값 사이에 공백 없음). 우리가 사용할 수있는 경우 b와 d는 문자열이라는 것이 분명합니다.
ipdb> whatis b
<type 'str'>
중단 점을 사용하여 더 깊이 들어가기
70 %의 시간 %debug
이 해결책을 제시합니다. 중단 점 과 같은 더 많은 기능이 필요할 때 Spyder를 사용할 때입니다. 이 경우 왜 b
문자열 옆에 중단 점을 두 었는지 이해하려고 합니다. 내가 발견 훨씬 더 디버깅을 시작하기 전에 콘솔을 선택 그래서 디버깅을위한 IPython 콘솔 대신 표준 파이썬 콘솔을 사용하여 :
그런 다음 variable explorer
변수가 있으면 열어서 삭제하십시오. Ctrl+ F5를 사용 하여 디버깅을 시작하고 상단의 버튼을 사용할 수 있지만 아래 표시된 단축키를 사용하는 것을 선호합니다.
(Pdb) c # we go to the breakpoint
(Pdb) s # we step into the function
(Pdb) args # we see what parameters are inserted
(Pdb) s # going step-by-step
(Pdb) ⏎ # series of Enters go line by line quicker
#Here I'll use whatis command but in fact I just look to
# the type in variable explorer of spyder.
(Pdb) whatis result #check if result is still int
(Pdb) unt #or until -useful to exiting from loops see doc.
(Pdb) n # we don't enter to the Waiting_fun function
(Pdb) s # going step-by-step
(Pdb) whatis result #we find that there the int is converted
(Pdb) j 6 # for double checking we jump back to 6 were the result is assigned
# We may be tempted to j(ump) to line 12 but doing so we would skip all the code
#for avoiding a series of `s`,`unt` and `n` we can use this solution:
(Pdb) tbreak 12 #set a new temporary breakpoint. Also `b` it's ok most of the time
(Pdb) c # go to it
(Pdb) j 6 # we jump to 6 the code we jump is NOT executed
(Pdb) whatis result# we find that if we jump 12-13 result is still int
이제 오류를 찾았습니다. 12까지 단계를 반복하고 설정 한 솔루션 을 테스트 할 수도 있습니다.to_s = False
(Pdb) to_s = False #!to_s = False to be on the safe side
It works. One important feature using the standard pdb in the Python console, is that you have auto competition and you can use the variable explorer instead of using whatis
and pp
:
Using the variable explorer you can also change the value of the variables which makes the things even more quick.
Conditional breakpoints
Another more clever way to locate the error is to use conditional breakpoint (Shift+F12) a great advantage of Spyder is going to debug and use list breakpoints. Conditional breakpoints are activated when the condition is True
In our case, we want to locate where b becomes a string so the condition is: type(b) == str
. I usually place a lot of conditional breakpoints and see which one meet the condition. For doing so don't use Shift+F12 but place normal breakpoints double-clicking next to the line and go to Debug->List breakpoints and copy and past the condition in the table to every breakpoint as shown in the figure below.
From here the commands to use are:
(Pdb) c # go to the first
(Pdb) u # it helps to understand when it happened
(Pdb) d # come back to the breakpoint
The pdb debugger works just fine with regular python. So in Spyder, I just switch to the python console whenever I want to debug interactively.
import pdb
def yourfunction():
# Interesting stuff done here
pdb.set_trace()
Nice intro to debugging with pdb https://pythonconquerstheuniverse.wordpress.com/category/python-debugger/
Here is how I debug in Spyder in order to avoid freezing the IDE. I do this if I alter the script while in debugging mode.
- I close out the current IPython (debugging) console [x]
- Open a new one [Menu bar-> Consoles-> Open an IPython Console]
- Enter debug mode again [blue play pause button].
Still a bit annoying, but it has the added benefit of clearing (resetting) variable list.
No one has ever mentioned about these two before apparently:
Before Python, I was using VBA. Although it is a relatively old language that is not regularly updated, one thing I loved about VBA was the debugging function. The 2 debugging functions that are closest to VBA or which can also be termed as "visual debugging" I had come across are:
1-PyCharm Debugger
This 6 minutes video demonstrates PyCharm debugger.
2-PixieDebugger - The Visual Python Debugger for Jupyter Notebooks You’ve Always Wanted
Since many coders tend to use JupyterNotebook, this debugger would come in handy. PixieDebugger is almost the same as PyCharm debugger. I will not go into detail in here.
But you can refer to this link
One minor extra regarding point 3:
또한 디버그 콘솔이 자주 멈추고 인쇄하고 평가하는 것처럼 보였지만 중지 (디버그 종료) 버튼을 누르면 일반적으로 호출 스택의 맨 아래로 돌아간 다음 다시 돌아갈 수 있습니다 ( 'u'). 내가 디버깅하고 있던 프레임에. 시도할만한 가치가 있습니다. 이것은 최신 버전의 Spyder (2.3.5.2) 용일 수 있습니다.
다음과 같은 디버그 단축키를 사용할 수 있습니다. 도구> 환경 설정> 키보드 단축키에서 F10 단계로 단계 F11 단계로 단계
참고 URL : https://stackoverflow.com/questions/28280308/how-do-i-debug-efficiently-with-spyder-in-python
'Nice programing' 카테고리의 다른 글
항목을 삽입하거나 정렬 된 목록에 추가 한 후 목록을 정렬하는 것이 더 빠릅니까? (0) | 2020.11.28 |
---|---|
스윙 : JFrame 이미지 얻기 (0) | 2020.11.28 |
Windows 10에서 Python 설치를 어떻게 업그레이드합니까? (0) | 2020.11.28 |
Excel Interop-효율성 및 성능 (0) | 2020.11.28 |
Java-널 변수에 메모리 공간이 필요합니까? (0) | 2020.11.28 |