##// END OF EJS Templates
%clear magic now fully restored...
Paul Ivanov -
Show More
@@ -1,385 +1,385 b''
1 """Tests for various magic functions.
1 """Tests for various magic functions.
2
2
3 Needs to be run by nose (to make ipython session available).
3 Needs to be run by nose (to make ipython session available).
4 """
4 """
5 from __future__ import absolute_import
5 from __future__ import absolute_import
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Imports
8 # Imports
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 import os
11 import os
12
12
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 from IPython.testing import decorators as dec
15 from IPython.testing import decorators as dec
16 from IPython.testing import tools as tt
16 from IPython.testing import tools as tt
17 from IPython.utils import py3compat
17 from IPython.utils import py3compat
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Test functions begin
20 # Test functions begin
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 def test_rehashx():
23 def test_rehashx():
24 # clear up everything
24 # clear up everything
25 _ip = get_ipython()
25 _ip = get_ipython()
26 _ip.alias_manager.alias_table.clear()
26 _ip.alias_manager.alias_table.clear()
27 del _ip.db['syscmdlist']
27 del _ip.db['syscmdlist']
28
28
29 _ip.magic('rehashx')
29 _ip.magic('rehashx')
30 # Practically ALL ipython development systems will have more than 10 aliases
30 # Practically ALL ipython development systems will have more than 10 aliases
31
31
32 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
32 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
33 for key, val in _ip.alias_manager.alias_table.iteritems():
33 for key, val in _ip.alias_manager.alias_table.iteritems():
34 # we must strip dots from alias names
34 # we must strip dots from alias names
35 nt.assert_true('.' not in key)
35 nt.assert_true('.' not in key)
36
36
37 # rehashx must fill up syscmdlist
37 # rehashx must fill up syscmdlist
38 scoms = _ip.db['syscmdlist']
38 scoms = _ip.db['syscmdlist']
39 yield (nt.assert_true, len(scoms) > 10)
39 yield (nt.assert_true, len(scoms) > 10)
40
40
41
41
42 def test_magic_parse_options():
42 def test_magic_parse_options():
43 """Test that we don't mangle paths when parsing magic options."""
43 """Test that we don't mangle paths when parsing magic options."""
44 ip = get_ipython()
44 ip = get_ipython()
45 path = 'c:\\x'
45 path = 'c:\\x'
46 opts = ip.parse_options('-f %s' % path,'f:')[0]
46 opts = ip.parse_options('-f %s' % path,'f:')[0]
47 # argv splitting is os-dependent
47 # argv splitting is os-dependent
48 if os.name == 'posix':
48 if os.name == 'posix':
49 expected = 'c:x'
49 expected = 'c:x'
50 else:
50 else:
51 expected = path
51 expected = path
52 nt.assert_equals(opts['f'], expected)
52 nt.assert_equals(opts['f'], expected)
53
53
54
54
55 @dec.skip_without('sqlite3')
55 @dec.skip_without('sqlite3')
56 def doctest_hist_f():
56 def doctest_hist_f():
57 """Test %hist -f with temporary filename.
57 """Test %hist -f with temporary filename.
58
58
59 In [9]: import tempfile
59 In [9]: import tempfile
60
60
61 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
61 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
62
62
63 In [11]: %hist -nl -f $tfile 3
63 In [11]: %hist -nl -f $tfile 3
64
64
65 In [13]: import os; os.unlink(tfile)
65 In [13]: import os; os.unlink(tfile)
66 """
66 """
67
67
68
68
69 @dec.skip_without('sqlite3')
69 @dec.skip_without('sqlite3')
70 def doctest_hist_r():
70 def doctest_hist_r():
71 """Test %hist -r
71 """Test %hist -r
72
72
73 XXX - This test is not recording the output correctly. For some reason, in
73 XXX - This test is not recording the output correctly. For some reason, in
74 testing mode the raw history isn't getting populated. No idea why.
74 testing mode the raw history isn't getting populated. No idea why.
75 Disabling the output checking for now, though at least we do run it.
75 Disabling the output checking for now, though at least we do run it.
76
76
77 In [1]: 'hist' in _ip.lsmagic()
77 In [1]: 'hist' in _ip.lsmagic()
78 Out[1]: True
78 Out[1]: True
79
79
80 In [2]: x=1
80 In [2]: x=1
81
81
82 In [3]: %hist -rl 2
82 In [3]: %hist -rl 2
83 x=1 # random
83 x=1 # random
84 %hist -r 2
84 %hist -r 2
85 """
85 """
86
86
87
87
88 @dec.skip_without('sqlite3')
88 @dec.skip_without('sqlite3')
89 def doctest_hist_op():
89 def doctest_hist_op():
90 """Test %hist -op
90 """Test %hist -op
91
91
92 In [1]: class b(float):
92 In [1]: class b(float):
93 ...: pass
93 ...: pass
94 ...:
94 ...:
95
95
96 In [2]: class s(object):
96 In [2]: class s(object):
97 ...: def __str__(self):
97 ...: def __str__(self):
98 ...: return 's'
98 ...: return 's'
99 ...:
99 ...:
100
100
101 In [3]:
101 In [3]:
102
102
103 In [4]: class r(b):
103 In [4]: class r(b):
104 ...: def __repr__(self):
104 ...: def __repr__(self):
105 ...: return 'r'
105 ...: return 'r'
106 ...:
106 ...:
107
107
108 In [5]: class sr(s,r): pass
108 In [5]: class sr(s,r): pass
109 ...:
109 ...:
110
110
111 In [6]:
111 In [6]:
112
112
113 In [7]: bb=b()
113 In [7]: bb=b()
114
114
115 In [8]: ss=s()
115 In [8]: ss=s()
116
116
117 In [9]: rr=r()
117 In [9]: rr=r()
118
118
119 In [10]: ssrr=sr()
119 In [10]: ssrr=sr()
120
120
121 In [11]: 4.5
121 In [11]: 4.5
122 Out[11]: 4.5
122 Out[11]: 4.5
123
123
124 In [12]: str(ss)
124 In [12]: str(ss)
125 Out[12]: 's'
125 Out[12]: 's'
126
126
127 In [13]:
127 In [13]:
128
128
129 In [14]: %hist -op
129 In [14]: %hist -op
130 >>> class b:
130 >>> class b:
131 ... pass
131 ... pass
132 ...
132 ...
133 >>> class s(b):
133 >>> class s(b):
134 ... def __str__(self):
134 ... def __str__(self):
135 ... return 's'
135 ... return 's'
136 ...
136 ...
137 >>>
137 >>>
138 >>> class r(b):
138 >>> class r(b):
139 ... def __repr__(self):
139 ... def __repr__(self):
140 ... return 'r'
140 ... return 'r'
141 ...
141 ...
142 >>> class sr(s,r): pass
142 >>> class sr(s,r): pass
143 >>>
143 >>>
144 >>> bb=b()
144 >>> bb=b()
145 >>> ss=s()
145 >>> ss=s()
146 >>> rr=r()
146 >>> rr=r()
147 >>> ssrr=sr()
147 >>> ssrr=sr()
148 >>> 4.5
148 >>> 4.5
149 4.5
149 4.5
150 >>> str(ss)
150 >>> str(ss)
151 's'
151 's'
152 >>>
152 >>>
153 """
153 """
154
154
155
155
156 @dec.skip_without('sqlite3')
156 @dec.skip_without('sqlite3')
157 def test_macro():
157 def test_macro():
158 ip = get_ipython()
158 ip = get_ipython()
159 ip.history_manager.reset() # Clear any existing history.
159 ip.history_manager.reset() # Clear any existing history.
160 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
160 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
161 for i, cmd in enumerate(cmds, start=1):
161 for i, cmd in enumerate(cmds, start=1):
162 ip.history_manager.store_inputs(i, cmd)
162 ip.history_manager.store_inputs(i, cmd)
163 ip.magic("macro test 1-3")
163 ip.magic("macro test 1-3")
164 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
164 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
165
165
166 # List macros.
166 # List macros.
167 assert "test" in ip.magic("macro")
167 assert "test" in ip.magic("macro")
168
168
169
169
170 @dec.skip_without('sqlite3')
170 @dec.skip_without('sqlite3')
171 def test_macro_run():
171 def test_macro_run():
172 """Test that we can run a multi-line macro successfully."""
172 """Test that we can run a multi-line macro successfully."""
173 ip = get_ipython()
173 ip = get_ipython()
174 ip.history_manager.reset()
174 ip.history_manager.reset()
175 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
175 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
176 "%macro test 2-3"]
176 "%macro test 2-3"]
177 for cmd in cmds:
177 for cmd in cmds:
178 ip.run_cell(cmd, store_history=True)
178 ip.run_cell(cmd, store_history=True)
179 nt.assert_equal(ip.user_ns["test"].value,
179 nt.assert_equal(ip.user_ns["test"].value,
180 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
180 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
181 with tt.AssertPrints("12"):
181 with tt.AssertPrints("12"):
182 ip.run_cell("test")
182 ip.run_cell("test")
183 with tt.AssertPrints("13"):
183 with tt.AssertPrints("13"):
184 ip.run_cell("test")
184 ip.run_cell("test")
185
185
186
186
187 @dec.skipif_not_numpy
187 @dec.skipif_not_numpy
188 def test_numpy_clear_array_undec():
188 def test_numpy_clear_array_undec():
189 "Test '%clear array' functionality"
189 "Test '%clear array' functionality"
190 from IPython.extensions import clearcmd
190 from IPython.extensions import clearcmd
191
191
192 _ip.ex('import numpy as np')
192 _ip.ex('import numpy as np')
193 _ip.ex('a = np.empty(2)')
193 _ip.ex('a = np.empty(2)')
194 yield (nt.assert_true, 'a' in _ip.user_ns)
194 yield (nt.assert_true, 'a' in _ip.user_ns)
195 _ip.magic('clear array')
195 _ip.magic('clear array')
196 yield (nt.assert_false, 'a' in _ip.user_ns)
196 yield (nt.assert_false, 'a' in _ip.user_ns)
197
197
198 def test_clear():
198 def test_clear():
199 "Test '%clear' magic provided by IPython.extensions.clearcmd"
199 "Test '%clear' magic provided by IPython.extensions.clearcmd"
200 from IPython.extensions import clearcmd
200 from IPython.extensions import clearcmd
201 _ip = get_ipython()
201 _ip = get_ipython()
202 _ip.run_cell("parrot = 'dead'", store_history=True)
202 _ip.run_cell("parrot = 'dead'", store_history=True)
203 # test '%clear out', make an Out prompt
203 # test '%clear out', make an Out prompt
204 _ip.run_cell("parrot", store_history=True)
204 _ip.run_cell("parrot", store_history=True)
205 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
205 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
206 _ip.magic('clear out')
206 _ip.magic('clear out')
207 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
207 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
208 nt.assert_true(len(_ip.user_ns['Out']) ==0)
208 nt.assert_true(len(_ip.user_ns['Out']) == 0)
209
209
210 # test '%clear in'
210 # test '%clear in'
211 _ip.run_cell("parrot", store_history=True)
211 _ip.run_cell("parrot", store_history=True)
212 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
212 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
213 _ip.magic('%clear in')
213 _ip.magic('%clear in')
214 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
214 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
215 nt.assert_true(len(_ip.user_ns['In'] ==0))
215 nt.assert_true(len(_ip.user_ns['In']) == 0)
216
216
217 # test '%clear dhist'
217 # test '%clear dhist'
218 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
218 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
219 _ip.magic('cd')
219 _ip.magic('cd')
220 _ip.magic('cd -')
220 _ip.magic('cd -')
221 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
221 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
222 _ip.magic('clear dhist')
222 _ip.magic('clear dhist')
223 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
223 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
224 _ip.run_cell("_dh = [d for d in tmp]") #restore
224 _ip.run_cell("_dh = [d for d in tmp]") #restore
225
225
226 def test_time():
226 def test_time():
227 _ip.magic('time None')
227 _ip.magic('time None')
228
228
229
229
230 @py3compat.doctest_refactor_print
230 @py3compat.doctest_refactor_print
231 def doctest_time():
231 def doctest_time():
232 """
232 """
233 In [10]: %time None
233 In [10]: %time None
234 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
234 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
235 Wall time: 0.00 s
235 Wall time: 0.00 s
236
236
237 In [11]: def f(kmjy):
237 In [11]: def f(kmjy):
238 ....: %time print 2*kmjy
238 ....: %time print 2*kmjy
239
239
240 In [12]: f(3)
240 In [12]: f(3)
241 6
241 6
242 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
242 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
243 Wall time: 0.00 s
243 Wall time: 0.00 s
244 """
244 """
245
245
246
246
247 def test_doctest_mode():
247 def test_doctest_mode():
248 "Toggle doctest_mode twice, it should be a no-op and run without error"
248 "Toggle doctest_mode twice, it should be a no-op and run without error"
249 _ip.magic('doctest_mode')
249 _ip.magic('doctest_mode')
250 _ip.magic('doctest_mode')
250 _ip.magic('doctest_mode')
251
251
252
252
253 def test_parse_options():
253 def test_parse_options():
254 """Tests for basic options parsing in magics."""
254 """Tests for basic options parsing in magics."""
255 # These are only the most minimal of tests, more should be added later. At
255 # These are only the most minimal of tests, more should be added later. At
256 # the very least we check that basic text/unicode calls work OK.
256 # the very least we check that basic text/unicode calls work OK.
257 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
257 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
258 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
258 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
259
259
260
260
261 def test_dirops():
261 def test_dirops():
262 """Test various directory handling operations."""
262 """Test various directory handling operations."""
263 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
263 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
264 curpath = os.getcwdu
264 curpath = os.getcwdu
265 startdir = os.getcwdu()
265 startdir = os.getcwdu()
266 ipdir = os.path.realpath(_ip.ipython_dir)
266 ipdir = os.path.realpath(_ip.ipython_dir)
267 try:
267 try:
268 _ip.magic('cd "%s"' % ipdir)
268 _ip.magic('cd "%s"' % ipdir)
269 nt.assert_equal(curpath(), ipdir)
269 nt.assert_equal(curpath(), ipdir)
270 _ip.magic('cd -')
270 _ip.magic('cd -')
271 nt.assert_equal(curpath(), startdir)
271 nt.assert_equal(curpath(), startdir)
272 _ip.magic('pushd "%s"' % ipdir)
272 _ip.magic('pushd "%s"' % ipdir)
273 nt.assert_equal(curpath(), ipdir)
273 nt.assert_equal(curpath(), ipdir)
274 _ip.magic('popd')
274 _ip.magic('popd')
275 nt.assert_equal(curpath(), startdir)
275 nt.assert_equal(curpath(), startdir)
276 finally:
276 finally:
277 os.chdir(startdir)
277 os.chdir(startdir)
278
278
279
279
280 def test_xmode():
280 def test_xmode():
281 # Calling xmode three times should be a no-op
281 # Calling xmode three times should be a no-op
282 xmode = _ip.InteractiveTB.mode
282 xmode = _ip.InteractiveTB.mode
283 for i in range(3):
283 for i in range(3):
284 _ip.magic("xmode")
284 _ip.magic("xmode")
285 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
285 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
286
286
287 def test_reset_hard():
287 def test_reset_hard():
288 monitor = []
288 monitor = []
289 class A(object):
289 class A(object):
290 def __del__(self):
290 def __del__(self):
291 monitor.append(1)
291 monitor.append(1)
292 def __repr__(self):
292 def __repr__(self):
293 return "<A instance>"
293 return "<A instance>"
294
294
295 _ip.user_ns["a"] = A()
295 _ip.user_ns["a"] = A()
296 _ip.run_cell("a")
296 _ip.run_cell("a")
297
297
298 nt.assert_equal(monitor, [])
298 nt.assert_equal(monitor, [])
299 _ip.magic_reset("-f")
299 _ip.magic_reset("-f")
300 nt.assert_equal(monitor, [1])
300 nt.assert_equal(monitor, [1])
301
301
302 class TestXdel(tt.TempFileMixin):
302 class TestXdel(tt.TempFileMixin):
303 def test_xdel(self):
303 def test_xdel(self):
304 """Test that references from %run are cleared by xdel."""
304 """Test that references from %run are cleared by xdel."""
305 src = ("class A(object):\n"
305 src = ("class A(object):\n"
306 " monitor = []\n"
306 " monitor = []\n"
307 " def __del__(self):\n"
307 " def __del__(self):\n"
308 " self.monitor.append(1)\n"
308 " self.monitor.append(1)\n"
309 "a = A()\n")
309 "a = A()\n")
310 self.mktmp(src)
310 self.mktmp(src)
311 # %run creates some hidden references...
311 # %run creates some hidden references...
312 _ip.magic("run %s" % self.fname)
312 _ip.magic("run %s" % self.fname)
313 # ... as does the displayhook.
313 # ... as does the displayhook.
314 _ip.run_cell("a")
314 _ip.run_cell("a")
315
315
316 monitor = _ip.user_ns["A"].monitor
316 monitor = _ip.user_ns["A"].monitor
317 nt.assert_equal(monitor, [])
317 nt.assert_equal(monitor, [])
318
318
319 _ip.magic("xdel a")
319 _ip.magic("xdel a")
320
320
321 # Check that a's __del__ method has been called.
321 # Check that a's __del__ method has been called.
322 nt.assert_equal(monitor, [1])
322 nt.assert_equal(monitor, [1])
323
323
324 def doctest_who():
324 def doctest_who():
325 """doctest for %who
325 """doctest for %who
326
326
327 In [1]: %reset -f
327 In [1]: %reset -f
328
328
329 In [2]: alpha = 123
329 In [2]: alpha = 123
330
330
331 In [3]: beta = 'beta'
331 In [3]: beta = 'beta'
332
332
333 In [4]: %who int
333 In [4]: %who int
334 alpha
334 alpha
335
335
336 In [5]: %who str
336 In [5]: %who str
337 beta
337 beta
338
338
339 In [6]: %whos
339 In [6]: %whos
340 Variable Type Data/Info
340 Variable Type Data/Info
341 ----------------------------
341 ----------------------------
342 alpha int 123
342 alpha int 123
343 beta str beta
343 beta str beta
344
344
345 In [7]: %who_ls
345 In [7]: %who_ls
346 Out[7]: ['alpha', 'beta']
346 Out[7]: ['alpha', 'beta']
347 """
347 """
348
348
349 @py3compat.u_format
349 @py3compat.u_format
350 def doctest_precision():
350 def doctest_precision():
351 """doctest for %precision
351 """doctest for %precision
352
352
353 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
353 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
354
354
355 In [2]: %precision 5
355 In [2]: %precision 5
356 Out[2]: {u}'%.5f'
356 Out[2]: {u}'%.5f'
357
357
358 In [3]: f.float_format
358 In [3]: f.float_format
359 Out[3]: {u}'%.5f'
359 Out[3]: {u}'%.5f'
360
360
361 In [4]: %precision %e
361 In [4]: %precision %e
362 Out[4]: {u}'%e'
362 Out[4]: {u}'%e'
363
363
364 In [5]: f(3.1415927)
364 In [5]: f(3.1415927)
365 Out[5]: {u}'3.141593e+00'
365 Out[5]: {u}'3.141593e+00'
366 """
366 """
367
367
368 def test_psearch():
368 def test_psearch():
369 with tt.AssertPrints("dict.fromkeys"):
369 with tt.AssertPrints("dict.fromkeys"):
370 _ip.run_cell("dict.fr*?")
370 _ip.run_cell("dict.fr*?")
371
371
372 def test_timeit_shlex():
372 def test_timeit_shlex():
373 """test shlex issues with timeit (#1109)"""
373 """test shlex issues with timeit (#1109)"""
374 _ip.ex("def f(*a,**kw): pass")
374 _ip.ex("def f(*a,**kw): pass")
375 _ip.magic('timeit -n1 "this is a bug".count(" ")')
375 _ip.magic('timeit -n1 "this is a bug".count(" ")')
376 _ip.magic('timeit -r1 -n1 f(" ", 1)')
376 _ip.magic('timeit -r1 -n1 f(" ", 1)')
377 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
377 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
378 _ip.magic('timeit -r1 -n1 ("a " + "b")')
378 _ip.magic('timeit -r1 -n1 ("a " + "b")')
379 _ip.magic('timeit -r1 -n1 f("a " + "b")')
379 _ip.magic('timeit -r1 -n1 f("a " + "b")')
380 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
380 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
381
381
382
382
383 def test_timeit_arguments():
383 def test_timeit_arguments():
384 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
384 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
385 _ip.magic("timeit ('#')")
385 _ip.magic("timeit ('#')")
@@ -1,86 +1,83 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """ IPython extension: add %clear magic """
2 """ IPython extension: add %clear magic """
3
3
4 from IPython.core import ipapi
4 from IPython.core import ipapi
5 import gc
5 import gc
6 ip = ipapi.get()
6 ip = ipapi.get()
7
7
8 def clear_f(self,arg):
8 def clear_f(self,arg):
9 """ Clear various data (e.g. stored history data)
9 """ Clear various data (e.g. stored history data)
10
10
11 %clear in - clear input history
11 %clear in - clear input history
12 %clear out - clear output history
12 %clear out - clear output history
13 %clear shadow_compress - Compresses shadow history (to speed up ipython)
13 %clear shadow_compress - Compresses shadow history (to speed up ipython)
14 %clear shadow_nuke - permanently erase all entries in shadow history
14 %clear shadow_nuke - permanently erase all entries in shadow history
15 %clear dhist - clear dir history
15 %clear dhist - clear dir history
16 %clear array - clear only variables that are NumPy arrays
16 %clear array - clear only variables that are NumPy arrays
17
17
18 Examples:
18 Examples:
19
19
20 In [1]: clear in
20 In [1]: clear in
21 Flushing input history
21 Flushing input history
22
22
23 In [2]: clear shadow_compress
23 In [2]: clear shadow_compress
24 Compressing shadow history
24 Compressing shadow history
25
25
26 In [3]: clear shadow_nuke
26 In [3]: clear shadow_nuke
27 Erased all keys from shadow history
27 Erased all keys from shadow history
28
28
29 In [4]: clear dhist
29 In [4]: clear dhist
30 Clearing directory history
30 Clearing directory history
31 """
31 """
32
32
33 api = self.get_ipython()
33 api = self.get_ipython()
34 user_ns = self.user_ns # local lookup, heavily used
34 user_ns = self.user_ns # local lookup, heavily used
35
35
36
36
37 for target in arg.split():
37 for target in arg.split():
38
38
39 if target == 'out':
39 if target == 'out':
40 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
40 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
41 self.displayhook.flush()
41 self.displayhook.flush()
42
42
43 elif target == 'in':
43 elif target == 'in':
44 print "Flushing input history"
44 print "Flushing input history"
45 pc = self.displayhook.prompt_count + 1
45 pc = self.displayhook.prompt_count + 1
46 for n in range(1, pc):
46 for n in range(1, pc):
47 key = '_i'+`n`
47 key = '_i'+repr(n)
48 user_ns.pop(key,None)
48 user_ns.pop(key,None)
49 try:
49 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
50 del user_ns[key]
50 del self.history_manager.input_hist_parsed[:]
51 except: pass
51 del self.history_manager.input_hist_raw[:]
52 # must be done in-place
53 self.history_manager.input_hist_parsed[:] = ['\n'] * pc
54 self.history_manager.input_hist_raw[:] = ['\n'] * pc
55
52
56 elif target == 'array':
53 elif target == 'array':
57 # Support cleaning up numpy arrays
54 # Support cleaning up numpy arrays
58 try:
55 try:
59 from numpy import ndarray
56 from numpy import ndarray
60 # This must be done with items and not iteritems because we're
57 # This must be done with items and not iteritems because we're
61 # going to modify the dict in-place.
58 # going to modify the dict in-place.
62 for x,val in user_ns.items():
59 for x,val in user_ns.items():
63 if isinstance(val,ndarray):
60 if isinstance(val,ndarray):
64 del user_ns[x]
61 del user_ns[x]
65 except AttributeError:
62 except ImportError:
66 print "Clear array only works if Numpy is available."
63 print "Clear array only works if Numpy is available."
67
64
68 elif target == 'shadow_compress':
65 elif target == 'shadow_compress':
69 print "Compressing shadow history"
66 print "Compressing shadow history"
70 api.db.hcompress('shadowhist')
67 api.db.hcompress('shadowhist')
71
68
72 elif target == 'shadow_nuke':
69 elif target == 'shadow_nuke':
73 print "Erased all keys from shadow history "
70 print "Erased all keys from shadow history "
74 for k in ip.db.keys('shadowhist/*'):
71 for k in ip.db.keys('shadowhist/*'):
75 del ip.db[k]
72 del ip.db[k]
76
73
77 elif target == 'dhist':
74 elif target == 'dhist':
78 print "Clearing directory history"
75 print "Clearing directory history"
79 del user_ns['_dh'][:]
76 del user_ns['_dh'][:]
80
77
81 gc.collect()
78 gc.collect()
82
79
83 # Activate the extension
80 # Activate the extension
84 ip.define_magic("clear",clear_f)
81 ip.define_magic("clear",clear_f)
85 from IPython.core.completerlib import quick_completer
82 from IPython.core.completerlib import quick_completer
86 quick_completer( '%clear','in out shadow_nuke shadow_compress dhist')
83 quick_completer('%clear','in out array shadow_nuke shadow_compress dhist')
General Comments 0
You need to be logged in to leave comments. Login now