Programing

파이썬 디버깅 팁

알 수 없는 사용자 2020. 5. 30. 09:09
반응형

파이썬 디버깅 팁


파이썬 디버깅을위한 가장 좋은 팁은 무엇입니까?

실제로 할 수있는 일을 말하지 않고 특정 디버거를 나열하지 마십시오.

관련


PDB

pdb 모듈을 사용하고 pdb.set_trace()어디에서나 삽입 하면 중단 점으로 작동합니다.

>>> import pdb
>>> a="a string"
>>> pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) p a
'a string'
(Pdb)

실행을 계속하려면 c(또는 cont또는 continue)를 사용하십시오.

pdb를 사용하여 임의의 파이썬 표현식을 실행할 수 있습니다. 예를 들어 실수를 발견 한 경우 코드를 수정 한 다음 실행중인 코드에서 동일한 효과를 갖도록 유형 표현식을 입력 할 수 있습니다.

ipdb는 IPython 용 pdb 버전입니다 . 탭 완성을 포함한 모든 IPython 기능과 함께 pdb를 사용할 수 있습니다.

포착되지 않은 예외에서 pdb가 자동으로 실행되도록 설정할 수도 있습니다 .

Pydb 는 Pdb의 향상된 버전으로 작성되었습니다. 혜택?


전체 화면 콘솔 기반 Python 디버거 인 http://pypi.python.org/pypi/pudb

이 제품의 목표는 최신 GUI 기반 디버거의 모든 장점을보다 가볍고 키보드 친화적 인 패키지로 제공하는 것입니다. PuDB를 사용하면 터미널에서 코드를 작성하고 테스트 할 때 바로 코드를 디버깅 할 수 있습니다. 뛰어난 (현재는 고대의) DOS 기반 Turbo Pascal 또는 C 도구로 작업 한 경우 PuDB의 UI가 익숙해 보일 수 있습니다.

pudb 스크린 샷

독립형 스크립트 디버깅에 좋습니다.

python -m pudb.run my-script.py

pdb를 사용하는 경우 바로 가기의 별명을 정의 할 수 있습니다. 나는 이것을 사용한다 :

# Ned's .pdbrc

# Print a dictionary, sorted. %1 is the dict, %2 is the prefix for the names.
alias p_ for k in sorted(%1.keys()): print "%s%-15s= %-80.80s" % ("%2",k,repr(%1[k]))

# Print the instance variables of a thing.
alias pi p_ %1.__dict__ %1.

# Print the instance variables of self.
alias ps pi self

# Print the locals.
alias pl p_ locals() local:

# Next and list, and step and list.
alias nl n;;l
alias sl s;;l

# Short cuts for walking up and down the stack
alias uu u;;u
alias uuu u;;u;;u
alias uuuu u;;u;;u;;u
alias uuuuu u;;u;;u;;u;;u
alias dd d;;d
alias ddd d;;d;;d
alias dddd d;;d;;d;;d
alias ddddd d;;d;;d;;d;;d

벌채 반출

파이썬에는 이미 훌륭한 내장 로깅 모듈이 있습니다. 여기서 로깅 템플릿 을 사용할 수 있습니다 .

로깅 모듈을 사용하면 중요도 수준을 지정할 수 있습니다. 디버깅 중에는 모든 것을 기록 할 수 있지만 정상 작동 중에는 중요한 것만 기록 할 수 있습니다. 사물을 켜고 끌 수 있습니다.

대부분의 사람들은 기본 인쇄 문을 사용하여 디버그 한 다음 인쇄 문을 제거합니다. 그대로 두는 것이 좋지만 비활성화하십시오. 그런 다음 다른 버그가 있으면 모든 것을 다시 활성화하고 로그를 살펴볼 수 있습니다.

This can be the best possible way to debug programs that need to do things quickly, such as networking programs that need to respond before the other end of the network connection times out and goes away. You might not have much time to single-step a debugger; but you can just let your code run, and log everything, then pore over the logs and figure out what's really happening.

EDIT: The original URL for the templates was: http://aymanh.com/python-debugging-techniques

This page is missing so I replaced it with a reference to the snapshot saved at archive.org: http://web.archive.org/web/20120819135307/http://aymanh.com/python-debugging-techniques

In case it disappears again, here are the templates I mentioned. This is code taken from the blog; I didn't write it.

import logging
import optparse

LOGGING_LEVELS = {'critical': logging.CRITICAL,
                  'error': logging.ERROR,
                  'warning': logging.WARNING,
                  'info': logging.INFO,
                  'debug': logging.DEBUG}

def main():
  parser = optparse.OptionParser()
  parser.add_option('-l', '--logging-level', help='Logging level')
  parser.add_option('-f', '--logging-file', help='Logging file name')
  (options, args) = parser.parse_args()
  logging_level = LOGGING_LEVELS.get(options.logging_level, logging.NOTSET)
  logging.basicConfig(level=logging_level, filename=options.logging_file,
                      format='%(asctime)s %(levelname)s: %(message)s',
                      datefmt='%Y-%m-%d %H:%M:%S')

  # Your program goes here.
  # You can access command-line arguments using the args variable.

if __name__ == '__main__':
  main()

And here is his explanation of how to use the above. Again, I don't get the credit for this:


By default, the logging module prints critical, error and warning messages. To change this so that all levels are printed, use:

$ ./your-program.py --logging=debug

To send log messages to a file called debug.log, use:

$ ./your-program.py --logging-level=debug --logging-file=debug.log


It is possible to print what Python lines are executed (thanks Geo!). This has any number of applications, for example, you could modify it to check when particular functions are called or add something like ## make it only track particular lines.

code.interact takes you into a interactive console

import code; code.interact(local=locals())

If you want to be able to easily access your console history look at: "Can I have a history mechanism like in the shell?" (will have to look down for it).

Auto-complete can be enabled for the interpreter.


ipdb is like pdb, with the awesomeness of ipython.


print statements

  • Some people recommend a debug_print function instead of print for easy disabling
  • The pprint module is invaluable for complex structures

the obvious way to debug a script

python -m pdb script.py
  • useful when that script raises an exception
  • useful when using virtualenv and pdb command is not running with the venvs python version.

if you don't know exactly where that script is

python -m pdb ``which <python-script-name>``

PyDev

PyDev has a pretty good interactive debugger. It has watch expressions, hover-to-evaluate, thread and stack listings and (almost) all the usual amenities you expect from a modern visual debugger. You can even attach to a running process and do remote debugging.

Like other visual debuggers, though, I find it useful mostly for simple problems, or for very complicated problems after I've tried everything else. I still do most of the heavy lifting with logging.


If you are familiar with Visual Studio, Python Tools for Visual Studio is what you look for.

여기에 이미지 설명을 입력하십시오


Winpdb is very nice, and contrary to its name it's completely cross-platform.

It's got a very nice prompt-based and GUI debugger, and supports remote debugging.


In Vim, I have these three bindings:

map <F9> Oimport rpdb2; rpdb2.start_embedded_debugger("asdf") #BREAK<esc>
map <F8> Ofrom nose.tools import set_trace; set_trace() #BREAK<esc>
map <F7> Oimport traceback, sys; traceback.print_exception(*sys.exc_info()) #TRACEBACK<esc>

rpdb2 is a Remote Python Debugger, which can be used with WinPDB, a solid graphical debugger. Because I know you'll ask, it can do everything I expect a graphical debugger to do :)

I use pdb from nose.tools so that I can debug unit tests as well as normal code.

Finally, the F7 mapping will print a traceback (similar to the kind you get when an exception bubbles to the top of the stack). I've found it really useful more than a few times.


Defining useful repr() methods for your classes (so you can see what an object is) and using repr() or "%r" % (...) or "...{0!r}..".format(...) in your debug messages/logs is IMHO a key to efficient debugging.

Also, the debuggers mentioned in other answers will make use of the repr() methods.


Getting a stack trace from a running Python application

There are several tricks here. These include

  • Breaking into an interpreter/printing a stack trace by sending a signal
  • Getting a stack trace out of an unprepared Python process
  • Running the interpreter with flags to make it useful for debugging

If you don't like spending time in debuggers (and don't appreciate poor usability of pdb command line interface), you can dump execution trace and analyze it later. For example:

python -m trace -t setup.py install > execution.log

This will dump all source line of setup.py install execution to execution.log.

To make it easier to customize trace output and write your own tracers, I put together some pieces of code into xtrace module (public domain).


When possible, I debug using M-x pdb in emacs for source level debugging.


There is a full online course called "Software Debugging" by Andreas Zeller on Udacity, packed with tips about debugging:

Course Summary

In this class you will learn how to debug programs systematically, how to automate the debugging process and build several automated debugging tools in Python.

Why Take This Course?

At the end of this course you will have a solid understanding about systematic debugging, will know how to automate debugging and will have built several functional debugging tools in Python.

Prerequisites and Requirements

Basic knowledge of programming and Python at the level of Udacity CS101 or better is required. Basic understanding of Object-oriented programming is helpful.

Highly recommended.


호출 스택을 읽기 쉬운 방식으로 인쇄하는 멋진 그래픽 방법을 원한다면 다음 유틸리티를 확인하십시오. https://github.com/joerick/pyinstrument

명령 행에서 실행하십시오.

python -m pyinstrument myscript.py [args...]

모듈로 실행하십시오.

from pyinstrument import Profiler

profiler = Profiler()
profiler.start()

# code you want to profile

profiler.stop()
print(profiler.output_text(unicode=True, color=True))

장고와 함께 실행 :

그냥 추가 pyinstrument.middleware.ProfilerMiddleware하는 MIDDLEWARE_CLASSES후 추가 ?profile프로파일을 활성화 요청 URL의 끝에.

참고 URL : https://stackoverflow.com/questions/1623039/python-debugging-tips

반응형