用kill信号输入pdb [英] enter pdb with kill signal
问题描述
在最近的项目中,我想在生产使用状态下调试程序.生产环境非常复杂,因此我一发现问题就想调试程序.
In a recent project, I want to debug my program in production use state. The production environment is very complicated so I want to debug the program whenever I find a problem.
这是我要实现的目标:每当我要调试时,我都会向程序发送终止信号,并希望出现pdb调试器.是这样的:
This is what I want to achieve: whenever I want to debug, I will send a kill signal to the program and hopefully pdb debugger will appear. It is something like this:
import pdb
import signal
import time
def handler(signal, frame):
pdb.set_trace()
signal.signal(signal.SIGTERM, handler)
a=1
while True:
a+=1
time.sleep(1)
但是,由于我必须使用nohup
运行程序,所以所有输出都将重定向到nohup.out,因此我无法与pdb进行交互.
However, since I have to run the program with nohup
, all output will be redirected to nohup.out, so there's no way I can interact with pdb.
有什么类似的方法吗?
推荐答案
如果从终端运行程序,则可以使用tty
命令来记录
您所在的tty设备,并将其传递到环境中的程序中:
If you run the program from a terminal you can use the tty
command to note the
tty device you are on, and pass it to the program in the environment:
TTY=`tty` nohup ./myprog.py
,然后在处理程序中再次打开tty并将stdin和stdout设置为文件:
and then in the handler open the tty again and set stdin and stdout to the file:
import sys,os
def handler(signal, frame):
tty = os.getenv('TTY')
sys.stdin = sys.stdout = open(tty,"r+")
pdb.set_trace()
如果按照注释中的说明从当前tty分离程序,则您 可以尝试使用相同的python代码进行类似的操作.这次使用以下程序运行程序:
If you are detaching the program from the current tty as in your comment, then you can try something similar, with the same python code. This time run your program with:
TTY=/tmp/link nohup ./myprog.py &
并关闭终端.打开一个新终端,并创建指向该新tty的缺少链接:
and close the terminal. Open a new terminal and create the missing link to this new tty:
ln -s `tty` /tmp/link
然后在一行中给出kill命令,以信号通知python进程,并且
然后立即执行sleep
.这样一来,壳就不再与之竞争
从tty输入的pdb.例如,一行:
Then give, in one single line, the kill command to signal the python process, and
then immediately do a sleep
. This is so that the shell is no longer competing with
pdb for input from the tty. Eg, on one line:
kill -term $pid; sleep 99999
然后,您将让pdb连接到/tmp/link,这是您的tty.退出pdb时,键入 ctrl-c 将停止睡眠.
You will then have pdb connect to /tmp/link, which is your tty. When you quit pdb, typing ctrl-c will stop the sleep.
如果您需要在pdb中使用 ctrl-c ,并且您正在使用bash,
将sleep 99999
替换为suspend
.退出pdb时,使用终端的菜单发送信号sigcont
取回暂停的bash的过程.
If you need to use ctrl-c in pdb, and you are using bash,
replace the sleep 99999
by suspend
. When you quit pdb, use your terminal's menus to send signal sigcont
to the process to get back the suspended bash.
这篇关于用kill信号输入pdb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!