简体   繁体   English

如何检查正在执行的Python脚本的哪一行?

[英]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.

相关问题 这行是如何在python中执行的? - How is this line being executed in python? 如何在执行时打印 python 脚本的每一行(包括控制台)? - How print every line of a python script as its being executed (including the console)? 如果将目录路径作为命令行参数传递给 python,则执行哪个 python 脚本? - Which python script is executed if directory path is passed as command line argument to python? 确定Python脚本是在本地执行还是作为CGI执行 - Determine if Python script is being executed locally or as CGI 过时的脚本正在根据Python跟踪执行 - the outdated script is being executed according to Python traceback 如何捕获从另一个python脚本执行的python脚本的打印件? - How to capture the prints of a python script being executed from another python script? 杀死python脚本并查看执行的最后一行 - kill python script and see last line executed 如何使用命令执行python脚本 - How to executed python script with command 如何检查函数中执行了哪个return语句? - How to check which return statement was executed in a function? 如何让 Perl 和 Python 打印正在执行的程序的每一行? - How can I make Perl and Python print each line of the program being executed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM