##// END OF EJS Templates
Merge pull request #2404 from tkf/history-magic-search-limit...
Bussonnier Matthias -
r8686:fb4a45e8 merge
parent child Browse files
Show More
@@ -173,11 +173,17 b' class magic_arguments(ArgDecorator):'
173 return func
173 return func
174
174
175
175
176 class argument(ArgDecorator):
176 class ArgMethodWrapper(ArgDecorator):
177 """ Store arguments and keywords to pass to add_argument().
177
178 """
179 Base class to define a wrapper for ArgumentParser method.
180
181 Child class must define either `_method_name` or `add_to_parser`.
178
182
179 Instances also serve to decorate command methods.
180 """
183 """
184
185 _method_name = None
186
181 def __init__(self, *args, **kwds):
187 def __init__(self, *args, **kwds):
182 self.args = args
188 self.args = args
183 self.kwds = kwds
189 self.kwds = kwds
@@ -187,18 +193,31 b' class argument(ArgDecorator):'
187 """
193 """
188 if group is not None:
194 if group is not None:
189 parser = group
195 parser = group
190 parser.add_argument(*self.args, **self.kwds)
196 getattr(parser, self._method_name)(*self.args, **self.kwds)
191 return None
197 return None
192
198
193
199
194 class argument_group(ArgDecorator):
200 class argument(ArgMethodWrapper):
201 """ Store arguments and keywords to pass to add_argument().
202
203 Instances also serve to decorate command methods.
204 """
205 _method_name = 'add_argument'
206
207
208 class defaults(ArgMethodWrapper):
209 """ Store arguments and keywords to pass to set_defaults().
210
211 Instances also serve to decorate command methods.
212 """
213 _method_name = 'set_defaults'
214
215
216 class argument_group(ArgMethodWrapper):
195 """ Store arguments and keywords to pass to add_argument_group().
217 """ Store arguments and keywords to pass to add_argument_group().
196
218
197 Instances also serve to decorate command methods.
219 Instances also serve to decorate command methods.
198 """
220 """
199 def __init__(self, *args, **kwds):
200 self.args = args
201 self.kwds = kwds
202
221
203 def add_to_parser(self, parser, group):
222 def add_to_parser(self, parser, group):
204 """ Add this object's information to the parser.
223 """ Add this object's information to the parser.
@@ -16,10 +16,13 b' from __future__ import print_function'
16 # Stdlib
16 # Stdlib
17 import os
17 import os
18 from io import open as io_open
18 from io import open as io_open
19 from IPython.external.argparse import Action
19
20
20 # Our own packages
21 # Our own packages
21 from IPython.core.error import StdinNotImplementedError
22 from IPython.core.error import StdinNotImplementedError
22 from IPython.core.magic import Magics, magics_class, line_magic
23 from IPython.core.magic import Magics, magics_class, line_magic
24 from IPython.core.magic_arguments import (argument, magic_arguments,
25 parse_argstring)
23 from IPython.testing.skipdoctest import skip_doctest
26 from IPython.testing.skipdoctest import skip_doctest
24 from IPython.utils import io
27 from IPython.utils import io
25
28
@@ -27,16 +30,71 b' from IPython.utils import io'
27 # Magics class implementation
30 # Magics class implementation
28 #-----------------------------------------------------------------------------
31 #-----------------------------------------------------------------------------
29
32
33
34 _unspecified = object()
35
36
30 @magics_class
37 @magics_class
31 class HistoryMagics(Magics):
38 class HistoryMagics(Magics):
32
39
40 @magic_arguments()
41 @argument(
42 '-n', dest='print_nums', action='store_true', default=False,
43 help="""
44 print line numbers for each input.
45 This feature is only available if numbered prompts are in use.
46 """)
47 @argument(
48 '-o', dest='get_output', action='store_true', default=False,
49 help="also print outputs for each input.")
50 @argument(
51 '-p', dest='pyprompts', action='store_true', default=False,
52 help="""
53 print classic '>>>' python prompts before each input.
54 This is useful for making documentation, and in conjunction
55 with -o, for producing doctest-ready output.
56 """)
57 @argument(
58 '-t', dest='raw', action='store_false', default=True,
59 help="""
60 print the 'translated' history, as IPython understands it.
61 IPython filters your input and converts it all into valid Python
62 source before executing it (things like magics or aliases are turned
63 into function calls, for example). With this option, you'll see the
64 native history instead of the user-entered version: '%%cd /' will be
65 seen as 'get_ipython().magic("%%cd /")' instead of '%%cd /'.
66 """)
67 @argument(
68 '-f', dest='filename',
69 help="""
70 FILENAME: instead of printing the output to the screen, redirect
71 it to the given file. The file is always overwritten, though *when
72 it can*, IPython asks for confirmation first. In particular, running
73 the command 'history -f FILENAME' from the IPython Notebook
74 interface will replace FILENAME even if it already exists *without*
75 confirmation.
76 """)
77 @argument(
78 '-g', dest='pattern', nargs='*', default=None,
79 help="""
80 treat the arg as a glob pattern to search for in (full) history.
81 This includes the saved history (almost all commands ever written).
82 The pattern may contain '?' to match one unknown character and '*'
83 to match any number of unknown characters. Use '%%hist -g' to show
84 full saved history (may be very long).
85 """)
86 @argument(
87 '-l', dest='limit', type=int, nargs='?', default=_unspecified,
88 help="""
89 get the last n lines from all sessions. Specify n as a single
90 arg, or the default is the last 10 lines.
91 """)
92 @argument('range', nargs='*')
33 @skip_doctest
93 @skip_doctest
34 @line_magic
94 @line_magic
35 def history(self, parameter_s = ''):
95 def history(self, parameter_s = ''):
36 """Print input history (_i<n> variables), with most recent last.
96 """Print input history (_i<n> variables), with most recent last.
37
97
38 %history [-o -p -t -n] [-f filename] [range | -g pattern | -l number]
39
40 By default, input history is printed without line numbers so it can be
98 By default, input history is printed without line numbers so it can be
41 directly pasted into an editor. Use -n to show them.
99 directly pasted into an editor. Use -n to show them.
42
100
@@ -52,43 +110,6 b' class HistoryMagics(Magics):'
52
110
53 The same syntax is used by %macro, %save, %edit, %rerun
111 The same syntax is used by %macro, %save, %edit, %rerun
54
112
55 Options:
56
57 -n: print line numbers for each input.
58 This feature is only available if numbered prompts are in use.
59
60 -o: also print outputs for each input.
61
62 -p: print classic '>>>' python prompts before each input. This is
63 useful for making documentation, and in conjunction with -o, for
64 producing doctest-ready output.
65
66 -r: (default) print the 'raw' history, i.e. the actual commands you
67 typed.
68
69 -t: print the 'translated' history, as IPython understands it.
70 IPython filters your input and converts it all into valid Python
71 source before executing it (things like magics or aliases are turned
72 into function calls, for example). With this option, you'll see the
73 native history instead of the user-entered version: '%cd /' will be
74 seen as 'get_ipython().magic("%cd /")' instead of '%cd /'.
75
76 -g: treat the arg as a pattern to grep for in (full) history.
77 This includes the saved history (almost all commands ever written).
78 The pattern may contain '?' to match one unknown character and '*'
79 to match any number of unknown characters. Use '%hist -g' to show
80 full saved history (may be very long).
81
82 -l: get the last n lines from all sessions. Specify n as a single
83 arg, or the default is the last 10 lines.
84
85 -f FILENAME: instead of printing the output to the screen, redirect
86 it to the given file. The file is always overwritten, though *when
87 it can*, IPython asks for confirmation first. In particular, running
88 the command 'history -f FILENAME' from the IPython Notebook
89 interface will replace FILENAME even if it already exists *without*
90 confirmation.
91
92 Examples
113 Examples
93 --------
114 --------
94 ::
115 ::
@@ -104,7 +125,7 b' class HistoryMagics(Magics):'
104 print('This feature is only available if numbered prompts '
125 print('This feature is only available if numbered prompts '
105 'are in use.')
126 'are in use.')
106 return
127 return
107 opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string')
128 args = parse_argstring(self.history, parameter_s)
108
129
109 # For brevity
130 # For brevity
110 history_manager = self.shell.history_manager
131 history_manager = self.shell.history_manager
@@ -116,9 +137,8 b' class HistoryMagics(Magics):'
116 return "%s/%s" % (session, line)
137 return "%s/%s" % (session, line)
117
138
118 # Check if output to specific file was requested.
139 # Check if output to specific file was requested.
119 try:
140 outfname = args.filename
120 outfname = opts['f']
141 if not outfname:
121 except KeyError:
122 outfile = io.stdout # default
142 outfile = io.stdout # default
123 # We don't want to close stdout at the end!
143 # We don't want to close stdout at the end!
124 close_at_end = False
144 close_at_end = False
@@ -135,27 +155,29 b' class HistoryMagics(Magics):'
135 outfile = io_open(outfname, 'w', encoding='utf-8')
155 outfile = io_open(outfname, 'w', encoding='utf-8')
136 close_at_end = True
156 close_at_end = True
137
157
138 print_nums = 'n' in opts
158 print_nums = args.print_nums
139 get_output = 'o' in opts
159 get_output = args.get_output
140 pyprompts = 'p' in opts
160 pyprompts = args.pyprompts
141 # Raw history is the default
161 raw = args.raw
142 raw = not('t' in opts)
143
162
144 pattern = None
163 pattern = None
164 limit = None if args.limit is _unspecified else args.limit
145
165
146 if 'g' in opts: # Glob search
166 if args.pattern is not None:
147 pattern = "*" + args + "*" if args else "*"
167 if args.pattern:
148 hist = history_manager.search(pattern, raw=raw, output=get_output)
168 pattern = "*" + " ".join(args.pattern) + "*"
169 else:
170 pattern = "*"
171 hist = history_manager.search(pattern, raw=raw, output=get_output,
172 n=limit)
149 print_nums = True
173 print_nums = True
150 elif 'l' in opts: # Get 'tail'
174 elif args.limit is not _unspecified:
151 try:
175 n = 10 if limit is None else limit
152 n = int(args)
153 except (ValueError, IndexError):
154 n = 10
155 hist = history_manager.get_tail(n, raw=raw, output=get_output)
176 hist = history_manager.get_tail(n, raw=raw, output=get_output)
156 else:
177 else:
157 if args: # Get history by ranges
178 if args.range: # Get history by ranges
158 hist = history_manager.get_range_by_str(args, raw, get_output)
179 hist = history_manager.get_range_by_str(" ".join(args.range),
180 raw, get_output)
159 else: # Just get history for the current session
181 else: # Just get history for the current session
160 hist = history_manager.get_range(raw=raw, output=get_output)
182 hist = history_manager.get_range(raw=raw, output=get_output)
161
183
General Comments 0
You need to be logged in to leave comments. Login now