Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print commands in Python?

I'm not in the programming area but I recently got interested in Python. I was writing some functions but for debugging I need to see what commands are running. For instance:

def foo():
    for i in xrange(0,5):
        a = 1 + i

Is it possible to make the interpreter output

>>> for i in xrange(0,5)
>>> a = 1 + 0
>>> a = 1 + 1
>>> a = 1 + 2
>>> a = 1 + 3
>>> a = 1 + 4

For

>>> foo()

Or at least write to a file what is happening? I did some scripting in the past and I remember that this was possible in DOS, using @ECHO ON or something. I did some reading and I feel like it's related to stdin and stdout in Python so I tried

import sys
def foo():
    for i in xrange(0,5):
        a = 1 + i
        sys.stdin.flush()
        sys.stdout.flush()

But I get nothing... I also tried

import sys
# foo()
sys.stdin.read()
sys.stdout.read()

and https://stackoverflow.com/a/3289051/2032568, but it just hangs. Sorry if this is not the right place for beginners. I couldn't find anything that answers my question.

like image 855
user2280382 Avatar asked Jun 18 '26 15:06

user2280382


1 Answers

Have a look at the trace-module

python -m trace --count -C . somefile.py

output is placed in currebt directory:

$ cat somefile.trace
    1: def foo():
    6:     for i in xrange(5):
    5:         a = 1 + i

    1: foo()

-c, --count Produce a set of annotated listing files upon program completion that shows how many times each statement was executed

If using the -t option you get this:

$ python -m trace --count -t tr.py 
 --- modulename: tr, funcname: <module>
tr.py(1): def foo():
tr.py(5): foo()
 --- modulename: tr, funcname: foo
tr.py(2):     for i in xrange(5):
tr.py(3):         a = 1 + i
tr.py(2):     for i in xrange(5):
tr.py(3):         a = 1 + i
tr.py(2):     for i in xrange(5):
tr.py(3):         a = 1 + i
tr.py(2):     for i in xrange(5):
tr.py(3):         a = 1 + i
tr.py(2):     for i in xrange(5):
tr.py(3):         a = 1 + i
tr.py(2):     for i in xrange(5):
like image 158
Fredrik Pihl Avatar answered Jun 21 '26 05:06

Fredrik Pihl