为 Python 添加远程调试能力而不修改系统代码

2018-10-2314:21:05后端程序开发为 Python 添加远程调试能力而不修改系统代码已关闭评论3,860 views字数 1090阅读模式

如何在不改动一行系统代码的情况下,实现 Python 应用的开启调试和关闭调试。这篇博文里我不会给出实现代码,因为读者知道了实现原理之后,自己动手实现一下,也许就是几十分钟的事情。需要强调的是,这里的「系统代码」,其实是「业务系统代码」的意思,也就是我们维护的应用的代码。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/7016.html

我们知道,要想使用 ptvsd 为 Python 服务器开启远程调试功能,需要在代码的入口处 import ptvsd,并调用 ptvsd.settrace 方法启动 debug server。具体用法见「使用 VS Code 远程调试 Python 程序」,当时我是在代码中硬编码了对 ptvsd 的调用。我们这里需要做的,就是将这种硬编码的调用,从业务代码中剥离。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/7016.html

先理一下需求:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/7016.html

  1. 在业务代码启动之前,完成对 ptvsd 的调用
  2. 对 ptvsd 的调用,不出现在业务系统的代码中

在 Python 中,是否能做到在执行一个 py 文件之前,先执行一点别的代码呢?如果可以,那么我们就能把对 ptvsd 的调用,作为这「一点别的代码」了。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/7016.html

答案是肯定的。与此相关的知识点是 sitecustomize.py。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/7016.html

After these path manipulations, an attempt is made to import a module named sitecustomize, which can perform arbitrary site-specific customizations. It is typically created by a system administrator in the site-packages directory. If this import fails with an ImportError exception, it is silently ignored. If Python is started without output streams available, as with pythonw.exe on Windows (which is used by default to start IDLE), attempted output from sitecustomize is ignored. Any exception other than ImportError causes a silent and perhaps mysterious failure of the process.文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/7016.html

上面这段文档来自 Python 标准库的 site 模块,勉强算是解释了 sitecustomize 的用途,以及加载时机。反正基本上只要知道当我们执行 python a.py时,sitecustomize.py 的代码会在 Python 解释器启动之后,py 文件执行之前执行就%文章源自菜鸟学院-https://www.cainiaoxueyuan.com/bc/7016.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/bc/7016.html