Saving your work from the python console
One of those things I always wanted to write about, and never found enough time to do it ;D.
One of the things I really like about Python is the python interpreter, usually called python shell or python console too.
It is a very useful feature of the programming language, because (as with any other shell like bash, tcsh or ksh) you can execute any source code in it, checking for results. I use it a lot for debugging/testing purposes (as you can even import modules, methods, etc).
Ok, now imagine you are testing a piece of code, or perhaps just writting some lines to get some information from, for example, data behind some django models. The actual code could be something like:
>>> import socialize.models as sclzmodels
>>> import socialize.utils as sclzutils
>>> sclzmodels.Person.objects.all().count()
>>> typeA = []
>>> typeB = []
>>> typeC = []
>>> for i in sclzmodels.Person.objects.all():
... real_i = sclzutils.get_object_real_class_from_hierarchy(i, sclzmodels.Person)
... if real_i.__class__.__name__ == 'TypeA':
... typeA.append(real_i)
... elif real_i.__class__.__name__ == 'TypeB':
... typeB.append(real_i)
... else:
... typeC.append(real_i)
Do not pay too much attention on the code, as it is only an example. Basically it will filter a list (really a queryset) of objects and put them into three separate lists depending on some checks.
This is a piece of code really useful for me, that I could use quite often to get some valuable information. So, it could be very nice to put it in a script, just to execute it later without having to re-write those lines every time.
Now comes the handy trick.
As I've executed such code within the python shell, it is already in a buffer that I can easily export into a file, without having to copy/paste anything. The only thing I need to do is, within the same python shell:
>>> import readline
>>> readline.write_history_file('/path/to/where/I/want/to/save/history.txt')
After that you will have a file /path/to/where/I/want/to/save/history.txt that will contain the same code you executed in the python shell (without the >>> and ... promtps):
import socialize.models as sclzmodels
import socialize.utils as sclzutils
sclzmodels.Person.objects.all().count()
typeA = []
typeB = []
typeC = []
for i in sclzmodels.Person.objects.all():
real_i = sclzutils.get_object_real_class_from_hierarchy(i, sclzmodels.Person)
if real_i.__class__.__name__ == 'TypeA':
typeA.append(real_i)
elif real_i.__class__.__name__ == 'TypeB':
typeB.append(real_i)
else:
typeC.append(real_i)
Nice, isn't it?