The following works nice to see what the interpreter does:
python -m trace --ignore-dir=$HOME/lib64:$HOME/lib:/usr -t path-to/script.py
But there are too many lines. I would like to hide the lines which happen during importing a file.
Example: I am not interested in lines like this:
saved_filter.py(9): class SavedFilter(models.Model):
saved_filter.py(10): name = models.TextField(max_length=256)
saved_filter.py(11): user = models.ForeignKey('auth.User', null=True, blank=True)
I could not find a solution in the docs: https://docs.python.org/2/library/trace.html
Update If there is a different way to get the result, for example a different python package (not trace), this would be a good solution, too.
Update 2 The tracing should be non-interactive.
Update 3
I tried the solution provided by Martin v. Löwis. It works in some cases, but not all.
file foo.py
import bar
def main():
f=bar.Foo()
f.my_func()
if __name__=='__main__':
main()
file bar.py
class Foo(object):
def my_func(self):
def inner():
print('#in inner')
return 'inner'
print('#in my_func()')
inner()
return 1
If I call foo.py, the wanted result looks similar to this:
foo.py: f=bar.Foo() foo.py: f.my_func() bar.py: print('#in my_func()') bar.py: inner() bar.py: print('#in inner') bar.py: return 'inner' bar.py: return 1
Result of trace2.py
> python tmp/trace2-orig.py --trace tmp/foo.py
--- modulename: foo, funcname: <module>
--- modulename: bar, funcname: <module>
--- modulename: bar, funcname: Foo
bar.py(1): class Foo(object): <======= Import lines
bar.py(2): def my_func(self):
--- modulename: foo, funcname: main
foo.py(4): f=bar.Foo()
foo.py(5): f.my_func()
--- modulename: bar, funcname: my_func
bar.py(3): def inner():
bar.py(6): print('#in my_func()')
#in my_func()
bar.py(7): inner()
--- modulename: bar, funcname: inner
bar.py(4): print('#in inner')
#in inner
bar.py(5): return 'inner'
bar.py(8): return 1
--- modulename: trace, funcname: _unsettrace
trace.py(80): sys.settrace(None)
Unfortunately there is still class Foo(object) which is something executed during import.
I guess the detection of code loading and executing does not cover all cases.