python - 远程热插拔 Python 调试器

标签 python debugging pycharm uwsgi

如何通过 Python IDE 集成设置可热插拔远程调试器?例如使用 PyCharm。我所说的可热插拔的意思是:可以动态连接和断开与开发服务器的连接。

我在云端有开发服务器(django、nginx、uwsgi、postgres、debian),并使用 PyCharm 作为主要 IDE(但如果您有任何其他 IDE 的解决方案,请提供)。

有时,我需要在不停止/重新启动开发服务器的情况下连接和调试脚本。使用 PyCharm 的调试器 (pydevd),开发服务器在没有工作调试器服务器的情况下无法启动(连接被拒绝),如果我在开发服务器运行时停止远程调试器,它会崩溃,例如

An existing connection was forcibly closed by the remote host

我找到了 pdg/epdg,但它们没有与 PyCharm 集成。 PyCharm 还有一个很好的功能:“附加到进程”,但它仅适用于本地进程。

最佳答案

可能有效的基本方法是为要调试的程序设置一个信号处理程序以在调试器中加载。然后向进程发送一个信号进行调试(通过 kill 命令),然后您就可以远程附加。

以下是通过 python trepan 执行此操作的方法debuggers

import signal

def signal_handler(num, f):
    from trepan.interfaces import server as Mserver
    from trepan.api import debug
    connection_opts={'IO': 'TCP', 'PORT': 1955}
    intf = Mserver.ServerInterface(connection_opts=connection_opts)
    dbg_opts = {'interface': intf}
    print('Starting TCP server listening on port 1955.')
    debug(dbg_opts=dbg_opts)
    return

signal.signal(signal.SIGUSR1, signal_handler)
# Go about your business...

import time
import os
print(os.getpid())
for i in range(10000):
    time.sleep(0.2)

现在运行:

$ python /tmp/foo.py
8530

从上面的输出中,我们列出了要调试的 Python 进程的 pid。

现在,在 shell 中,我们发送一个信号来告诉进程进入信号处理程序中设置的调试器。您将必须调整 进程ID。

$ kill -USR1 8530   # Adjust the pid to what you see above

在我们运行 /tmp/foo.py 的 shell 中,您现在应该看到 新输出:

$ python /tmp/foo.py
8530
Starting TCP server listening on port 1955. # This is new

回到我们发出 kill -USR1 的 shell,我们现在将现在停止的进程附加到调试器中:

$ trepan2 --client --port 1955
Connected.
(/tmp/foo.py:11 @101): signal_handler
-- 11     return
(trepan2*) list
  6         connection_opts={'IO': 'TCP', 'PORT': 1955}
  7         intf = Mserver.ServerInterface(connection_opts=connection_opts)
  8         dbg_opts = {'interface': intf}
  9         print('Starting TCP server listening on port 1955.')
 10         debug(dbg_opts=dbg_opts)
 11  ->     return
 12
 13     signal.signal(signal.SIGUSR1, signal_handler)
 14     # Go about your business...
 (trepan2*) backtrace
 ->   0 signal_handler(num=10, f=<frame object at 0x7f9036796050>)
      called from file '/tmp/foo.py' at line 11
 ##   1 <module> file '/tmp/foo.py' at line 20

关于python - 远程热插拔 Python 调试器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40364069/

相关文章:

java - 在java中打开/关闭println的任何方法(详细模式)

python - 在 PyCharm 中禁用 IPython 控制台

python - 发现 py 错误 : Statement expected,:Ddent

python - 遗传算法图像进化的不正确结果

python - 在python中的类中定义一个方法

c++ - free(): invalid pointer error in C++

c# - 在此文件夹中找不到匹配的符号文件

python - PyCharm STDOUT 窗口

python - 将类型指定为数字列表(整数和/或 float )?

python - 我应该在 docker build 期间运行测试吗?