Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

pdb - Tracing the execution of a Python program line/statement by line programmatically

What would be the easiest way to execute a Python script and, for each executed statement, pass the line number or the line itself to a callback function? For example

A piece of code to be executed

for i in range(5):
    z = i**2

and a callback

def callback(line):
   print line

The output would be:

for i in range(5):
    z = i**2
for i in range(5):
    z = i**2
for i in range(5):
    z = i**2
...
etc

Another way of stating this is that I want to know the piece of code that would be next to execute if I were running the script stepping through a debugger.. I've seen this question about tracing but I'm interested in doing more than tracing the number of times executed in the callback function.

A debugger is going to be helpful, but only if I can run it non-interactive mode with the ability to call back to the python code

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Look at the sys.settrace function. This allows you to specify a tracing function which is executed for every line of code. It was, I think, specifically implemented to create pdb so it's at the right level of abstraction you seem to want. Implementing what you want will not be trivial but I think it's the best place to start.

For an production program that uses this, look at coverage.py.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...