我喜欢使用以下方法检查Python脚本中的错误:
$ python3 -m pdb my_script.py
这让我进入了一个pdb提示符,从那里我可以继续执行c
,当它遇到错误时,我可以检查变量,然后q
退出脚本执行以返回到我的shell。
我尝试使用iPython调试器模块,因为它更加丰富多彩:
$ python3 -m ipdb my_script.py
但是,一旦检查完错误,我就无法退出调试器。使用q
quit命令只是在重新执行脚本和事后模式之间保持切换:
$ python3 -m ipdb my_script.py
ipdb> c
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
ipdb> Inspect some variables at this point
ipdb> q
Post mortem debugger finished. The my_script.py will be restarted
ipdb> q
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
ipdb> q
Post mortem debugger finished. The my_script.py will be restarted
ipdb> q
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
ipdb> q
Post mortem debugger finished. The my_script.py will be restarted
ipdb> q
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
如何退出此调试器?
这是IPython 5.1中的一个错误。它在this pull request中得到修复,不再是IPython 5.2及其后的问题。您现在可以使用q
,quit()
或Ctrl + d退出调试器。
正如用户@ffeast评论的那样,有an open ipdb issue,并提出了一些解决方法。对我来说这些效果很好:
kill %1
(或任何工作号码)ipdb> import os; os._exit(1)
使用ctrl + z(或第二个终端),并终止进程。
ssh server
建立新连接(使用选项B或C,这样您就可以打开第二个连接来执行命令):(如果ctrl + z不起作用,你可以打开第二个终端)
PID
的相应python ps -ax | grep python
。例如,我的进程(python my_stucked_process.py
)的进程ID将是112923
: 3085 tty1 Sl+ 15:53 /usr/bin/python /usr/bin/x-terminal-emulator
112923 pts/2 Tl 0:01 python my_stucked_process.py
113118 pts/2 S+ 0:00 grep --color=auto python
kill -9 112923
@tutuDajuju建议使用ctrl + z但他们的建议只会将进程发送到后台(它仍然会消耗内存)。你需要按照上面的顺序来真正杀死这个过程