sangwoo-joh
sangwoo-joh

Reputation: 127

How can I embed pdb in my program? - Python

I know that pdb is an interactive system and it is very helpful. My ultimate goal is to gather all memory states after executing each command in certain function, command by command. For example, with a code snippet

 0: def foo() :
 1: if True:
 2:   x=1
 3: else:
 4:   x=2
 5: x

then the memory state of each command is

 0: empty
 1: empty
 2: x = 1
 3: x = 1
 4: (not taken)
 5: x = 1

To do this, what I'd like to do with pdb is to write a script that interact with pdb class. I know that s is a function to step forward in statements and print var(in the above case, var is x) is a function to print the value of certain variable. I can gather variables at each command. Then, I want to run a script like below:

import pdb
pdb.run('foo()')
while(not pdb.end()):
  pdb.s()
  pdb.print('x')

But I cannot find any way how to implement this functionality. Can anybody help me??

Upvotes: 0

Views: 316

Answers (1)

grundic
grundic

Reputation: 4921

Try memory_profiler:

The line-by-line memory usage mode is used much in the same way of the line_profiler: first decorate the function you would like to profile with @profile and then run the script with a special script (in this case with specific arguments to the Python interpreter).

Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

Or Heapy:

The aim of Heapy is to support debugging and optimization regarding memory related issues in Python programs.

Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
0  35144  27  2140412  26   2140412  26 str
1  38397  29  1309020  16   3449432  42 tuple
2    530   0   739856   9   4189288  50 dict (no owner)

Upvotes: 2

Related Questions