简体   繁体   English

在python中如何看一个程序一行一行的执行?

[英]How do you see the execution of a programme line by line in python?

Is there a way to see the details of the execution of a python file?有没有办法查看python文件的执行细节? I know that you can use logging, but obviously it would be unreasonable to set up the number of logs needed to see every line that's eventually executed.我知道您可以使用日志记录,但显然设置查看最终执行的每一行所需的日志数量是不合理的。 The python programme, of course, goes through the programme execution on a line by line basis, so to me, there must be a way to see the details of at the very least what line is being executed, and possibly where from.当然,python 程序是逐行执行程序的,所以对我来说,必须有一种方法至少可以查看正在执行的行的详细信息,以及可能从哪里执行。

I imagine that something like this would be possible:我想这样的事情是可能的:

lineno (27) 'test_file'
lineno (54) 'test_file'
lineno (12) 'test_file'
lineno (13) 'test_file'

What you want is a debugger .你想要的是一个调试器

There are several options, such as:有多种选择,例如:

Debuggers are probably the better answer but you might also just use the trace module ( https://docs.python.org/3.6/library/trace.html ):调试器可能是更好的答案,但您也可能只使用跟踪模块( https://docs.python.org/3.6/library/trace.html ):

python -m trace -t yourscript.py

will display all lines your program is executing.将显示您的程序正在执行的所有行。 If you just want to see how python steps through one script you could do.如果您只是想看看 Python 如何逐步执行一个脚本,您可以这样做。

python -m trace -t yourscript.py | grep yourscript.py

Please check following example and the output.请检查以下示例和输出。 Contents of tst.py : tst.py内容:

sum = 0
for i in range(4):
    sum += i
print(sum)

And now the output you get:现在你得到的输出:

$ python -m trace -t tst.py
 --- modulename: tst, funcname: <module>
tst.py(1): sum = 0
tst.py(2): for i in range(4):
tst.py(3):     sum += i
tst.py(2): for i in range(4):
tst.py(3):     sum += i
tst.py(2): for i in range(4):
tst.py(3):     sum += i
tst.py(2): for i in range(4):
tst.py(3):     sum += i
tst.py(2): for i in range(4):
tst.py(4): print(sum)
6
 --- modulename: trace, funcname: _unsettrace
trace.py(77):         sys.settrace(None)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM