Is there tool to turn an interactive session into a script, automatically removing errors / redundant lines?
I often find myself wanting to turn an interactive session into a saved script. Usually this means manually editing the output of ipython's %hist. So for example I would paste
n_max = 10
sines = np.sin(np.arange(n_max)) #ImportError
import numpy as np
sines = np.sin(np.arange(n_max))
cosines = np.cos(np.arange(n_max))
tans = sines / cosines
tans #Display values
arctans = np.arctan2(cosines / sines) #Invalid number of arguments
np.arctan2? #View documentation
arctans = np.arctan2(cosines, sines)
print arctans
n_max = 30 #new value of constant
sines = np.sin(np.arange(n_max))
cosines = np.cos(np.arange(n_max))
arctans = np.arctan2(cosines, sines)
n_max = 10000 #large number for profiling
sines = np.sin(np.arange(n_max))
cosines = np.cos(np.arange(n_max))
%timeit np.arctan2(cosines, sines) #timing the operation
n_max = 30
sines = np.sin(np.arange(n_max))
cosines = np.cos(np.arange(n_max))
arctans = np.arctan2(cosines, sines)
print arctans
into a text editor and manually prune it down to
import numpy as np
n_max = 30
sines = np.sin(np.arange(n_max))
cosines = np.cos(np.arange(n_max))
arctans = np.arctan2(cosines, sines)
print arctans
Removing lines that gave errors, lines that defined variables that got re-defined later, etc.
My question is: is there a tool that will automate this process - look at such an input history and try to remove obviously redundant or unsuccessful lines such that the end result of running the shortened code is the same as entering the original lines one-by-one?
Posted May 16, 2018, 9:30 PM UTC
02
I can't think of any tool that would automate this, but if you convert %hist to a single text string, then the following code might help you with the pruning:
This would get you to:
Starting from the last line, it filters any duplicate print or import/from statements, and keeps the most recent variable assignments only. You'd still have to find a way to handle any statements with errors (such as the tans = on line 2)), and it doesn't check that all variables used have already been created, but as a first pass it should help.