问题
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