##// END OF EJS Templates
Update IPython/core/magic_arguments.py...
Andrew Spiers -
Show More
@@ -1,223 +1,222
1 1 ''' A decorator-based method of constructing IPython magics with `argparse`
2 2 option handling.
3 3
4 4 New magic functions can be defined like so::
5 5
6 6 from IPython.core.magic_arguments import (argument, magic_arguments,
7 7 parse_argstring)
8 8
9 9 @magic_arguments()
10 10 @argument('-o', '--option', help='An optional argument.')
11 11 @argument('arg', type=int, help='An integer positional argument.')
12 12 def magic_cool(self, arg):
13 13 """ A really cool magic command.
14 14
15 15 """
16 16 args = parse_argstring(magic_cool, arg)
17 17 ...
18 18
19 19 The `@magic_arguments` decorator marks the function as having argparse arguments.
20 20 The `@argument` decorator adds an argument using the same syntax as argparse's
21 21 `add_argument()` method. More sophisticated uses may also require the
22 22 `@argument_group` or `@kwds` decorator to customize the formatting and the
23 23 parsing.
24 24
25 25 Help text for the magic is automatically generated from the docstring and the
26 26 arguments::
27 27
28 28 In[1]: %cool?
29 29 %cool [-o OPTION] arg
30 30
31 31 A really cool magic command.
32 32
33 33 positional arguments:
34 34 arg An integer positional argument.
35 35
36 36 optional arguments:
37 37 -o OPTION, --option OPTION
38 38 An optional argument.
39 39
40 40 '''
41 41 #-----------------------------------------------------------------------------
42 42 # Copyright (C) 2010-2011, IPython Development Team.
43 43 #
44 44 # Distributed under the terms of the Modified BSD License.
45 45 #
46 46 # The full license is in the file COPYING.txt, distributed with this software.
47 47 #-----------------------------------------------------------------------------
48 48
49 49 # Our own imports
50 50 from IPython.external import argparse
51 51 from IPython.core.error import UsageError
52 52 from IPython.utils.process import arg_split
53 53 from IPython.utils.text import dedent
54 54
55 55 class MagicHelpFormatter(argparse.RawDescriptionHelpFormatter):
56 56 """ A HelpFormatter which dedents but otherwise preserves indentation.
57 57 """
58 58 def _fill_text(self, text, width, indent):
59 59 return argparse.RawDescriptionHelpFormatter._fill_text(self, dedent(text), width, indent)
60 60
61 61 class MagicArgumentParser(argparse.ArgumentParser):
62 62 """ An ArgumentParser tweaked for use by IPython magics.
63 63 """
64 64 def __init__(self,
65 65 prog=None,
66 66 usage=None,
67 67 description=None,
68 68 epilog=None,
69 version=None,
70 69 parents=None,
71 70 formatter_class=MagicHelpFormatter,
72 71 prefix_chars='-',
73 72 argument_default=None,
74 73 conflict_handler='error',
75 74 add_help=False):
76 75 if parents is None:
77 76 parents = []
78 77 super(MagicArgumentParser, self).__init__(prog=prog, usage=usage,
79 description=description, epilog=epilog, version=version,
78 description=description, epilog=epilog,
80 79 parents=parents, formatter_class=formatter_class,
81 80 prefix_chars=prefix_chars, argument_default=argument_default,
82 81 conflict_handler=conflict_handler, add_help=add_help)
83 82
84 83 def error(self, message):
85 84 """ Raise a catchable error instead of exiting.
86 85 """
87 86 raise UsageError(message)
88 87
89 88 def parse_argstring(self, argstring):
90 89 """ Split a string into an argument list and parse that argument list.
91 90 """
92 91 argv = arg_split(argstring)
93 92 return self.parse_args(argv)
94 93
95 94
96 95 def construct_parser(magic_func):
97 96 """ Construct an argument parser using the function decorations.
98 97 """
99 98 kwds = getattr(magic_func, 'argcmd_kwds', {})
100 99 if 'description' not in kwds:
101 100 kwds['description'] = getattr(magic_func, '__doc__', None)
102 101 arg_name = real_name(magic_func)
103 102 parser = MagicArgumentParser(arg_name, **kwds)
104 103 # Reverse the list of decorators in order to apply them in the
105 104 # order in which they appear in the source.
106 105 group = None
107 106 for deco in magic_func.decorators[::-1]:
108 107 result = deco.add_to_parser(parser, group)
109 108 if result is not None:
110 109 group = result
111 110
112 111 # Replace the starting 'usage: ' with IPython's %.
113 112 help_text = parser.format_help()
114 113 if help_text.startswith('usage: '):
115 114 help_text = help_text.replace('usage: ', '%', 1)
116 115 else:
117 116 help_text = '%' + help_text
118 117
119 118 # Replace the magic function's docstring with the full help text.
120 119 magic_func.__doc__ = help_text
121 120
122 121 return parser
123 122
124 123
125 124 def parse_argstring(magic_func, argstring):
126 125 """ Parse the string of arguments for the given magic function.
127 126 """
128 127 return magic_func.parser.parse_argstring(argstring)
129 128
130 129
131 130 def real_name(magic_func):
132 131 """ Find the real name of the magic.
133 132 """
134 133 magic_name = magic_func.__name__
135 134 if magic_name.startswith('magic_'):
136 135 magic_name = magic_name[len('magic_'):]
137 136 return getattr(magic_func, 'argcmd_name', magic_name)
138 137
139 138
140 139 class ArgDecorator(object):
141 140 """ Base class for decorators to add ArgumentParser information to a method.
142 141 """
143 142
144 143 def __call__(self, func):
145 144 if not getattr(func, 'has_arguments', False):
146 145 func.has_arguments = True
147 146 func.decorators = []
148 147 func.decorators.append(self)
149 148 return func
150 149
151 150 def add_to_parser(self, parser, group):
152 151 """ Add this object's information to the parser, if necessary.
153 152 """
154 153 pass
155 154
156 155
157 156 class magic_arguments(ArgDecorator):
158 157 """ Mark the magic as having argparse arguments and possibly adjust the
159 158 name.
160 159 """
161 160
162 161 def __init__(self, name=None):
163 162 self.name = name
164 163
165 164 def __call__(self, func):
166 165 if not getattr(func, 'has_arguments', False):
167 166 func.has_arguments = True
168 167 func.decorators = []
169 168 if self.name is not None:
170 169 func.argcmd_name = self.name
171 170 # This should be the first decorator in the list of decorators, thus the
172 171 # last to execute. Build the parser.
173 172 func.parser = construct_parser(func)
174 173 return func
175 174
176 175
177 176 class argument(ArgDecorator):
178 177 """ Store arguments and keywords to pass to add_argument().
179 178
180 179 Instances also serve to decorate command methods.
181 180 """
182 181 def __init__(self, *args, **kwds):
183 182 self.args = args
184 183 self.kwds = kwds
185 184
186 185 def add_to_parser(self, parser, group):
187 186 """ Add this object's information to the parser.
188 187 """
189 188 if group is not None:
190 189 parser = group
191 190 parser.add_argument(*self.args, **self.kwds)
192 191 return None
193 192
194 193
195 194 class argument_group(ArgDecorator):
196 195 """ Store arguments and keywords to pass to add_argument_group().
197 196
198 197 Instances also serve to decorate command methods.
199 198 """
200 199 def __init__(self, *args, **kwds):
201 200 self.args = args
202 201 self.kwds = kwds
203 202
204 203 def add_to_parser(self, parser, group):
205 204 """ Add this object's information to the parser.
206 205 """
207 206 return parser.add_argument_group(*self.args, **self.kwds)
208 207
209 208
210 209 class kwds(ArgDecorator):
211 210 """ Provide other keywords to the sub-parser constructor.
212 211 """
213 212 def __init__(self, **kwds):
214 213 self.kwds = kwds
215 214
216 215 def __call__(self, func):
217 216 func = super(kwds, self).__call__(func)
218 217 func.argcmd_kwds = self.kwds
219 218 return func
220 219
221 220
222 221 __all__ = ['magic_arguments', 'argument', 'argument_group', 'kwds',
223 222 'parse_argstring']
General Comments 0
You need to be logged in to leave comments. Login now