简体   繁体   English

调试Python解释器中的代码

[英]Debugging code in the Python interpreter

I like testing functions in the Python interpreter . 我喜欢在Python解释器中测试函数。 Is it possible to debug a function in the Python interpreter when I want to see more than a return value and a side effect? 当我想看到的不仅仅是返回值和副作用时,是否可以在Python解释器中调试函数?

If so, could you show basic debugger operations ( launching the function with arguments, setting breakpoint, next step, step into, watching variable )? 如果是这样,你能展示基本的调试器操作( 启动带参数的函数,设置断点,下一步,进入,观察变量 )? If not, how would you debug a function another way? 如果没有,你会如何以另一种方式调试函数?

The point is, I want to debug only a particular function which will be supplied with arguments. 关键是,我想只调试一个将提供参数的特定函数。 I don't want to debug whole module code. 我不想调试整个模块代码。

thank you for advice 谢谢你的建议

If you want to debug specific function you can using this - 如果你想调试特定的功能,你可以使用这个 -

>>> import pdb
>>> import yourmodule
>>> pdb.run('yourmodule.foo()')

over the command line. 通过命令行。 pdb.set_trace() should be added in your function to break there. 应该在你的函数中添加pdb.set_trace()来打破它。

More info on pdb can be seen here - http://docs.python.org/library/pdb.html 关于pdb的更多信息可以在这里看到 - http://docs.python.org/library/pdb.html

See pdb module. 请参阅pdb模块。 Insert into code: 插入代码:

import pdb
pdb.set_trace()

... makes a breakpoint. ......做一个断点。

The code-to-debug does not need to be modified to include pdb.set_trace() . 不需要修改代码调试以包含pdb.set_trace() That call can be made directly in the interpreter just before the code-to-debug: 该调用可以在代码调试之前直接在解释器中进行:

>>> import pdb
>>> pdb.set_trace(); <code-to-debug>

For example, given test_script.py with the following code: 例如,给定test_script.py并使用以下代码:

def some_func(text):
    print 'Given text is {}'.format(repr(text))
    for index,char in enumerate(text):
        print ' '*index, char

an interpreter session to debug some_func using the debugger commands step-into ( s ), next ( n ) and continue ( c ) would look like: 使用调试器命令step-into( s )调试some_func的解释器会话,next( n )和continue( c )将如下所示:

>>> import pdb
>>> import test_script
>>> pdb.set_trace(); test_script.some_func('hello')
--Call--
> c:\src\test_script.py(1)some_func()
-> def some_func(text):
(Pdb) s
> c:\src\test_script.py(2)some_func()
-> print 'Given text is {}'.format(repr(text))
(Pdb) n
Given text is 'hello'
> c:\src\test_script.py(3)some_func()
-> for index,char in enumerate(text):
(Pdb) c
 h
  e
   l
    l
     o
>>> 

See the docs for the pdb module for more information on how to use the debugger: http://docs.python.org/library/pdb.html 有关如何使用调试器的更多信息,请参阅pdb模块的文档: http//docs.python.org/library/pdb.html

Additionally, while using the debugger, the help command provides a nice list of commands and help <command> gives help specific to the given command. 此外,在使用调试器时, help命令提供了一个很好的命令列表, help <command>提供了给定命令的特定帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM