From 6921c62436b10cd24d32f37c743d2ad8b7f1db37 2009-03-10 19:39:05 From: Fernando Perez Date: 2009-03-10 19:39:05 Subject: [PATCH] Add tests and fixes to clearcmd extension, when using numpy. --- diff --git a/IPython/Extensions/clearcmd.py b/IPython/Extensions/clearcmd.py index 49fbd59..76cfbf7 100644 --- a/IPython/Extensions/clearcmd.py +++ b/IPython/Extensions/clearcmd.py @@ -5,43 +5,65 @@ import IPython.ipapi import gc ip = IPython.ipapi.get() - def clear_f(self,arg): """ Clear various data (e.g. stored history data) - %clear out - clear output history %clear in - clear input history + %clear out - clear output history %clear shadow_compress - Compresses shadow history (to speed up ipython) %clear shadow_nuke - permanently erase all entries in shadow history %clear dhist - clear dir history + %clear array - clear only variables that are NumPy arrays + + Examples: + + In [1]: clear in + Flushing input history + + In [2]: clear shadow_compress + Compressing shadow history + + In [3]: clear shadow_nuke + Erased all keys from shadow history + + In [4]: clear dhist + Clearing directory history """ api = self.getapi() + user_ns = self.user_ns # local lookup, heavily used + + for target in arg.split(): + if target == 'out': - print "Flushing output cache (%d entries)" % len(api.user_ns['_oh']) + print "Flushing output cache (%d entries)" % len(user_ns['_oh']) self.outputcache.flush() + elif target == 'in': print "Flushing input history" - from IPython import iplib pc = self.outputcache.prompt_count + 1 for n in range(1, pc): key = '_i'+`n` + user_ns.pop(key,None) try: - del self.user_ns[key] + del user_ns[key] except: pass # must be done in-place self.input_hist[:] = ['\n'] * pc self.input_hist_raw[:] = ['\n'] * pc + elif target == 'array': + # Support cleaning up numpy arrays try: - pylab=ip.IP.pylab - for x in self.user_ns.keys(): - if isinstance(self.user_ns[x],pylab.arraytype): - del self.user_ns[x] + from numpy import ndarray + # This must be done with items and not iteritems because we're + # going to modify the dict in-place. + for x,val in user_ns.items(): + if isinstance(val,ndarray): + del user_ns[x] except AttributeError: - print "Clear array only available in -pylab mode" - gc.collect() + print "Clear array only works if Numpy is available." elif target == 'shadow_compress': print "Compressing shadow history" @@ -51,16 +73,15 @@ def clear_f(self,arg): print "Erased all keys from shadow history " for k in ip.db.keys('shadowhist/*'): del ip.db[k] + elif target == 'dhist': print "Clearing directory history" - del ip.user_ns['_dh'][:] + del user_ns['_dh'][:] - + gc.collect() + +# Activate the extension ip.expose_magic("clear",clear_f) import ipy_completers ipy_completers.quick_completer( - '%clear','in out shadow_nuke shadow_compress dhist') - - - - + '%clear','in out shadow_nuke shadow_compress dhist')