Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to save current variables while debugging?

I have a general debugging question in python (pycharm IDE if it matters)

Lets say I have code which is made up of 2 blocks:

Code block 1 (takes very long to run)
Code block 2 (where I want to debug)

Is there a way to save the current variables at the end of running code block 1, so that I can "rewind" back to those variables states and debug from there, without having the re-run the entire script to recompute those variables?

like image 239
Lee88 Avatar asked Jan 02 '17 22:01

Lee88


People also ask

How do I save a variable in Python?

We can use concatenation within the write() function to save a variable to a file in Python. Here, we will also use the str() or the repr() function to convert the variable to a string and then store it in the file. The following code uses string concatenation to save a variable to a file in Python.

How do I continue debugging in Python?

For example c = 1 will trigger the continue command. To force the debugger to execute Python code, prefix the line with ! , e.g. ! c = 1 . Pressing the Enter key at the (Pdb) prompt will execute the previous command again.

How do I change value while debugging?

You can change variable values during debugging of script and keyword tests. To do this, pause the script or test at the desired point and then use one of the ways described below. For JavaScript users: Currently, you cannot modify local variables during debugging.

Is Python slower in debug mode?

Unfortunately, debugger speed has some runtime limitations, which can't be easily fixed. If your code does some high performance computations, Debugger will be at least 3 times slower than usual Run.


1 Answers

I am unaware of a general solution to this problem. But an application specific solution can be constructed using various methods for serializing objects, but I would suggest pickle for this problem.

Like so much else, there is a small example already on SO.

like image 196
Stephen Rauch Avatar answered Oct 14 '22 17:10

Stephen Rauch