Python非常酷,但不幸的是,它的调试器不如perl -d好.
在试验代码时,我常常做的一件事是从调试器中调用一个函数,然后进入该函数,如下所示:
# NOTE THAT THIS PROGRAM EXITS IMMEDIATELY WITHOUT CALLING FOO() ~> cat -n /tmp/show_perl.pl 1 #!/usr/local/bin/perl 2 3 sub foo { 4 print "hi\n"; 5 print "bye\n"; 6 } 7 8 exit 0; ~> perl -d /tmp/show_perl.pl Loading DB routines from perl5db.pl version 1.28 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(/tmp/show_perl.pl:8): exit 0; # MAGIC HAPPENS HERE -- I AM STEPPING INTO A FUNCTION THAT I AM CALLING INTERACTIVELY DB<1> s foo() main::((eval 6)[/usr/local/lib/perl5/5.8.6/perl5db.pl:628]:3): 3: foo(); DB<<2>> s main::foo(/tmp/show_perl.pl:4): print "hi\n"; DB<<2>> n hi main::foo(/tmp/show_perl.pl:5): print "bye\n"; DB<<2>> n bye DB<2> n Debugged program terminated. Use q to quit or R to restart, use O inhibit_exit to avoid stopping after program termination, h q, h R or h O to get additional info. DB<2> q
当尝试逐步执行函数处理各种不同输入以找出失败原因时,这非常有用.但是,它似乎无法在pdb或pydb中工作(我将向上面显示一个等效的python示例,但它会导致一个大的异常堆栈转储).
所以我的问题是双重的:
我错过了什么吗?
是否有一个python调试器确实让我这样做?
显然我可以自己将调用放在代码中,但我喜欢以交互方式工作,例如.当我想尝试使用稍微不同的参数集调用时,不必从头开始.
我已经回答了我自己的问题!这是pydb中的"debug"命令:
~> cat -n /tmp/test_python.py 1 #!/usr/local/bin/python 2 3 def foo(): 4 print "hi" 5 print "bye" 6 7 exit(0) 8 ~> pydb /tmp/test_python.py (/tmp/test_python.py:7):7 exit(0) (Pydb) debug foo() ENTERING RECURSIVE DEBUGGER ------------------------Call level 11 (/tmp/test_python.py:3): foo 3 def foo(): ((Pydb)) s (/tmp/test_python.py:4): foo 4 print "hi" ((Pydb)) s hi (/tmp/test_python.py:5): foo 5 print "bye" ((Pydb)) s bye ------------------------Return from level 11 ( ) ----------------------Return from level 10 ( ) LEAVING RECURSIVE DEBUGGER (/tmp/test_python.py:7):
您也可以使用pdb以交互方式调试函数,前提是您要调试的脚本最后不会退出():
$ cat test.py #!/usr/bin/python def foo(f, g): h = f+g print h return 2*f
要调试,启动交互式python会话并导入pdb:
$ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import pdb >>> import test >>> pdb.runcall(test.foo, 1, 2) > /Users/simon/Desktop/test.py(4)foo() -> h = f+g (Pdb) n > /Users/simon/Desktop/test.py(5)foo() -> print h (Pdb)
pdb模块附带python,并在http://docs.python.org/modindex.html的模块文档中进行了说明