Can Python print out the line by line flow (or order) of a run?

烈酒焚心 提交于 2021-02-10 18:32:45

问题


I have a Python assignment where I need to describe the order in which Python ran the program by identifying line numbers. This is to help us understand the try/except and errors.

I'm pretty sure I've achieved this through inspection, but I wanted to know if Python has the ability to print out the flow by line numbers so I may check my work. If Python does not have this built in, is there a way in which I could do this?

I am working with Python 2.7.


回答1:


Try the trace module:

Example:

test.py:

def main():
    print("Hello, world")

if __name__ == '__main__': 
    main()

Then on the command line:

$ python -m trace --trace test.py 
 --- modulename: test, funcname: <module>
test.py(1): def main():
test.py(4): if __name__ == '__main__': 
test.py(5):     main()
 --- modulename: test, funcname: main
test.py(2):     print("Hello, world")
Hello, world
 --- modulename: trace, funcname: _unsettrace
trace.py(80):         sys.settrace(None)

It has a handful of other options that might be useful as well, such as --listfuncs.




回答2:


You can use the trace module in the python standard library.



来源:https://stackoverflow.com/questions/19988798/can-python-print-out-the-line-by-line-flow-or-order-of-a-run

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!