##// END OF EJS Templates
Merge pull request #1309 from ivanov/inoculate-clear-magic...
Fernando Perez -
r5979:12b8a648 merge
parent child Browse files
Show More
@@ -181,7 +181,6 b' def quick_completer(cmd, completions):'
181
181
182 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
182 get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
183
183
184
185 def module_completion(line):
184 def module_completion(line):
186 """
185 """
187 Returns a list containing the completion possibilities for an import line.
186 Returns a list containing the completion possibilities for an import line.
@@ -316,3 +315,7 b' def cd_completer(self, event):'
316 raise TryNext
315 raise TryNext
317
316
318 return [compress_user(p, tilde_expand, tilde_val) for p in found]
317 return [compress_user(p, tilde_expand, tilde_val) for p in found]
318
319 def reset_completer(self, event):
320 "A completer for %reset magic"
321 return '-f -s in out array dhist'.split()
@@ -1840,7 +1840,7 b' class InteractiveShell(SingletonConfigurable, Magic):'
1840 """
1840 """
1841 from IPython.core.completer import IPCompleter
1841 from IPython.core.completer import IPCompleter
1842 from IPython.core.completerlib import (module_completer,
1842 from IPython.core.completerlib import (module_completer,
1843 magic_run_completer, cd_completer)
1843 magic_run_completer, cd_completer, reset_completer)
1844
1844
1845 self.Completer = IPCompleter(shell=self,
1845 self.Completer = IPCompleter(shell=self,
1846 namespace=self.user_ns,
1846 namespace=self.user_ns,
@@ -1860,6 +1860,7 b' class InteractiveShell(SingletonConfigurable, Magic):'
1860 self.set_hook('complete_command', module_completer, str_key = 'from')
1860 self.set_hook('complete_command', module_completer, str_key = 'from')
1861 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1861 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1862 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1862 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1863 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1863
1864
1864 # Only configure readline if we truly are using readline. IPython can
1865 # Only configure readline if we truly are using readline. IPython can
1865 # do tab-completion over the network, in GUIs, etc, where readline
1866 # do tab-completion over the network, in GUIs, etc, where readline
@@ -25,6 +25,7 b' import sys'
25 import shutil
25 import shutil
26 import re
26 import re
27 import time
27 import time
28 import gc
28 from StringIO import StringIO
29 from StringIO import StringIO
29 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
30 from pprint import pformat
31 from pprint import pformat
@@ -959,16 +960,31 b' Currently the magic system has the following functions:\\n"""'
959 print vstr[:25] + "<...>" + vstr[-25:]
960 print vstr[:25] + "<...>" + vstr[-25:]
960
961
961 def magic_reset(self, parameter_s=''):
962 def magic_reset(self, parameter_s=''):
962 """Resets the namespace by removing all names defined by the user.
963 """Resets the namespace by removing all names defined by the user, if
964 called without arguments, or by removing some types of objects, such
965 as everything currently in IPython's In[] and Out[] containers (see
966 the parameters for details).
963
967
964 Parameters
968 Parameters
965 ----------
969 ----------
966 -f : force reset without asking for confirmation.
970 -f : force reset without asking for confirmation.
971
972 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
973 References to objects may be kept. By default (without this option),
974 we do a 'hard' reset, giving you a new session and removing all
975 references to objects from the current session.
976
977 in : reset input history
978
979 out : reset output history
980
981 dhist : reset directory history
982
983 array : reset only variables that are NumPy arrays
967
984
968 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
985 See Also
969 References to objects may be kept. By default (without this option),
986 --------
970 we do a 'hard' reset, giving you a new session and removing all
987 %reset_selective
971 references to objects from the current session.
972
988
973 Examples
989 Examples
974 --------
990 --------
@@ -985,13 +1001,20 b' Currently the magic system has the following functions:\\n"""'
985 In [1]: 'a' in _ip.user_ns
1001 In [1]: 'a' in _ip.user_ns
986 Out[1]: False
1002 Out[1]: False
987
1003
1004 In [2]: %reset -f in
1005 Flushing input history
1006
1007 In [3]: %reset -f dhist in
1008 Flushing directory history
1009 Flushing input history
1010
988 Notes
1011 Notes
989 -----
1012 -----
990 Calling this magic from clients that do not implement standard input,
1013 Calling this magic from clients that do not implement standard input,
991 such as the ipython notebook interface, will reset the namespace
1014 such as the ipython notebook interface, will reset the namespace
992 without confirmation.
1015 without confirmation.
993 """
1016 """
994 opts, args = self.parse_options(parameter_s,'sf')
1017 opts, args = self.parse_options(parameter_s,'sf', mode='list')
995 if 'f' in opts:
1018 if 'f' in opts:
996 ans = True
1019 ans = True
997 else:
1020 else:
@@ -1008,11 +1031,55 b' Currently the magic system has the following functions:\\n"""'
1008 user_ns = self.shell.user_ns
1031 user_ns = self.shell.user_ns
1009 for i in self.magic_who_ls():
1032 for i in self.magic_who_ls():
1010 del(user_ns[i])
1033 del(user_ns[i])
1011
1034 elif len(args) == 0: # Hard reset
1012 else: # Hard reset
1013 self.shell.reset(new_session = False)
1035 self.shell.reset(new_session = False)
1036
1037 # reset in/out/dhist/array: previously extensinions/clearcmd.py
1038 ip = self.shell
1039 user_ns = self.user_ns # local lookup, heavily used
1040
1041 for target in args:
1042 target = target.lower() # make matches case insensitive
1043 if target == 'out':
1044 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
1045 self.displayhook.flush()
1046
1047 elif target == 'in':
1048 print "Flushing input history"
1049 pc = self.displayhook.prompt_count + 1
1050 for n in range(1, pc):
1051 key = '_i'+repr(n)
1052 user_ns.pop(key,None)
1053 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
1054 hm = ip.history_manager
1055 # don't delete these, as %save and %macro depending on the length
1056 # of these lists to be preserved
1057 hm.input_hist_parsed[:] = [''] * pc
1058 hm.input_hist_raw[:] = [''] * pc
1059 # hm has internal machinery for _i,_ii,_iii, clear it out
1060 hm._i = hm._ii = hm._iii = hm._i00 = u''
1061
1062 elif target == 'array':
1063 # Support cleaning up numpy arrays
1064 try:
1065 from numpy import ndarray
1066 # This must be done with items and not iteritems because we're
1067 # going to modify the dict in-place.
1068 for x,val in user_ns.items():
1069 if isinstance(val,ndarray):
1070 del user_ns[x]
1071 except ImportError:
1072 print "reset array only works if Numpy is available."
1073
1074 elif target == 'dhist':
1075 print "Flushing directory history"
1076 del user_ns['_dh'][:]
1014
1077
1078 else:
1079 print "Don't know how to reset ",
1080 print target + ", please run `%reset?` for details"
1015
1081
1082 gc.collect()
1016
1083
1017 def magic_reset_selective(self, parameter_s=''):
1084 def magic_reset_selective(self, parameter_s=''):
1018 """Resets the namespace by removing names defined by the user.
1085 """Resets the namespace by removing names defined by the user.
@@ -1026,6 +1093,10 b' Currently the magic system has the following functions:\\n"""'
1026 Options
1093 Options
1027 -f : force reset without asking for confirmation.
1094 -f : force reset without asking for confirmation.
1028
1095
1096 See Also
1097 --------
1098 %reset
1099
1029 Examples
1100 Examples
1030 --------
1101 --------
1031
1102
@@ -183,20 +183,50 b' def test_macro_run():'
183 with tt.AssertPrints("13"):
183 with tt.AssertPrints("13"):
184 ip.run_cell("test")
184 ip.run_cell("test")
185
185
186
187 # XXX failing for now, until we get clearcmd out of quarantine. But we should
188 # fix this and revert the skip to happen only if numpy is not around.
189 #@dec.skipif_not_numpy
190 @dec.skip_known_failure
191 def test_numpy_clear_array_undec():
192 from IPython.extensions import clearcmd
193
186
187 @dec.skipif_not_numpy
188 def test_numpy_reset_array_undec():
189 "Test '%reset array' functionality"
194 _ip.ex('import numpy as np')
190 _ip.ex('import numpy as np')
195 _ip.ex('a = np.empty(2)')
191 _ip.ex('a = np.empty(2)')
196 yield (nt.assert_true, 'a' in _ip.user_ns)
192 yield (nt.assert_true, 'a' in _ip.user_ns)
197 _ip.magic('clear array')
193 _ip.magic('reset -f array')
198 yield (nt.assert_false, 'a' in _ip.user_ns)
194 yield (nt.assert_false, 'a' in _ip.user_ns)
199
195
196 def test_reset_out():
197 "Test '%reset out' magic"
198 _ip.run_cell("parrot = 'dead'", store_history=True)
199 # test '%reset -f out', make an Out prompt
200 _ip.run_cell("parrot", store_history=True)
201 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
202 _ip.magic('reset -f out')
203 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
204 nt.assert_true(len(_ip.user_ns['Out']) == 0)
205
206 def test_reset_in():
207 "Test '%reset in' magic"
208 # test '%reset -f in'
209 _ip.run_cell("parrot", store_history=True)
210 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
211 _ip.magic('%reset -f in')
212 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
213 nt.assert_true(len(set(_ip.user_ns['In'])) == 1)
214
215 def test_reset_dhist():
216 "Test '%reset dhist' magic"
217 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
218 _ip.magic('cd ' + os.path.dirname(nt.__file__))
219 _ip.magic('cd -')
220 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
221 _ip.magic('reset -f dhist')
222 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
223 _ip.run_cell("_dh = [d for d in tmp]") #restore
224
225 def test_reset_in_length():
226 "Test that '%reset in' preserves In[] length"
227 _ip.run_cell("print 'foo'")
228 _ip.run_cell("reset -f in")
229 nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1)
200
230
201 def test_time():
231 def test_time():
202 _ip.magic('time None')
232 _ip.magic('time None')
@@ -116,8 +116,6 b" def jot_obj(self, obj, name, comment=''):"
116
116
117 uname = 'jot/'+name+suffix
117 uname = 'jot/'+name+suffix
118
118
119 # which one works better?
120 #all = ip.shadowhist.all()
121 all = ip.shell.history_manager.input_hist_parsed
119 all = ip.shell.history_manager.input_hist_parsed
122
120
123 # We may actually want to make snapshot of files that are run-ned.
121 # We may actually want to make snapshot of files that are run-ned.
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now