dbliss dbliss - 1 year ago 69
Python Question

"Return" in the middle of a script

I'm debugging a script and temporarily would like to stop the script in the middle and plot some of the values for different variables. Is there no way in Python to "return" from a script? I don't want to exit Python entirely. What I want, in essence, is to freeze the script at a particular point. It would be so nice if there were a single command I could insert -- e.g.,

-- that would do this -- which I would then remove when finished with the debugging.

Here are a couple of ways to achieve this sort of thing that I consider inelegant in the context of my work at this moment:

(1) Put the script's code in a function, and return the needed variables midway through this function.

(2) Comment out all the code after the point at which I want to stop.

(3) Save all the desired variables to disk, and use a call to
to exit Python entirely.

Is there no better option?

Theoretical question

Why would the designers of Python have decided not to allow
statements in scripts? Is there a logic to that?

Answer Source

You can use pdb to plot something (at least, it works just fine for me on OS-X):

from matplotlib import pyplot as plt
import numpy as np

array_x = np.arange(10)
array_y = np.arange(10)

import pdb; pdb.set_trace()

print (array_x, array_y)

And my console output (including a typo):

$ python ~/sandbox/test.py
> /Users/mgilson/sandbox/test.py(9)<module>()
-> print (array_x, array_y)
(Pdb) plt.ion()
(Pdb) plt.plit(array_x, array_y)
*** AttributeError: 'module' object has no attribute 'plit'
(Pdb) plt.plot(array_x, array_y)
[<matplotlib.lines.Line2D object at 0x112120610>]
(Pdb) c
(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))

I used plt.ion(), but you could probably use plt.show() just as easily (after you've defined your plot).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download