##// END OF EJS Templates
%reset now takes optional in/out/dhist/array args...
Paul Ivanov -
Show More
@@ -316,6 +316,6 b' def cd_completer(self, event):'
316 316
317 317 return [compress_user(p, tilde_expand, tilde_val) for p in found]
318 318
319 def clear_completer(self, event):
320 "A completer for %clear magic"
321 return 'in out array dhist'.split()
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 1841 from IPython.core.completer import IPCompleter
1842 1842 from IPython.core.completerlib import (module_completer,
1843 magic_run_completer, cd_completer, clear_completer)
1843 magic_run_completer, cd_completer, reset_completer)
1844 1844
1845 1845 self.Completer = IPCompleter(shell=self,
1846 1846 namespace=self.user_ns,
@@ -1860,7 +1860,7 b' class InteractiveShell(SingletonConfigurable, Magic):'
1860 1860 self.set_hook('complete_command', module_completer, str_key = 'from')
1861 1861 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1862 1862 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1863 self.set_hook('complete_command', clear_completer, str_key = '%clear')
1863 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1864 1864
1865 1865 # Only configure readline if we truly are using readline. IPython can
1866 1866 # do tab-completion over the network, in GUIs, etc, where readline
@@ -960,16 +960,31 b' Currently the magic system has the following functions:\\n"""'
960 960 print vstr[:25] + "<...>" + vstr[-25:]
961 961
962 962 def magic_reset(self, parameter_s=''):
963 """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).
964 967
965 968 Parameters
966 969 ----------
967 -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
968 984
969 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
970 References to objects may be kept. By default (without this option),
971 we do a 'hard' reset, giving you a new session and removing all
972 references to objects from the current session.
985 See Also
986 --------
987 %reset_selective
973 988
974 989 Examples
975 990 --------
@@ -986,13 +1001,20 b' Currently the magic system has the following functions:\\n"""'
986 1001 In [1]: 'a' in _ip.user_ns
987 1002 Out[1]: False
988 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
989 1011 Notes
990 1012 -----
991 1013 Calling this magic from clients that do not implement standard input,
992 1014 such as the ipython notebook interface, will reset the namespace
993 1015 without confirmation.
994 1016 """
995 opts, args = self.parse_options(parameter_s,'sf')
1017 opts, args = self.parse_options(parameter_s,'sf', mode='list')
996 1018 if 'f' in opts:
997 1019 ans = True
998 1020 else:
@@ -1009,11 +1031,54 b' Currently the magic system has the following functions:\\n"""'
1009 1031 user_ns = self.shell.user_ns
1010 1032 for i in self.magic_who_ls():
1011 1033 del(user_ns[i])
1012
1013 else: # Hard reset
1034 elif len(args) == 0: # Hard reset
1014 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 if target == 'out':
1043 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
1044 self.displayhook.flush()
1045
1046 elif target == 'in':
1047 print "Flushing input history"
1048 pc = self.displayhook.prompt_count + 1
1049 for n in range(1, pc):
1050 key = '_i'+repr(n)
1051 user_ns.pop(key,None)
1052 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
1053 hm = ip.history_manager
1054 # don't delete these, as %save and %macro depending on the length
1055 # of these lists to be preserved
1056 hm.input_hist_parsed[:] = [''] * pc
1057 hm.input_hist_raw[:] = [''] * pc
1058 # hm has internal machinery for _i,_ii,_iii, clear it out
1059 hm._i = hm._ii = hm._iii = hm._i00 = u''
1060
1061 elif target == 'array':
1062 # Support cleaning up numpy arrays
1063 try:
1064 from numpy import ndarray
1065 # This must be done with items and not iteritems because we're
1066 # going to modify the dict in-place.
1067 for x,val in user_ns.items():
1068 if isinstance(val,ndarray):
1069 del user_ns[x]
1070 except ImportError:
1071 print "reset array only works if Numpy is available."
1072
1073 elif target == 'dhist':
1074 print "Flushing directory history"
1075 del user_ns['_dh'][:]
1015 1076
1077 else:
1078 print "Don't know how to reset ",
1079 print target + ", please run `%reset?` for details"
1016 1080
1081 gc.collect()
1017 1082
1018 1083 def magic_reset_selective(self, parameter_s=''):
1019 1084 """Resets the namespace by removing names defined by the user.
@@ -1027,6 +1092,10 b' Currently the magic system has the following functions:\\n"""'
1027 1092 Options
1028 1093 -f : force reset without asking for confirmation.
1029 1094
1095 See Also
1096 --------
1097 %reset
1098
1030 1099 Examples
1031 1100 --------
1032 1101
@@ -3698,60 +3767,4 b' Defaulting color scheme to \'NoColor\'"""'
3698 3767 except Exception as e:
3699 3768 error(e)
3700 3769
3701 def magic_clear(self, s):
3702 """Clear various data (e.g. stored history data)
3703
3704 %clear in - clear input history
3705 %clear out - clear output history
3706 %clear dhist - clear dir history
3707 %clear array - clear only variables that are NumPy arrays
3708
3709 Examples
3710 --------
3711 ::
3712
3713 In [1]: clear in
3714 Flushing input history
3715
3716 In [2]: clear dhist
3717 Clearing directory history
3718 """
3719 ip = self.shell
3720 user_ns = self.user_ns # local lookup, heavily used
3721
3722 for target in s.split():
3723 if target == 'out':
3724 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
3725 self.displayhook.flush()
3726
3727 elif target == 'in':
3728 print "Flushing input history"
3729 pc = self.displayhook.prompt_count + 1
3730 for n in range(1, pc):
3731 key = '_i'+repr(n)
3732 user_ns.pop(key,None)
3733 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
3734 # don't delete these, as %save and %macro depending on the length
3735 # of these lists to be preserved
3736 self.history_manager.input_hist_parsed[:] = [''] * pc
3737 self.history_manager.input_hist_raw[:] = [''] * pc
3738
3739 elif target == 'array':
3740 # Support cleaning up numpy arrays
3741 try:
3742 from numpy import ndarray
3743 # This must be done with items and not iteritems because we're
3744 # going to modify the dict in-place.
3745 for x,val in user_ns.items():
3746 if isinstance(val,ndarray):
3747 del user_ns[x]
3748 except ImportError:
3749 print "Clear array only works if Numpy is available."
3750
3751 elif target == 'dhist':
3752 print "Clearing directory history"
3753 del user_ns['_dh'][:]
3754
3755 gc.collect()
3756
3757 3770 # end Magic
@@ -185,44 +185,44 b' def test_macro_run():'
185 185
186 186
187 187 @dec.skipif_not_numpy
188 def test_numpy_clear_array_undec():
189 "Test '%clear array' functionality"
188 def test_numpy_reset_array_undec():
189 "Test '%reset array' functionality"
190 190 _ip.ex('import numpy as np')
191 191 _ip.ex('a = np.empty(2)')
192 192 yield (nt.assert_true, 'a' in _ip.user_ns)
193 _ip.magic('clear array')
193 _ip.magic('reset -f array')
194 194 yield (nt.assert_false, 'a' in _ip.user_ns)
195 195
196 def test_clear():
197 "Test '%clear' magic provided by IPython.extensions.clearcmd"
196 def test_reset_args():
197 "Test '%reset' magic with args which used to be extensions.clearcmd"
198 198 _ip = get_ipython()
199 199 _ip.run_cell("parrot = 'dead'", store_history=True)
200 # test '%clear out', make an Out prompt
200 # test '%reset -f out', make an Out prompt
201 201 _ip.run_cell("parrot", store_history=True)
202 202 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
203 _ip.magic('clear out')
203 _ip.magic('reset -f out')
204 204 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
205 205 nt.assert_true(len(_ip.user_ns['Out']) == 0)
206 206
207 # test '%clear in'
207 # test '%reset -f in'
208 208 _ip.run_cell("parrot", store_history=True)
209 209 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
210 _ip.magic('%clear in')
210 _ip.magic('%reset -f in')
211 211 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
212 212 nt.assert_true(len(set(_ip.user_ns['In'])) == 1)
213 213
214 # test '%clear dhist'
214 # test '%reset -f dhist'
215 215 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
216 216 _ip.magic('cd')
217 217 _ip.magic('cd -')
218 218 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
219 _ip.magic('clear dhist')
219 _ip.magic('reset -f dhist')
220 220 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
221 221 _ip.run_cell("_dh = [d for d in tmp]") #restore
222 222
223 223 # test that In length is preserved for %macro
224 224 _ip.run_cell("print 'foo'")
225 _ip.run_cell("clear in")
225 _ip.run_cell("reset -f in")
226 226 nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1)
227 227
228 228 def test_time():
General Comments 0
You need to be logged in to leave comments. Login now