[英]How to check which line of a Python script is being executed?
I've got a Python script which is running on a Linux server for hours, crunching some numbers for me. 我有一个在Linux服务器上运行了几个小时的Python脚本,为我计算了一些数字。 I'd like to check its progress, so I'd like to see what line is being executed right now.
我想检查它的进度,所以我想看看现在正在执行哪一行。 If that was a C or C++ program then I would just attach to the process with
gdb -p <pid>
and examine the stacktrace with where
. 如果那是C或C ++程序,那么我将使用
gdb -p <pid>
附加到进程,并使用where
检查stacktrace。 Of course, I can do the same with the Python interpreter process, but I can't see the Python script's line in the stacktrace. 当然,我可以对Python解释程序执行相同的操作,但是在stacktrace中看不到Python脚本的行。
So, how can I find out which line of the Python script is being executed currently? 那么,如何找出当前正在执行的Python脚本的哪一行呢?
You can add a signal handler to the Python script that sends this information to the terminal, or to a file, then hit ^C in the terminal to send the signal to the process. 您可以在Python脚本中添加一个信号处理程序,以将该信息发送到终端或文件,然后在终端中按^ C将该信号发送到进程。
import signal
def print_linenum(signum, frame):
print "Currently at line", frame.f_lineno
signal.signal(signal.SIGINT, print_linenum)
You could also use some other signal and use the kill
command to send the signal, if you need ^C to be able to interrupt the script, or set a signal.alarm()
to print the information periodically, eg once a second. 如果需要^ C才能中断脚本,也可以使用其他信号并使用
kill
命令发送该信号,或者设置signal.alarm()
定期(例如每秒一次signal.alarm()
打印信息。
You could print out other things from the stack frame if you like; 如果愿意,可以从堆栈框架中打印出其他内容。 there's a lot there.
那里很多。 See the attributes of
frame
objects in this table . 请参阅此表中
frame
对象的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.