Show More
This diff has been collapsed as it changes many lines, (1867 lines changed) Show them Hide them | |||||
@@ -0,0 +1,1867 b'' | |||||
|
1 | # -*- coding: utf-8 -*- | |||
|
2 | ||||
|
3 | # Copyright οΏ½ 2006 Steven J. Bethard <steven.bethard@gmail.com>. | |||
|
4 | # | |||
|
5 | # Redistribution and use in source and binary forms, with or without | |||
|
6 | # modification, are permitted under the terms of the 3-clause BSD | |||
|
7 | # license. No warranty expressed or implied. | |||
|
8 | # For details, see the accompanying file LICENSE.txt. | |||
|
9 | ||||
|
10 | """Command-line parsing library | |||
|
11 | ||||
|
12 | This module is an optparse-inspired command-line parsing library that: | |||
|
13 | ||||
|
14 | * handles both optional and positional arguments | |||
|
15 | * produces highly informative usage messages | |||
|
16 | * supports parsers that dispatch to sub-parsers | |||
|
17 | ||||
|
18 | The following is a simple usage example that sums integers from the | |||
|
19 | command-line and writes the result to a file: | |||
|
20 | ||||
|
21 | parser = argparse.ArgumentParser( | |||
|
22 | description='sum the integers at the command line') | |||
|
23 | parser.add_argument( | |||
|
24 | 'integers', metavar='int', nargs='+', type=int, | |||
|
25 | help='an integer to be summed') | |||
|
26 | parser.add_argument( | |||
|
27 | '--log', default=sys.stdout, type=argparse.FileType('w'), | |||
|
28 | help='the file where the sum should be written') | |||
|
29 | args = parser.parse_args() | |||
|
30 | args.log.write('%s' % sum(args.integers)) | |||
|
31 | args.log.close() | |||
|
32 | ||||
|
33 | The module contains the following public classes: | |||
|
34 | ||||
|
35 | ArgumentParser -- The main entry point for command-line parsing. As the | |||
|
36 | example above shows, the add_argument() method is used to populate | |||
|
37 | the parser with actions for optional and positional arguments. Then | |||
|
38 | the parse_args() method is invoked to convert the args at the | |||
|
39 | command-line into an object with attributes. | |||
|
40 | ||||
|
41 | ArgumentError -- The exception raised by ArgumentParser objects when | |||
|
42 | there are errors with the parser's actions. Errors raised while | |||
|
43 | parsing the command-line are caught by ArgumentParser and emitted | |||
|
44 | as command-line messages. | |||
|
45 | ||||
|
46 | FileType -- A factory for defining types of files to be created. As the | |||
|
47 | example above shows, instances of FileType are typically passed as | |||
|
48 | the type= argument of add_argument() calls. | |||
|
49 | ||||
|
50 | Action -- The base class for parser actions. Typically actions are | |||
|
51 | selected by passing strings like 'store_true' or 'append_const' to | |||
|
52 | the action= argument of add_argument(). However, for greater | |||
|
53 | customization of ArgumentParser actions, subclasses of Action may | |||
|
54 | be defined and passed as the action= argument. | |||
|
55 | ||||
|
56 | HelpFormatter, RawDescriptionHelpFormatter -- Formatter classes which | |||
|
57 | may be passed as the formatter_class= argument to the | |||
|
58 | ArgumentParser constructor. HelpFormatter is the default, while | |||
|
59 | RawDescriptionHelpFormatter tells the parser not to perform any | |||
|
60 | line-wrapping on description text. | |||
|
61 | ||||
|
62 | All other classes in this module are considered implementation details. | |||
|
63 | (Also note that HelpFormatter and RawDescriptionHelpFormatter are only | |||
|
64 | considered public as object names -- the API of the formatter objects is | |||
|
65 | still considered an implementation detail.) | |||
|
66 | """ | |||
|
67 | ||||
|
68 | __version__ = '0.8.0' | |||
|
69 | ||||
|
70 | import os as _os | |||
|
71 | import re as _re | |||
|
72 | import sys as _sys | |||
|
73 | import textwrap as _textwrap | |||
|
74 | ||||
|
75 | from gettext import gettext as _ | |||
|
76 | ||||
|
77 | SUPPRESS = '==SUPPRESS==' | |||
|
78 | ||||
|
79 | OPTIONAL = '?' | |||
|
80 | ZERO_OR_MORE = '*' | |||
|
81 | ONE_OR_MORE = '+' | |||
|
82 | PARSER = '==PARSER==' | |||
|
83 | ||||
|
84 | # ============================= | |||
|
85 | # Utility functions and classes | |||
|
86 | # ============================= | |||
|
87 | ||||
|
88 | class _AttributeHolder(object): | |||
|
89 | """Abstract base class that provides __repr__. | |||
|
90 | ||||
|
91 | The __repr__ method returns a string in the format: | |||
|
92 | ClassName(attr=name, attr=name, ...) | |||
|
93 | The attributes are determined either by a class-level attribute, | |||
|
94 | '_kwarg_names', or by inspecting the instance __dict__. | |||
|
95 | """ | |||
|
96 | ||||
|
97 | def __repr__(self): | |||
|
98 | type_name = type(self).__name__ | |||
|
99 | arg_strings = [] | |||
|
100 | for arg in self._get_args(): | |||
|
101 | arg_strings.append(repr(arg)) | |||
|
102 | for name, value in self._get_kwargs(): | |||
|
103 | arg_strings.append('%s=%r' % (name, value)) | |||
|
104 | return '%s(%s)' % (type_name, ', '.join(arg_strings)) | |||
|
105 | ||||
|
106 | def _get_kwargs(self): | |||
|
107 | return sorted(self.__dict__.items()) | |||
|
108 | ||||
|
109 | def _get_args(self): | |||
|
110 | return [] | |||
|
111 | ||||
|
112 | def _ensure_value(namespace, name, value): | |||
|
113 | if getattr(namespace, name, None) is None: | |||
|
114 | setattr(namespace, name, value) | |||
|
115 | return getattr(namespace, name) | |||
|
116 | ||||
|
117 | ||||
|
118 | ||||
|
119 | # =============== | |||
|
120 | # Formatting Help | |||
|
121 | # =============== | |||
|
122 | ||||
|
123 | class HelpFormatter(object): | |||
|
124 | ||||
|
125 | def __init__(self, | |||
|
126 | prog, | |||
|
127 | indent_increment=2, | |||
|
128 | max_help_position=24, | |||
|
129 | width=None): | |||
|
130 | ||||
|
131 | # default setting for width | |||
|
132 | if width is None: | |||
|
133 | try: | |||
|
134 | width = int(_os.environ['COLUMNS']) | |||
|
135 | except (KeyError, ValueError): | |||
|
136 | width = 80 | |||
|
137 | width -= 2 | |||
|
138 | ||||
|
139 | self._prog = prog | |||
|
140 | self._indent_increment = indent_increment | |||
|
141 | self._max_help_position = max_help_position | |||
|
142 | self._width = width | |||
|
143 | ||||
|
144 | self._current_indent = 0 | |||
|
145 | self._level = 0 | |||
|
146 | self._action_max_length = 0 | |||
|
147 | ||||
|
148 | self._root_section = self._Section(self, None) | |||
|
149 | self._current_section = self._root_section | |||
|
150 | ||||
|
151 | self._whitespace_matcher = _re.compile(r'\s+') | |||
|
152 | self._long_break_matcher = _re.compile(r'\n\n\n+') | |||
|
153 | ||||
|
154 | # =============================== | |||
|
155 | # Section and indentation methods | |||
|
156 | # =============================== | |||
|
157 | ||||
|
158 | def _indent(self): | |||
|
159 | self._current_indent += self._indent_increment | |||
|
160 | self._level += 1 | |||
|
161 | ||||
|
162 | def _dedent(self): | |||
|
163 | self._current_indent -= self._indent_increment | |||
|
164 | assert self._current_indent >= 0, 'Indent decreased below 0.' | |||
|
165 | self._level -= 1 | |||
|
166 | ||||
|
167 | class _Section(object): | |||
|
168 | def __init__(self, formatter, parent, heading=None): | |||
|
169 | self.formatter = formatter | |||
|
170 | self.parent = parent | |||
|
171 | self.heading = heading | |||
|
172 | self.items = [] | |||
|
173 | ||||
|
174 | def format_help(self): | |||
|
175 | # format the indented section | |||
|
176 | if self.parent is not None: | |||
|
177 | self.formatter._indent() | |||
|
178 | join = self.formatter._join_parts | |||
|
179 | for func, args in self.items: | |||
|
180 | func(*args) | |||
|
181 | item_help = join(func(*args) for func, args in self.items) | |||
|
182 | if self.parent is not None: | |||
|
183 | self.formatter._dedent() | |||
|
184 | ||||
|
185 | # return nothing if the section was empty | |||
|
186 | if not item_help: | |||
|
187 | return '' | |||
|
188 | ||||
|
189 | # add the heading if the section was non-empty | |||
|
190 | if self.heading is not SUPPRESS and self.heading is not None: | |||
|
191 | current_indent = self.formatter._current_indent | |||
|
192 | heading = '%*s%s:\n' % (current_indent, '', self.heading) | |||
|
193 | else: | |||
|
194 | heading = '' | |||
|
195 | ||||
|
196 | # join the section-initial newline, the heading and the help | |||
|
197 | return join(['\n', heading, item_help, '\n']) | |||
|
198 | ||||
|
199 | def _add_item(self, func, args): | |||
|
200 | self._current_section.items.append((func, args)) | |||
|
201 | ||||
|
202 | # ======================== | |||
|
203 | # Message building methods | |||
|
204 | # ======================== | |||
|
205 | ||||
|
206 | def start_section(self, heading): | |||
|
207 | self._indent() | |||
|
208 | section = self._Section(self, self._current_section, heading) | |||
|
209 | self._add_item(section.format_help, []) | |||
|
210 | self._current_section = section | |||
|
211 | ||||
|
212 | def end_section(self): | |||
|
213 | self._current_section = self._current_section.parent | |||
|
214 | self._dedent() | |||
|
215 | ||||
|
216 | def add_text(self, text): | |||
|
217 | if text is not SUPPRESS and text is not None: | |||
|
218 | self._add_item(self._format_text, [text]) | |||
|
219 | ||||
|
220 | def add_usage(self, usage, optionals, positionals, prefix=None): | |||
|
221 | if usage is not SUPPRESS: | |||
|
222 | args = usage, optionals, positionals, prefix | |||
|
223 | self._add_item(self._format_usage, args) | |||
|
224 | ||||
|
225 | def add_argument(self, action): | |||
|
226 | if action.help is not SUPPRESS: | |||
|
227 | ||||
|
228 | # find all invocations | |||
|
229 | get_invocation = self._format_action_invocation | |||
|
230 | invocations = [get_invocation(action)] | |||
|
231 | for subaction in self._iter_indented_subactions(action): | |||
|
232 | invocations.append(get_invocation(subaction)) | |||
|
233 | ||||
|
234 | # update the maximum item length | |||
|
235 | invocation_length = max(len(s) for s in invocations) | |||
|
236 | action_length = invocation_length + self._current_indent | |||
|
237 | self._action_max_length = max(self._action_max_length, | |||
|
238 | action_length) | |||
|
239 | ||||
|
240 | # add the item to the list | |||
|
241 | self._add_item(self._format_action, [action]) | |||
|
242 | ||||
|
243 | def add_arguments(self, actions): | |||
|
244 | for action in actions: | |||
|
245 | self.add_argument(action) | |||
|
246 | ||||
|
247 | # ======================= | |||
|
248 | # Help-formatting methods | |||
|
249 | # ======================= | |||
|
250 | ||||
|
251 | def format_help(self): | |||
|
252 | help = self._root_section.format_help() % dict(prog=self._prog) | |||
|
253 | if help: | |||
|
254 | help = self._long_break_matcher.sub('\n\n', help) | |||
|
255 | help = help.strip('\n') + '\n' | |||
|
256 | return help | |||
|
257 | ||||
|
258 | def _join_parts(self, part_strings): | |||
|
259 | return ''.join(part | |||
|
260 | for part in part_strings | |||
|
261 | if part and part is not SUPPRESS) | |||
|
262 | ||||
|
263 | def _format_usage(self, usage, optionals, positionals, prefix): | |||
|
264 | if prefix is None: | |||
|
265 | prefix = _('usage: ') | |||
|
266 | ||||
|
267 | # if no optionals or positionals are available, usage is just prog | |||
|
268 | if usage is None and not optionals and not positionals: | |||
|
269 | usage = '%(prog)s' | |||
|
270 | ||||
|
271 | # if optionals and positionals are available, calculate usage | |||
|
272 | elif usage is None: | |||
|
273 | usage = '%(prog)s' % dict(prog=self._prog) | |||
|
274 | ||||
|
275 | # determine width of "usage: PROG" and width of text | |||
|
276 | prefix_width = len(prefix) + len(usage) + 1 | |||
|
277 | prefix_indent = self._current_indent + prefix_width | |||
|
278 | text_width = self._width - self._current_indent | |||
|
279 | ||||
|
280 | # put them on one line if they're short enough | |||
|
281 | format = self._format_actions_usage | |||
|
282 | action_usage = format(optionals + positionals) | |||
|
283 | if prefix_width + len(action_usage) + 1 < text_width: | |||
|
284 | usage = '%s %s' % (usage, action_usage) | |||
|
285 | ||||
|
286 | # if they're long, wrap optionals and positionals individually | |||
|
287 | else: | |||
|
288 | optional_usage = format(optionals) | |||
|
289 | positional_usage = format(positionals) | |||
|
290 | indent = ' ' * prefix_indent | |||
|
291 | ||||
|
292 | # usage is made of PROG, optionals and positionals | |||
|
293 | parts = [usage, ' '] | |||
|
294 | ||||
|
295 | # options always get added right after PROG | |||
|
296 | if optional_usage: | |||
|
297 | parts.append(_textwrap.fill( | |||
|
298 | optional_usage, text_width, | |||
|
299 | initial_indent=indent, | |||
|
300 | subsequent_indent=indent).lstrip()) | |||
|
301 | ||||
|
302 | # if there were options, put arguments on the next line | |||
|
303 | # otherwise, start them right after PROG | |||
|
304 | if positional_usage: | |||
|
305 | part = _textwrap.fill( | |||
|
306 | positional_usage, text_width, | |||
|
307 | initial_indent=indent, | |||
|
308 | subsequent_indent=indent).lstrip() | |||
|
309 | if optional_usage: | |||
|
310 | part = '\n' + indent + part | |||
|
311 | parts.append(part) | |||
|
312 | usage = ''.join(parts) | |||
|
313 | ||||
|
314 | # prefix with 'usage:' | |||
|
315 | return '%s%s\n\n' % (prefix, usage) | |||
|
316 | ||||
|
317 | def _format_actions_usage(self, actions): | |||
|
318 | parts = [] | |||
|
319 | for action in actions: | |||
|
320 | if action.help is SUPPRESS: | |||
|
321 | continue | |||
|
322 | ||||
|
323 | # produce all arg strings | |||
|
324 | if not action.option_strings: | |||
|
325 | parts.append(self._format_args(action, action.dest)) | |||
|
326 | ||||
|
327 | # produce the first way to invoke the option in brackets | |||
|
328 | else: | |||
|
329 | option_string = action.option_strings[0] | |||
|
330 | ||||
|
331 | # if the Optional doesn't take a value, format is: | |||
|
332 | # -s or --long | |||
|
333 | if action.nargs == 0: | |||
|
334 | part = '%s' % option_string | |||
|
335 | ||||
|
336 | # if the Optional takes a value, format is: | |||
|
337 | # -s ARGS or --long ARGS | |||
|
338 | else: | |||
|
339 | default = action.dest.upper() | |||
|
340 | args_string = self._format_args(action, default) | |||
|
341 | part = '%s %s' % (option_string, args_string) | |||
|
342 | ||||
|
343 | # make it look optional if it's not required | |||
|
344 | if not action.required: | |||
|
345 | part = '[%s]' % part | |||
|
346 | parts.append(part) | |||
|
347 | ||||
|
348 | return ' '.join(parts) | |||
|
349 | ||||
|
350 | def _format_text(self, text): | |||
|
351 | text_width = self._width - self._current_indent | |||
|
352 | indent = ' ' * self._current_indent | |||
|
353 | return self._fill_text(text, text_width, indent) + '\n\n' | |||
|
354 | ||||
|
355 | def _format_action(self, action): | |||
|
356 | # determine the required width and the entry label | |||
|
357 | help_position = min(self._action_max_length + 2, | |||
|
358 | self._max_help_position) | |||
|
359 | help_width = self._width - help_position | |||
|
360 | action_width = help_position - self._current_indent - 2 | |||
|
361 | action_header = self._format_action_invocation(action) | |||
|
362 | ||||
|
363 | # ho nelp; start on same line and add a final newline | |||
|
364 | if not action.help: | |||
|
365 | tup = self._current_indent, '', action_header | |||
|
366 | action_header = '%*s%s\n' % tup | |||
|
367 | ||||
|
368 | # short action name; start on the same line and pad two spaces | |||
|
369 | elif len(action_header) <= action_width: | |||
|
370 | tup = self._current_indent, '', action_width, action_header | |||
|
371 | action_header = '%*s%-*s ' % tup | |||
|
372 | indent_first = 0 | |||
|
373 | ||||
|
374 | # long action name; start on the next line | |||
|
375 | else: | |||
|
376 | tup = self._current_indent, '', action_header | |||
|
377 | action_header = '%*s%s\n' % tup | |||
|
378 | indent_first = help_position | |||
|
379 | ||||
|
380 | # collect the pieces of the action help | |||
|
381 | parts = [action_header] | |||
|
382 | ||||
|
383 | # if there was help for the action, add lines of help text | |||
|
384 | if action.help: | |||
|
385 | help_text = self._expand_help(action) | |||
|
386 | help_lines = self._split_lines(help_text, help_width) | |||
|
387 | parts.append('%*s%s\n' % (indent_first, '', help_lines[0])) | |||
|
388 | for line in help_lines[1:]: | |||
|
389 | parts.append('%*s%s\n' % (help_position, '', line)) | |||
|
390 | ||||
|
391 | # or add a newline if the description doesn't end with one | |||
|
392 | elif not action_header.endswith('\n'): | |||
|
393 | parts.append('\n') | |||
|
394 | ||||
|
395 | # if there are any sub-actions, add their help as well | |||
|
396 | for subaction in self._iter_indented_subactions(action): | |||
|
397 | parts.append(self._format_action(subaction)) | |||
|
398 | ||||
|
399 | # return a single string | |||
|
400 | return self._join_parts(parts) | |||
|
401 | ||||
|
402 | def _format_action_invocation(self, action): | |||
|
403 | if not action.option_strings: | |||
|
404 | return self._format_metavar(action, action.dest) | |||
|
405 | ||||
|
406 | else: | |||
|
407 | parts = [] | |||
|
408 | ||||
|
409 | # if the Optional doesn't take a value, format is: | |||
|
410 | # -s, --long | |||
|
411 | if action.nargs == 0: | |||
|
412 | parts.extend(action.option_strings) | |||
|
413 | ||||
|
414 | # if the Optional takes a value, format is: | |||
|
415 | # -s ARGS, --long ARGS | |||
|
416 | else: | |||
|
417 | default = action.dest.upper() | |||
|
418 | args_string = self._format_args(action, default) | |||
|
419 | for option_string in action.option_strings: | |||
|
420 | parts.append('%s %s' % (option_string, args_string)) | |||
|
421 | ||||
|
422 | return ', '.join(parts) | |||
|
423 | ||||
|
424 | def _format_metavar(self, action, default_metavar): | |||
|
425 | if action.metavar is not None: | |||
|
426 | name = action.metavar | |||
|
427 | elif action.choices is not None: | |||
|
428 | choice_strs = (str(choice) for choice in action.choices) | |||
|
429 | name = '{%s}' % ','.join(choice_strs) | |||
|
430 | else: | |||
|
431 | name = default_metavar | |||
|
432 | return name | |||
|
433 | ||||
|
434 | def _format_args(self, action, default_metavar): | |||
|
435 | name = self._format_metavar(action, default_metavar) | |||
|
436 | if action.nargs is None: | |||
|
437 | result = name | |||
|
438 | elif action.nargs == OPTIONAL: | |||
|
439 | result = '[%s]' % name | |||
|
440 | elif action.nargs == ZERO_OR_MORE: | |||
|
441 | result = '[%s [%s ...]]' % (name, name) | |||
|
442 | elif action.nargs == ONE_OR_MORE: | |||
|
443 | result = '%s [%s ...]' % (name, name) | |||
|
444 | elif action.nargs is PARSER: | |||
|
445 | result = '%s ...' % name | |||
|
446 | else: | |||
|
447 | result = ' '.join([name] * action.nargs) | |||
|
448 | return result | |||
|
449 | ||||
|
450 | def _expand_help(self, action): | |||
|
451 | params = dict(vars(action), prog=self._prog) | |||
|
452 | for name, value in params.items(): | |||
|
453 | if value is SUPPRESS: | |||
|
454 | del params[name] | |||
|
455 | if params.get('choices') is not None: | |||
|
456 | choices_str = ', '.join(str(c) for c in params['choices']) | |||
|
457 | params['choices'] = choices_str | |||
|
458 | return action.help % params | |||
|
459 | ||||
|
460 | def _iter_indented_subactions(self, action): | |||
|
461 | try: | |||
|
462 | get_subactions = action._get_subactions | |||
|
463 | except AttributeError: | |||
|
464 | pass | |||
|
465 | else: | |||
|
466 | self._indent() | |||
|
467 | for subaction in get_subactions(): | |||
|
468 | yield subaction | |||
|
469 | self._dedent() | |||
|
470 | ||||
|
471 | def _split_lines(self, text, width): | |||
|
472 | text = self._whitespace_matcher.sub(' ', text).strip() | |||
|
473 | return _textwrap.wrap(text, width) | |||
|
474 | ||||
|
475 | def _fill_text(self, text, width, indent): | |||
|
476 | text = self._whitespace_matcher.sub(' ', text).strip() | |||
|
477 | return _textwrap.fill(text, width, initial_indent=indent, | |||
|
478 | subsequent_indent=indent) | |||
|
479 | ||||
|
480 | class RawDescriptionHelpFormatter(HelpFormatter): | |||
|
481 | ||||
|
482 | def _fill_text(self, text, width, indent): | |||
|
483 | return ''.join(indent + line for line in text.splitlines(True)) | |||
|
484 | ||||
|
485 | class RawTextHelpFormatter(RawDescriptionHelpFormatter): | |||
|
486 | ||||
|
487 | def _split_lines(self, text, width): | |||
|
488 | return text.splitlines() | |||
|
489 | ||||
|
490 | # ===================== | |||
|
491 | # Options and Arguments | |||
|
492 | # ===================== | |||
|
493 | ||||
|
494 | class ArgumentError(Exception): | |||
|
495 | """ArgumentError(message, argument) | |||
|
496 | ||||
|
497 | Raised whenever there was an error creating or using an argument | |||
|
498 | (optional or positional). | |||
|
499 | ||||
|
500 | The string value of this exception is the message, augmented with | |||
|
501 | information about the argument that caused it. | |||
|
502 | """ | |||
|
503 | ||||
|
504 | def __init__(self, argument, message): | |||
|
505 | if argument.option_strings: | |||
|
506 | self.argument_name = '/'.join(argument.option_strings) | |||
|
507 | elif argument.metavar not in (None, SUPPRESS): | |||
|
508 | self.argument_name = argument.metavar | |||
|
509 | elif argument.dest not in (None, SUPPRESS): | |||
|
510 | self.argument_name = argument.dest | |||
|
511 | else: | |||
|
512 | self.argument_name = None | |||
|
513 | self.message = message | |||
|
514 | ||||
|
515 | def __str__(self): | |||
|
516 | if self.argument_name is None: | |||
|
517 | format = '%(message)s' | |||
|
518 | else: | |||
|
519 | format = 'argument %(argument_name)s: %(message)s' | |||
|
520 | return format % dict(message=self.message, | |||
|
521 | argument_name=self.argument_name) | |||
|
522 | ||||
|
523 | # ============== | |||
|
524 | # Action classes | |||
|
525 | # ============== | |||
|
526 | ||||
|
527 | class Action(_AttributeHolder): | |||
|
528 | """Action(*strings, **options) | |||
|
529 | ||||
|
530 | Action objects hold the information necessary to convert a | |||
|
531 | set of command-line arguments (possibly including an initial option | |||
|
532 | string) into the desired Python object(s). | |||
|
533 | ||||
|
534 | Keyword Arguments: | |||
|
535 | ||||
|
536 | option_strings -- A list of command-line option strings which | |||
|
537 | should be associated with this action. | |||
|
538 | ||||
|
539 | dest -- The name of the attribute to hold the created object(s) | |||
|
540 | ||||
|
541 | nargs -- The number of command-line arguments that should be consumed. | |||
|
542 | By default, one argument will be consumed and a single value will | |||
|
543 | be produced. Other values include: | |||
|
544 | * N (an integer) consumes N arguments (and produces a list) | |||
|
545 | * '?' consumes zero or one arguments | |||
|
546 | * '*' consumes zero or more arguments (and produces a list) | |||
|
547 | * '+' consumes one or more arguments (and produces a list) | |||
|
548 | Note that the difference between the default and nargs=1 is that | |||
|
549 | with the default, a single value will be produced, while with | |||
|
550 | nargs=1, a list containing a single value will be produced. | |||
|
551 | ||||
|
552 | const -- The value to be produced if the option is specified and the | |||
|
553 | option uses an action that takes no values. | |||
|
554 | ||||
|
555 | default -- The value to be produced if the option is not specified. | |||
|
556 | ||||
|
557 | type -- The type which the command-line arguments should be converted | |||
|
558 | to, should be one of 'string', 'int', 'float', 'complex' or a | |||
|
559 | callable object that accepts a single string argument. If None, | |||
|
560 | 'string' is assumed. | |||
|
561 | ||||
|
562 | choices -- A container of values that should be allowed. If not None, | |||
|
563 | after a command-line argument has been converted to the appropriate | |||
|
564 | type, an exception will be raised if it is not a member of this | |||
|
565 | collection. | |||
|
566 | ||||
|
567 | required -- True if the action must always be specified at the command | |||
|
568 | line. This is only meaningful for optional command-line arguments. | |||
|
569 | ||||
|
570 | help -- The help string describing the argument. | |||
|
571 | ||||
|
572 | metavar -- The name to be used for the option's argument with the help | |||
|
573 | string. If None, the 'dest' value will be used as the name. | |||
|
574 | """ | |||
|
575 | ||||
|
576 | ||||
|
577 | def __init__(self, | |||
|
578 | option_strings, | |||
|
579 | dest, | |||
|
580 | nargs=None, | |||
|
581 | const=None, | |||
|
582 | default=None, | |||
|
583 | type=None, | |||
|
584 | choices=None, | |||
|
585 | required=False, | |||
|
586 | help=None, | |||
|
587 | metavar=None): | |||
|
588 | self.option_strings = option_strings | |||
|
589 | self.dest = dest | |||
|
590 | self.nargs = nargs | |||
|
591 | self.const = const | |||
|
592 | self.default = default | |||
|
593 | self.type = type | |||
|
594 | self.choices = choices | |||
|
595 | self.required = required | |||
|
596 | self.help = help | |||
|
597 | self.metavar = metavar | |||
|
598 | ||||
|
599 | def _get_kwargs(self): | |||
|
600 | names = [ | |||
|
601 | 'option_strings', | |||
|
602 | 'dest', | |||
|
603 | 'nargs', | |||
|
604 | 'const', | |||
|
605 | 'default', | |||
|
606 | 'type', | |||
|
607 | 'choices', | |||
|
608 | 'help', | |||
|
609 | 'metavar' | |||
|
610 | ] | |||
|
611 | return [(name, getattr(self, name)) for name in names] | |||
|
612 | ||||
|
613 | def __call__(self, parser, namespace, values, option_string=None): | |||
|
614 | raise NotImplementedError(_('.__call__() not defined')) | |||
|
615 | ||||
|
616 | class _StoreAction(Action): | |||
|
617 | def __init__(self, | |||
|
618 | option_strings, | |||
|
619 | dest, | |||
|
620 | nargs=None, | |||
|
621 | const=None, | |||
|
622 | default=None, | |||
|
623 | type=None, | |||
|
624 | choices=None, | |||
|
625 | required=False, | |||
|
626 | help=None, | |||
|
627 | metavar=None): | |||
|
628 | if nargs == 0: | |||
|
629 | raise ValueError('nargs must be > 0') | |||
|
630 | if const is not None and nargs != OPTIONAL: | |||
|
631 | raise ValueError('nargs must be %r to supply const' % OPTIONAL) | |||
|
632 | super(_StoreAction, self).__init__( | |||
|
633 | option_strings=option_strings, | |||
|
634 | dest=dest, | |||
|
635 | nargs=nargs, | |||
|
636 | const=const, | |||
|
637 | default=default, | |||
|
638 | type=type, | |||
|
639 | choices=choices, | |||
|
640 | required=required, | |||
|
641 | help=help, | |||
|
642 | metavar=metavar) | |||
|
643 | ||||
|
644 | def __call__(self, parser, namespace, values, option_string=None): | |||
|
645 | setattr(namespace, self.dest, values) | |||
|
646 | ||||
|
647 | class _StoreConstAction(Action): | |||
|
648 | def __init__(self, | |||
|
649 | option_strings, | |||
|
650 | dest, | |||
|
651 | const, | |||
|
652 | default=None, | |||
|
653 | required=False, | |||
|
654 | help=None, | |||
|
655 | metavar=None): | |||
|
656 | super(_StoreConstAction, self).__init__( | |||
|
657 | option_strings=option_strings, | |||
|
658 | dest=dest, | |||
|
659 | nargs=0, | |||
|
660 | const=const, | |||
|
661 | default=default, | |||
|
662 | required=required, | |||
|
663 | help=help) | |||
|
664 | ||||
|
665 | def __call__(self, parser, namespace, values, option_string=None): | |||
|
666 | setattr(namespace, self.dest, self.const) | |||
|
667 | ||||
|
668 | class _StoreTrueAction(_StoreConstAction): | |||
|
669 | def __init__(self, | |||
|
670 | option_strings, | |||
|
671 | dest, | |||
|
672 | default=False, | |||
|
673 | required=False, | |||
|
674 | help=None): | |||
|
675 | super(_StoreTrueAction, self).__init__( | |||
|
676 | option_strings=option_strings, | |||
|
677 | dest=dest, | |||
|
678 | const=True, | |||
|
679 | default=default, | |||
|
680 | required=required, | |||
|
681 | help=help) | |||
|
682 | ||||
|
683 | class _StoreFalseAction(_StoreConstAction): | |||
|
684 | def __init__(self, | |||
|
685 | option_strings, | |||
|
686 | dest, | |||
|
687 | default=True, | |||
|
688 | required=False, | |||
|
689 | help=None): | |||
|
690 | super(_StoreFalseAction, self).__init__( | |||
|
691 | option_strings=option_strings, | |||
|
692 | dest=dest, | |||
|
693 | const=False, | |||
|
694 | default=default, | |||
|
695 | required=required, | |||
|
696 | help=help) | |||
|
697 | ||||
|
698 | class _AppendAction(Action): | |||
|
699 | def __init__(self, | |||
|
700 | option_strings, | |||
|
701 | dest, | |||
|
702 | nargs=None, | |||
|
703 | const=None, | |||
|
704 | default=None, | |||
|
705 | type=None, | |||
|
706 | choices=None, | |||
|
707 | required=False, | |||
|
708 | help=None, | |||
|
709 | metavar=None): | |||
|
710 | if nargs == 0: | |||
|
711 | raise ValueError('nargs must be > 0') | |||
|
712 | if const is not None and nargs != OPTIONAL: | |||
|
713 | raise ValueError('nargs must be %r to supply const' % OPTIONAL) | |||
|
714 | super(_AppendAction, self).__init__( | |||
|
715 | option_strings=option_strings, | |||
|
716 | dest=dest, | |||
|
717 | nargs=nargs, | |||
|
718 | const=const, | |||
|
719 | default=default, | |||
|
720 | type=type, | |||
|
721 | choices=choices, | |||
|
722 | required=required, | |||
|
723 | help=help, | |||
|
724 | metavar=metavar) | |||
|
725 | ||||
|
726 | def __call__(self, parser, namespace, values, option_string=None): | |||
|
727 | _ensure_value(namespace, self.dest, []).append(values) | |||
|
728 | ||||
|
729 | class _AppendConstAction(Action): | |||
|
730 | def __init__(self, | |||
|
731 | option_strings, | |||
|
732 | dest, | |||
|
733 | const, | |||
|
734 | default=None, | |||
|
735 | required=False, | |||
|
736 | help=None, | |||
|
737 | metavar=None): | |||
|
738 | super(_AppendConstAction, self).__init__( | |||
|
739 | option_strings=option_strings, | |||
|
740 | dest=dest, | |||
|
741 | nargs=0, | |||
|
742 | const=const, | |||
|
743 | default=default, | |||
|
744 | required=required, | |||
|
745 | help=help, | |||
|
746 | metavar=metavar) | |||
|
747 | ||||
|
748 | def __call__(self, parser, namespace, values, option_string=None): | |||
|
749 | _ensure_value(namespace, self.dest, []).append(self.const) | |||
|
750 | ||||
|
751 | class _CountAction(Action): | |||
|
752 | def __init__(self, | |||
|
753 | option_strings, | |||
|
754 | dest, | |||
|
755 | default=None, | |||
|
756 | required=False, | |||
|
757 | help=None): | |||
|
758 | super(_CountAction, self).__init__( | |||
|
759 | option_strings=option_strings, | |||
|
760 | dest=dest, | |||
|
761 | nargs=0, | |||
|
762 | default=default, | |||
|
763 | required=required, | |||
|
764 | help=help) | |||
|
765 | ||||
|
766 | def __call__(self, parser, namespace, values, option_string=None): | |||
|
767 | new_count = _ensure_value(namespace, self.dest, 0) + 1 | |||
|
768 | setattr(namespace, self.dest, new_count) | |||
|
769 | ||||
|
770 | class _HelpAction(Action): | |||
|
771 | def __init__(self, | |||
|
772 | option_strings, | |||
|
773 | dest=SUPPRESS, | |||
|
774 | default=SUPPRESS, | |||
|
775 | help=None): | |||
|
776 | super(_HelpAction, self).__init__( | |||
|
777 | option_strings=option_strings, | |||
|
778 | dest=dest, | |||
|
779 | default=default, | |||
|
780 | nargs=0, | |||
|
781 | help=help) | |||
|
782 | ||||
|
783 | def __call__(self, parser, namespace, values, option_string=None): | |||
|
784 | parser.print_help() | |||
|
785 | parser.exit() | |||
|
786 | ||||
|
787 | class _VersionAction(Action): | |||
|
788 | def __init__(self, | |||
|
789 | option_strings, | |||
|
790 | dest=SUPPRESS, | |||
|
791 | default=SUPPRESS, | |||
|
792 | help=None): | |||
|
793 | super(_VersionAction, self).__init__( | |||
|
794 | option_strings=option_strings, | |||
|
795 | dest=dest, | |||
|
796 | default=default, | |||
|
797 | nargs=0, | |||
|
798 | help=help) | |||
|
799 | ||||
|
800 | def __call__(self, parser, namespace, values, option_string=None): | |||
|
801 | parser.print_version() | |||
|
802 | parser.exit() | |||
|
803 | ||||
|
804 | class _SubParsersAction(Action): | |||
|
805 | ||||
|
806 | class _ChoicesPseudoAction(Action): | |||
|
807 | def __init__(self, name, help): | |||
|
808 | sup = super(_SubParsersAction._ChoicesPseudoAction, self) | |||
|
809 | sup.__init__(option_strings=[], dest=name, help=help) | |||
|
810 | ||||
|
811 | ||||
|
812 | def __init__(self, | |||
|
813 | option_strings, | |||
|
814 | prog, | |||
|
815 | parser_class, | |||
|
816 | dest=SUPPRESS, | |||
|
817 | help=None, | |||
|
818 | metavar=None): | |||
|
819 | ||||
|
820 | self._prog_prefix = prog | |||
|
821 | self._parser_class = parser_class | |||
|
822 | self._name_parser_map = {} | |||
|
823 | self._choices_actions = [] | |||
|
824 | ||||
|
825 | super(_SubParsersAction, self).__init__( | |||
|
826 | option_strings=option_strings, | |||
|
827 | dest=dest, | |||
|
828 | nargs=PARSER, | |||
|
829 | choices=self._name_parser_map, | |||
|
830 | help=help, | |||
|
831 | metavar=metavar) | |||
|
832 | ||||
|
833 | def add_parser(self, name, **kwargs): | |||
|
834 | # set prog from the existing prefix | |||
|
835 | if kwargs.get('prog') is None: | |||
|
836 | kwargs['prog'] = '%s %s' % (self._prog_prefix, name) | |||
|
837 | ||||
|
838 | # create a pseudo-action to hold the choice help | |||
|
839 | if 'help' in kwargs: | |||
|
840 | help = kwargs.pop('help') | |||
|
841 | choice_action = self._ChoicesPseudoAction(name, help) | |||
|
842 | self._choices_actions.append(choice_action) | |||
|
843 | ||||
|
844 | # create the parser and add it to the map | |||
|
845 | parser = self._parser_class(**kwargs) | |||
|
846 | self._name_parser_map[name] = parser | |||
|
847 | return parser | |||
|
848 | ||||
|
849 | def _get_subactions(self): | |||
|
850 | return self._choices_actions | |||
|
851 | ||||
|
852 | def __call__(self, parser, namespace, values, option_string=None): | |||
|
853 | parser_name = values[0] | |||
|
854 | arg_strings = values[1:] | |||
|
855 | ||||
|
856 | # set the parser name if requested | |||
|
857 | if self.dest is not SUPPRESS: | |||
|
858 | setattr(namespace, self.dest, parser_name) | |||
|
859 | ||||
|
860 | # select the parser | |||
|
861 | try: | |||
|
862 | parser = self._name_parser_map[parser_name] | |||
|
863 | except KeyError: | |||
|
864 | tup = parser_name, ', '.join(self._name_parser_map) | |||
|
865 | msg = _('unknown parser %r (choices: %s)' % tup) | |||
|
866 | raise ArgumentError(self, msg) | |||
|
867 | ||||
|
868 | # parse all the remaining options into the namespace | |||
|
869 | parser.parse_args(arg_strings, namespace) | |||
|
870 | ||||
|
871 | ||||
|
872 | # ============== | |||
|
873 | # Type classes | |||
|
874 | # ============== | |||
|
875 | ||||
|
876 | class FileType(object): | |||
|
877 | """Factory for creating file object types | |||
|
878 | ||||
|
879 | Instances of FileType are typically passed as type= arguments to the | |||
|
880 | ArgumentParser add_argument() method. | |||
|
881 | ||||
|
882 | Keyword Arguments: | |||
|
883 | mode -- A string indicating how the file is to be opened. Accepts the | |||
|
884 | same values as the builtin open() function. | |||
|
885 | bufsize -- The file's desired buffer size. Accepts the same values as | |||
|
886 | the builtin open() function. | |||
|
887 | """ | |||
|
888 | def __init__(self, mode='r', bufsize=None): | |||
|
889 | self._mode = mode | |||
|
890 | self._bufsize = bufsize | |||
|
891 | ||||
|
892 | def __call__(self, string): | |||
|
893 | # the special argument "-" means sys.std{in,out} | |||
|
894 | if string == '-': | |||
|
895 | if self._mode == 'r': | |||
|
896 | return _sys.stdin | |||
|
897 | elif self._mode == 'w': | |||
|
898 | return _sys.stdout | |||
|
899 | else: | |||
|
900 | msg = _('argument "-" with mode %r' % self._mode) | |||
|
901 | raise ValueError(msg) | |||
|
902 | ||||
|
903 | # all other arguments are used as file names | |||
|
904 | if self._bufsize: | |||
|
905 | return open(string, self._mode, self._bufsize) | |||
|
906 | else: | |||
|
907 | return open(string, self._mode) | |||
|
908 | ||||
|
909 | ||||
|
910 | # =========================== | |||
|
911 | # Optional and Positional Parsing | |||
|
912 | # =========================== | |||
|
913 | ||||
|
914 | class Namespace(_AttributeHolder): | |||
|
915 | ||||
|
916 | def __init__(self, **kwargs): | |||
|
917 | for name, value in kwargs.iteritems(): | |||
|
918 | setattr(self, name, value) | |||
|
919 | ||||
|
920 | def __eq__(self, other): | |||
|
921 | return vars(self) == vars(other) | |||
|
922 | ||||
|
923 | def __ne__(self, other): | |||
|
924 | return not (self == other) | |||
|
925 | ||||
|
926 | ||||
|
927 | class _ActionsContainer(object): | |||
|
928 | def __init__(self, | |||
|
929 | description, | |||
|
930 | prefix_chars, | |||
|
931 | argument_default, | |||
|
932 | conflict_handler): | |||
|
933 | super(_ActionsContainer, self).__init__() | |||
|
934 | ||||
|
935 | self.description = description | |||
|
936 | self.argument_default = argument_default | |||
|
937 | self.prefix_chars = prefix_chars | |||
|
938 | self.conflict_handler = conflict_handler | |||
|
939 | ||||
|
940 | # set up registries | |||
|
941 | self._registries = {} | |||
|
942 | ||||
|
943 | # register actions | |||
|
944 | self.register('action', None, _StoreAction) | |||
|
945 | self.register('action', 'store', _StoreAction) | |||
|
946 | self.register('action', 'store_const', _StoreConstAction) | |||
|
947 | self.register('action', 'store_true', _StoreTrueAction) | |||
|
948 | self.register('action', 'store_false', _StoreFalseAction) | |||
|
949 | self.register('action', 'append', _AppendAction) | |||
|
950 | self.register('action', 'append_const', _AppendConstAction) | |||
|
951 | self.register('action', 'count', _CountAction) | |||
|
952 | self.register('action', 'help', _HelpAction) | |||
|
953 | self.register('action', 'version', _VersionAction) | |||
|
954 | self.register('action', 'parsers', _SubParsersAction) | |||
|
955 | ||||
|
956 | # raise an exception if the conflict handler is invalid | |||
|
957 | self._get_handler() | |||
|
958 | ||||
|
959 | # action storage | |||
|
960 | self._optional_actions_list = [] | |||
|
961 | self._positional_actions_list = [] | |||
|
962 | self._positional_actions_full_list = [] | |||
|
963 | self._option_strings = {} | |||
|
964 | ||||
|
965 | # defaults storage | |||
|
966 | self._defaults = {} | |||
|
967 | ||||
|
968 | # ==================== | |||
|
969 | # Registration methods | |||
|
970 | # ==================== | |||
|
971 | ||||
|
972 | def register(self, registry_name, value, object): | |||
|
973 | registry = self._registries.setdefault(registry_name, {}) | |||
|
974 | registry[value] = object | |||
|
975 | ||||
|
976 | def _registry_get(self, registry_name, value, default=None): | |||
|
977 | return self._registries[registry_name].get(value, default) | |||
|
978 | ||||
|
979 | # ================================== | |||
|
980 | # Namespace default settings methods | |||
|
981 | # ================================== | |||
|
982 | ||||
|
983 | def set_defaults(self, **kwargs): | |||
|
984 | self._defaults.update(kwargs) | |||
|
985 | ||||
|
986 | # if these defaults match any existing arguments, replace | |||
|
987 | # the previous default on the object with the new one | |||
|
988 | for action_list in [self._option_strings.values(), | |||
|
989 | self._positional_actions_full_list]: | |||
|
990 | for action in action_list: | |||
|
991 | if action.dest in kwargs: | |||
|
992 | action.default = kwargs[action.dest] | |||
|
993 | ||||
|
994 | # ======================= | |||
|
995 | # Adding argument actions | |||
|
996 | # ======================= | |||
|
997 | ||||
|
998 | def add_argument(self, *args, **kwargs): | |||
|
999 | """ | |||
|
1000 | add_argument(dest, ..., name=value, ...) | |||
|
1001 | add_argument(option_string, option_string, ..., name=value, ...) | |||
|
1002 | """ | |||
|
1003 | ||||
|
1004 | # if no positional args are supplied or only one is supplied and | |||
|
1005 | # it doesn't look like an option string, parse a positional | |||
|
1006 | # argument | |||
|
1007 | chars = self.prefix_chars | |||
|
1008 | if not args or len(args) == 1 and args[0][0] not in chars: | |||
|
1009 | kwargs = self._get_positional_kwargs(*args, **kwargs) | |||
|
1010 | ||||
|
1011 | # otherwise, we're adding an optional argument | |||
|
1012 | else: | |||
|
1013 | kwargs = self._get_optional_kwargs(*args, **kwargs) | |||
|
1014 | ||||
|
1015 | # if no default was supplied, use the parser-level default | |||
|
1016 | if 'default' not in kwargs: | |||
|
1017 | dest = kwargs['dest'] | |||
|
1018 | if dest in self._defaults: | |||
|
1019 | kwargs['default'] = self._defaults[dest] | |||
|
1020 | elif self.argument_default is not None: | |||
|
1021 | kwargs['default'] = self.argument_default | |||
|
1022 | ||||
|
1023 | # create the action object, and add it to the parser | |||
|
1024 | action_class = self._pop_action_class(kwargs) | |||
|
1025 | action = action_class(**kwargs) | |||
|
1026 | return self._add_action(action) | |||
|
1027 | ||||
|
1028 | def _add_action(self, action): | |||
|
1029 | # resolve any conflicts | |||
|
1030 | self._check_conflict(action) | |||
|
1031 | ||||
|
1032 | # add to optional or positional list | |||
|
1033 | if action.option_strings: | |||
|
1034 | self._optional_actions_list.append(action) | |||
|
1035 | else: | |||
|
1036 | self._positional_actions_list.append(action) | |||
|
1037 | self._positional_actions_full_list.append(action) | |||
|
1038 | action.container = self | |||
|
1039 | ||||
|
1040 | # index the action by any option strings it has | |||
|
1041 | for option_string in action.option_strings: | |||
|
1042 | self._option_strings[option_string] = action | |||
|
1043 | ||||
|
1044 | # return the created action | |||
|
1045 | return action | |||
|
1046 | ||||
|
1047 | def _add_container_actions(self, container): | |||
|
1048 | for action in container._optional_actions_list: | |||
|
1049 | self._add_action(action) | |||
|
1050 | for action in container._positional_actions_list: | |||
|
1051 | self._add_action(action) | |||
|
1052 | ||||
|
1053 | def _get_positional_kwargs(self, dest, **kwargs): | |||
|
1054 | # make sure required is not specified | |||
|
1055 | if 'required' in kwargs: | |||
|
1056 | msg = _("'required' is an invalid argument for positionals") | |||
|
1057 | raise TypeError(msg) | |||
|
1058 | ||||
|
1059 | # return the keyword arguments with no option strings | |||
|
1060 | return dict(kwargs, dest=dest, option_strings=[]) | |||
|
1061 | ||||
|
1062 | def _get_optional_kwargs(self, *args, **kwargs): | |||
|
1063 | # determine short and long option strings | |||
|
1064 | option_strings = [] | |||
|
1065 | long_option_strings = [] | |||
|
1066 | for option_string in args: | |||
|
1067 | # error on one-or-fewer-character option strings | |||
|
1068 | if len(option_string) < 2: | |||
|
1069 | msg = _('invalid option string %r: ' | |||
|
1070 | 'must be at least two characters long') | |||
|
1071 | raise ValueError(msg % option_string) | |||
|
1072 | ||||
|
1073 | # error on strings that don't start with an appropriate prefix | |||
|
1074 | if not option_string[0] in self.prefix_chars: | |||
|
1075 | msg = _('invalid option string %r: ' | |||
|
1076 | 'must start with a character %r') | |||
|
1077 | tup = option_string, self.prefix_chars | |||
|
1078 | raise ValueError(msg % tup) | |||
|
1079 | ||||
|
1080 | # error on strings that are all prefix characters | |||
|
1081 | if not (set(option_string) - set(self.prefix_chars)): | |||
|
1082 | msg = _('invalid option string %r: ' | |||
|
1083 | 'must contain characters other than %r') | |||
|
1084 | tup = option_string, self.prefix_chars | |||
|
1085 | raise ValueError(msg % tup) | |||
|
1086 | ||||
|
1087 | # strings starting with two prefix characters are long options | |||
|
1088 | option_strings.append(option_string) | |||
|
1089 | if option_string[0] in self.prefix_chars: | |||
|
1090 | if option_string[1] in self.prefix_chars: | |||
|
1091 | long_option_strings.append(option_string) | |||
|
1092 | ||||
|
1093 | # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' | |||
|
1094 | dest = kwargs.pop('dest', None) | |||
|
1095 | if dest is None: | |||
|
1096 | if long_option_strings: | |||
|
1097 | dest_option_string = long_option_strings[0] | |||
|
1098 | else: | |||
|
1099 | dest_option_string = option_strings[0] | |||
|
1100 | dest = dest_option_string.lstrip(self.prefix_chars) | |||
|
1101 | dest = dest.replace('-', '_') | |||
|
1102 | ||||
|
1103 | # return the updated keyword arguments | |||
|
1104 | return dict(kwargs, dest=dest, option_strings=option_strings) | |||
|
1105 | ||||
|
1106 | def _pop_action_class(self, kwargs, default=None): | |||
|
1107 | action = kwargs.pop('action', default) | |||
|
1108 | return self._registry_get('action', action, action) | |||
|
1109 | ||||
|
1110 | def _get_handler(self): | |||
|
1111 | # determine function from conflict handler string | |||
|
1112 | handler_func_name = '_handle_conflict_%s' % self.conflict_handler | |||
|
1113 | try: | |||
|
1114 | return getattr(self, handler_func_name) | |||
|
1115 | except AttributeError: | |||
|
1116 | msg = _('invalid conflict_resolution value: %r') | |||
|
1117 | raise ValueError(msg % self.conflict_handler) | |||
|
1118 | ||||
|
1119 | def _check_conflict(self, action): | |||
|
1120 | ||||
|
1121 | # find all options that conflict with this option | |||
|
1122 | confl_optionals = [] | |||
|
1123 | for option_string in action.option_strings: | |||
|
1124 | if option_string in self._option_strings: | |||
|
1125 | confl_optional = self._option_strings[option_string] | |||
|
1126 | confl_optionals.append((option_string, confl_optional)) | |||
|
1127 | ||||
|
1128 | # resolve any conflicts | |||
|
1129 | if confl_optionals: | |||
|
1130 | conflict_handler = self._get_handler() | |||
|
1131 | conflict_handler(action, confl_optionals) | |||
|
1132 | ||||
|
1133 | def _handle_conflict_error(self, action, conflicting_actions): | |||
|
1134 | message = _('conflicting option string(s): %s') | |||
|
1135 | conflict_string = ', '.join(option_string | |||
|
1136 | for option_string, action | |||
|
1137 | in conflicting_actions) | |||
|
1138 | raise ArgumentError(action, message % conflict_string) | |||
|
1139 | ||||
|
1140 | def _handle_conflict_resolve(self, action, conflicting_actions): | |||
|
1141 | ||||
|
1142 | # remove all conflicting options | |||
|
1143 | for option_string, action in conflicting_actions: | |||
|
1144 | ||||
|
1145 | # remove the conflicting option | |||
|
1146 | action.option_strings.remove(option_string) | |||
|
1147 | self._option_strings.pop(option_string, None) | |||
|
1148 | ||||
|
1149 | # if the option now has no option string, remove it from the | |||
|
1150 | # container holding it | |||
|
1151 | if not action.option_strings: | |||
|
1152 | action.container._optional_actions_list.remove(action) | |||
|
1153 | ||||
|
1154 | ||||
|
1155 | class _ArgumentGroup(_ActionsContainer): | |||
|
1156 | ||||
|
1157 | def __init__(self, container, title=None, description=None, **kwargs): | |||
|
1158 | # add any missing keyword arguments by checking the container | |||
|
1159 | update = kwargs.setdefault | |||
|
1160 | update('conflict_handler', container.conflict_handler) | |||
|
1161 | update('prefix_chars', container.prefix_chars) | |||
|
1162 | update('argument_default', container.argument_default) | |||
|
1163 | super_init = super(_ArgumentGroup, self).__init__ | |||
|
1164 | super_init(description=description, **kwargs) | |||
|
1165 | ||||
|
1166 | self.title = title | |||
|
1167 | self._registries = container._registries | |||
|
1168 | self._positional_actions_full_list = container._positional_actions_full_list | |||
|
1169 | self._option_strings = container._option_strings | |||
|
1170 | self._defaults = container._defaults | |||
|
1171 | ||||
|
1172 | ||||
|
1173 | class ArgumentParser(_AttributeHolder, _ActionsContainer): | |||
|
1174 | ||||
|
1175 | def __init__(self, | |||
|
1176 | prog=None, | |||
|
1177 | usage=None, | |||
|
1178 | description=None, | |||
|
1179 | epilog=None, | |||
|
1180 | version=None, | |||
|
1181 | parents=[], | |||
|
1182 | formatter_class=HelpFormatter, | |||
|
1183 | prefix_chars='-', | |||
|
1184 | argument_default=None, | |||
|
1185 | conflict_handler='error', | |||
|
1186 | add_help=True): | |||
|
1187 | ||||
|
1188 | superinit = super(ArgumentParser, self).__init__ | |||
|
1189 | superinit(description=description, | |||
|
1190 | prefix_chars=prefix_chars, | |||
|
1191 | argument_default=argument_default, | |||
|
1192 | conflict_handler=conflict_handler) | |||
|
1193 | ||||
|
1194 | # default setting for prog | |||
|
1195 | if prog is None: | |||
|
1196 | prog = _os.path.basename(_sys.argv[0]) | |||
|
1197 | ||||
|
1198 | self.prog = prog | |||
|
1199 | self.usage = usage | |||
|
1200 | self.epilog = epilog | |||
|
1201 | self.version = version | |||
|
1202 | self.formatter_class = formatter_class | |||
|
1203 | self.add_help = add_help | |||
|
1204 | ||||
|
1205 | self._argument_group_class = _ArgumentGroup | |||
|
1206 | self._has_subparsers = False | |||
|
1207 | self._argument_groups = [] | |||
|
1208 | ||||
|
1209 | # register types | |||
|
1210 | def identity(string): | |||
|
1211 | return string | |||
|
1212 | self.register('type', None, identity) | |||
|
1213 | ||||
|
1214 | # add help and version arguments if necessary | |||
|
1215 | # (using explicit default to override global argument_default) | |||
|
1216 | if self.add_help: | |||
|
1217 | self.add_argument( | |||
|
1218 | '-h', '--help', action='help', default=SUPPRESS, | |||
|
1219 | help=_('show this help message and exit')) | |||
|
1220 | if self.version: | |||
|
1221 | self.add_argument( | |||
|
1222 | '-v', '--version', action='version', default=SUPPRESS, | |||
|
1223 | help=_("show program's version number and exit")) | |||
|
1224 | ||||
|
1225 | # add parent arguments and defaults | |||
|
1226 | for parent in parents: | |||
|
1227 | self._add_container_actions(parent) | |||
|
1228 | try: | |||
|
1229 | defaults = parent._defaults | |||
|
1230 | except AttributeError: | |||
|
1231 | pass | |||
|
1232 | else: | |||
|
1233 | self._defaults.update(defaults) | |||
|
1234 | ||||
|
1235 | # determines whether an "option" looks like a negative number | |||
|
1236 | self._negative_number_matcher = _re.compile(r'^-\d+|-\d*.\d+$') | |||
|
1237 | ||||
|
1238 | ||||
|
1239 | # ======================= | |||
|
1240 | # Pretty __repr__ methods | |||
|
1241 | # ======================= | |||
|
1242 | ||||
|
1243 | def _get_kwargs(self): | |||
|
1244 | names = [ | |||
|
1245 | 'prog', | |||
|
1246 | 'usage', | |||
|
1247 | 'description', | |||
|
1248 | 'version', | |||
|
1249 | 'formatter_class', | |||
|
1250 | 'conflict_handler', | |||
|
1251 | 'add_help', | |||
|
1252 | ] | |||
|
1253 | return [(name, getattr(self, name)) for name in names] | |||
|
1254 | ||||
|
1255 | # ================================== | |||
|
1256 | # Optional/Positional adding methods | |||
|
1257 | # ================================== | |||
|
1258 | ||||
|
1259 | def add_argument_group(self, *args, **kwargs): | |||
|
1260 | group = self._argument_group_class(self, *args, **kwargs) | |||
|
1261 | self._argument_groups.append(group) | |||
|
1262 | return group | |||
|
1263 | ||||
|
1264 | def add_subparsers(self, **kwargs): | |||
|
1265 | if self._has_subparsers: | |||
|
1266 | self.error(_('cannot have multiple subparser arguments')) | |||
|
1267 | ||||
|
1268 | # add the parser class to the arguments if it's not present | |||
|
1269 | kwargs.setdefault('parser_class', type(self)) | |||
|
1270 | ||||
|
1271 | # prog defaults to the usage message of this parser, skipping | |||
|
1272 | # optional arguments and with no "usage:" prefix | |||
|
1273 | if kwargs.get('prog') is None: | |||
|
1274 | formatter = self._get_formatter() | |||
|
1275 | formatter.add_usage(self.usage, [], | |||
|
1276 | self._get_positional_actions(), '') | |||
|
1277 | kwargs['prog'] = formatter.format_help().strip() | |||
|
1278 | ||||
|
1279 | # create the parsers action and add it to the positionals list | |||
|
1280 | parsers_class = self._pop_action_class(kwargs, 'parsers') | |||
|
1281 | action = parsers_class(option_strings=[], **kwargs) | |||
|
1282 | self._positional_actions_list.append(action) | |||
|
1283 | self._positional_actions_full_list.append(action) | |||
|
1284 | self._has_subparsers = True | |||
|
1285 | ||||
|
1286 | # return the created parsers action | |||
|
1287 | return action | |||
|
1288 | ||||
|
1289 | def _add_container_actions(self, container): | |||
|
1290 | super(ArgumentParser, self)._add_container_actions(container) | |||
|
1291 | try: | |||
|
1292 | groups = container._argument_groups | |||
|
1293 | except AttributeError: | |||
|
1294 | pass | |||
|
1295 | else: | |||
|
1296 | for group in groups: | |||
|
1297 | new_group = self.add_argument_group( | |||
|
1298 | title=group.title, | |||
|
1299 | description=group.description, | |||
|
1300 | conflict_handler=group.conflict_handler) | |||
|
1301 | new_group._add_container_actions(group) | |||
|
1302 | ||||
|
1303 | def _get_optional_actions(self): | |||
|
1304 | actions = [] | |||
|
1305 | actions.extend(self._optional_actions_list) | |||
|
1306 | for argument_group in self._argument_groups: | |||
|
1307 | actions.extend(argument_group._optional_actions_list) | |||
|
1308 | return actions | |||
|
1309 | ||||
|
1310 | def _get_positional_actions(self): | |||
|
1311 | return list(self._positional_actions_full_list) | |||
|
1312 | ||||
|
1313 | ||||
|
1314 | # ===================================== | |||
|
1315 | # Command line argument parsing methods | |||
|
1316 | # ===================================== | |||
|
1317 | ||||
|
1318 | def parse_args(self, args=None, namespace=None): | |||
|
1319 | # args default to the system args | |||
|
1320 | if args is None: | |||
|
1321 | args = _sys.argv[1:] | |||
|
1322 | ||||
|
1323 | # default Namespace built from parser defaults | |||
|
1324 | if namespace is None: | |||
|
1325 | namespace = Namespace() | |||
|
1326 | ||||
|
1327 | # add any action defaults that aren't present | |||
|
1328 | optional_actions = self._get_optional_actions() | |||
|
1329 | positional_actions = self._get_positional_actions() | |||
|
1330 | for action in optional_actions + positional_actions: | |||
|
1331 | if action.dest is not SUPPRESS: | |||
|
1332 | if not hasattr(namespace, action.dest): | |||
|
1333 | if action.default is not SUPPRESS: | |||
|
1334 | default = action.default | |||
|
1335 | if isinstance(action.default, basestring): | |||
|
1336 | default = self._get_value(action, default) | |||
|
1337 | setattr(namespace, action.dest, default) | |||
|
1338 | ||||
|
1339 | # add any parser defaults that aren't present | |||
|
1340 | for dest, value in self._defaults.iteritems(): | |||
|
1341 | if not hasattr(namespace, dest): | |||
|
1342 | setattr(namespace, dest, value) | |||
|
1343 | ||||
|
1344 | # parse the arguments and exit if there are any errors | |||
|
1345 | try: | |||
|
1346 | result = self._parse_args(args, namespace) | |||
|
1347 | except ArgumentError, err: | |||
|
1348 | self.error(str(err)) | |||
|
1349 | ||||
|
1350 | # make sure all required optionals are present | |||
|
1351 | for action in self._get_optional_actions(): | |||
|
1352 | if action.required: | |||
|
1353 | if getattr(result, action.dest, None) is None: | |||
|
1354 | opt_strs = '/'.join(action.option_strings) | |||
|
1355 | msg = _('option %s is required' % opt_strs) | |||
|
1356 | self.error(msg) | |||
|
1357 | ||||
|
1358 | # return the parsed arguments | |||
|
1359 | return result | |||
|
1360 | ||||
|
1361 | def _parse_args(self, arg_strings, namespace): | |||
|
1362 | ||||
|
1363 | # find all option indices, and determine the arg_string_pattern | |||
|
1364 | # which has an 'O' if there is an option at an index, | |||
|
1365 | # an 'A' if there is an argument, or a '-' if there is a '--' | |||
|
1366 | option_string_indices = {} | |||
|
1367 | arg_string_pattern_parts = [] | |||
|
1368 | arg_strings_iter = iter(arg_strings) | |||
|
1369 | for i, arg_string in enumerate(arg_strings_iter): | |||
|
1370 | ||||
|
1371 | # all args after -- are non-options | |||
|
1372 | if arg_string == '--': | |||
|
1373 | arg_string_pattern_parts.append('-') | |||
|
1374 | for arg_string in arg_strings_iter: | |||
|
1375 | arg_string_pattern_parts.append('A') | |||
|
1376 | ||||
|
1377 | # otherwise, add the arg to the arg strings | |||
|
1378 | # and note the index if it was an option | |||
|
1379 | else: | |||
|
1380 | option_tuple = self._parse_optional(arg_string) | |||
|
1381 | if option_tuple is None: | |||
|
1382 | pattern = 'A' | |||
|
1383 | else: | |||
|
1384 | option_string_indices[i] = option_tuple | |||
|
1385 | pattern = 'O' | |||
|
1386 | arg_string_pattern_parts.append(pattern) | |||
|
1387 | ||||
|
1388 | # join the pieces together to form the pattern | |||
|
1389 | arg_strings_pattern = ''.join(arg_string_pattern_parts) | |||
|
1390 | ||||
|
1391 | # converts arg strings to the appropriate and then takes the action | |||
|
1392 | def take_action(action, argument_strings, option_string=None): | |||
|
1393 | argument_values = self._get_values(action, argument_strings) | |||
|
1394 | # take the action if we didn't receive a SUPPRESS value | |||
|
1395 | # (e.g. from a default) | |||
|
1396 | if argument_values is not SUPPRESS: | |||
|
1397 | action(self, namespace, argument_values, option_string) | |||
|
1398 | ||||
|
1399 | # function to convert arg_strings into an optional action | |||
|
1400 | def consume_optional(start_index): | |||
|
1401 | ||||
|
1402 | # determine the optional action and parse any explicit | |||
|
1403 | # argument out of the option string | |||
|
1404 | option_tuple = option_string_indices[start_index] | |||
|
1405 | action, option_string, explicit_arg = option_tuple | |||
|
1406 | ||||
|
1407 | # loop because single-dash options can be chained | |||
|
1408 | # (e.g. -xyz is the same as -x -y -z if no args are required) | |||
|
1409 | match_argument = self._match_argument | |||
|
1410 | action_tuples = [] | |||
|
1411 | while True: | |||
|
1412 | ||||
|
1413 | # if we found no optional action, raise an error | |||
|
1414 | if action is None: | |||
|
1415 | self.error(_('no such option: %s') % option_string) | |||
|
1416 | ||||
|
1417 | # if there is an explicit argument, try to match the | |||
|
1418 | # optional's string arguments to only this | |||
|
1419 | if explicit_arg is not None: | |||
|
1420 | arg_count = match_argument(action, 'A') | |||
|
1421 | ||||
|
1422 | # if the action is a single-dash option and takes no | |||
|
1423 | # arguments, try to parse more single-dash options out | |||
|
1424 | # of the tail of the option string | |||
|
1425 | chars = self.prefix_chars | |||
|
1426 | if arg_count == 0 and option_string[1] not in chars: | |||
|
1427 | action_tuples.append((action, [], option_string)) | |||
|
1428 | parse_optional = self._parse_optional | |||
|
1429 | for char in self.prefix_chars: | |||
|
1430 | option_string = char + explicit_arg | |||
|
1431 | option_tuple = parse_optional(option_string) | |||
|
1432 | if option_tuple[0] is not None: | |||
|
1433 | break | |||
|
1434 | else: | |||
|
1435 | msg = _('ignored explicit argument %r') | |||
|
1436 | raise ArgumentError(action, msg % explicit_arg) | |||
|
1437 | ||||
|
1438 | # set the action, etc. for the next loop iteration | |||
|
1439 | action, option_string, explicit_arg = option_tuple | |||
|
1440 | ||||
|
1441 | # if the action expect exactly one argument, we've | |||
|
1442 | # successfully matched the option; exit the loop | |||
|
1443 | elif arg_count == 1: | |||
|
1444 | stop = start_index + 1 | |||
|
1445 | args = [explicit_arg] | |||
|
1446 | action_tuples.append((action, args, option_string)) | |||
|
1447 | break | |||
|
1448 | ||||
|
1449 | # error if a double-dash option did not use the | |||
|
1450 | # explicit argument | |||
|
1451 | else: | |||
|
1452 | msg = _('ignored explicit argument %r') | |||
|
1453 | raise ArgumentError(action, msg % explicit_arg) | |||
|
1454 | ||||
|
1455 | # if there is no explicit argument, try to match the | |||
|
1456 | # optional's string arguments with the following strings | |||
|
1457 | # if successful, exit the loop | |||
|
1458 | else: | |||
|
1459 | start = start_index + 1 | |||
|
1460 | selected_patterns = arg_strings_pattern[start:] | |||
|
1461 | arg_count = match_argument(action, selected_patterns) | |||
|
1462 | stop = start + arg_count | |||
|
1463 | args = arg_strings[start:stop] | |||
|
1464 | action_tuples.append((action, args, option_string)) | |||
|
1465 | break | |||
|
1466 | ||||
|
1467 | # add the Optional to the list and return the index at which | |||
|
1468 | # the Optional's string args stopped | |||
|
1469 | assert action_tuples | |||
|
1470 | for action, args, option_string in action_tuples: | |||
|
1471 | take_action(action, args, option_string) | |||
|
1472 | return stop | |||
|
1473 | ||||
|
1474 | # the list of Positionals left to be parsed; this is modified | |||
|
1475 | # by consume_positionals() | |||
|
1476 | positionals = self._get_positional_actions() | |||
|
1477 | ||||
|
1478 | # function to convert arg_strings into positional actions | |||
|
1479 | def consume_positionals(start_index): | |||
|
1480 | # match as many Positionals as possible | |||
|
1481 | match_partial = self._match_arguments_partial | |||
|
1482 | selected_pattern = arg_strings_pattern[start_index:] | |||
|
1483 | arg_counts = match_partial(positionals, selected_pattern) | |||
|
1484 | ||||
|
1485 | # slice off the appropriate arg strings for each Positional | |||
|
1486 | # and add the Positional and its args to the list | |||
|
1487 | for action, arg_count in zip(positionals, arg_counts): | |||
|
1488 | args = arg_strings[start_index: start_index + arg_count] | |||
|
1489 | start_index += arg_count | |||
|
1490 | take_action(action, args) | |||
|
1491 | ||||
|
1492 | # slice off the Positionals that we just parsed and return the | |||
|
1493 | # index at which the Positionals' string args stopped | |||
|
1494 | positionals[:] = positionals[len(arg_counts):] | |||
|
1495 | return start_index | |||
|
1496 | ||||
|
1497 | # consume Positionals and Optionals alternately, until we have | |||
|
1498 | # passed the last option string | |||
|
1499 | start_index = 0 | |||
|
1500 | if option_string_indices: | |||
|
1501 | max_option_string_index = max(option_string_indices) | |||
|
1502 | else: | |||
|
1503 | max_option_string_index = -1 | |||
|
1504 | while start_index <= max_option_string_index: | |||
|
1505 | ||||
|
1506 | # consume any Positionals preceding the next option | |||
|
1507 | next_option_string_index = min( | |||
|
1508 | index | |||
|
1509 | for index in option_string_indices | |||
|
1510 | if index >= start_index) | |||
|
1511 | if start_index != next_option_string_index: | |||
|
1512 | positionals_end_index = consume_positionals(start_index) | |||
|
1513 | ||||
|
1514 | # only try to parse the next optional if we didn't consume | |||
|
1515 | # the option string during the positionals parsing | |||
|
1516 | if positionals_end_index > start_index: | |||
|
1517 | start_index = positionals_end_index | |||
|
1518 | continue | |||
|
1519 | else: | |||
|
1520 | start_index = positionals_end_index | |||
|
1521 | ||||
|
1522 | # if we consumed all the positionals we could and we're not | |||
|
1523 | # at the index of an option string, there were unparseable | |||
|
1524 | # arguments | |||
|
1525 | if start_index not in option_string_indices: | |||
|
1526 | msg = _('extra arguments found: %s') | |||
|
1527 | extras = arg_strings[start_index:next_option_string_index] | |||
|
1528 | self.error(msg % ' '.join(extras)) | |||
|
1529 | ||||
|
1530 | # consume the next optional and any arguments for it | |||
|
1531 | start_index = consume_optional(start_index) | |||
|
1532 | ||||
|
1533 | # consume any positionals following the last Optional | |||
|
1534 | stop_index = consume_positionals(start_index) | |||
|
1535 | ||||
|
1536 | # if we didn't consume all the argument strings, there were too | |||
|
1537 | # many supplied | |||
|
1538 | if stop_index != len(arg_strings): | |||
|
1539 | extras = arg_strings[stop_index:] | |||
|
1540 | self.error(_('extra arguments found: %s') % ' '.join(extras)) | |||
|
1541 | ||||
|
1542 | # if we didn't use all the Positional objects, there were too few | |||
|
1543 | # arg strings supplied. | |||
|
1544 | if positionals: | |||
|
1545 | self.error(_('too few arguments')) | |||
|
1546 | ||||
|
1547 | # return the updated namespace | |||
|
1548 | return namespace | |||
|
1549 | ||||
|
1550 | def _match_argument(self, action, arg_strings_pattern): | |||
|
1551 | # match the pattern for this action to the arg strings | |||
|
1552 | nargs_pattern = self._get_nargs_pattern(action) | |||
|
1553 | match = _re.match(nargs_pattern, arg_strings_pattern) | |||
|
1554 | ||||
|
1555 | # raise an exception if we weren't able to find a match | |||
|
1556 | if match is None: | |||
|
1557 | nargs_errors = { | |||
|
1558 | None:_('expected one argument'), | |||
|
1559 | OPTIONAL:_('expected at most one argument'), | |||
|
1560 | ONE_OR_MORE:_('expected at least one argument') | |||
|
1561 | } | |||
|
1562 | default = _('expected %s argument(s)') % action.nargs | |||
|
1563 | msg = nargs_errors.get(action.nargs, default) | |||
|
1564 | raise ArgumentError(action, msg) | |||
|
1565 | ||||
|
1566 | # return the number of arguments matched | |||
|
1567 | return len(match.group(1)) | |||
|
1568 | ||||
|
1569 | def _match_arguments_partial(self, actions, arg_strings_pattern): | |||
|
1570 | # progressively shorten the actions list by slicing off the | |||
|
1571 | # final actions until we find a match | |||
|
1572 | result = [] | |||
|
1573 | for i in xrange(len(actions), 0, -1): | |||
|
1574 | actions_slice = actions[:i] | |||
|
1575 | pattern = ''.join(self._get_nargs_pattern(action) | |||
|
1576 | for action in actions_slice) | |||
|
1577 | match = _re.match(pattern, arg_strings_pattern) | |||
|
1578 | if match is not None: | |||
|
1579 | result.extend(len(string) for string in match.groups()) | |||
|
1580 | break | |||
|
1581 | ||||
|
1582 | # return the list of arg string counts | |||
|
1583 | return result | |||
|
1584 | ||||
|
1585 | def _parse_optional(self, arg_string): | |||
|
1586 | # if it doesn't start with a prefix, it was meant to be positional | |||
|
1587 | if not arg_string[0] in self.prefix_chars: | |||
|
1588 | return None | |||
|
1589 | ||||
|
1590 | # if it's just dashes, it was meant to be positional | |||
|
1591 | if not arg_string.strip('-'): | |||
|
1592 | return None | |||
|
1593 | ||||
|
1594 | # if the option string is present in the parser, return the action | |||
|
1595 | if arg_string in self._option_strings: | |||
|
1596 | action = self._option_strings[arg_string] | |||
|
1597 | return action, arg_string, None | |||
|
1598 | ||||
|
1599 | # search through all possible prefixes of the option string | |||
|
1600 | # and all actions in the parser for possible interpretations | |||
|
1601 | option_tuples = [] | |||
|
1602 | prefix_tuples = self._get_option_prefix_tuples(arg_string) | |||
|
1603 | for option_string in self._option_strings: | |||
|
1604 | for option_prefix, explicit_arg in prefix_tuples: | |||
|
1605 | if option_string.startswith(option_prefix): | |||
|
1606 | action = self._option_strings[option_string] | |||
|
1607 | tup = action, option_string, explicit_arg | |||
|
1608 | option_tuples.append(tup) | |||
|
1609 | break | |||
|
1610 | ||||
|
1611 | # if multiple actions match, the option string was ambiguous | |||
|
1612 | if len(option_tuples) > 1: | |||
|
1613 | options = ', '.join(opt_str for _, opt_str, _ in option_tuples) | |||
|
1614 | tup = arg_string, options | |||
|
1615 | self.error(_('ambiguous option: %s could match %s') % tup) | |||
|
1616 | ||||
|
1617 | # if exactly one action matched, this segmentation is good, | |||
|
1618 | # so return the parsed action | |||
|
1619 | elif len(option_tuples) == 1: | |||
|
1620 | option_tuple, = option_tuples | |||
|
1621 | return option_tuple | |||
|
1622 | ||||
|
1623 | # if it was not found as an option, but it looks like a negative | |||
|
1624 | # number, it was meant to be positional | |||
|
1625 | if self._negative_number_matcher.match(arg_string): | |||
|
1626 | return None | |||
|
1627 | ||||
|
1628 | # it was meant to be an optional but there is no such option | |||
|
1629 | # in this parser (though it might be a valid option in a subparser) | |||
|
1630 | return None, arg_string, None | |||
|
1631 | ||||
|
1632 | def _get_option_prefix_tuples(self, option_string): | |||
|
1633 | result = [] | |||
|
1634 | ||||
|
1635 | # option strings starting with two prefix characters are only | |||
|
1636 | # split at the '=' | |||
|
1637 | chars = self.prefix_chars | |||
|
1638 | if option_string[0] in chars and option_string[1] in chars: | |||
|
1639 | if '=' in option_string: | |||
|
1640 | option_prefix, explicit_arg = option_string.split('=', 1) | |||
|
1641 | else: | |||
|
1642 | option_prefix = option_string | |||
|
1643 | explicit_arg = None | |||
|
1644 | tup = option_prefix, explicit_arg | |||
|
1645 | result.append(tup) | |||
|
1646 | ||||
|
1647 | # option strings starting with a single prefix character are | |||
|
1648 | # split at all indices | |||
|
1649 | else: | |||
|
1650 | for first_index, char in enumerate(option_string): | |||
|
1651 | if char not in self.prefix_chars: | |||
|
1652 | break | |||
|
1653 | for i in xrange(len(option_string), first_index, -1): | |||
|
1654 | tup = option_string[:i], option_string[i:] or None | |||
|
1655 | result.append(tup) | |||
|
1656 | ||||
|
1657 | # return the collected prefix tuples | |||
|
1658 | return result | |||
|
1659 | ||||
|
1660 | def _get_nargs_pattern(self, action): | |||
|
1661 | # in all examples below, we have to allow for '--' args | |||
|
1662 | # which are represented as '-' in the pattern | |||
|
1663 | nargs = action.nargs | |||
|
1664 | ||||
|
1665 | # the default (None) is assumed to be a single argument | |||
|
1666 | if nargs is None: | |||
|
1667 | nargs_pattern = '(-*A-*)' | |||
|
1668 | ||||
|
1669 | # allow zero or one arguments | |||
|
1670 | elif nargs == OPTIONAL: | |||
|
1671 | nargs_pattern = '(-*A?-*)' | |||
|
1672 | ||||
|
1673 | # allow zero or more arguments | |||
|
1674 | elif nargs == ZERO_OR_MORE: | |||
|
1675 | nargs_pattern = '(-*[A-]*)' | |||
|
1676 | ||||
|
1677 | # allow one or more arguments | |||
|
1678 | elif nargs == ONE_OR_MORE: | |||
|
1679 | nargs_pattern = '(-*A[A-]*)' | |||
|
1680 | ||||
|
1681 | # allow one argument followed by any number of options or arguments | |||
|
1682 | elif nargs is PARSER: | |||
|
1683 | nargs_pattern = '(-*A[-AO]*)' | |||
|
1684 | ||||
|
1685 | # all others should be integers | |||
|
1686 | else: | |||
|
1687 | nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs) | |||
|
1688 | ||||
|
1689 | # if this is an optional action, -- is not allowed | |||
|
1690 | if action.option_strings: | |||
|
1691 | nargs_pattern = nargs_pattern.replace('-*', '') | |||
|
1692 | nargs_pattern = nargs_pattern.replace('-', '') | |||
|
1693 | ||||
|
1694 | # return the pattern | |||
|
1695 | return nargs_pattern | |||
|
1696 | ||||
|
1697 | # ======================== | |||
|
1698 | # Value conversion methods | |||
|
1699 | # ======================== | |||
|
1700 | ||||
|
1701 | def _get_values(self, action, arg_strings): | |||
|
1702 | # for everything but PARSER args, strip out '--' | |||
|
1703 | if action.nargs is not PARSER: | |||
|
1704 | arg_strings = [s for s in arg_strings if s != '--'] | |||
|
1705 | ||||
|
1706 | # optional argument produces a default when not present | |||
|
1707 | if not arg_strings and action.nargs == OPTIONAL: | |||
|
1708 | if action.option_strings: | |||
|
1709 | value = action.const | |||
|
1710 | else: | |||
|
1711 | value = action.default | |||
|
1712 | if isinstance(value, basestring): | |||
|
1713 | value = self._get_value(action, value) | |||
|
1714 | self._check_value(action, value) | |||
|
1715 | ||||
|
1716 | # when nargs='*' on a positional, if there were no command-line | |||
|
1717 | # args, use the default if it is anything other than None | |||
|
1718 | elif (not arg_strings and action.nargs == ZERO_OR_MORE and | |||
|
1719 | not action.option_strings): | |||
|
1720 | if action.default is not None: | |||
|
1721 | value = action.default | |||
|
1722 | else: | |||
|
1723 | value = arg_strings | |||
|
1724 | self._check_value(action, value) | |||
|
1725 | ||||
|
1726 | # single argument or optional argument produces a single value | |||
|
1727 | elif len(arg_strings) == 1 and action.nargs in [None, OPTIONAL]: | |||
|
1728 | arg_string, = arg_strings | |||
|
1729 | value = self._get_value(action, arg_string) | |||
|
1730 | self._check_value(action, value) | |||
|
1731 | ||||
|
1732 | # PARSER arguments convert all values, but check only the first | |||
|
1733 | elif action.nargs is PARSER: | |||
|
1734 | value = list(self._get_value(action, v) for v in arg_strings) | |||
|
1735 | self._check_value(action, value[0]) | |||
|
1736 | ||||
|
1737 | # all other types of nargs produce a list | |||
|
1738 | else: | |||
|
1739 | value = list(self._get_value(action, v) for v in arg_strings) | |||
|
1740 | for v in value: | |||
|
1741 | self._check_value(action, v) | |||
|
1742 | ||||
|
1743 | # return the converted value | |||
|
1744 | return value | |||
|
1745 | ||||
|
1746 | def _get_value(self, action, arg_string): | |||
|
1747 | type_func = self._registry_get('type', action.type, action.type) | |||
|
1748 | if not callable(type_func): | |||
|
1749 | msg = _('%r is not callable') | |||
|
1750 | raise ArgumentError(action, msg % type_func) | |||
|
1751 | ||||
|
1752 | # convert the value to the appropriate type | |||
|
1753 | try: | |||
|
1754 | result = type_func(arg_string) | |||
|
1755 | ||||
|
1756 | # TypeErrors or ValueErrors indicate errors | |||
|
1757 | except (TypeError, ValueError): | |||
|
1758 | name = getattr(action.type, '__name__', repr(action.type)) | |||
|
1759 | msg = _('invalid %s value: %r') | |||
|
1760 | raise ArgumentError(action, msg % (name, arg_string)) | |||
|
1761 | ||||
|
1762 | # return the converted value | |||
|
1763 | return result | |||
|
1764 | ||||
|
1765 | def _check_value(self, action, value): | |||
|
1766 | # converted value must be one of the choices (if specified) | |||
|
1767 | if action.choices is not None and value not in action.choices: | |||
|
1768 | tup = value, ', '.join(map(repr, action.choices)) | |||
|
1769 | msg = _('invalid choice: %r (choose from %s)') % tup | |||
|
1770 | raise ArgumentError(action, msg) | |||
|
1771 | ||||
|
1772 | ||||
|
1773 | ||||
|
1774 | # ======================= | |||
|
1775 | # Help-formatting methods | |||
|
1776 | # ======================= | |||
|
1777 | ||||
|
1778 | def format_usage(self): | |||
|
1779 | formatter = self._get_formatter() | |||
|
1780 | formatter.add_usage(self.usage, | |||
|
1781 | self._get_optional_actions(), | |||
|
1782 | self._get_positional_actions()) | |||
|
1783 | return formatter.format_help() | |||
|
1784 | ||||
|
1785 | def format_help(self): | |||
|
1786 | formatter = self._get_formatter() | |||
|
1787 | ||||
|
1788 | # usage | |||
|
1789 | formatter.add_usage(self.usage, | |||
|
1790 | self._get_optional_actions(), | |||
|
1791 | self._get_positional_actions()) | |||
|
1792 | ||||
|
1793 | # description | |||
|
1794 | formatter.add_text(self.description) | |||
|
1795 | ||||
|
1796 | # positionals | |||
|
1797 | formatter.start_section(_('positional arguments')) | |||
|
1798 | formatter.add_arguments(self._positional_actions_list) | |||
|
1799 | formatter.end_section() | |||
|
1800 | ||||
|
1801 | # optionals | |||
|
1802 | formatter.start_section(_('optional arguments')) | |||
|
1803 | formatter.add_arguments(self._optional_actions_list) | |||
|
1804 | formatter.end_section() | |||
|
1805 | ||||
|
1806 | # user-defined groups | |||
|
1807 | for argument_group in self._argument_groups: | |||
|
1808 | formatter.start_section(argument_group.title) | |||
|
1809 | formatter.add_text(argument_group.description) | |||
|
1810 | formatter.add_arguments(argument_group._positional_actions_list) | |||
|
1811 | formatter.add_arguments(argument_group._optional_actions_list) | |||
|
1812 | formatter.end_section() | |||
|
1813 | ||||
|
1814 | # epilog | |||
|
1815 | formatter.add_text(self.epilog) | |||
|
1816 | ||||
|
1817 | # determine help from format above | |||
|
1818 | return formatter.format_help() | |||
|
1819 | ||||
|
1820 | def format_version(self): | |||
|
1821 | formatter = self._get_formatter() | |||
|
1822 | formatter.add_text(self.version) | |||
|
1823 | return formatter.format_help() | |||
|
1824 | ||||
|
1825 | def _get_formatter(self): | |||
|
1826 | return self.formatter_class(prog=self.prog) | |||
|
1827 | ||||
|
1828 | # ===================== | |||
|
1829 | # Help-printing methods | |||
|
1830 | # ===================== | |||
|
1831 | ||||
|
1832 | def print_usage(self, file=None): | |||
|
1833 | self._print_message(self.format_usage(), file) | |||
|
1834 | ||||
|
1835 | def print_help(self, file=None): | |||
|
1836 | self._print_message(self.format_help(), file) | |||
|
1837 | ||||
|
1838 | def print_version(self, file=None): | |||
|
1839 | self._print_message(self.format_version(), file) | |||
|
1840 | ||||
|
1841 | def _print_message(self, message, file=None): | |||
|
1842 | if message: | |||
|
1843 | if file is None: | |||
|
1844 | file = _sys.stderr | |||
|
1845 | file.write(message) | |||
|
1846 | ||||
|
1847 | ||||
|
1848 | # =============== | |||
|
1849 | # Exiting methods | |||
|
1850 | # =============== | |||
|
1851 | ||||
|
1852 | def exit(self, status=0, message=None): | |||
|
1853 | if message: | |||
|
1854 | _sys.stderr.write(message) | |||
|
1855 | _sys.exit(status) | |||
|
1856 | ||||
|
1857 | def error(self, message): | |||
|
1858 | """error(message: string) | |||
|
1859 | ||||
|
1860 | Prints a usage message incorporating the message to stderr and | |||
|
1861 | exits. | |||
|
1862 | ||||
|
1863 | If you override this in a subclass, it should not return -- it | |||
|
1864 | should either exit or raise an exception. | |||
|
1865 | """ | |||
|
1866 | self.print_usage(_sys.stderr) | |||
|
1867 | self.exit(2, _('%s: error: %s\n') % (self.prog, message)) |
@@ -0,0 +1,33 b'' | |||||
|
1 | ========================================= | |||
|
2 | Notes on the IPython configuration system | |||
|
3 | ========================================= | |||
|
4 | ||||
|
5 | This document has some random notes on the configuration system. | |||
|
6 | ||||
|
7 | To start, an IPython process needs: | |||
|
8 | ||||
|
9 | * Configuration files | |||
|
10 | * Command line options | |||
|
11 | * Additional files (FURL files, extra scripts, etc.) | |||
|
12 | ||||
|
13 | It feeds these things into the core logic of the process, and as output, | |||
|
14 | produces: | |||
|
15 | ||||
|
16 | * Log files | |||
|
17 | * Security files | |||
|
18 | ||||
|
19 | There are a number of things that complicate this: | |||
|
20 | ||||
|
21 | * A process may need to be started on a different host that doesn't have | |||
|
22 | any of the config files or additional files. Those files need to be | |||
|
23 | moved over and put in a staging area. The process then needs to be told | |||
|
24 | about them. | |||
|
25 | * The location of the output files should somehow be set by config files or | |||
|
26 | command line options. | |||
|
27 | * Our config files are very hierarchical, but command line options are flat, | |||
|
28 | making it difficult to relate command line options to config files. | |||
|
29 | * Some processes (like ipcluster and the daemons) have to manage the input and | |||
|
30 | output files for multiple different subprocesses, each possibly on a | |||
|
31 | different host. Ahhhh! | |||
|
32 | * Our configurations are not singletons. A given user will likely have | |||
|
33 | many different configurations for different clusters. |
@@ -0,0 +1,251 b'' | |||||
|
1 | .. _parallel_process: | |||
|
2 | ||||
|
3 | =========================================== | |||
|
4 | Starting the IPython controller and engines | |||
|
5 | =========================================== | |||
|
6 | ||||
|
7 | To use IPython for parallel computing, you need to start one instance of | |||
|
8 | the controller and one or more instances of the engine. The controller | |||
|
9 | and each engine can run on different machines or on the same machine. | |||
|
10 | Because of this, there are many different possibilities. | |||
|
11 | ||||
|
12 | Broadly speaking, there are two ways of going about starting a controller and engines: | |||
|
13 | ||||
|
14 | * In an automated manner using the :command:`ipcluster` command. | |||
|
15 | * In a more manual way using the :command:`ipcontroller` and | |||
|
16 | :command:`ipengine` commands. | |||
|
17 | ||||
|
18 | This document describes both of these methods. We recommend that new users start with the :command:`ipcluster` command as it simplifies many common usage cases. | |||
|
19 | ||||
|
20 | General considerations | |||
|
21 | ====================== | |||
|
22 | ||||
|
23 | Before delving into the details about how you can start a controller and engines using the various methods, we outline some of the general issues that come up when starting the controller and engines. These things come up no matter which method you use to start your IPython cluster. | |||
|
24 | ||||
|
25 | Let's say that you want to start the controller on ``host0`` and engines on hosts ``host1``-``hostn``. The following steps are then required: | |||
|
26 | ||||
|
27 | 1. Start the controller on ``host0`` by running :command:`ipcontroller` on | |||
|
28 | ``host0``. | |||
|
29 | 2. Move the FURL file (:file:`ipcontroller-engine.furl`) created by the | |||
|
30 | controller from ``host0`` to hosts ``host1``-``hostn``. | |||
|
31 | 3. Start the engines on hosts ``host1``-``hostn`` by running | |||
|
32 | :command:`ipengine`. This command has to be told where the FURL file | |||
|
33 | (:file:`ipcontroller-engine.furl`) is located. | |||
|
34 | ||||
|
35 | At this point, the controller and engines will be connected. By default, the | |||
|
36 | FURL files created by the controller are put into the | |||
|
37 | :file:`~/.ipython/security` directory. If the engines share a filesystem with | |||
|
38 | the controller, step 2 can be skipped as the engines will automatically look | |||
|
39 | at that location. | |||
|
40 | ||||
|
41 | The final step required required to actually use the running controller from a | |||
|
42 | client is to move the FURL files :file:`ipcontroller-mec.furl` and | |||
|
43 | :file:`ipcontroller-tc.furl` from ``host0`` to the host where the clients will | |||
|
44 | be run. If these file are put into the :file:`~/.ipython/security` directory of the client's host, they will be found automatically. Otherwise, the full path to them has to be passed to the client's constructor. | |||
|
45 | ||||
|
46 | Using :command:`ipcluster` | |||
|
47 | ========================== | |||
|
48 | ||||
|
49 | The :command:`ipcluster` command provides a simple way of starting a controller and engines in the following situations: | |||
|
50 | ||||
|
51 | 1. When the controller and engines are all run on localhost. This is useful | |||
|
52 | for testing or running on a multicore computer. | |||
|
53 | 2. When engines are started using the :command:`mpirun` command that comes | |||
|
54 | with most MPI [MPI]_ implementations | |||
|
55 | 3. When engines are started using the PBS [PBS]_ batch system. | |||
|
56 | ||||
|
57 | .. note:: | |||
|
58 | ||||
|
59 | It is also possible for advanced users to add support to | |||
|
60 | :command:`ipcluster` for starting controllers and engines using other | |||
|
61 | methods (like Sun's Grid Engine for example). | |||
|
62 | ||||
|
63 | .. note:: | |||
|
64 | ||||
|
65 | Currently :command:`ipcluster` requires that the | |||
|
66 | :file:`~/.ipython/security` directory live on a shared filesystem that is | |||
|
67 | seen by both the controller and engines. If you don't have a shared file | |||
|
68 | system you will need to use :command:`ipcontroller` and | |||
|
69 | :command:`ipengine` directly. | |||
|
70 | ||||
|
71 | Underneath the hood, :command:`ipcluster` just uses :command:`ipcontroller` | |||
|
72 | and :command:`ipengine` to perform the steps described above. | |||
|
73 | ||||
|
74 | Using :command:`ipcluster` in local mode | |||
|
75 | ---------------------------------------- | |||
|
76 | ||||
|
77 | To start one controller and 4 engines on localhost, just do:: | |||
|
78 | ||||
|
79 | $ ipcluster local -n 4 | |||
|
80 | ||||
|
81 | To see other command line options for the local mode, do:: | |||
|
82 | ||||
|
83 | $ ipcluster local -h | |||
|
84 | ||||
|
85 | Using :command:`ipcluster` in mpirun mode | |||
|
86 | ----------------------------------------- | |||
|
87 | ||||
|
88 | The mpirun mode is useful if you: | |||
|
89 | ||||
|
90 | 1. Have MPI installed. | |||
|
91 | 2. Your systems are configured to use the :command:`mpirun` command to start | |||
|
92 | processes. | |||
|
93 | ||||
|
94 | If these are satisfied, you can start an IPython cluster using:: | |||
|
95 | ||||
|
96 | $ ipcluster mpirun -n 4 | |||
|
97 | ||||
|
98 | This does the following: | |||
|
99 | ||||
|
100 | 1. Starts the IPython controller on current host. | |||
|
101 | 2. Uses :command:`mpirun` to start 4 engines. | |||
|
102 | ||||
|
103 | On newer MPI implementations (such as OpenMPI), this will work even if you don't make any calls to MPI or call :func:`MPI_Init`. However, older MPI implementations actually require each process to call :func:`MPI_Init` upon starting. The easiest way of having this done is to install the mpi4py [mpi4py]_ package and then call ipcluster with the ``--mpi`` option:: | |||
|
104 | ||||
|
105 | $ ipcluster mpirun -n 4 --mpi=mpi4py | |||
|
106 | ||||
|
107 | Unfortunately, even this won't work for some MPI implementations. If you are having problems with this, you will likely have to use a custom Python executable that itself calls :func:`MPI_Init` at the appropriate time. Fortunately, mpi4py comes with such a custom Python executable that is easy to install and use. However, this custom Python executable approach will not work with :command:`ipcluster` currently. | |||
|
108 | ||||
|
109 | Additional command line options for this mode can be found by doing:: | |||
|
110 | ||||
|
111 | $ ipcluster mpirun -h | |||
|
112 | ||||
|
113 | More details on using MPI with IPython can be found :ref:`here <parallelmpi>`. | |||
|
114 | ||||
|
115 | ||||
|
116 | Using :command:`ipcluster` in PBS mode | |||
|
117 | -------------------------------------- | |||
|
118 | ||||
|
119 | The PBS mode uses the Portable Batch System [PBS]_ to start the engines. To use this mode, you first need to create a PBS script template that will be used to start the engines. Here is a sample PBS script template: | |||
|
120 | ||||
|
121 | .. sourcecode:: bash | |||
|
122 | ||||
|
123 | #PBS -N ipython | |||
|
124 | #PBS -j oe | |||
|
125 | #PBS -l walltime=00:10:00 | |||
|
126 | #PBS -l nodes=${n/4}:ppn=4 | |||
|
127 | #PBS -q parallel | |||
|
128 | ||||
|
129 | cd $$PBS_O_WORKDIR | |||
|
130 | export PATH=$$HOME/usr/local/bin | |||
|
131 | export PYTHONPATH=$$HOME/usr/local/lib/python2.4/site-packages | |||
|
132 | /usr/local/bin/mpiexec -n ${n} ipengine --logfile=$$PBS_O_WORKDIR/ipengine | |||
|
133 | ||||
|
134 | There are a few important points about this template: | |||
|
135 | ||||
|
136 | 1. This template will be rendered at runtime using IPython's :mod:`Itpl` | |||
|
137 | template engine. | |||
|
138 | ||||
|
139 | 2. Instead of putting in the actual number of engines, use the notation | |||
|
140 | ``${n}`` to indicate the number of engines to be started. You can also uses | |||
|
141 | expressions like ``${n/4}`` in the template to indicate the number of | |||
|
142 | nodes. | |||
|
143 | ||||
|
144 | 3. Because ``$`` is a special character used by the template engine, you must | |||
|
145 | escape any ``$`` by using ``$$``. This is important when referring to | |||
|
146 | environment variables in the template. | |||
|
147 | ||||
|
148 | 4. Any options to :command:`ipengine` should be given in the batch script | |||
|
149 | template. | |||
|
150 | ||||
|
151 | 5. Depending on the configuration of you system, you may have to set | |||
|
152 | environment variables in the script template. | |||
|
153 | ||||
|
154 | Once you have created such a script, save it with a name like :file:`pbs.template`. Now you are ready to start your job:: | |||
|
155 | ||||
|
156 | $ ipcluster pbs -n 128 --pbs-script=pbs.template | |||
|
157 | ||||
|
158 | Additional command line options for this mode can be found by doing:: | |||
|
159 | ||||
|
160 | $ ipcluster pbs -h | |||
|
161 | ||||
|
162 | Using the :command:`ipcontroller` and :command:`ipengine` commands | |||
|
163 | ================================================================== | |||
|
164 | ||||
|
165 | It is also possible to use the :command:`ipcontroller` and :command:`ipengine` commands to start your controller and engines. This approach gives you full control over all aspects of the startup process. | |||
|
166 | ||||
|
167 | Starting the controller and engine on your local machine | |||
|
168 | -------------------------------------------------------- | |||
|
169 | ||||
|
170 | To use :command:`ipcontroller` and :command:`ipengine` to start things on your | |||
|
171 | local machine, do the following. | |||
|
172 | ||||
|
173 | First start the controller:: | |||
|
174 | ||||
|
175 | $ ipcontroller | |||
|
176 | ||||
|
177 | Next, start however many instances of the engine you want using (repeatedly) the command:: | |||
|
178 | ||||
|
179 | $ ipengine | |||
|
180 | ||||
|
181 | The engines should start and automatically connect to the controller using the FURL files in :file:`~./ipython/security`. You are now ready to use the controller and engines from IPython. | |||
|
182 | ||||
|
183 | .. warning:: | |||
|
184 | ||||
|
185 | The order of the above operations is very important. You *must* | |||
|
186 | start the controller before the engines, since the engines connect | |||
|
187 | to the controller as they get started. | |||
|
188 | ||||
|
189 | .. note:: | |||
|
190 | ||||
|
191 | On some platforms (OS X), to put the controller and engine into the | |||
|
192 | background you may need to give these commands in the form ``(ipcontroller | |||
|
193 | &)`` and ``(ipengine &)`` (with the parentheses) for them to work | |||
|
194 | properly. | |||
|
195 | ||||
|
196 | Starting the controller and engines on different hosts | |||
|
197 | ------------------------------------------------------ | |||
|
198 | ||||
|
199 | When the controller and engines are running on different hosts, things are | |||
|
200 | slightly more complicated, but the underlying ideas are the same: | |||
|
201 | ||||
|
202 | 1. Start the controller on a host using :command:`ipcontroller`. | |||
|
203 | 2. Copy :file:`ipcontroller-engine.furl` from :file:`~./ipython/security` on the controller's host to the host where the engines will run. | |||
|
204 | 3. Use :command:`ipengine` on the engine's hosts to start the engines. | |||
|
205 | ||||
|
206 | The only thing you have to be careful of is to tell :command:`ipengine` where the :file:`ipcontroller-engine.furl` file is located. There are two ways you can do this: | |||
|
207 | ||||
|
208 | * Put :file:`ipcontroller-engine.furl` in the :file:`~./ipython/security` | |||
|
209 | directory on the engine's host, where it will be found automatically. | |||
|
210 | * Call :command:`ipengine` with the ``--furl-file=full_path_to_the_file`` | |||
|
211 | flag. | |||
|
212 | ||||
|
213 | The ``--furl-file`` flag works like this:: | |||
|
214 | ||||
|
215 | $ ipengine --furl-file=/path/to/my/ipcontroller-engine.furl | |||
|
216 | ||||
|
217 | .. note:: | |||
|
218 | ||||
|
219 | If the controller's and engine's hosts all have a shared file system | |||
|
220 | (:file:`~./ipython/security` is the same on all of them), then things | |||
|
221 | will just work! | |||
|
222 | ||||
|
223 | Make FURL files persistent | |||
|
224 | --------------------------- | |||
|
225 | ||||
|
226 | At fist glance it may seem that that managing the FURL files is a bit annoying. Going back to the house and key analogy, copying the FURL around each time you start the controller is like having to make a new key every time you want to unlock the door and enter your house. As with your house, you want to be able to create the key (or FURL file) once, and then simply use it at any point in the future. | |||
|
227 | ||||
|
228 | This is possible. The only thing you have to do is decide what ports the controller will listen on for the engines and clients. This is done as follows:: | |||
|
229 | ||||
|
230 | $ ipcontroller -r --client-port=10101 --engine-port=10102 | |||
|
231 | ||||
|
232 | Then, just copy the furl files over the first time and you are set. You can start and stop the controller and engines any many times as you want in the future, just make sure to tell the controller to use the *same* ports. | |||
|
233 | ||||
|
234 | .. note:: | |||
|
235 | ||||
|
236 | You may ask the question: what ports does the controller listen on if you | |||
|
237 | don't tell is to use specific ones? The default is to use high random port | |||
|
238 | numbers. We do this for two reasons: i) to increase security through | |||
|
239 | obscurity and ii) to multiple controllers on a given host to start and | |||
|
240 | automatically use different ports. | |||
|
241 | ||||
|
242 | Log files | |||
|
243 | --------- | |||
|
244 | ||||
|
245 | All of the components of IPython have log files associated with them. | |||
|
246 | These log files can be extremely useful in debugging problems with | |||
|
247 | IPython and can be found in the directory :file:`~/.ipython/log`. Sending | |||
|
248 | the log files to us will often help us to debug any problems. | |||
|
249 | ||||
|
250 | ||||
|
251 | .. [PBS] Portable Batch System. http://www.openpbs.org/ |
@@ -0,0 +1,363 b'' | |||||
|
1 | .. _parallelsecurity: | |||
|
2 | ||||
|
3 | =========================== | |||
|
4 | Security details of IPython | |||
|
5 | =========================== | |||
|
6 | ||||
|
7 | IPython's :mod:`IPython.kernel` package exposes the full power of the Python | |||
|
8 | interpreter over a TCP/IP network for the purposes of parallel computing. This | |||
|
9 | feature brings up the important question of IPython's security model. This | |||
|
10 | document gives details about this model and how it is implemented in IPython's | |||
|
11 | architecture. | |||
|
12 | ||||
|
13 | Processs and network topology | |||
|
14 | ============================= | |||
|
15 | ||||
|
16 | To enable parallel computing, IPython has a number of different processes that | |||
|
17 | run. These processes are discussed at length in the IPython documentation and | |||
|
18 | are summarized here: | |||
|
19 | ||||
|
20 | * The IPython *engine*. This process is a full blown Python | |||
|
21 | interpreter in which user code is executed. Multiple | |||
|
22 | engines are started to make parallel computing possible. | |||
|
23 | * The IPython *controller*. This process manages a set of | |||
|
24 | engines, maintaining a queue for each and presenting | |||
|
25 | an asynchronous interface to the set of engines. | |||
|
26 | * The IPython *client*. This process is typically an | |||
|
27 | interactive Python process that is used to coordinate the | |||
|
28 | engines to get a parallel computation done. | |||
|
29 | ||||
|
30 | Collectively, these three processes are called the IPython *kernel*. | |||
|
31 | ||||
|
32 | These three processes communicate over TCP/IP connections with a well defined | |||
|
33 | topology. The IPython controller is the only process that listens on TCP/IP | |||
|
34 | sockets. Upon starting, an engine connects to a controller and registers | |||
|
35 | itself with the controller. These engine/controller TCP/IP connections persist | |||
|
36 | for the lifetime of each engine. | |||
|
37 | ||||
|
38 | The IPython client also connects to the controller using one or more TCP/IP | |||
|
39 | connections. These connections persist for the lifetime of the client only. | |||
|
40 | ||||
|
41 | A given IPython controller and set of engines typically has a relatively short | |||
|
42 | lifetime. Typically this lifetime corresponds to the duration of a single | |||
|
43 | parallel simulation performed by a single user. Finally, the controller, | |||
|
44 | engines and client processes typically execute with the permissions of that | |||
|
45 | same user. More specifically, the controller and engines are *not* executed as | |||
|
46 | root or with any other superuser permissions. | |||
|
47 | ||||
|
48 | Application logic | |||
|
49 | ================= | |||
|
50 | ||||
|
51 | When running the IPython kernel to perform a parallel computation, a user | |||
|
52 | utilizes the IPython client to send Python commands and data through the | |||
|
53 | IPython controller to the IPython engines, where those commands are executed | |||
|
54 | and the data processed. The design of IPython ensures that the client is the | |||
|
55 | only access point for the capabilities of the engines. That is, the only way of addressing the engines is through a client. | |||
|
56 | ||||
|
57 | A user can utilize the client to instruct the IPython engines to execute | |||
|
58 | arbitrary Python commands. These Python commands can include calls to the | |||
|
59 | system shell, access the filesystem, etc., as required by the user's | |||
|
60 | application code. From this perspective, when a user runs an IPython engine on | |||
|
61 | a host, that engine has the same capabilities and permissions as the user | |||
|
62 | themselves (as if they were logged onto the engine's host with a terminal). | |||
|
63 | ||||
|
64 | Secure network connections | |||
|
65 | ========================== | |||
|
66 | ||||
|
67 | Overview | |||
|
68 | -------- | |||
|
69 | ||||
|
70 | All TCP/IP connections between the client and controller as well as the | |||
|
71 | engines and controller are fully encrypted and authenticated. This section | |||
|
72 | describes the details of the encryption and authentication approached used | |||
|
73 | within IPython. | |||
|
74 | ||||
|
75 | IPython uses the Foolscap network protocol [Foolscap]_ for all communications | |||
|
76 | between processes. Thus, the details of IPython's security model are directly | |||
|
77 | related to those of Foolscap. Thus, much of the following discussion is | |||
|
78 | actually just a discussion of the security that is built in to Foolscap. | |||
|
79 | ||||
|
80 | Encryption | |||
|
81 | ---------- | |||
|
82 | ||||
|
83 | For encryption purposes, IPython and Foolscap use the well known Secure Socket | |||
|
84 | Layer (SSL) protocol [RFC5246]_. We use the implementation of this protocol | |||
|
85 | provided by the OpenSSL project through the pyOpenSSL [pyOpenSSL]_ Python | |||
|
86 | bindings to OpenSSL. | |||
|
87 | ||||
|
88 | Authentication | |||
|
89 | -------------- | |||
|
90 | ||||
|
91 | IPython clients and engines must also authenticate themselves with the | |||
|
92 | controller. This is handled in a capabilities based security model | |||
|
93 | [Capability]_. In this model, the controller creates a strong cryptographic | |||
|
94 | key or token that represents each set of capability that the controller | |||
|
95 | offers. Any party who has this key and presents it to the controller has full | |||
|
96 | access to the corresponding capabilities of the controller. This model is | |||
|
97 | analogous to using a physical key to gain access to physical items | |||
|
98 | (capabilities) behind a locked door. | |||
|
99 | ||||
|
100 | For a capabilities based authentication system to prevent unauthorized access, | |||
|
101 | two things must be ensured: | |||
|
102 | ||||
|
103 | * The keys must be cryptographically strong. Otherwise attackers could gain | |||
|
104 | access by a simple brute force key guessing attack. | |||
|
105 | * The actual keys must be distributed only to authorized parties. | |||
|
106 | ||||
|
107 | The keys in Foolscap are called Foolscap URL's or FURLs. The following section | |||
|
108 | gives details about how these FURLs are created in Foolscap. The IPython | |||
|
109 | controller creates a number of FURLs for different purposes: | |||
|
110 | ||||
|
111 | * One FURL that grants IPython engines access to the controller. Also | |||
|
112 | implicit in this access is permission to execute code sent by an | |||
|
113 | authenticated IPython client. | |||
|
114 | * Two or more FURLs that grant IPython clients access to the controller. | |||
|
115 | Implicit in this access is permission to give the controller's engine code | |||
|
116 | to execute. | |||
|
117 | ||||
|
118 | Upon starting, the controller creates these different FURLS and writes them | |||
|
119 | files in the user-read-only directory :file:`$HOME/.ipython/security`. Thus, only the | |||
|
120 | user who starts the controller has access to the FURLs. | |||
|
121 | ||||
|
122 | For an IPython client or engine to authenticate with a controller, it must | |||
|
123 | present the appropriate FURL to the controller upon connecting. If the | |||
|
124 | FURL matches what the controller expects for a given capability, access is | |||
|
125 | granted. If not, access is denied. The exchange of FURLs is done after | |||
|
126 | encrypted communications channels have been established to prevent attackers | |||
|
127 | from capturing them. | |||
|
128 | ||||
|
129 | .. note:: | |||
|
130 | ||||
|
131 | The FURL is similar to an unsigned private key in SSH. | |||
|
132 | ||||
|
133 | Details of the Foolscap handshake | |||
|
134 | --------------------------------- | |||
|
135 | ||||
|
136 | In this section we detail the precise security handshake that takes place at | |||
|
137 | the beginning of any network connection in IPython. For the purposes of this | |||
|
138 | discussion, the SERVER is the IPython controller process and the CLIENT is the | |||
|
139 | IPython engine or client process. | |||
|
140 | ||||
|
141 | Upon starting, all IPython processes do the following: | |||
|
142 | ||||
|
143 | 1. Create a public key x509 certificate (ISO/IEC 9594). | |||
|
144 | 2. Create a hash of the contents of the certificate using the SHA-1 algorithm. | |||
|
145 | The base-32 encoded version of this hash is saved by the process as its | |||
|
146 | process id (actually in Foolscap, this is the Tub id, but here refer to | |||
|
147 | it as the process id). | |||
|
148 | ||||
|
149 | Upon starting, the IPython controller also does the following: | |||
|
150 | ||||
|
151 | 1. Save the x509 certificate to disk in a secure location. The CLIENT | |||
|
152 | certificate is never saved to disk. | |||
|
153 | 2. Create a FURL for each capability that the controller has. There are | |||
|
154 | separate capabilities the controller offers for clients and engines. The | |||
|
155 | FURL is created using: a) the process id of the SERVER, b) the IP | |||
|
156 | address and port the SERVER is listening on and c) a 160 bit, | |||
|
157 | cryptographically secure string that represents the capability (the | |||
|
158 | "capability id"). | |||
|
159 | 3. The FURLs are saved to disk in a secure location on the SERVER's host. | |||
|
160 | ||||
|
161 | For a CLIENT to be able to connect to the SERVER and access a capability of | |||
|
162 | that SERVER, the CLIENT must have knowledge of the FURL for that SERVER's | |||
|
163 | capability. This typically requires that the file containing the FURL be | |||
|
164 | moved from the SERVER's host to the CLIENT's host. This is done by the end | |||
|
165 | user who started the SERVER and wishes to have a CLIENT connect to the SERVER. | |||
|
166 | ||||
|
167 | When a CLIENT connects to the SERVER, the following handshake protocol takes | |||
|
168 | place: | |||
|
169 | ||||
|
170 | 1. The CLIENT tells the SERVER what process (or Tub) id it expects the SERVER | |||
|
171 | to have. | |||
|
172 | 2. If the SERVER has that process id, it notifies the CLIENT that it will now | |||
|
173 | enter encrypted mode. If the SERVER has a different id, the SERVER aborts. | |||
|
174 | 3. Both CLIENT and SERVER initiate the SSL handshake protocol. | |||
|
175 | 4. Both CLIENT and SERVER request the certificate of their peer and verify | |||
|
176 | that certificate. If this succeeds, all further communications are | |||
|
177 | encrypted. | |||
|
178 | 5. Both CLIENT and SERVER send a hello block containing connection parameters | |||
|
179 | and their process id. | |||
|
180 | 6. The CLIENT and SERVER check that their peer's stated process id matches the | |||
|
181 | hash of the x509 certificate the peer presented. If not, the connection is | |||
|
182 | aborted. | |||
|
183 | 7. The CLIENT verifies that the SERVER's stated id matches the id of the | |||
|
184 | SERVER the CLIENT is intending to connect to. If not, the connection is | |||
|
185 | aborted. | |||
|
186 | 8. The CLIENT and SERVER elect a master who decides on the final connection | |||
|
187 | parameters. | |||
|
188 | ||||
|
189 | The public/private key pair associated with each process's x509 certificate | |||
|
190 | are completely hidden from this handshake protocol. There are however, used | |||
|
191 | internally by OpenSSL as part of the SSL handshake protocol. Each process | |||
|
192 | keeps their own private key hidden and sends its peer only the public key | |||
|
193 | (embedded in the certificate). | |||
|
194 | ||||
|
195 | Finally, when the CLIENT requests access to a particular SERVER capability, | |||
|
196 | the following happens: | |||
|
197 | ||||
|
198 | 1. The CLIENT asks the SERVER for access to a capability by presenting that | |||
|
199 | capabilities id. | |||
|
200 | 2. If the SERVER has a capability with that id, access is granted. If not, | |||
|
201 | access is not granted. | |||
|
202 | 3. Once access has been gained, the CLIENT can use the capability. | |||
|
203 | ||||
|
204 | Specific security vulnerabilities | |||
|
205 | ================================= | |||
|
206 | ||||
|
207 | There are a number of potential security vulnerabilities present in IPython's | |||
|
208 | architecture. In this section we discuss those vulnerabilities and detail how | |||
|
209 | the security architecture described above prevents them from being exploited. | |||
|
210 | ||||
|
211 | Unauthorized clients | |||
|
212 | -------------------- | |||
|
213 | ||||
|
214 | The IPython client can instruct the IPython engines to execute arbitrary | |||
|
215 | Python code with the permissions of the user who started the engines. If an | |||
|
216 | attacker were able to connect their own hostile IPython client to the IPython | |||
|
217 | controller, they could instruct the engines to execute code. | |||
|
218 | ||||
|
219 | This attack is prevented by the capabilities based client authentication | |||
|
220 | performed after the encrypted channel has been established. The relevant | |||
|
221 | authentication information is encoded into the FURL that clients must | |||
|
222 | present to gain access to the IPython controller. By limiting the distribution | |||
|
223 | of those FURLs, a user can grant access to only authorized persons. | |||
|
224 | ||||
|
225 | It is highly unlikely that a client FURL could be guessed by an attacker | |||
|
226 | in a brute force guessing attack. A given instance of the IPython controller | |||
|
227 | only runs for a relatively short amount of time (on the order of hours). Thus | |||
|
228 | an attacker would have only a limited amount of time to test a search space of | |||
|
229 | size 2**320. Furthermore, even if a controller were to run for a longer amount | |||
|
230 | of time, this search space is quite large (larger for instance than that of | |||
|
231 | typical username/password pair). | |||
|
232 | ||||
|
233 | Unauthorized engines | |||
|
234 | -------------------- | |||
|
235 | ||||
|
236 | If an attacker were able to connect a hostile engine to a user's controller, | |||
|
237 | the user might unknowingly send sensitive code or data to the hostile engine. | |||
|
238 | This attacker's engine would then have full access to that code and data. | |||
|
239 | ||||
|
240 | This type of attack is prevented in the same way as the unauthorized client | |||
|
241 | attack, through the usage of the capabilities based authentication scheme. | |||
|
242 | ||||
|
243 | Unauthorized controllers | |||
|
244 | ------------------------ | |||
|
245 | ||||
|
246 | It is also possible that an attacker could try to convince a user's IPython | |||
|
247 | client or engine to connect to a hostile IPython controller. That controller | |||
|
248 | would then have full access to the code and data sent between the IPython | |||
|
249 | client and the IPython engines. | |||
|
250 | ||||
|
251 | Again, this attack is prevented through the FURLs, which ensure that a | |||
|
252 | client or engine connects to the correct controller. It is also important to | |||
|
253 | note that the FURLs also encode the IP address and port that the | |||
|
254 | controller is listening on, so there is little chance of mistakenly connecting | |||
|
255 | to a controller running on a different IP address and port. | |||
|
256 | ||||
|
257 | When starting an engine or client, a user must specify which FURL to use | |||
|
258 | for that connection. Thus, in order to introduce a hostile controller, the | |||
|
259 | attacker must convince the user to use the FURLs associated with the | |||
|
260 | hostile controller. As long as a user is diligent in only using FURLs from | |||
|
261 | trusted sources, this attack is not possible. | |||
|
262 | ||||
|
263 | Other security measures | |||
|
264 | ======================= | |||
|
265 | ||||
|
266 | A number of other measures are taken to further limit the security risks | |||
|
267 | involved in running the IPython kernel. | |||
|
268 | ||||
|
269 | First, by default, the IPython controller listens on random port numbers. | |||
|
270 | While this can be overridden by the user, in the default configuration, an | |||
|
271 | attacker would have to do a port scan to even find a controller to attack. | |||
|
272 | When coupled with the relatively short running time of a typical controller | |||
|
273 | (on the order of hours), an attacker would have to work extremely hard and | |||
|
274 | extremely *fast* to even find a running controller to attack. | |||
|
275 | ||||
|
276 | Second, much of the time, especially when run on supercomputers or clusters, | |||
|
277 | the controller is running behind a firewall. Thus, for engines or client to | |||
|
278 | connect to the controller: | |||
|
279 | ||||
|
280 | * The different processes have to all be behind the firewall. | |||
|
281 | ||||
|
282 | or: | |||
|
283 | ||||
|
284 | * The user has to use SSH port forwarding to tunnel the | |||
|
285 | connections through the firewall. | |||
|
286 | ||||
|
287 | In either case, an attacker is presented with addition barriers that prevent | |||
|
288 | attacking or even probing the system. | |||
|
289 | ||||
|
290 | Summary | |||
|
291 | ======= | |||
|
292 | ||||
|
293 | IPython's architecture has been carefully designed with security in mind. The | |||
|
294 | capabilities based authentication model, in conjunction with the encrypted | |||
|
295 | TCP/IP channels, address the core potential vulnerabilities in the system, | |||
|
296 | while still enabling user's to use the system in open networks. | |||
|
297 | ||||
|
298 | Other questions | |||
|
299 | =============== | |||
|
300 | ||||
|
301 | About keys | |||
|
302 | ---------- | |||
|
303 | ||||
|
304 | Can you clarify the roles of the certificate and its keys versus the FURL, | |||
|
305 | which is also called a key? | |||
|
306 | ||||
|
307 | The certificate created by IPython processes is a standard public key x509 | |||
|
308 | certificate, that is used by the SSL handshake protocol to setup encrypted | |||
|
309 | channel between the controller and the IPython engine or client. This public | |||
|
310 | and private key associated with this certificate are used only by the SSL | |||
|
311 | handshake protocol in setting up this encrypted channel. | |||
|
312 | ||||
|
313 | The FURL serves a completely different and independent purpose from the | |||
|
314 | key pair associated with the certificate. When we refer to a FURL as a | |||
|
315 | key, we are using the word "key" in the capabilities based security model | |||
|
316 | sense. This has nothing to do with "key" in the public/private key sense used | |||
|
317 | in the SSL protocol. | |||
|
318 | ||||
|
319 | With that said the FURL is used as an cryptographic key, to grant | |||
|
320 | IPython engines and clients access to particular capabilities that the | |||
|
321 | controller offers. | |||
|
322 | ||||
|
323 | Self signed certificates | |||
|
324 | ------------------------ | |||
|
325 | ||||
|
326 | Is the controller creating a self-signed certificate? Is this created for per | |||
|
327 | instance/session, one-time-setup or each-time the controller is started? | |||
|
328 | ||||
|
329 | The Foolscap network protocol, which handles the SSL protocol details, creates | |||
|
330 | a self-signed x509 certificate using OpenSSL for each IPython process. The | |||
|
331 | lifetime of the certificate is handled differently for the IPython controller | |||
|
332 | and the engines/client. | |||
|
333 | ||||
|
334 | For the IPython engines and client, the certificate is only held in memory for | |||
|
335 | the lifetime of its process. It is never written to disk. | |||
|
336 | ||||
|
337 | For the controller, the certificate can be created anew each time the | |||
|
338 | controller starts or it can be created once and reused each time the | |||
|
339 | controller starts. If at any point, the certificate is deleted, a new one is | |||
|
340 | created the next time the controller starts. | |||
|
341 | ||||
|
342 | SSL private key | |||
|
343 | --------------- | |||
|
344 | ||||
|
345 | How the private key (associated with the certificate) is distributed? | |||
|
346 | ||||
|
347 | In the usual implementation of the SSL protocol, the private key is never | |||
|
348 | distributed. We follow this standard always. | |||
|
349 | ||||
|
350 | SSL versus Foolscap authentication | |||
|
351 | ---------------------------------- | |||
|
352 | ||||
|
353 | Many SSL connections only perform one sided authentication (the server to the | |||
|
354 | client). How is the client authentication in IPython's system related to SSL | |||
|
355 | authentication? | |||
|
356 | ||||
|
357 | We perform a two way SSL handshake in which both parties request and verify | |||
|
358 | the certificate of their peer. This mutual authentication is handled by the | |||
|
359 | SSL handshake and is separate and independent from the additional | |||
|
360 | authentication steps that the CLIENT and SERVER perform after an encrypted | |||
|
361 | channel is established. | |||
|
362 | ||||
|
363 | .. [RFC5246] <http://tools.ietf.org/html/rfc5246> |
@@ -0,0 +1,172 b'' | |||||
|
1 | #!/usr/bin/env python | |||
|
2 | """A parallel tasking tool that uses asynchronous programming. This uses | |||
|
3 | blocking client to get taskid, but returns a Deferred as the result of | |||
|
4 | run(). Users should attach their callbacks on these Deferreds. | |||
|
5 | ||||
|
6 | Only returning of results is asynchronous. Submitting tasks and getting task | |||
|
7 | ids are done synchronously. | |||
|
8 | ||||
|
9 | Yichun Wei 03/2008 | |||
|
10 | """ | |||
|
11 | ||||
|
12 | import inspect | |||
|
13 | import itertools | |||
|
14 | import numpy as N | |||
|
15 | ||||
|
16 | from twisted.python import log | |||
|
17 | from ipython1.kernel import client | |||
|
18 | from ipython1.kernel.client import Task | |||
|
19 | ||||
|
20 | """ After http://trac.pocoo.org/repos/pocoo/trunk/pocoo/utils/decorators.py | |||
|
21 | """ | |||
|
22 | class submit_job(object): | |||
|
23 | """ a decorator factory: takes a MultiEngineClient a TaskClient, returns a | |||
|
24 | decorator, that makes a call to the decorated func as a task in ipython1 | |||
|
25 | and submit it to IPython1 controller: | |||
|
26 | """ | |||
|
27 | def __init__(self, rc, tc): | |||
|
28 | self.rc = rc | |||
|
29 | self.tc = tc | |||
|
30 | ||||
|
31 | def __call__(self, func): | |||
|
32 | return self._decorate(func) | |||
|
33 | ||||
|
34 | def _getinfo(self, func): | |||
|
35 | assert inspect.ismethod(func) or inspect.isfunction(func) | |||
|
36 | regargs, varargs, varkwargs, defaults = inspect.getargspec(func) | |||
|
37 | argnames = list(regargs) | |||
|
38 | if varargs: | |||
|
39 | argnames.append(varargs) | |||
|
40 | if varkwargs: | |||
|
41 | argnames.append(varkwargs) | |||
|
42 | counter = itertools.count() | |||
|
43 | fullsign = inspect.formatargspec( | |||
|
44 | regargs, varargs, varkwargs, defaults, | |||
|
45 | formatvalue=lambda value: '=defarg[%i]' % counter.next())[1:-1] | |||
|
46 | shortsign = inspect.formatargspec( | |||
|
47 | regargs, varargs, varkwargs, defaults, | |||
|
48 | formatvalue=lambda value: '')[1:-1] | |||
|
49 | dic = dict(('arg%s' % n, name) for n, name in enumerate(argnames)) | |||
|
50 | dic.update(name=func.__name__, argnames=argnames, shortsign=shortsign, | |||
|
51 | fullsign = fullsign, defarg = func.func_defaults or ()) | |||
|
52 | return dic | |||
|
53 | ||||
|
54 | def _decorate(self, func): | |||
|
55 | """ | |||
|
56 | Takes a function and a remote controller and returns a function | |||
|
57 | decorated that is going to submit the job with the controller. | |||
|
58 | The decorated function is obtained by evaluating a lambda | |||
|
59 | function with the correct signature. | |||
|
60 | ||||
|
61 | the TaskController setupNS doesn't cope with functions, but we | |||
|
62 | can use RemoteController to push functions/modules into engines. | |||
|
63 | ||||
|
64 | Changes: | |||
|
65 | 200803. In new ipython1, we use push_function for functions. | |||
|
66 | """ | |||
|
67 | rc, tc = self.rc, self.tc | |||
|
68 | infodict = self._getinfo(func) | |||
|
69 | if 'rc' in infodict['argnames']: | |||
|
70 | raise NameError, "You cannot use rc as argument names!" | |||
|
71 | ||||
|
72 | # we assume the engines' namepace has been prepared. | |||
|
73 | # ns[func.__name__] is already the decorated closure function. | |||
|
74 | # we need to change it back to the original function: | |||
|
75 | ns = {} | |||
|
76 | ns[func.__name__] = func | |||
|
77 | ||||
|
78 | # push func and all its environment/prerequesites to engines | |||
|
79 | rc.push_function(ns, block=True) # note it is nonblock by default, not know if it causes problems | |||
|
80 | ||||
|
81 | def do_submit_func(*args, **kwds): | |||
|
82 | jobns = {} | |||
|
83 | ||||
|
84 | # Initialize job namespace with args that have default args | |||
|
85 | # now we support calls that uses default args | |||
|
86 | for n in infodict['fullsign'].split(','): | |||
|
87 | try: | |||
|
88 | vname, var = n.split('=') | |||
|
89 | vname, var = vname.strip(), var.strip() | |||
|
90 | except: # no defarg, one of vname, var is None | |||
|
91 | pass | |||
|
92 | else: | |||
|
93 | jobns.setdefault(vname, eval(var, infodict)) | |||
|
94 | ||||
|
95 | # push args and kwds, overwritting default args if needed. | |||
|
96 | nokwds = dict((n,v) for n,v in zip(infodict['argnames'], args)) # truncated | |||
|
97 | jobns.update(nokwds) | |||
|
98 | jobns.update(kwds) | |||
|
99 | ||||
|
100 | task = Task('a_very_long_and_rare_name = %(name)s(%(shortsign)s)' % infodict, | |||
|
101 | pull=['a_very_long_and_rare_name'], push=jobns,) | |||
|
102 | jobid = tc.run(task) | |||
|
103 | # res is a deferred, one can attach callbacks on it | |||
|
104 | res = tc.task_controller.get_task_result(jobid, block=True) | |||
|
105 | res.addCallback(lambda x: x.ns['a_very_long_and_rare_name']) | |||
|
106 | res.addErrback(log.err) | |||
|
107 | return res | |||
|
108 | ||||
|
109 | do_submit_func.rc = rc | |||
|
110 | do_submit_func.tc = tc | |||
|
111 | return do_submit_func | |||
|
112 | ||||
|
113 | ||||
|
114 | def parallelized(rc, tc, initstrlist=[]): | |||
|
115 | """ rc - remote controller | |||
|
116 | tc - taks controller | |||
|
117 | strlist - a list of str that's being executed on engines. | |||
|
118 | """ | |||
|
119 | for cmd in initstrlist: | |||
|
120 | rc.execute(cmd, block=True) | |||
|
121 | return submit_job(rc, tc) | |||
|
122 | ||||
|
123 | ||||
|
124 | from twisted.internet import defer | |||
|
125 | from numpy import array, nan | |||
|
126 | ||||
|
127 | def pmap(func, parr, **kwds): | |||
|
128 | """Run func on every element of parr (array), using the elements | |||
|
129 | as the only one parameter (so you can usually use a dict that | |||
|
130 | wraps many parameters). -> a result array of Deferreds with the | |||
|
131 | same shape. func.tc will be used as the taskclient. | |||
|
132 | ||||
|
133 | **kwds are passed on to func, not changed. | |||
|
134 | """ | |||
|
135 | assert func.tc | |||
|
136 | tc = func.tc | |||
|
137 | ||||
|
138 | def run(p, **kwds): | |||
|
139 | if p: | |||
|
140 | return func(p, **kwds) | |||
|
141 | else: | |||
|
142 | return defer.succeed(nan) | |||
|
143 | ||||
|
144 | reslist = [run(p, **kwds).addErrback(log.err) for p in parr.flat] | |||
|
145 | resarr = array(reslist) | |||
|
146 | resarr.shape = parr.shape | |||
|
147 | return resarr | |||
|
148 | ||||
|
149 | ||||
|
150 | if __name__=='__main__': | |||
|
151 | ||||
|
152 | rc = client.MultiEngineClient(client.default_address) | |||
|
153 | tc = client.TaskClient(client.default_task_address) | |||
|
154 | ||||
|
155 | # if commenting out the decorator you get a local running version | |||
|
156 | # instantly | |||
|
157 | @parallelized(rc, tc) | |||
|
158 | def f(a, b=1): | |||
|
159 | #from time import sleep | |||
|
160 | #sleep(1) | |||
|
161 | print "a,b=", a,b | |||
|
162 | return a+b | |||
|
163 | ||||
|
164 | def showres(x): | |||
|
165 | print 'ans:',x | |||
|
166 | ||||
|
167 | res = f(11,5) | |||
|
168 | res.addCallback(showres) | |||
|
169 | ||||
|
170 | # this is not necessary in Twisted 8.0 | |||
|
171 | from twisted.internet import reactor | |||
|
172 | reactor.run() |
@@ -0,0 +1,119 b'' | |||||
|
1 | import types | |||
|
2 | ||||
|
3 | class AttributeBase(object): | |||
|
4 | ||||
|
5 | def __get__(self, inst, cls=None): | |||
|
6 | if inst is None: | |||
|
7 | return self | |||
|
8 | try: | |||
|
9 | return inst._attributes[self.name] | |||
|
10 | except KeyError: | |||
|
11 | raise AttributeError("object has no attribute %r" % self.name) | |||
|
12 | ||||
|
13 | def __set__(self, inst, value): | |||
|
14 | actualValue = self.validate(inst, self.name, value) | |||
|
15 | inst._attributes[self.name] = actualValue | |||
|
16 | ||||
|
17 | def validate(self, inst, name, value): | |||
|
18 | raise NotImplementedError("validate must be implemented by a subclass") | |||
|
19 | ||||
|
20 | class NameFinder(type): | |||
|
21 | ||||
|
22 | def __new__(cls, name, bases, classdict): | |||
|
23 | attributeList = [] | |||
|
24 | for k,v in classdict.iteritems(): | |||
|
25 | if isinstance(v, AttributeBase): | |||
|
26 | v.name = k | |||
|
27 | attributeList.append(k) | |||
|
28 | classdict['_attributeList'] = attributeList | |||
|
29 | return type.__new__(cls, name, bases, classdict) | |||
|
30 | ||||
|
31 | class HasAttributes(object): | |||
|
32 | __metaclass__ = NameFinder | |||
|
33 | ||||
|
34 | def __init__(self): | |||
|
35 | self._attributes = {} | |||
|
36 | ||||
|
37 | def getAttributeNames(self): | |||
|
38 | return self._attributeList | |||
|
39 | ||||
|
40 | def getAttributesOfType(self, t, default=None): | |||
|
41 | result = {} | |||
|
42 | for a in self._attributeList: | |||
|
43 | if self.__class__.__dict__[a].__class__ == t: | |||
|
44 | try: | |||
|
45 | value = getattr(self, a) | |||
|
46 | except AttributeError: | |||
|
47 | value = None | |||
|
48 | result[a] = value | |||
|
49 | return result | |||
|
50 | ||||
|
51 | class TypedAttribute(AttributeBase): | |||
|
52 | ||||
|
53 | def validate(self, inst, name, value): | |||
|
54 | if type(value) != self._type: | |||
|
55 | raise TypeError("attribute %s must be of type %s" % (name, self._type)) | |||
|
56 | else: | |||
|
57 | return value | |||
|
58 | ||||
|
59 | # class Option(TypedAttribute): | |||
|
60 | # | |||
|
61 | # _type = types.IntType | |||
|
62 | # | |||
|
63 | # class Param(TypedAttribute): | |||
|
64 | # | |||
|
65 | # _type = types.FloatType | |||
|
66 | # | |||
|
67 | # class String(TypedAttribute): | |||
|
68 | # | |||
|
69 | # _type = types.StringType | |||
|
70 | ||||
|
71 | class TypedSequenceAttribute(AttributeBase): | |||
|
72 | ||||
|
73 | def validate(self, inst, name, value): | |||
|
74 | if type(value) != types.TupleType and type(value) != types.ListType: | |||
|
75 | raise TypeError("attribute %s must be a list or tuple" % (name)) | |||
|
76 | else: | |||
|
77 | for item in value: | |||
|
78 | if type(item) != self._subtype: | |||
|
79 | raise TypeError("attribute %s must be a list or tuple of items with type %s" % (name, self._subtype)) | |||
|
80 | return value | |||
|
81 | ||||
|
82 | # class Instance(AttributeBase): | |||
|
83 | # | |||
|
84 | # def __init__(self, cls): | |||
|
85 | # self.cls = cls | |||
|
86 | # | |||
|
87 | # def validate(self, inst, name, value): | |||
|
88 | # if not isinstance(value, self.cls): | |||
|
89 | # raise TypeError("attribute %s must be an instance of class %s" % (name, self.cls)) | |||
|
90 | # else: | |||
|
91 | # return value | |||
|
92 | ||||
|
93 | ||||
|
94 | # class OptVec(TypedSequenceAttribute): | |||
|
95 | # | |||
|
96 | # _subtype = types.IntType | |||
|
97 | # | |||
|
98 | # class PrmVec(TypedSequenceAttribute): | |||
|
99 | # | |||
|
100 | # _subtype = types.FloatType | |||
|
101 | # | |||
|
102 | # class StrVec(TypedSequenceAttribute): | |||
|
103 | # | |||
|
104 | # _subtype = types.StringType | |||
|
105 | # | |||
|
106 | # | |||
|
107 | # class Bar(HasAttributes): | |||
|
108 | # | |||
|
109 | # a = Option() | |||
|
110 | # | |||
|
111 | # class Foo(HasAttributes): | |||
|
112 | # | |||
|
113 | # a = Option() | |||
|
114 | # b = Param() | |||
|
115 | # c = String() | |||
|
116 | # d = OptVec() | |||
|
117 | # e = PrmVec() | |||
|
118 | # f = StrVec() | |||
|
119 | # h = Instance(Bar) No newline at end of file |
@@ -1,123 +1,124 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 |
|
2 | |||
3 | """Default kernel configuration.""" |
|
3 | """Default kernel configuration.""" | |
4 |
|
4 | |||
5 | __docformat__ = "restructuredtext en" |
|
5 | __docformat__ = "restructuredtext en" | |
6 |
|
6 | |||
7 | #------------------------------------------------------------------------------- |
|
7 | #------------------------------------------------------------------------------- | |
8 | # Copyright (C) 2008 The IPython Development Team |
|
8 | # Copyright (C) 2008 The IPython Development Team | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #------------------------------------------------------------------------------- |
|
12 | #------------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #------------------------------------------------------------------------------- |
|
14 | #------------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #------------------------------------------------------------------------------- |
|
16 | #------------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | from os.path import join as pjoin |
|
18 | from os.path import join as pjoin | |
19 |
|
19 | |||
20 | from IPython.external.configobj import ConfigObj |
|
20 | from IPython.external.configobj import ConfigObj | |
21 | from IPython.config.api import ConfigObjManager |
|
21 | from IPython.config.api import ConfigObjManager | |
22 | from IPython.genutils import get_ipython_dir, get_security_dir |
|
22 | from IPython.genutils import get_ipython_dir, get_security_dir | |
23 |
|
23 | |||
24 | default_kernel_config = ConfigObj() |
|
24 | default_kernel_config = ConfigObj() | |
25 |
|
25 | |||
26 | security_dir = get_security_dir() |
|
26 | security_dir = get_security_dir() | |
27 |
|
27 | |||
28 | #------------------------------------------------------------------------------- |
|
28 | #------------------------------------------------------------------------------- | |
29 | # Engine Configuration |
|
29 | # Engine Configuration | |
30 | #------------------------------------------------------------------------------- |
|
30 | #------------------------------------------------------------------------------- | |
31 |
|
31 | |||
32 | engine_config = dict( |
|
32 | engine_config = dict( | |
33 | logfile = '', # Empty means log to stdout |
|
33 | logfile = '', # Empty means log to stdout | |
34 | furl_file = pjoin(security_dir, 'ipcontroller-engine.furl') |
|
34 | furl_file = pjoin(security_dir, 'ipcontroller-engine.furl') | |
35 | ) |
|
35 | ) | |
36 |
|
36 | |||
37 | #------------------------------------------------------------------------------- |
|
37 | #------------------------------------------------------------------------------- | |
38 | # MPI Configuration |
|
38 | # MPI Configuration | |
39 | #------------------------------------------------------------------------------- |
|
39 | #------------------------------------------------------------------------------- | |
40 |
|
40 | |||
41 | mpi_config = dict( |
|
41 | mpi_config = dict( | |
42 | mpi4py = """from mpi4py import MPI as mpi |
|
42 | mpi4py = """from mpi4py import MPI as mpi | |
43 | mpi.size = mpi.COMM_WORLD.Get_size() |
|
43 | mpi.size = mpi.COMM_WORLD.Get_size() | |
44 | mpi.rank = mpi.COMM_WORLD.Get_rank() |
|
44 | mpi.rank = mpi.COMM_WORLD.Get_rank() | |
45 | """, |
|
45 | """, | |
46 | pytrilinos = """from PyTrilinos import Epetra |
|
46 | pytrilinos = """from PyTrilinos import Epetra | |
47 | class SimpleStruct: |
|
47 | class SimpleStruct: | |
48 | pass |
|
48 | pass | |
49 | mpi = SimpleStruct() |
|
49 | mpi = SimpleStruct() | |
50 | mpi.rank = 0 |
|
50 | mpi.rank = 0 | |
51 | mpi.size = 0 |
|
51 | mpi.size = 0 | |
52 | """, |
|
52 | """, | |
53 | default = '' |
|
53 | default = '' | |
54 | ) |
|
54 | ) | |
55 |
|
55 | |||
56 | #------------------------------------------------------------------------------- |
|
56 | #------------------------------------------------------------------------------- | |
57 | # Controller Configuration |
|
57 | # Controller Configuration | |
58 | #------------------------------------------------------------------------------- |
|
58 | #------------------------------------------------------------------------------- | |
59 |
|
59 | |||
60 | controller_config = dict( |
|
60 | controller_config = dict( | |
61 |
|
61 | |||
62 | logfile = '', # Empty means log to stdout |
|
62 | logfile = '', # Empty means log to stdout | |
63 | import_statement = '', |
|
63 | import_statement = '', | |
|
64 | reuse_furls = False, # If False, old furl files are deleted | |||
64 |
|
65 | |||
65 | engine_tub = dict( |
|
66 | engine_tub = dict( | |
66 | ip = '', # Empty string means all interfaces |
|
67 | ip = '', # Empty string means all interfaces | |
67 | port = 0, # 0 means pick a port for me |
|
68 | port = 0, # 0 means pick a port for me | |
68 | location = '', # Empty string means try to set automatically |
|
69 | location = '', # Empty string means try to set automatically | |
69 | secure = True, |
|
70 | secure = True, | |
70 | cert_file = pjoin(security_dir, 'ipcontroller-engine.pem'), |
|
71 | cert_file = pjoin(security_dir, 'ipcontroller-engine.pem'), | |
71 | ), |
|
72 | ), | |
72 | engine_fc_interface = 'IPython.kernel.enginefc.IFCControllerBase', |
|
73 | engine_fc_interface = 'IPython.kernel.enginefc.IFCControllerBase', | |
73 | engine_furl_file = pjoin(security_dir, 'ipcontroller-engine.furl'), |
|
74 | engine_furl_file = pjoin(security_dir, 'ipcontroller-engine.furl'), | |
74 |
|
75 | |||
75 | controller_interfaces = dict( |
|
76 | controller_interfaces = dict( | |
76 | # multiengine = dict( |
|
77 | # multiengine = dict( | |
77 | # controller_interface = 'IPython.kernel.multiengine.IMultiEngine', |
|
78 | # controller_interface = 'IPython.kernel.multiengine.IMultiEngine', | |
78 | # fc_interface = 'IPython.kernel.multienginefc.IFCMultiEngine', |
|
79 | # fc_interface = 'IPython.kernel.multienginefc.IFCMultiEngine', | |
79 | # furl_file = 'ipcontroller-mec.furl' |
|
80 | # furl_file = 'ipcontroller-mec.furl' | |
80 | # ), |
|
81 | # ), | |
81 | task = dict( |
|
82 | task = dict( | |
82 | controller_interface = 'IPython.kernel.task.ITaskController', |
|
83 | controller_interface = 'IPython.kernel.task.ITaskController', | |
83 | fc_interface = 'IPython.kernel.taskfc.IFCTaskController', |
|
84 | fc_interface = 'IPython.kernel.taskfc.IFCTaskController', | |
84 | furl_file = pjoin(security_dir, 'ipcontroller-tc.furl') |
|
85 | furl_file = pjoin(security_dir, 'ipcontroller-tc.furl') | |
85 | ), |
|
86 | ), | |
86 | multiengine = dict( |
|
87 | multiengine = dict( | |
87 | controller_interface = 'IPython.kernel.multiengine.IMultiEngine', |
|
88 | controller_interface = 'IPython.kernel.multiengine.IMultiEngine', | |
88 | fc_interface = 'IPython.kernel.multienginefc.IFCSynchronousMultiEngine', |
|
89 | fc_interface = 'IPython.kernel.multienginefc.IFCSynchronousMultiEngine', | |
89 | furl_file = pjoin(security_dir, 'ipcontroller-mec.furl') |
|
90 | furl_file = pjoin(security_dir, 'ipcontroller-mec.furl') | |
90 | ) |
|
91 | ) | |
91 | ), |
|
92 | ), | |
92 |
|
93 | |||
93 | client_tub = dict( |
|
94 | client_tub = dict( | |
94 | ip = '', # Empty string means all interfaces |
|
95 | ip = '', # Empty string means all interfaces | |
95 | port = 0, # 0 means pick a port for me |
|
96 | port = 0, # 0 means pick a port for me | |
96 | location = '', # Empty string means try to set automatically |
|
97 | location = '', # Empty string means try to set automatically | |
97 | secure = True, |
|
98 | secure = True, | |
98 | cert_file = pjoin(security_dir, 'ipcontroller-client.pem') |
|
99 | cert_file = pjoin(security_dir, 'ipcontroller-client.pem') | |
99 | ) |
|
100 | ) | |
100 | ) |
|
101 | ) | |
101 |
|
102 | |||
102 | #------------------------------------------------------------------------------- |
|
103 | #------------------------------------------------------------------------------- | |
103 | # Client Configuration |
|
104 | # Client Configuration | |
104 | #------------------------------------------------------------------------------- |
|
105 | #------------------------------------------------------------------------------- | |
105 |
|
106 | |||
106 | client_config = dict( |
|
107 | client_config = dict( | |
107 | client_interfaces = dict( |
|
108 | client_interfaces = dict( | |
108 | task = dict( |
|
109 | task = dict( | |
109 | furl_file = pjoin(security_dir, 'ipcontroller-tc.furl') |
|
110 | furl_file = pjoin(security_dir, 'ipcontroller-tc.furl') | |
110 | ), |
|
111 | ), | |
111 | multiengine = dict( |
|
112 | multiengine = dict( | |
112 | furl_file = pjoin(security_dir, 'ipcontroller-mec.furl') |
|
113 | furl_file = pjoin(security_dir, 'ipcontroller-mec.furl') | |
113 | ) |
|
114 | ) | |
114 | ) |
|
115 | ) | |
115 | ) |
|
116 | ) | |
116 |
|
117 | |||
117 | default_kernel_config['engine'] = engine_config |
|
118 | default_kernel_config['engine'] = engine_config | |
118 | default_kernel_config['mpi'] = mpi_config |
|
119 | default_kernel_config['mpi'] = mpi_config | |
119 | default_kernel_config['controller'] = controller_config |
|
120 | default_kernel_config['controller'] = controller_config | |
120 | default_kernel_config['client'] = client_config |
|
121 | default_kernel_config['client'] = client_config | |
121 |
|
122 | |||
122 |
|
123 | |||
123 | config_manager = ConfigObjManager(default_kernel_config, 'IPython.kernel.ini') No newline at end of file |
|
124 | config_manager = ConfigObjManager(default_kernel_config, 'IPython.kernel.ini') |
@@ -1,87 +1,92 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 |
|
2 | |||
3 | """A class that manages the engines connection to the controller.""" |
|
3 | """A class that manages the engines connection to the controller.""" | |
4 |
|
4 | |||
5 | __docformat__ = "restructuredtext en" |
|
5 | __docformat__ = "restructuredtext en" | |
6 |
|
6 | |||
7 | #------------------------------------------------------------------------------- |
|
7 | #------------------------------------------------------------------------------- | |
8 | # Copyright (C) 2008 The IPython Development Team |
|
8 | # Copyright (C) 2008 The IPython Development Team | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #------------------------------------------------------------------------------- |
|
12 | #------------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #------------------------------------------------------------------------------- |
|
14 | #------------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #------------------------------------------------------------------------------- |
|
16 | #------------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | import os |
|
18 | import os | |
19 | import cPickle as pickle |
|
19 | import cPickle as pickle | |
20 |
|
20 | |||
21 | from twisted.python import log |
|
21 | from twisted.python import log, failure | |
|
22 | from twisted.internet import defer | |||
22 |
|
23 | |||
23 | from IPython.kernel.fcutil import find_furl |
|
24 | from IPython.kernel.fcutil import find_furl | |
24 | from IPython.kernel.enginefc import IFCEngine |
|
25 | from IPython.kernel.enginefc import IFCEngine | |
25 |
|
26 | |||
26 | #------------------------------------------------------------------------------- |
|
27 | #------------------------------------------------------------------------------- | |
27 | # The ClientConnector class |
|
28 | # The ClientConnector class | |
28 | #------------------------------------------------------------------------------- |
|
29 | #------------------------------------------------------------------------------- | |
29 |
|
30 | |||
30 | class EngineConnector(object): |
|
31 | class EngineConnector(object): | |
31 | """Manage an engines connection to a controller. |
|
32 | """Manage an engines connection to a controller. | |
32 |
|
33 | |||
33 | This class takes a foolscap `Tub` and provides a `connect_to_controller` |
|
34 | This class takes a foolscap `Tub` and provides a `connect_to_controller` | |
34 | method that will use the `Tub` to connect to a controller and register |
|
35 | method that will use the `Tub` to connect to a controller and register | |
35 | the engine with the controller. |
|
36 | the engine with the controller. | |
36 | """ |
|
37 | """ | |
37 |
|
38 | |||
38 | def __init__(self, tub): |
|
39 | def __init__(self, tub): | |
39 | self.tub = tub |
|
40 | self.tub = tub | |
40 |
|
41 | |||
41 | def connect_to_controller(self, engine_service, furl_or_file): |
|
42 | def connect_to_controller(self, engine_service, furl_or_file): | |
42 | """ |
|
43 | """ | |
43 | Make a connection to a controller specified by a furl. |
|
44 | Make a connection to a controller specified by a furl. | |
44 |
|
45 | |||
45 | This method takes an `IEngineBase` instance and a foolcap URL and uses |
|
46 | This method takes an `IEngineBase` instance and a foolcap URL and uses | |
46 | the `tub` attribute to make a connection to the controller. The |
|
47 | the `tub` attribute to make a connection to the controller. The | |
47 | foolscap URL contains all the information needed to connect to the |
|
48 | foolscap URL contains all the information needed to connect to the | |
48 | controller, including the ip and port as well as any encryption and |
|
49 | controller, including the ip and port as well as any encryption and | |
49 | authentication information needed for the connection. |
|
50 | authentication information needed for the connection. | |
50 |
|
51 | |||
51 | After getting a reference to the controller, this method calls the |
|
52 | After getting a reference to the controller, this method calls the | |
52 | `register_engine` method of the controller to actually register the |
|
53 | `register_engine` method of the controller to actually register the | |
53 | engine. |
|
54 | engine. | |
54 |
|
55 | |||
55 | :Parameters: |
|
56 | :Parameters: | |
56 | engine_service : IEngineBase |
|
57 | engine_service : IEngineBase | |
57 | An instance of an `IEngineBase` implementer |
|
58 | An instance of an `IEngineBase` implementer | |
58 | furl_or_file : str |
|
59 | furl_or_file : str | |
59 | A furl or a filename containing a furl |
|
60 | A furl or a filename containing a furl | |
60 | """ |
|
61 | """ | |
61 | if not self.tub.running: |
|
62 | if not self.tub.running: | |
62 | self.tub.startService() |
|
63 | self.tub.startService() | |
63 | self.engine_service = engine_service |
|
64 | self.engine_service = engine_service | |
64 | self.engine_reference = IFCEngine(self.engine_service) |
|
65 | self.engine_reference = IFCEngine(self.engine_service) | |
65 | self.furl = find_furl(furl_or_file) |
|
66 | try: | |
|
67 | self.furl = find_furl(furl_or_file) | |||
|
68 | except ValueError: | |||
|
69 | return defer.fail(failure.Failure()) | |||
|
70 | # return defer.fail(failure.Failure(ValueError('not a valid furl or furl file: %r' % furl_or_file))) | |||
66 | d = self.tub.getReference(self.furl) |
|
71 | d = self.tub.getReference(self.furl) | |
67 | d.addCallbacks(self._register, self._log_failure) |
|
72 | d.addCallbacks(self._register, self._log_failure) | |
68 | return d |
|
73 | return d | |
69 |
|
74 | |||
70 | def _log_failure(self, reason): |
|
75 | def _log_failure(self, reason): | |
71 | log.err('engine registration failed:') |
|
76 | log.err('EngineConnector: engine registration failed:') | |
72 | log.err(reason) |
|
77 | log.err(reason) | |
73 | return reason |
|
78 | return reason | |
74 |
|
79 | |||
75 | def _register(self, rr): |
|
80 | def _register(self, rr): | |
76 | self.remote_ref = rr |
|
81 | self.remote_ref = rr | |
77 | # Now register myself with the controller |
|
82 | # Now register myself with the controller | |
78 | desired_id = self.engine_service.id |
|
83 | desired_id = self.engine_service.id | |
79 | d = self.remote_ref.callRemote('register_engine', self.engine_reference, |
|
84 | d = self.remote_ref.callRemote('register_engine', self.engine_reference, | |
80 | desired_id, os.getpid(), pickle.dumps(self.engine_service.properties,2)) |
|
85 | desired_id, os.getpid(), pickle.dumps(self.engine_service.properties,2)) | |
81 | return d.addCallbacks(self._reference_sent, self._log_failure) |
|
86 | return d.addCallbacks(self._reference_sent, self._log_failure) | |
82 |
|
87 | |||
83 | def _reference_sent(self, registration_dict): |
|
88 | def _reference_sent(self, registration_dict): | |
84 | self.engine_service.id = registration_dict['id'] |
|
89 | self.engine_service.id = registration_dict['id'] | |
85 | log.msg("engine registration succeeded, got id: %r" % self.engine_service.id) |
|
90 | log.msg("engine registration succeeded, got id: %r" % self.engine_service.id) | |
86 | return self.engine_service.id |
|
91 | return self.engine_service.id | |
87 |
|
92 |
This diff has been collapsed as it changes many lines, (749 lines changed) Show them Hide them | |||||
@@ -1,347 +1,486 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 |
|
3 | |||
4 |
"""Start an IPython cluster |
|
4 | """Start an IPython cluster = (controller + engines).""" | |
5 |
|
5 | |||
6 | Basic usage |
|
6 | #----------------------------------------------------------------------------- | |
7 | ----------- |
|
|||
8 |
|
||||
9 | For local operation, the simplest mode of usage is: |
|
|||
10 |
|
||||
11 | %prog -n N |
|
|||
12 |
|
||||
13 | where N is the number of engines you want started. |
|
|||
14 |
|
||||
15 | For remote operation, you must call it with a cluster description file: |
|
|||
16 |
|
||||
17 | %prog -f clusterfile.py |
|
|||
18 |
|
||||
19 | The cluster file is a normal Python script which gets run via execfile(). You |
|
|||
20 | can have arbitrary logic in it, but all that matters is that at the end of the |
|
|||
21 | execution, it declares the variables 'controller', 'engines', and optionally |
|
|||
22 | 'sshx'. See the accompanying examples for details on what these variables must |
|
|||
23 | contain. |
|
|||
24 |
|
||||
25 |
|
||||
26 | Notes |
|
|||
27 | ----- |
|
|||
28 |
|
||||
29 | WARNING: this code is still UNFINISHED and EXPERIMENTAL! It is incomplete, |
|
|||
30 | some listed options are not really implemented, and all of its interfaces are |
|
|||
31 | subject to change. |
|
|||
32 |
|
||||
33 | When operating over SSH for a remote cluster, this program relies on the |
|
|||
34 | existence of a particular script called 'sshx'. This script must live in the |
|
|||
35 | target systems where you'll be running your controller and engines, and is |
|
|||
36 | needed to configure your PATH and PYTHONPATH variables for further execution of |
|
|||
37 | python code at the other end of an SSH connection. The script can be as simple |
|
|||
38 | as: |
|
|||
39 |
|
||||
40 | #!/bin/sh |
|
|||
41 | . $HOME/.bashrc |
|
|||
42 | "$@" |
|
|||
43 |
|
||||
44 | which is the default one provided by IPython. You can modify this or provide |
|
|||
45 | your own. Since it's quite likely that for different clusters you may need |
|
|||
46 | this script to configure things differently or that it may live in different |
|
|||
47 | locations, its full path can be set in the same file where you define the |
|
|||
48 | cluster setup. IPython's order of evaluation for this variable is the |
|
|||
49 | following: |
|
|||
50 |
|
||||
51 | a) Internal default: 'sshx'. This only works if it is in the default system |
|
|||
52 | path which SSH sets up in non-interactive mode. |
|
|||
53 |
|
||||
54 | b) Environment variable: if $IPYTHON_SSHX is defined, this overrides the |
|
|||
55 | internal default. |
|
|||
56 |
|
||||
57 | c) Variable 'sshx' in the cluster configuration file: finally, this will |
|
|||
58 | override the previous two values. |
|
|||
59 |
|
||||
60 | This code is Unix-only, with precious little hope of any of this ever working |
|
|||
61 | under Windows, since we need SSH from the ground up, we background processes, |
|
|||
62 | etc. Ports of this functionality to Windows are welcome. |
|
|||
63 |
|
||||
64 |
|
||||
65 | Call summary |
|
|||
66 | ------------ |
|
|||
67 |
|
||||
68 | %prog [options] |
|
|||
69 | """ |
|
|||
70 |
|
||||
71 | __docformat__ = "restructuredtext en" |
|
|||
72 |
|
||||
73 | #------------------------------------------------------------------------------- |
|
|||
74 | # Copyright (C) 2008 The IPython Development Team |
|
7 | # Copyright (C) 2008 The IPython Development Team | |
75 | # |
|
8 | # | |
76 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
77 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
78 |
#----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
79 |
|
12 | |||
80 |
#----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
81 |
# |
|
14 | # Imports | |
82 |
#----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
83 |
|
16 | |||
84 | import os |
|
17 | import os | |
85 |
import |
|
18 | import re | |
86 | import sys |
|
19 | import sys | |
87 |
import |
|
20 | import signal | |
|
21 | pjoin = os.path.join | |||
88 |
|
22 | |||
89 | from optparse import OptionParser |
|
23 | from twisted.internet import reactor, defer | |
90 | from subprocess import Popen,call |
|
24 | from twisted.internet.protocol import ProcessProtocol | |
|
25 | from twisted.python import failure, log | |||
|
26 | from twisted.internet.error import ProcessDone, ProcessTerminated | |||
|
27 | from twisted.internet.utils import getProcessOutput | |||
91 |
|
28 | |||
92 | #--------------------------------------------------------------------------- |
|
29 | from IPython.external import argparse | |
93 |
|
|
30 | from IPython.external import Itpl | |
94 | #--------------------------------------------------------------------------- |
|
31 | from IPython.kernel.twistedutil import gatherBoth | |
95 |
from IPython. |
|
32 | from IPython.kernel.util import printer | |
96 | from IPython.genutils import get_ipython_dir |
|
33 | from IPython.genutils import get_ipython_dir, num_cpus | |
97 |
|
34 | |||
98 | #--------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
99 | # Normal code begins |
|
36 | # General process handling code | |
100 | #--------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
101 |
|
38 | |||
102 | def parse_args(): |
|
39 | def find_exe(cmd): | |
103 | """Parse command line and return opts,args.""" |
|
40 | try: | |
|
41 | import win32api | |||
|
42 | except ImportError: | |||
|
43 | raise ImportError('you need to have pywin32 installed for this to work') | |||
|
44 | else: | |||
|
45 | (path, offest) = win32api.SearchPath(os.environ['PATH'],cmd) | |||
|
46 | return path | |||
104 |
|
47 | |||
105 | parser = OptionParser(usage=__doc__) |
|
48 | class ProcessStateError(Exception): | |
106 | newopt = parser.add_option # shorthand |
|
49 | pass | |
107 |
|
50 | |||
108 | newopt("--controller-port", type="int", dest="controllerport", |
|
51 | class UnknownStatus(Exception): | |
109 | help="the TCP port the controller is listening on") |
|
52 | pass | |
110 |
|
53 | |||
111 | newopt("--controller-ip", type="string", dest="controllerip", |
|
54 | class LauncherProcessProtocol(ProcessProtocol): | |
112 | help="the TCP ip address of the controller") |
|
55 | """ | |
|
56 | A ProcessProtocol to go with the ProcessLauncher. | |||
|
57 | """ | |||
|
58 | def __init__(self, process_launcher): | |||
|
59 | self.process_launcher = process_launcher | |||
|
60 | ||||
|
61 | def connectionMade(self): | |||
|
62 | self.process_launcher.fire_start_deferred(self.transport.pid) | |||
|
63 | ||||
|
64 | def processEnded(self, status): | |||
|
65 | value = status.value | |||
|
66 | if isinstance(value, ProcessDone): | |||
|
67 | self.process_launcher.fire_stop_deferred(0) | |||
|
68 | elif isinstance(value, ProcessTerminated): | |||
|
69 | self.process_launcher.fire_stop_deferred( | |||
|
70 | {'exit_code':value.exitCode, | |||
|
71 | 'signal':value.signal, | |||
|
72 | 'status':value.status | |||
|
73 | } | |||
|
74 | ) | |||
|
75 | else: | |||
|
76 | raise UnknownStatus("unknown exit status, this is probably a bug in Twisted") | |||
113 |
|
77 | |||
114 | newopt("-n", "--num", type="int", dest="n",default=2, |
|
78 | def outReceived(self, data): | |
115 | help="the number of engines to start") |
|
79 | log.msg(data) | |
116 |
|
80 | |||
117 | newopt("--engine-port", type="int", dest="engineport", |
|
81 | def errReceived(self, data): | |
118 | help="the TCP port the controller will listen on for engine " |
|
82 | log.err(data) | |
119 | "connections") |
|
|||
120 |
|
||||
121 | newopt("--engine-ip", type="string", dest="engineip", |
|
|||
122 | help="the TCP ip address the controller will listen on " |
|
|||
123 | "for engine connections") |
|
|||
124 |
|
83 | |||
125 | newopt("--mpi", type="string", dest="mpi", |
|
84 | class ProcessLauncher(object): | |
126 | help="use mpi with package: for instance --mpi=mpi4py") |
|
85 | """ | |
|
86 | Start and stop an external process in an asynchronous manner. | |||
|
87 | ||||
|
88 | Currently this uses deferreds to notify other parties of process state | |||
|
89 | changes. This is an awkward design and should be moved to using | |||
|
90 | a formal NotificationCenter. | |||
|
91 | """ | |||
|
92 | def __init__(self, cmd_and_args): | |||
|
93 | self.cmd = cmd_and_args[0] | |||
|
94 | self.args = cmd_and_args | |||
|
95 | self._reset() | |||
|
96 | ||||
|
97 | def _reset(self): | |||
|
98 | self.process_protocol = None | |||
|
99 | self.pid = None | |||
|
100 | self.start_deferred = None | |||
|
101 | self.stop_deferreds = [] | |||
|
102 | self.state = 'before' # before, running, or after | |||
|
103 | ||||
|
104 | @property | |||
|
105 | def running(self): | |||
|
106 | if self.state == 'running': | |||
|
107 | return True | |||
|
108 | else: | |||
|
109 | return False | |||
|
110 | ||||
|
111 | def fire_start_deferred(self, pid): | |||
|
112 | self.pid = pid | |||
|
113 | self.state = 'running' | |||
|
114 | log.msg('Process %r has started with pid=%i' % (self.args, pid)) | |||
|
115 | self.start_deferred.callback(pid) | |||
|
116 | ||||
|
117 | def start(self): | |||
|
118 | if self.state == 'before': | |||
|
119 | self.process_protocol = LauncherProcessProtocol(self) | |||
|
120 | self.start_deferred = defer.Deferred() | |||
|
121 | self.process_transport = reactor.spawnProcess( | |||
|
122 | self.process_protocol, | |||
|
123 | self.cmd, | |||
|
124 | self.args, | |||
|
125 | env=os.environ | |||
|
126 | ) | |||
|
127 | return self.start_deferred | |||
|
128 | else: | |||
|
129 | s = 'the process has already been started and has state: %r' % \ | |||
|
130 | self.state | |||
|
131 | return defer.fail(ProcessStateError(s)) | |||
|
132 | ||||
|
133 | def get_stop_deferred(self): | |||
|
134 | if self.state == 'running' or self.state == 'before': | |||
|
135 | d = defer.Deferred() | |||
|
136 | self.stop_deferreds.append(d) | |||
|
137 | return d | |||
|
138 | else: | |||
|
139 | s = 'this process is already complete' | |||
|
140 | return defer.fail(ProcessStateError(s)) | |||
|
141 | ||||
|
142 | def fire_stop_deferred(self, exit_code): | |||
|
143 | log.msg('Process %r has stopped with %r' % (self.args, exit_code)) | |||
|
144 | self.state = 'after' | |||
|
145 | for d in self.stop_deferreds: | |||
|
146 | d.callback(exit_code) | |||
|
147 | ||||
|
148 | def signal(self, sig): | |||
|
149 | """ | |||
|
150 | Send a signal to the process. | |||
|
151 | ||||
|
152 | The argument sig can be ('KILL','INT', etc.) or any signal number. | |||
|
153 | """ | |||
|
154 | if self.state == 'running': | |||
|
155 | self.process_transport.signalProcess(sig) | |||
127 |
|
156 | |||
128 | newopt("-l", "--logfile", type="string", dest="logfile", |
|
157 | # def __del__(self): | |
129 | help="log file name") |
|
158 | # self.signal('KILL') | |
|
159 | ||||
|
160 | def interrupt_then_kill(self, delay=1.0): | |||
|
161 | self.signal('INT') | |||
|
162 | reactor.callLater(delay, self.signal, 'KILL') | |||
|
163 | ||||
130 |
|
164 | |||
131 | newopt('-f','--cluster-file',dest='clusterfile', |
|
165 | #----------------------------------------------------------------------------- | |
132 | help='file describing a remote cluster') |
|
166 | # Code for launching controller and engines | |
|
167 | #----------------------------------------------------------------------------- | |||
133 |
|
168 | |||
134 | return parser.parse_args() |
|
|||
135 |
|
169 | |||
136 | def numAlive(controller,engines): |
|
170 | class ControllerLauncher(ProcessLauncher): | |
137 | """Return the number of processes still alive.""" |
|
171 | ||
138 | retcodes = [controller.poll()] + \ |
|
172 | def __init__(self, extra_args=None): | |
139 | [e.poll() for e in engines] |
|
173 | if sys.platform == 'win32': | |
140 | return retcodes.count(None) |
|
174 | args = [find_exe('ipcontroller.bat')] | |
|
175 | else: | |||
|
176 | args = ['ipcontroller'] | |||
|
177 | self.extra_args = extra_args | |||
|
178 | if extra_args is not None: | |||
|
179 | args.extend(extra_args) | |||
|
180 | ||||
|
181 | ProcessLauncher.__init__(self, args) | |||
141 |
|
182 | |||
142 | stop = lambda pid: os.kill(pid,signal.SIGINT) |
|
|||
143 | kill = lambda pid: os.kill(pid,signal.SIGTERM) |
|
|||
144 |
|
183 | |||
145 | def cleanup(clean,controller,engines): |
|
184 | class EngineLauncher(ProcessLauncher): | |
146 | """Stop the controller and engines with the given cleanup method.""" |
|
|||
147 |
|
185 | |||
148 | for e in engines: |
|
186 | def __init__(self, extra_args=None): | |
149 | if e.poll() is None: |
|
187 | if sys.platform == 'win32': | |
150 | print 'Stopping engine, pid',e.pid |
|
188 | args = [find_exe('ipengine.bat')] | |
151 | clean(e.pid) |
|
189 | else: | |
152 | if controller.poll() is None: |
|
190 | args = ['ipengine'] | |
153 | print 'Stopping controller, pid',controller.pid |
|
191 | self.extra_args = extra_args | |
154 | clean(controller.pid) |
|
192 | if extra_args is not None: | |
155 |
|
193 | args.extend(extra_args) | ||
156 |
|
194 | |||
157 | def ensureDir(path): |
|
195 | ProcessLauncher.__init__(self, args) | |
158 | """Ensure a directory exists or raise an exception.""" |
|
|||
159 | if not os.path.isdir(path): |
|
|||
160 | os.makedirs(path) |
|
|||
161 |
|
||||
162 |
|
||||
163 | def startMsg(control_host,control_port=10105): |
|
|||
164 | """Print a startup message""" |
|
|||
165 |
|
||||
166 | print 'Your cluster is up and running.' |
|
|||
167 |
|
||||
168 | print 'For interactive use, you can make a MultiEngineClient with:' |
|
|||
169 |
|
||||
170 | print 'from IPython.kernel import client' |
|
|||
171 | print "mec = client.MultiEngineClient()" |
|
|||
172 |
|
||||
173 | print 'You can then cleanly stop the cluster from IPython using:' |
|
|||
174 |
|
||||
175 | print 'mec.kill(controller=True)' |
|
|||
176 |
|
||||
177 |
|
196 | |||
|
197 | ||||
|
198 | class LocalEngineSet(object): | |||
178 |
|
199 | |||
179 | def clusterLocal(opt,arg): |
|
200 | def __init__(self, extra_args=None): | |
180 | """Start a cluster on the local machine.""" |
|
201 | self.extra_args = extra_args | |
|
202 | self.launchers = [] | |||
181 |
|
203 | |||
182 | # Store all logs inside the ipython directory |
|
204 | def start(self, n): | |
183 | ipdir = get_ipython_dir() |
|
205 | dlist = [] | |
184 | pjoin = os.path.join |
|
206 | for i in range(n): | |
185 |
|
207 | el = EngineLauncher(extra_args=self.extra_args) | ||
186 | logfile = opt.logfile |
|
208 | d = el.start() | |
187 | if logfile is None: |
|
209 | self.launchers.append(el) | |
188 | logdir_base = pjoin(ipdir,'log') |
|
210 | dlist.append(d) | |
189 | ensureDir(logdir_base) |
|
211 | dfinal = gatherBoth(dlist, consumeErrors=True) | |
190 | logfile = pjoin(logdir_base,'ipcluster-') |
|
212 | dfinal.addCallback(self._handle_start) | |
191 |
|
213 | return dfinal | ||
192 | print 'Starting controller:', |
|
|||
193 | controller = Popen(['ipcontroller','--logfile',logfile,'-x','-y']) |
|
|||
194 | print 'Controller PID:',controller.pid |
|
|||
195 |
|
||||
196 | print 'Starting engines: ', |
|
|||
197 | time.sleep(5) |
|
|||
198 |
|
||||
199 | englogfile = '%s%s-' % (logfile,controller.pid) |
|
|||
200 | mpi = opt.mpi |
|
|||
201 | if mpi: # start with mpi - killing the engines with sigterm will not work if you do this |
|
|||
202 | engines = [Popen(['mpirun', '-np', str(opt.n), 'ipengine', '--mpi', |
|
|||
203 | mpi, '--logfile',englogfile])] |
|
|||
204 | # engines = [Popen(['mpirun', '-np', str(opt.n), 'ipengine', '--mpi', mpi])] |
|
|||
205 | else: # do what we would normally do |
|
|||
206 | engines = [ Popen(['ipengine','--logfile',englogfile]) |
|
|||
207 | for i in range(opt.n) ] |
|
|||
208 | eids = [e.pid for e in engines] |
|
|||
209 | print 'Engines PIDs: ',eids |
|
|||
210 | print 'Log files: %s*' % englogfile |
|
|||
211 |
|
214 | |||
212 | proc_ids = eids + [controller.pid] |
|
215 | def _handle_start(self, r): | |
213 | procs = engines + [controller] |
|
216 | log.msg('Engines started with pids: %r' % r) | |
214 |
|
217 | return r | ||
215 | grpid = os.getpgrp() |
|
|||
216 | try: |
|
|||
217 | startMsg('127.0.0.1') |
|
|||
218 | print 'You can also hit Ctrl-C to stop it, or use from the cmd line:' |
|
|||
219 |
|
||||
220 | print 'kill -INT',grpid |
|
|||
221 |
|
||||
222 | try: |
|
|||
223 | while True: |
|
|||
224 | time.sleep(5) |
|
|||
225 | except: |
|
|||
226 | pass |
|
|||
227 | finally: |
|
|||
228 | print 'Stopping cluster. Cleaning up...' |
|
|||
229 | cleanup(stop,controller,engines) |
|
|||
230 | for i in range(4): |
|
|||
231 | time.sleep(i+2) |
|
|||
232 | nZombies = numAlive(controller,engines) |
|
|||
233 | if nZombies== 0: |
|
|||
234 | print 'OK: All processes cleaned up.' |
|
|||
235 | break |
|
|||
236 | print 'Trying again, %d processes did not stop...' % nZombies |
|
|||
237 | cleanup(kill,controller,engines) |
|
|||
238 | if numAlive(controller,engines) == 0: |
|
|||
239 | print 'OK: All processes cleaned up.' |
|
|||
240 | break |
|
|||
241 | else: |
|
|||
242 | print '*'*75 |
|
|||
243 | print 'ERROR: could not kill some processes, try to do it', |
|
|||
244 | print 'manually.' |
|
|||
245 | zombies = [] |
|
|||
246 | if controller.returncode is None: |
|
|||
247 | print 'Controller is alive: pid =',controller.pid |
|
|||
248 | zombies.append(controller.pid) |
|
|||
249 | liveEngines = [ e for e in engines if e.returncode is None ] |
|
|||
250 | for e in liveEngines: |
|
|||
251 | print 'Engine is alive: pid =',e.pid |
|
|||
252 | zombies.append(e.pid) |
|
|||
253 |
|
||||
254 | print 'Zombie summary:',' '.join(map(str,zombies)) |
|
|||
255 |
|
||||
256 | def clusterRemote(opt,arg): |
|
|||
257 | """Start a remote cluster over SSH""" |
|
|||
258 |
|
||||
259 | # B. Granger, 9/3/08 |
|
|||
260 | # The launching of a remote cluster using SSH and a clusterfile |
|
|||
261 | # is broken. Because it won't be fixed before the 0.9 release, |
|
|||
262 | # we are removing it. For now, we just print a message to the |
|
|||
263 | # user and abort. |
|
|||
264 |
|
218 | |||
265 | print """The launching of a remote IPython cluster using SSL |
|
219 | def _handle_stop(self, r): | |
266 | and a clusterfile has been removed in this release. |
|
220 | log.msg('Engines received signal: %r' % r) | |
267 | It has been broken for a while and we are in the process |
|
221 | return r | |
268 | of building a new process management system that will be |
|
222 | ||
269 | used to provide a more robust way of starting an IPython |
|
223 | def signal(self, sig): | |
270 | cluster. |
|
224 | dlist = [] | |
271 |
|
225 | for el in self.launchers: | ||
272 | For now remote clusters have to be launched using ipcontroller |
|
226 | d = el.get_stop_deferred() | |
273 | and ipengine separately. |
|
227 | dlist.append(d) | |
274 | """ |
|
228 | el.signal(sig) | |
275 | sys.exit(1) |
|
229 | dfinal = gatherBoth(dlist, consumeErrors=True) | |
276 |
|
230 | dfinal.addCallback(self._handle_stop) | ||
277 | # Load the remote cluster configuration |
|
231 | return dfinal | |
278 | clConfig = {} |
|
232 | ||
279 | execfile(opt.clusterfile,clConfig) |
|
233 | def interrupt_then_kill(self, delay=1.0): | |
280 | contConfig = clConfig['controller'] |
|
234 | dlist = [] | |
281 | engConfig = clConfig['engines'] |
|
235 | for el in self.launchers: | |
282 | # Determine where to find sshx: |
|
236 | d = el.get_stop_deferred() | |
283 | sshx = clConfig.get('sshx',os.environ.get('IPYTHON_SSHX','sshx')) |
|
237 | dlist.append(d) | |
|
238 | el.interrupt_then_kill(delay) | |||
|
239 | dfinal = gatherBoth(dlist, consumeErrors=True) | |||
|
240 | dfinal.addCallback(self._handle_stop) | |||
|
241 | return dfinal | |||
|
242 | ||||
|
243 | ||||
|
244 | class BatchEngineSet(object): | |||
284 |
|
245 | |||
285 | # Store all logs inside the ipython directory |
|
246 | # Subclasses must fill these in. See PBSEngineSet | |
286 | ipdir = get_ipython_dir() |
|
247 | submit_command = '' | |
287 | pjoin = os.path.join |
|
248 | delete_command = '' | |
288 |
|
249 | job_id_regexp = '' | ||
289 | logfile = opt.logfile |
|
|||
290 | if logfile is None: |
|
|||
291 | logdir_base = pjoin(ipdir,'log') |
|
|||
292 | ensureDir(logdir_base) |
|
|||
293 | logfile = pjoin(logdir_base,'ipcluster') |
|
|||
294 |
|
||||
295 | # Append this script's PID to the logfile name always |
|
|||
296 | logfile = '%s-%s' % (logfile,os.getpid()) |
|
|||
297 |
|
250 | |||
298 | print 'Starting controller:' |
|
251 | def __init__(self, template_file, **kwargs): | |
299 | # Controller data: |
|
252 | self.template_file = template_file | |
300 | xsys = os.system |
|
253 | self.context = {} | |
301 |
|
254 | self.context.update(kwargs) | ||
302 | contHost = contConfig['host'] |
|
255 | self.batch_file = self.template_file+'-run' | |
303 | contLog = '%s-con-%s-' % (logfile,contHost) |
|
256 | ||
304 | cmd = "ssh %s '%s' 'ipcontroller --logfile %s' &" % \ |
|
257 | def parse_job_id(self, output): | |
305 | (contHost,sshx,contLog) |
|
258 | m = re.match(self.job_id_regexp, output) | |
306 | #print 'cmd:<%s>' % cmd # dbg |
|
259 | if m is not None: | |
307 | xsys(cmd) |
|
260 | job_id = m.group() | |
308 | time.sleep(2) |
|
|||
309 |
|
||||
310 | print 'Starting engines: ' |
|
|||
311 | for engineHost,engineData in engConfig.iteritems(): |
|
|||
312 | if isinstance(engineData,int): |
|
|||
313 | numEngines = engineData |
|
|||
314 | else: |
|
261 | else: | |
315 | raise NotImplementedError('port configuration not finished for engines') |
|
262 | raise Exception("job id couldn't be determined: %s" % output) | |
316 |
|
263 | self.job_id = job_id | ||
317 | print 'Sarting %d engines on %s' % (numEngines,engineHost) |
|
264 | log.msg('Job started with job id: %r' % job_id) | |
318 | engLog = '%s-eng-%s-' % (logfile,engineHost) |
|
265 | return job_id | |
319 | for i in range(numEngines): |
|
266 | ||
320 | cmd = "ssh %s '%s' 'ipengine --controller-ip %s --logfile %s' &" % \ |
|
267 | def write_batch_script(self, n): | |
321 | (engineHost,sshx,contHost,engLog) |
|
268 | self.context['n'] = n | |
322 | #print 'cmd:<%s>' % cmd # dbg |
|
269 | template = open(self.template_file, 'r').read() | |
323 | xsys(cmd) |
|
270 | log.msg('Using template for batch script: %s' % self.template_file) | |
324 | # Wait after each host a little bit |
|
271 | script_as_string = Itpl.itplns(template, self.context) | |
325 | time.sleep(1) |
|
272 | log.msg('Writing instantiated batch script: %s' % self.batch_file) | |
326 |
|
273 | f = open(self.batch_file,'w') | ||
327 | startMsg(contConfig['host']) |
|
274 | f.write(script_as_string) | |
|
275 | f.close() | |||
|
276 | ||||
|
277 | def handle_error(self, f): | |||
|
278 | f.printTraceback() | |||
|
279 | f.raiseException() | |||
|
280 | ||||
|
281 | def start(self, n): | |||
|
282 | self.write_batch_script(n) | |||
|
283 | d = getProcessOutput(self.submit_command, | |||
|
284 | [self.batch_file],env=os.environ) | |||
|
285 | d.addCallback(self.parse_job_id) | |||
|
286 | d.addErrback(self.handle_error) | |||
|
287 | return d | |||
328 |
|
288 | |||
329 | def main(): |
|
289 | def kill(self): | |
330 | """Main driver for the two big options: local or remote cluster.""" |
|
290 | d = getProcessOutput(self.delete_command, | |
|
291 | [self.job_id],env=os.environ) | |||
|
292 | return d | |||
|
293 | ||||
|
294 | class PBSEngineSet(BatchEngineSet): | |||
331 |
|
295 | |||
332 | if sys.platform=='win32': |
|
296 | submit_command = 'qsub' | |
333 | print """ipcluster does not work on Microsoft Windows. Please start |
|
297 | delete_command = 'qdel' | |
334 | your IPython cluster using the ipcontroller and ipengine scripts.""" |
|
298 | job_id_regexp = '\d+' | |
335 | sys.exit(1) |
|
|||
336 |
|
299 | |||
337 | opt,arg = parse_args() |
|
300 | def __init__(self, template_file, **kwargs): | |
|
301 | BatchEngineSet.__init__(self, template_file, **kwargs) | |||
|
302 | ||||
|
303 | ||||
|
304 | #----------------------------------------------------------------------------- | |||
|
305 | # Main functions for the different types of clusters | |||
|
306 | #----------------------------------------------------------------------------- | |||
|
307 | ||||
|
308 | # TODO: | |||
|
309 | # The logic in these codes should be moved into classes like LocalCluster | |||
|
310 | # MpirunCluster, PBSCluster, etc. This would remove alot of the duplications. | |||
|
311 | # The main functions should then just parse the command line arguments, create | |||
|
312 | # the appropriate class and call a 'start' method. | |||
|
313 | ||||
|
314 | def main_local(args): | |||
|
315 | cont_args = [] | |||
|
316 | cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller')) | |||
|
317 | if args.x: | |||
|
318 | cont_args.append('-x') | |||
|
319 | if args.y: | |||
|
320 | cont_args.append('-y') | |||
|
321 | cl = ControllerLauncher(extra_args=cont_args) | |||
|
322 | dstart = cl.start() | |||
|
323 | def start_engines(cont_pid): | |||
|
324 | engine_args = [] | |||
|
325 | engine_args.append('--logfile=%s' % \ | |||
|
326 | pjoin(args.logdir,'ipengine%s-' % cont_pid)) | |||
|
327 | eset = LocalEngineSet(extra_args=engine_args) | |||
|
328 | def shutdown(signum, frame): | |||
|
329 | log.msg('Stopping local cluster') | |||
|
330 | # We are still playing with the times here, but these seem | |||
|
331 | # to be reliable in allowing everything to exit cleanly. | |||
|
332 | eset.interrupt_then_kill(0.5) | |||
|
333 | cl.interrupt_then_kill(0.5) | |||
|
334 | reactor.callLater(1.0, reactor.stop) | |||
|
335 | signal.signal(signal.SIGINT,shutdown) | |||
|
336 | d = eset.start(args.n) | |||
|
337 | return d | |||
|
338 | def delay_start(cont_pid): | |||
|
339 | # This is needed because the controller doesn't start listening | |||
|
340 | # right when it starts and the controller needs to write | |||
|
341 | # furl files for the engine to pick up | |||
|
342 | reactor.callLater(1.0, start_engines, cont_pid) | |||
|
343 | dstart.addCallback(delay_start) | |||
|
344 | dstart.addErrback(lambda f: f.raiseException()) | |||
|
345 | ||||
|
346 | def main_mpirun(args): | |||
|
347 | cont_args = [] | |||
|
348 | cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller')) | |||
|
349 | if args.x: | |||
|
350 | cont_args.append('-x') | |||
|
351 | if args.y: | |||
|
352 | cont_args.append('-y') | |||
|
353 | cl = ControllerLauncher(extra_args=cont_args) | |||
|
354 | dstart = cl.start() | |||
|
355 | def start_engines(cont_pid): | |||
|
356 | raw_args = ['mpirun'] | |||
|
357 | raw_args.extend(['-n',str(args.n)]) | |||
|
358 | raw_args.append('ipengine') | |||
|
359 | raw_args.append('-l') | |||
|
360 | raw_args.append(pjoin(args.logdir,'ipengine%s-' % cont_pid)) | |||
|
361 | if args.mpi: | |||
|
362 | raw_args.append('--mpi=%s' % args.mpi) | |||
|
363 | eset = ProcessLauncher(raw_args) | |||
|
364 | def shutdown(signum, frame): | |||
|
365 | log.msg('Stopping local cluster') | |||
|
366 | # We are still playing with the times here, but these seem | |||
|
367 | # to be reliable in allowing everything to exit cleanly. | |||
|
368 | eset.interrupt_then_kill(1.0) | |||
|
369 | cl.interrupt_then_kill(1.0) | |||
|
370 | reactor.callLater(2.0, reactor.stop) | |||
|
371 | signal.signal(signal.SIGINT,shutdown) | |||
|
372 | d = eset.start() | |||
|
373 | return d | |||
|
374 | def delay_start(cont_pid): | |||
|
375 | # This is needed because the controller doesn't start listening | |||
|
376 | # right when it starts and the controller needs to write | |||
|
377 | # furl files for the engine to pick up | |||
|
378 | reactor.callLater(1.0, start_engines, cont_pid) | |||
|
379 | dstart.addCallback(delay_start) | |||
|
380 | dstart.addErrback(lambda f: f.raiseException()) | |||
|
381 | ||||
|
382 | def main_pbs(args): | |||
|
383 | cont_args = [] | |||
|
384 | cont_args.append('--logfile=%s' % pjoin(args.logdir,'ipcontroller')) | |||
|
385 | if args.x: | |||
|
386 | cont_args.append('-x') | |||
|
387 | if args.y: | |||
|
388 | cont_args.append('-y') | |||
|
389 | cl = ControllerLauncher(extra_args=cont_args) | |||
|
390 | dstart = cl.start() | |||
|
391 | def start_engines(r): | |||
|
392 | pbs_set = PBSEngineSet(args.pbsscript) | |||
|
393 | def shutdown(signum, frame): | |||
|
394 | log.msg('Stopping pbs cluster') | |||
|
395 | d = pbs_set.kill() | |||
|
396 | d.addBoth(lambda _: cl.interrupt_then_kill(1.0)) | |||
|
397 | d.addBoth(lambda _: reactor.callLater(2.0, reactor.stop)) | |||
|
398 | signal.signal(signal.SIGINT,shutdown) | |||
|
399 | d = pbs_set.start(args.n) | |||
|
400 | return d | |||
|
401 | dstart.addCallback(start_engines) | |||
|
402 | dstart.addErrback(lambda f: f.raiseException()) | |||
|
403 | ||||
|
404 | ||||
|
405 | def get_args(): | |||
|
406 | base_parser = argparse.ArgumentParser(add_help=False) | |||
|
407 | base_parser.add_argument( | |||
|
408 | '-x', | |||
|
409 | action='store_true', | |||
|
410 | dest='x', | |||
|
411 | help='turn off client security' | |||
|
412 | ) | |||
|
413 | base_parser.add_argument( | |||
|
414 | '-y', | |||
|
415 | action='store_true', | |||
|
416 | dest='y', | |||
|
417 | help='turn off engine security' | |||
|
418 | ) | |||
|
419 | base_parser.add_argument( | |||
|
420 | "--logdir", | |||
|
421 | type=str, | |||
|
422 | dest="logdir", | |||
|
423 | help="directory to put log files (default=$IPYTHONDIR/log)", | |||
|
424 | default=pjoin(get_ipython_dir(),'log') | |||
|
425 | ) | |||
|
426 | base_parser.add_argument( | |||
|
427 | "-n", | |||
|
428 | "--num", | |||
|
429 | type=int, | |||
|
430 | dest="n", | |||
|
431 | default=2, | |||
|
432 | help="the number of engines to start" | |||
|
433 | ) | |||
|
434 | ||||
|
435 | parser = argparse.ArgumentParser( | |||
|
436 | description='IPython cluster startup. This starts a controller and\ | |||
|
437 | engines using various approaches. THIS IS A TECHNOLOGY PREVIEW AND\ | |||
|
438 | THE API WILL CHANGE SIGNIFICANTLY BEFORE THE FINAL RELEASE.' | |||
|
439 | ) | |||
|
440 | subparsers = parser.add_subparsers( | |||
|
441 | help='available cluster types. For help, do "ipcluster TYPE --help"') | |||
|
442 | ||||
|
443 | parser_local = subparsers.add_parser( | |||
|
444 | 'local', | |||
|
445 | help='run a local cluster', | |||
|
446 | parents=[base_parser] | |||
|
447 | ) | |||
|
448 | parser_local.set_defaults(func=main_local) | |||
|
449 | ||||
|
450 | parser_mpirun = subparsers.add_parser( | |||
|
451 | 'mpirun', | |||
|
452 | help='run a cluster using mpirun', | |||
|
453 | parents=[base_parser] | |||
|
454 | ) | |||
|
455 | parser_mpirun.add_argument( | |||
|
456 | "--mpi", | |||
|
457 | type=str, | |||
|
458 | dest="mpi", # Don't put a default here to allow no MPI support | |||
|
459 | help="how to call MPI_Init (default=mpi4py)" | |||
|
460 | ) | |||
|
461 | parser_mpirun.set_defaults(func=main_mpirun) | |||
|
462 | ||||
|
463 | parser_pbs = subparsers.add_parser( | |||
|
464 | 'pbs', | |||
|
465 | help='run a pbs cluster', | |||
|
466 | parents=[base_parser] | |||
|
467 | ) | |||
|
468 | parser_pbs.add_argument( | |||
|
469 | '--pbs-script', | |||
|
470 | type=str, | |||
|
471 | dest='pbsscript', | |||
|
472 | help='PBS script template', | |||
|
473 | default='pbs.template' | |||
|
474 | ) | |||
|
475 | parser_pbs.set_defaults(func=main_pbs) | |||
|
476 | args = parser.parse_args() | |||
|
477 | return args | |||
338 |
|
478 | |||
339 | clusterfile = opt.clusterfile |
|
479 | def main(): | |
340 | if clusterfile: |
|
480 | args = get_args() | |
341 | clusterRemote(opt,arg) |
|
481 | reactor.callWhenRunning(args.func, args) | |
342 | else: |
|
482 | log.startLogging(sys.stdout) | |
343 | clusterLocal(opt,arg) |
|
483 | reactor.run() | |
344 |
|
484 | |||
345 |
|
485 | if __name__ == '__main__': | ||
346 | if __name__=='__main__': |
|
|||
347 | main() |
|
486 | main() |
@@ -1,366 +1,388 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 |
|
3 | |||
4 | """The IPython controller.""" |
|
4 | """The IPython controller.""" | |
5 |
|
5 | |||
6 | __docformat__ = "restructuredtext en" |
|
6 | __docformat__ = "restructuredtext en" | |
7 |
|
7 | |||
8 | #------------------------------------------------------------------------------- |
|
8 | #------------------------------------------------------------------------------- | |
9 | # Copyright (C) 2008 The IPython Development Team |
|
9 | # Copyright (C) 2008 The IPython Development Team | |
10 | # |
|
10 | # | |
11 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | # Distributed under the terms of the BSD License. The full license is in | |
12 | # the file COPYING, distributed as part of this software. |
|
12 | # the file COPYING, distributed as part of this software. | |
13 | #------------------------------------------------------------------------------- |
|
13 | #------------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | #------------------------------------------------------------------------------- |
|
15 | #------------------------------------------------------------------------------- | |
16 | # Imports |
|
16 | # Imports | |
17 | #------------------------------------------------------------------------------- |
|
17 | #------------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | # Python looks for an empty string at the beginning of sys.path to enable |
|
19 | # Python looks for an empty string at the beginning of sys.path to enable | |
20 | # importing from the cwd. |
|
20 | # importing from the cwd. | |
21 | import sys |
|
21 | import sys | |
22 | sys.path.insert(0, '') |
|
22 | sys.path.insert(0, '') | |
23 |
|
23 | |||
24 | import sys, time, os |
|
24 | import sys, time, os | |
25 | from optparse import OptionParser |
|
25 | from optparse import OptionParser | |
26 |
|
26 | |||
27 | from twisted.application import internet, service |
|
27 | from twisted.application import internet, service | |
28 | from twisted.internet import reactor, error, defer |
|
28 | from twisted.internet import reactor, error, defer | |
29 | from twisted.python import log |
|
29 | from twisted.python import log | |
30 |
|
30 | |||
31 | from IPython.kernel.fcutil import Tub, UnauthenticatedTub, have_crypto |
|
31 | from IPython.kernel.fcutil import Tub, UnauthenticatedTub, have_crypto | |
32 |
|
32 | |||
33 | # from IPython.tools import growl |
|
33 | # from IPython.tools import growl | |
34 | # growl.start("IPython1 Controller") |
|
34 | # growl.start("IPython1 Controller") | |
35 |
|
35 | |||
36 | from IPython.kernel.error import SecurityError |
|
36 | from IPython.kernel.error import SecurityError | |
37 | from IPython.kernel import controllerservice |
|
37 | from IPython.kernel import controllerservice | |
38 | from IPython.kernel.fcutil import check_furl_file_security |
|
38 | from IPython.kernel.fcutil import check_furl_file_security | |
39 |
|
39 | |||
40 | from IPython.kernel.config import config_manager as kernel_config_manager |
|
40 | from IPython.kernel.config import config_manager as kernel_config_manager | |
41 | from IPython.config.cutils import import_item |
|
41 | from IPython.config.cutils import import_item | |
42 |
|
42 | |||
43 |
|
43 | |||
44 | #------------------------------------------------------------------------------- |
|
44 | #------------------------------------------------------------------------------- | |
45 | # Code |
|
45 | # Code | |
46 | #------------------------------------------------------------------------------- |
|
46 | #------------------------------------------------------------------------------- | |
47 |
|
47 | |||
48 | def make_tub(ip, port, secure, cert_file): |
|
48 | def make_tub(ip, port, secure, cert_file): | |
49 | """ |
|
49 | """ | |
50 | Create a listening tub given an ip, port, and cert_file location. |
|
50 | Create a listening tub given an ip, port, and cert_file location. | |
51 |
|
51 | |||
52 | :Parameters: |
|
52 | :Parameters: | |
53 | ip : str |
|
53 | ip : str | |
54 | The ip address that the tub should listen on. Empty means all |
|
54 | The ip address that the tub should listen on. Empty means all | |
55 | port : int |
|
55 | port : int | |
56 | The port that the tub should listen on. A value of 0 means |
|
56 | The port that the tub should listen on. A value of 0 means | |
57 | pick a random port |
|
57 | pick a random port | |
58 | secure: boolean |
|
58 | secure: boolean | |
59 | Will the connection be secure (in the foolscap sense) |
|
59 | Will the connection be secure (in the foolscap sense) | |
60 | cert_file: |
|
60 | cert_file: | |
61 | A filename of a file to be used for theSSL certificate |
|
61 | A filename of a file to be used for theSSL certificate | |
62 | """ |
|
62 | """ | |
63 | if secure: |
|
63 | if secure: | |
64 | if have_crypto: |
|
64 | if have_crypto: | |
65 | tub = Tub(certFile=cert_file) |
|
65 | tub = Tub(certFile=cert_file) | |
66 | else: |
|
66 | else: | |
67 | raise SecurityError("OpenSSL is not available, so we can't run in secure mode, aborting") |
|
67 | raise SecurityError(""" | |
|
68 | OpenSSL/pyOpenSSL is not available, so we can't run in secure mode. | |||
|
69 | Try running without security using 'ipcontroller -xy'. | |||
|
70 | """) | |||
68 | else: |
|
71 | else: | |
69 | tub = UnauthenticatedTub() |
|
72 | tub = UnauthenticatedTub() | |
70 |
|
73 | |||
71 | # Set the strport based on the ip and port and start listening |
|
74 | # Set the strport based on the ip and port and start listening | |
72 | if ip == '': |
|
75 | if ip == '': | |
73 | strport = "tcp:%i" % port |
|
76 | strport = "tcp:%i" % port | |
74 | else: |
|
77 | else: | |
75 | strport = "tcp:%i:interface=%s" % (port, ip) |
|
78 | strport = "tcp:%i:interface=%s" % (port, ip) | |
76 | listener = tub.listenOn(strport) |
|
79 | listener = tub.listenOn(strport) | |
77 |
|
80 | |||
78 | return tub, listener |
|
81 | return tub, listener | |
79 |
|
82 | |||
80 | def make_client_service(controller_service, config): |
|
83 | def make_client_service(controller_service, config): | |
81 | """ |
|
84 | """ | |
82 | Create a service that will listen for clients. |
|
85 | Create a service that will listen for clients. | |
83 |
|
86 | |||
84 | This service is simply a `foolscap.Tub` instance that has a set of Referenceables |
|
87 | This service is simply a `foolscap.Tub` instance that has a set of Referenceables | |
85 | registered with it. |
|
88 | registered with it. | |
86 | """ |
|
89 | """ | |
87 |
|
90 | |||
88 | # Now create the foolscap tub |
|
91 | # Now create the foolscap tub | |
89 | ip = config['controller']['client_tub']['ip'] |
|
92 | ip = config['controller']['client_tub']['ip'] | |
90 | port = config['controller']['client_tub'].as_int('port') |
|
93 | port = config['controller']['client_tub'].as_int('port') | |
91 | location = config['controller']['client_tub']['location'] |
|
94 | location = config['controller']['client_tub']['location'] | |
92 | secure = config['controller']['client_tub']['secure'] |
|
95 | secure = config['controller']['client_tub']['secure'] | |
93 | cert_file = config['controller']['client_tub']['cert_file'] |
|
96 | cert_file = config['controller']['client_tub']['cert_file'] | |
94 | client_tub, client_listener = make_tub(ip, port, secure, cert_file) |
|
97 | client_tub, client_listener = make_tub(ip, port, secure, cert_file) | |
95 |
|
98 | |||
96 | # Set the location in the trivial case of localhost |
|
99 | # Set the location in the trivial case of localhost | |
97 | if ip == 'localhost' or ip == '127.0.0.1': |
|
100 | if ip == 'localhost' or ip == '127.0.0.1': | |
98 | location = "127.0.0.1" |
|
101 | location = "127.0.0.1" | |
99 |
|
102 | |||
100 | if not secure: |
|
103 | if not secure: | |
101 | log.msg("WARNING: you are running the controller with no client security") |
|
104 | log.msg("WARNING: you are running the controller with no client security") | |
102 |
|
105 | |||
103 | def set_location_and_register(): |
|
106 | def set_location_and_register(): | |
104 | """Set the location for the tub and return a deferred.""" |
|
107 | """Set the location for the tub and return a deferred.""" | |
105 |
|
108 | |||
106 | def register(empty, ref, furl_file): |
|
109 | def register(empty, ref, furl_file): | |
107 | client_tub.registerReference(ref, furlFile=furl_file) |
|
110 | client_tub.registerReference(ref, furlFile=furl_file) | |
108 |
|
111 | |||
109 | if location == '': |
|
112 | if location == '': | |
110 | d = client_tub.setLocationAutomatically() |
|
113 | d = client_tub.setLocationAutomatically() | |
111 | else: |
|
114 | else: | |
112 | d = defer.maybeDeferred(client_tub.setLocation, "%s:%i" % (location, client_listener.getPortnum())) |
|
115 | d = defer.maybeDeferred(client_tub.setLocation, "%s:%i" % (location, client_listener.getPortnum())) | |
113 |
|
116 | |||
114 | for ciname, ci in config['controller']['controller_interfaces'].iteritems(): |
|
117 | for ciname, ci in config['controller']['controller_interfaces'].iteritems(): | |
115 | log.msg("Adapting Controller to interface: %s" % ciname) |
|
118 | log.msg("Adapting Controller to interface: %s" % ciname) | |
116 | furl_file = ci['furl_file'] |
|
119 | furl_file = ci['furl_file'] | |
117 | log.msg("Saving furl for interface [%s] to file: %s" % (ciname, furl_file)) |
|
120 | log.msg("Saving furl for interface [%s] to file: %s" % (ciname, furl_file)) | |
118 | check_furl_file_security(furl_file, secure) |
|
121 | check_furl_file_security(furl_file, secure) | |
119 | adapted_controller = import_item(ci['controller_interface'])(controller_service) |
|
122 | adapted_controller = import_item(ci['controller_interface'])(controller_service) | |
120 | d.addCallback(register, import_item(ci['fc_interface'])(adapted_controller), |
|
123 | d.addCallback(register, import_item(ci['fc_interface'])(adapted_controller), | |
121 | furl_file=ci['furl_file']) |
|
124 | furl_file=ci['furl_file']) | |
122 |
|
125 | |||
123 | reactor.callWhenRunning(set_location_and_register) |
|
126 | reactor.callWhenRunning(set_location_and_register) | |
124 | return client_tub |
|
127 | return client_tub | |
125 |
|
128 | |||
126 |
|
129 | |||
127 | def make_engine_service(controller_service, config): |
|
130 | def make_engine_service(controller_service, config): | |
128 | """ |
|
131 | """ | |
129 | Create a service that will listen for engines. |
|
132 | Create a service that will listen for engines. | |
130 |
|
133 | |||
131 | This service is simply a `foolscap.Tub` instance that has a set of Referenceables |
|
134 | This service is simply a `foolscap.Tub` instance that has a set of Referenceables | |
132 | registered with it. |
|
135 | registered with it. | |
133 | """ |
|
136 | """ | |
134 |
|
137 | |||
135 | # Now create the foolscap tub |
|
138 | # Now create the foolscap tub | |
136 | ip = config['controller']['engine_tub']['ip'] |
|
139 | ip = config['controller']['engine_tub']['ip'] | |
137 | port = config['controller']['engine_tub'].as_int('port') |
|
140 | port = config['controller']['engine_tub'].as_int('port') | |
138 | location = config['controller']['engine_tub']['location'] |
|
141 | location = config['controller']['engine_tub']['location'] | |
139 | secure = config['controller']['engine_tub']['secure'] |
|
142 | secure = config['controller']['engine_tub']['secure'] | |
140 | cert_file = config['controller']['engine_tub']['cert_file'] |
|
143 | cert_file = config['controller']['engine_tub']['cert_file'] | |
141 | engine_tub, engine_listener = make_tub(ip, port, secure, cert_file) |
|
144 | engine_tub, engine_listener = make_tub(ip, port, secure, cert_file) | |
142 |
|
145 | |||
143 | # Set the location in the trivial case of localhost |
|
146 | # Set the location in the trivial case of localhost | |
144 | if ip == 'localhost' or ip == '127.0.0.1': |
|
147 | if ip == 'localhost' or ip == '127.0.0.1': | |
145 | location = "127.0.0.1" |
|
148 | location = "127.0.0.1" | |
146 |
|
149 | |||
147 | if not secure: |
|
150 | if not secure: | |
148 | log.msg("WARNING: you are running the controller with no engine security") |
|
151 | log.msg("WARNING: you are running the controller with no engine security") | |
149 |
|
152 | |||
150 | def set_location_and_register(): |
|
153 | def set_location_and_register(): | |
151 | """Set the location for the tub and return a deferred.""" |
|
154 | """Set the location for the tub and return a deferred.""" | |
152 |
|
155 | |||
153 | def register(empty, ref, furl_file): |
|
156 | def register(empty, ref, furl_file): | |
154 | engine_tub.registerReference(ref, furlFile=furl_file) |
|
157 | engine_tub.registerReference(ref, furlFile=furl_file) | |
155 |
|
158 | |||
156 | if location == '': |
|
159 | if location == '': | |
157 | d = engine_tub.setLocationAutomatically() |
|
160 | d = engine_tub.setLocationAutomatically() | |
158 | else: |
|
161 | else: | |
159 | d = defer.maybeDeferred(engine_tub.setLocation, "%s:%i" % (location, engine_listener.getPortnum())) |
|
162 | d = defer.maybeDeferred(engine_tub.setLocation, "%s:%i" % (location, engine_listener.getPortnum())) | |
160 |
|
163 | |||
161 | furl_file = config['controller']['engine_furl_file'] |
|
164 | furl_file = config['controller']['engine_furl_file'] | |
162 | engine_fc_interface = import_item(config['controller']['engine_fc_interface']) |
|
165 | engine_fc_interface = import_item(config['controller']['engine_fc_interface']) | |
163 | log.msg("Saving furl for the engine to file: %s" % furl_file) |
|
166 | log.msg("Saving furl for the engine to file: %s" % furl_file) | |
164 | check_furl_file_security(furl_file, secure) |
|
167 | check_furl_file_security(furl_file, secure) | |
165 | fc_controller = engine_fc_interface(controller_service) |
|
168 | fc_controller = engine_fc_interface(controller_service) | |
166 | d.addCallback(register, fc_controller, furl_file=furl_file) |
|
169 | d.addCallback(register, fc_controller, furl_file=furl_file) | |
167 |
|
170 | |||
168 | reactor.callWhenRunning(set_location_and_register) |
|
171 | reactor.callWhenRunning(set_location_and_register) | |
169 | return engine_tub |
|
172 | return engine_tub | |
170 |
|
173 | |||
171 | def start_controller(): |
|
174 | def start_controller(): | |
172 | """ |
|
175 | """ | |
173 | Start the controller by creating the service hierarchy and starting the reactor. |
|
176 | Start the controller by creating the service hierarchy and starting the reactor. | |
174 |
|
177 | |||
175 | This method does the following: |
|
178 | This method does the following: | |
176 |
|
179 | |||
177 | * It starts the controller logging |
|
180 | * It starts the controller logging | |
178 | * In execute an import statement for the controller |
|
181 | * In execute an import statement for the controller | |
179 | * It creates 2 `foolscap.Tub` instances for the client and the engines |
|
182 | * It creates 2 `foolscap.Tub` instances for the client and the engines | |
180 | and registers `foolscap.Referenceables` with the tubs to expose the |
|
183 | and registers `foolscap.Referenceables` with the tubs to expose the | |
181 | controller to engines and clients. |
|
184 | controller to engines and clients. | |
182 | """ |
|
185 | """ | |
183 | config = kernel_config_manager.get_config_obj() |
|
186 | config = kernel_config_manager.get_config_obj() | |
184 |
|
187 | |||
185 | # Start logging |
|
188 | # Start logging | |
186 | logfile = config['controller']['logfile'] |
|
189 | logfile = config['controller']['logfile'] | |
187 | if logfile: |
|
190 | if logfile: | |
188 | logfile = logfile + str(os.getpid()) + '.log' |
|
191 | logfile = logfile + str(os.getpid()) + '.log' | |
189 | try: |
|
192 | try: | |
190 | openLogFile = open(logfile, 'w') |
|
193 | openLogFile = open(logfile, 'w') | |
191 | except: |
|
194 | except: | |
192 | openLogFile = sys.stdout |
|
195 | openLogFile = sys.stdout | |
193 | else: |
|
196 | else: | |
194 | openLogFile = sys.stdout |
|
197 | openLogFile = sys.stdout | |
195 | log.startLogging(openLogFile) |
|
198 | log.startLogging(openLogFile) | |
196 |
|
199 | |||
197 | # Execute any user defined import statements |
|
200 | # Execute any user defined import statements | |
198 | cis = config['controller']['import_statement'] |
|
201 | cis = config['controller']['import_statement'] | |
199 | if cis: |
|
202 | if cis: | |
200 | try: |
|
203 | try: | |
201 | exec cis in globals(), locals() |
|
204 | exec cis in globals(), locals() | |
202 | except: |
|
205 | except: | |
203 | log.msg("Error running import_statement: %s" % cis) |
|
206 | log.msg("Error running import_statement: %s" % cis) | |
204 |
|
207 | |||
|
208 | # Delete old furl files unless the reuse_furls is set | |||
|
209 | reuse = config['controller']['reuse_furls'] | |||
|
210 | if not reuse: | |||
|
211 | paths = (config['controller']['engine_furl_file'], | |||
|
212 | config['controller']['controller_interfaces']['task']['furl_file'], | |||
|
213 | config['controller']['controller_interfaces']['multiengine']['furl_file'] | |||
|
214 | ) | |||
|
215 | for p in paths: | |||
|
216 | if os.path.isfile(p): | |||
|
217 | os.remove(p) | |||
|
218 | ||||
205 | # Create the service hierarchy |
|
219 | # Create the service hierarchy | |
206 | main_service = service.MultiService() |
|
220 | main_service = service.MultiService() | |
207 | # The controller service |
|
221 | # The controller service | |
208 | controller_service = controllerservice.ControllerService() |
|
222 | controller_service = controllerservice.ControllerService() | |
209 | controller_service.setServiceParent(main_service) |
|
223 | controller_service.setServiceParent(main_service) | |
210 | # The client tub and all its refereceables |
|
224 | # The client tub and all its refereceables | |
211 | client_service = make_client_service(controller_service, config) |
|
225 | client_service = make_client_service(controller_service, config) | |
212 | client_service.setServiceParent(main_service) |
|
226 | client_service.setServiceParent(main_service) | |
213 | # The engine tub |
|
227 | # The engine tub | |
214 | engine_service = make_engine_service(controller_service, config) |
|
228 | engine_service = make_engine_service(controller_service, config) | |
215 | engine_service.setServiceParent(main_service) |
|
229 | engine_service.setServiceParent(main_service) | |
216 | # Start the controller service and set things running |
|
230 | # Start the controller service and set things running | |
217 | main_service.startService() |
|
231 | main_service.startService() | |
218 | reactor.run() |
|
232 | reactor.run() | |
219 |
|
233 | |||
220 | def init_config(): |
|
234 | def init_config(): | |
221 | """ |
|
235 | """ | |
222 | Initialize the configuration using default and command line options. |
|
236 | Initialize the configuration using default and command line options. | |
223 | """ |
|
237 | """ | |
224 |
|
238 | |||
225 | parser = OptionParser() |
|
239 | parser = OptionParser() | |
226 |
|
240 | |||
227 | # Client related options |
|
241 | # Client related options | |
228 | parser.add_option( |
|
242 | parser.add_option( | |
229 | "--client-ip", |
|
243 | "--client-ip", | |
230 | type="string", |
|
244 | type="string", | |
231 | dest="client_ip", |
|
245 | dest="client_ip", | |
232 | help="the IP address or hostname the controller will listen on for client connections" |
|
246 | help="the IP address or hostname the controller will listen on for client connections" | |
233 | ) |
|
247 | ) | |
234 | parser.add_option( |
|
248 | parser.add_option( | |
235 | "--client-port", |
|
249 | "--client-port", | |
236 | type="int", |
|
250 | type="int", | |
237 | dest="client_port", |
|
251 | dest="client_port", | |
238 | help="the port the controller will listen on for client connections" |
|
252 | help="the port the controller will listen on for client connections" | |
239 | ) |
|
253 | ) | |
240 | parser.add_option( |
|
254 | parser.add_option( | |
241 | '--client-location', |
|
255 | '--client-location', | |
242 | type="string", |
|
256 | type="string", | |
243 | dest="client_location", |
|
257 | dest="client_location", | |
244 | help="hostname or ip for clients to connect to" |
|
258 | help="hostname or ip for clients to connect to" | |
245 | ) |
|
259 | ) | |
246 | parser.add_option( |
|
260 | parser.add_option( | |
247 | "-x", |
|
261 | "-x", | |
248 | action="store_false", |
|
262 | action="store_false", | |
249 | dest="client_secure", |
|
263 | dest="client_secure", | |
250 | help="turn off all client security" |
|
264 | help="turn off all client security" | |
251 | ) |
|
265 | ) | |
252 | parser.add_option( |
|
266 | parser.add_option( | |
253 | '--client-cert-file', |
|
267 | '--client-cert-file', | |
254 | type="string", |
|
268 | type="string", | |
255 | dest="client_cert_file", |
|
269 | dest="client_cert_file", | |
256 | help="file to store the client SSL certificate" |
|
270 | help="file to store the client SSL certificate" | |
257 | ) |
|
271 | ) | |
258 | parser.add_option( |
|
272 | parser.add_option( | |
259 | '--task-furl-file', |
|
273 | '--task-furl-file', | |
260 | type="string", |
|
274 | type="string", | |
261 | dest="task_furl_file", |
|
275 | dest="task_furl_file", | |
262 | help="file to store the FURL for task clients to connect with" |
|
276 | help="file to store the FURL for task clients to connect with" | |
263 | ) |
|
277 | ) | |
264 | parser.add_option( |
|
278 | parser.add_option( | |
265 | '--multiengine-furl-file', |
|
279 | '--multiengine-furl-file', | |
266 | type="string", |
|
280 | type="string", | |
267 | dest="multiengine_furl_file", |
|
281 | dest="multiengine_furl_file", | |
268 | help="file to store the FURL for multiengine clients to connect with" |
|
282 | help="file to store the FURL for multiengine clients to connect with" | |
269 | ) |
|
283 | ) | |
270 | # Engine related options |
|
284 | # Engine related options | |
271 | parser.add_option( |
|
285 | parser.add_option( | |
272 | "--engine-ip", |
|
286 | "--engine-ip", | |
273 | type="string", |
|
287 | type="string", | |
274 | dest="engine_ip", |
|
288 | dest="engine_ip", | |
275 | help="the IP address or hostname the controller will listen on for engine connections" |
|
289 | help="the IP address or hostname the controller will listen on for engine connections" | |
276 | ) |
|
290 | ) | |
277 | parser.add_option( |
|
291 | parser.add_option( | |
278 | "--engine-port", |
|
292 | "--engine-port", | |
279 | type="int", |
|
293 | type="int", | |
280 | dest="engine_port", |
|
294 | dest="engine_port", | |
281 | help="the port the controller will listen on for engine connections" |
|
295 | help="the port the controller will listen on for engine connections" | |
282 | ) |
|
296 | ) | |
283 | parser.add_option( |
|
297 | parser.add_option( | |
284 | '--engine-location', |
|
298 | '--engine-location', | |
285 | type="string", |
|
299 | type="string", | |
286 | dest="engine_location", |
|
300 | dest="engine_location", | |
287 | help="hostname or ip for engines to connect to" |
|
301 | help="hostname or ip for engines to connect to" | |
288 | ) |
|
302 | ) | |
289 | parser.add_option( |
|
303 | parser.add_option( | |
290 | "-y", |
|
304 | "-y", | |
291 | action="store_false", |
|
305 | action="store_false", | |
292 | dest="engine_secure", |
|
306 | dest="engine_secure", | |
293 | help="turn off all engine security" |
|
307 | help="turn off all engine security" | |
294 | ) |
|
308 | ) | |
295 | parser.add_option( |
|
309 | parser.add_option( | |
296 | '--engine-cert-file', |
|
310 | '--engine-cert-file', | |
297 | type="string", |
|
311 | type="string", | |
298 | dest="engine_cert_file", |
|
312 | dest="engine_cert_file", | |
299 | help="file to store the engine SSL certificate" |
|
313 | help="file to store the engine SSL certificate" | |
300 | ) |
|
314 | ) | |
301 | parser.add_option( |
|
315 | parser.add_option( | |
302 | '--engine-furl-file', |
|
316 | '--engine-furl-file', | |
303 | type="string", |
|
317 | type="string", | |
304 | dest="engine_furl_file", |
|
318 | dest="engine_furl_file", | |
305 | help="file to store the FURL for engines to connect with" |
|
319 | help="file to store the FURL for engines to connect with" | |
306 | ) |
|
320 | ) | |
307 | parser.add_option( |
|
321 | parser.add_option( | |
308 | "-l", "--logfile", |
|
322 | "-l", "--logfile", | |
309 | type="string", |
|
323 | type="string", | |
310 | dest="logfile", |
|
324 | dest="logfile", | |
311 | help="log file name (default is stdout)" |
|
325 | help="log file name (default is stdout)" | |
312 | ) |
|
326 | ) | |
313 | parser.add_option( |
|
327 | parser.add_option( | |
314 | "--ipythondir", |
|
328 | "--ipythondir", | |
315 | type="string", |
|
329 | type="string", | |
316 | dest="ipythondir", |
|
330 | dest="ipythondir", | |
317 | help="look for config files and profiles in this directory" |
|
331 | help="look for config files and profiles in this directory" | |
318 | ) |
|
332 | ) | |
|
333 | parser.add_option( | |||
|
334 | "-r", | |||
|
335 | action="store_true", | |||
|
336 | dest="reuse_furls", | |||
|
337 | help="try to reuse all furl files" | |||
|
338 | ) | |||
319 |
|
339 | |||
320 | (options, args) = parser.parse_args() |
|
340 | (options, args) = parser.parse_args() | |
321 |
|
341 | |||
322 | kernel_config_manager.update_config_obj_from_default_file(options.ipythondir) |
|
342 | kernel_config_manager.update_config_obj_from_default_file(options.ipythondir) | |
323 | config = kernel_config_manager.get_config_obj() |
|
343 | config = kernel_config_manager.get_config_obj() | |
324 |
|
344 | |||
325 | # Update with command line options |
|
345 | # Update with command line options | |
326 | if options.client_ip is not None: |
|
346 | if options.client_ip is not None: | |
327 | config['controller']['client_tub']['ip'] = options.client_ip |
|
347 | config['controller']['client_tub']['ip'] = options.client_ip | |
328 | if options.client_port is not None: |
|
348 | if options.client_port is not None: | |
329 | config['controller']['client_tub']['port'] = options.client_port |
|
349 | config['controller']['client_tub']['port'] = options.client_port | |
330 | if options.client_location is not None: |
|
350 | if options.client_location is not None: | |
331 | config['controller']['client_tub']['location'] = options.client_location |
|
351 | config['controller']['client_tub']['location'] = options.client_location | |
332 | if options.client_secure is not None: |
|
352 | if options.client_secure is not None: | |
333 | config['controller']['client_tub']['secure'] = options.client_secure |
|
353 | config['controller']['client_tub']['secure'] = options.client_secure | |
334 | if options.client_cert_file is not None: |
|
354 | if options.client_cert_file is not None: | |
335 | config['controller']['client_tub']['cert_file'] = options.client_cert_file |
|
355 | config['controller']['client_tub']['cert_file'] = options.client_cert_file | |
336 | if options.task_furl_file is not None: |
|
356 | if options.task_furl_file is not None: | |
337 | config['controller']['controller_interfaces']['task']['furl_file'] = options.task_furl_file |
|
357 | config['controller']['controller_interfaces']['task']['furl_file'] = options.task_furl_file | |
338 | if options.multiengine_furl_file is not None: |
|
358 | if options.multiengine_furl_file is not None: | |
339 | config['controller']['controller_interfaces']['multiengine']['furl_file'] = options.multiengine_furl_file |
|
359 | config['controller']['controller_interfaces']['multiengine']['furl_file'] = options.multiengine_furl_file | |
340 | if options.engine_ip is not None: |
|
360 | if options.engine_ip is not None: | |
341 | config['controller']['engine_tub']['ip'] = options.engine_ip |
|
361 | config['controller']['engine_tub']['ip'] = options.engine_ip | |
342 | if options.engine_port is not None: |
|
362 | if options.engine_port is not None: | |
343 | config['controller']['engine_tub']['port'] = options.engine_port |
|
363 | config['controller']['engine_tub']['port'] = options.engine_port | |
344 | if options.engine_location is not None: |
|
364 | if options.engine_location is not None: | |
345 | config['controller']['engine_tub']['location'] = options.engine_location |
|
365 | config['controller']['engine_tub']['location'] = options.engine_location | |
346 | if options.engine_secure is not None: |
|
366 | if options.engine_secure is not None: | |
347 | config['controller']['engine_tub']['secure'] = options.engine_secure |
|
367 | config['controller']['engine_tub']['secure'] = options.engine_secure | |
348 | if options.engine_cert_file is not None: |
|
368 | if options.engine_cert_file is not None: | |
349 | config['controller']['engine_tub']['cert_file'] = options.engine_cert_file |
|
369 | config['controller']['engine_tub']['cert_file'] = options.engine_cert_file | |
350 | if options.engine_furl_file is not None: |
|
370 | if options.engine_furl_file is not None: | |
351 | config['controller']['engine_furl_file'] = options.engine_furl_file |
|
371 | config['controller']['engine_furl_file'] = options.engine_furl_file | |
|
372 | if options.reuse_furls is not None: | |||
|
373 | config['controller']['reuse_furls'] = options.reuse_furls | |||
352 |
|
374 | |||
353 | if options.logfile is not None: |
|
375 | if options.logfile is not None: | |
354 | config['controller']['logfile'] = options.logfile |
|
376 | config['controller']['logfile'] = options.logfile | |
355 |
|
377 | |||
356 | kernel_config_manager.update_config_obj(config) |
|
378 | kernel_config_manager.update_config_obj(config) | |
357 |
|
379 | |||
358 | def main(): |
|
380 | def main(): | |
359 | """ |
|
381 | """ | |
360 | After creating the configuration information, start the controller. |
|
382 | After creating the configuration information, start the controller. | |
361 | """ |
|
383 | """ | |
362 | init_config() |
|
384 | init_config() | |
363 | start_controller() |
|
385 | start_controller() | |
364 |
|
386 | |||
365 | if __name__ == "__main__": |
|
387 | if __name__ == "__main__": | |
366 | main() |
|
388 | main() |
@@ -1,172 +1,176 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 |
|
3 | |||
4 | """Start the IPython Engine.""" |
|
4 | """Start the IPython Engine.""" | |
5 |
|
5 | |||
6 | __docformat__ = "restructuredtext en" |
|
6 | __docformat__ = "restructuredtext en" | |
7 |
|
7 | |||
8 | #------------------------------------------------------------------------------- |
|
8 | #------------------------------------------------------------------------------- | |
9 | # Copyright (C) 2008 The IPython Development Team |
|
9 | # Copyright (C) 2008 The IPython Development Team | |
10 | # |
|
10 | # | |
11 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | # Distributed under the terms of the BSD License. The full license is in | |
12 | # the file COPYING, distributed as part of this software. |
|
12 | # the file COPYING, distributed as part of this software. | |
13 | #------------------------------------------------------------------------------- |
|
13 | #------------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | #------------------------------------------------------------------------------- |
|
15 | #------------------------------------------------------------------------------- | |
16 | # Imports |
|
16 | # Imports | |
17 | #------------------------------------------------------------------------------- |
|
17 | #------------------------------------------------------------------------------- | |
18 |
|
18 | |||
19 | # Python looks for an empty string at the beginning of sys.path to enable |
|
19 | # Python looks for an empty string at the beginning of sys.path to enable | |
20 | # importing from the cwd. |
|
20 | # importing from the cwd. | |
21 | import sys |
|
21 | import sys | |
22 | sys.path.insert(0, '') |
|
22 | sys.path.insert(0, '') | |
23 |
|
23 | |||
24 | import sys, os |
|
24 | import sys, os | |
25 | from optparse import OptionParser |
|
25 | from optparse import OptionParser | |
26 |
|
26 | |||
27 | from twisted.application import service |
|
27 | from twisted.application import service | |
28 | from twisted.internet import reactor |
|
28 | from twisted.internet import reactor | |
29 | from twisted.python import log |
|
29 | from twisted.python import log | |
30 |
|
30 | |||
31 | from IPython.kernel.fcutil import Tub, UnauthenticatedTub |
|
31 | from IPython.kernel.fcutil import Tub, UnauthenticatedTub | |
32 |
|
32 | |||
33 | from IPython.kernel.core.config import config_manager as core_config_manager |
|
33 | from IPython.kernel.core.config import config_manager as core_config_manager | |
34 | from IPython.config.cutils import import_item |
|
34 | from IPython.config.cutils import import_item | |
35 | from IPython.kernel.engineservice import EngineService |
|
35 | from IPython.kernel.engineservice import EngineService | |
36 | from IPython.kernel.config import config_manager as kernel_config_manager |
|
36 | from IPython.kernel.config import config_manager as kernel_config_manager | |
37 | from IPython.kernel.engineconnector import EngineConnector |
|
37 | from IPython.kernel.engineconnector import EngineConnector | |
38 |
|
38 | |||
39 |
|
39 | |||
40 | #------------------------------------------------------------------------------- |
|
40 | #------------------------------------------------------------------------------- | |
41 | # Code |
|
41 | # Code | |
42 | #------------------------------------------------------------------------------- |
|
42 | #------------------------------------------------------------------------------- | |
43 |
|
43 | |||
44 | def start_engine(): |
|
44 | def start_engine(): | |
45 | """ |
|
45 | """ | |
46 | Start the engine, by creating it and starting the Twisted reactor. |
|
46 | Start the engine, by creating it and starting the Twisted reactor. | |
47 |
|
47 | |||
48 | This method does: |
|
48 | This method does: | |
49 |
|
49 | |||
50 | * If it exists, runs the `mpi_import_statement` to call `MPI_Init` |
|
50 | * If it exists, runs the `mpi_import_statement` to call `MPI_Init` | |
51 | * Starts the engine logging |
|
51 | * Starts the engine logging | |
52 | * Creates an IPython shell and wraps it in an `EngineService` |
|
52 | * Creates an IPython shell and wraps it in an `EngineService` | |
53 | * Creates a `foolscap.Tub` to use in connecting to a controller. |
|
53 | * Creates a `foolscap.Tub` to use in connecting to a controller. | |
54 | * Uses the tub and the `EngineService` along with a Foolscap URL |
|
54 | * Uses the tub and the `EngineService` along with a Foolscap URL | |
55 | (or FURL) to connect to the controller and register the engine |
|
55 | (or FURL) to connect to the controller and register the engine | |
56 | with the controller |
|
56 | with the controller | |
57 | """ |
|
57 | """ | |
58 | kernel_config = kernel_config_manager.get_config_obj() |
|
58 | kernel_config = kernel_config_manager.get_config_obj() | |
59 | core_config = core_config_manager.get_config_obj() |
|
59 | core_config = core_config_manager.get_config_obj() | |
60 |
|
60 | |||
61 |
|
61 | |||
62 | # Execute the mpi import statement that needs to call MPI_Init |
|
62 | # Execute the mpi import statement that needs to call MPI_Init | |
63 | global mpi |
|
63 | global mpi | |
64 | mpikey = kernel_config['mpi']['default'] |
|
64 | mpikey = kernel_config['mpi']['default'] | |
65 | mpi_import_statement = kernel_config['mpi'].get(mpikey, None) |
|
65 | mpi_import_statement = kernel_config['mpi'].get(mpikey, None) | |
66 | if mpi_import_statement is not None: |
|
66 | if mpi_import_statement is not None: | |
67 | try: |
|
67 | try: | |
68 | exec mpi_import_statement in globals() |
|
68 | exec mpi_import_statement in globals() | |
69 | except: |
|
69 | except: | |
70 | mpi = None |
|
70 | mpi = None | |
71 | else: |
|
71 | else: | |
72 | mpi = None |
|
72 | mpi = None | |
73 |
|
73 | |||
74 | # Start logging |
|
74 | # Start logging | |
75 | logfile = kernel_config['engine']['logfile'] |
|
75 | logfile = kernel_config['engine']['logfile'] | |
76 | if logfile: |
|
76 | if logfile: | |
77 | logfile = logfile + str(os.getpid()) + '.log' |
|
77 | logfile = logfile + str(os.getpid()) + '.log' | |
78 | try: |
|
78 | try: | |
79 | openLogFile = open(logfile, 'w') |
|
79 | openLogFile = open(logfile, 'w') | |
80 | except: |
|
80 | except: | |
81 | openLogFile = sys.stdout |
|
81 | openLogFile = sys.stdout | |
82 | else: |
|
82 | else: | |
83 | openLogFile = sys.stdout |
|
83 | openLogFile = sys.stdout | |
84 | log.startLogging(openLogFile) |
|
84 | log.startLogging(openLogFile) | |
85 |
|
85 | |||
86 | # Create the underlying shell class and EngineService |
|
86 | # Create the underlying shell class and EngineService | |
87 | shell_class = import_item(core_config['shell']['shell_class']) |
|
87 | shell_class = import_item(core_config['shell']['shell_class']) | |
88 | engine_service = EngineService(shell_class, mpi=mpi) |
|
88 | engine_service = EngineService(shell_class, mpi=mpi) | |
89 | shell_import_statement = core_config['shell']['import_statement'] |
|
89 | shell_import_statement = core_config['shell']['import_statement'] | |
90 | if shell_import_statement: |
|
90 | if shell_import_statement: | |
91 | try: |
|
91 | try: | |
92 | engine_service.execute(shell_import_statement) |
|
92 | engine_service.execute(shell_import_statement) | |
93 | except: |
|
93 | except: | |
94 | log.msg("Error running import_statement: %s" % shell_import_statement) |
|
94 | log.msg("Error running import_statement: %s" % shell_import_statement) | |
95 |
|
95 | |||
96 | # Create the service hierarchy |
|
96 | # Create the service hierarchy | |
97 | main_service = service.MultiService() |
|
97 | main_service = service.MultiService() | |
98 | engine_service.setServiceParent(main_service) |
|
98 | engine_service.setServiceParent(main_service) | |
99 | tub_service = Tub() |
|
99 | tub_service = Tub() | |
100 | tub_service.setServiceParent(main_service) |
|
100 | tub_service.setServiceParent(main_service) | |
101 | # This needs to be called before the connection is initiated |
|
101 | # This needs to be called before the connection is initiated | |
102 | main_service.startService() |
|
102 | main_service.startService() | |
103 |
|
103 | |||
104 | # This initiates the connection to the controller and calls |
|
104 | # This initiates the connection to the controller and calls | |
105 | # register_engine to tell the controller we are ready to do work |
|
105 | # register_engine to tell the controller we are ready to do work | |
106 | engine_connector = EngineConnector(tub_service) |
|
106 | engine_connector = EngineConnector(tub_service) | |
107 | furl_file = kernel_config['engine']['furl_file'] |
|
107 | furl_file = kernel_config['engine']['furl_file'] | |
108 | log.msg("Using furl file: %s" % furl_file) |
|
108 | log.msg("Using furl file: %s" % furl_file) | |
109 | d = engine_connector.connect_to_controller(engine_service, furl_file) |
|
109 | d = engine_connector.connect_to_controller(engine_service, furl_file) | |
110 | d.addErrback(lambda _: reactor.stop()) |
|
110 | def handle_error(f): | |
|
111 | log.err(f) | |||
|
112 | if reactor.running: | |||
|
113 | reactor.stop() | |||
|
114 | d.addErrback(handle_error) | |||
111 |
|
115 | |||
112 | reactor.run() |
|
116 | reactor.run() | |
113 |
|
117 | |||
114 |
|
118 | |||
115 | def init_config(): |
|
119 | def init_config(): | |
116 | """ |
|
120 | """ | |
117 | Initialize the configuration using default and command line options. |
|
121 | Initialize the configuration using default and command line options. | |
118 | """ |
|
122 | """ | |
119 |
|
123 | |||
120 | parser = OptionParser() |
|
124 | parser = OptionParser() | |
121 |
|
125 | |||
122 | parser.add_option( |
|
126 | parser.add_option( | |
123 | "--furl-file", |
|
127 | "--furl-file", | |
124 | type="string", |
|
128 | type="string", | |
125 | dest="furl_file", |
|
129 | dest="furl_file", | |
126 | help="The filename containing the FURL of the controller" |
|
130 | help="The filename containing the FURL of the controller" | |
127 | ) |
|
131 | ) | |
128 | parser.add_option( |
|
132 | parser.add_option( | |
129 | "--mpi", |
|
133 | "--mpi", | |
130 | type="string", |
|
134 | type="string", | |
131 | dest="mpi", |
|
135 | dest="mpi", | |
132 | help="How to enable MPI (mpi4py, pytrilinos, or empty string to disable)" |
|
136 | help="How to enable MPI (mpi4py, pytrilinos, or empty string to disable)" | |
133 | ) |
|
137 | ) | |
134 | parser.add_option( |
|
138 | parser.add_option( | |
135 | "-l", |
|
139 | "-l", | |
136 | "--logfile", |
|
140 | "--logfile", | |
137 | type="string", |
|
141 | type="string", | |
138 | dest="logfile", |
|
142 | dest="logfile", | |
139 | help="log file name (default is stdout)" |
|
143 | help="log file name (default is stdout)" | |
140 | ) |
|
144 | ) | |
141 | parser.add_option( |
|
145 | parser.add_option( | |
142 | "--ipythondir", |
|
146 | "--ipythondir", | |
143 | type="string", |
|
147 | type="string", | |
144 | dest="ipythondir", |
|
148 | dest="ipythondir", | |
145 | help="look for config files and profiles in this directory" |
|
149 | help="look for config files and profiles in this directory" | |
146 | ) |
|
150 | ) | |
147 |
|
151 | |||
148 | (options, args) = parser.parse_args() |
|
152 | (options, args) = parser.parse_args() | |
149 |
|
153 | |||
150 | kernel_config_manager.update_config_obj_from_default_file(options.ipythondir) |
|
154 | kernel_config_manager.update_config_obj_from_default_file(options.ipythondir) | |
151 | core_config_manager.update_config_obj_from_default_file(options.ipythondir) |
|
155 | core_config_manager.update_config_obj_from_default_file(options.ipythondir) | |
152 |
|
156 | |||
153 | kernel_config = kernel_config_manager.get_config_obj() |
|
157 | kernel_config = kernel_config_manager.get_config_obj() | |
154 | # Now override with command line options |
|
158 | # Now override with command line options | |
155 | if options.furl_file is not None: |
|
159 | if options.furl_file is not None: | |
156 | kernel_config['engine']['furl_file'] = options.furl_file |
|
160 | kernel_config['engine']['furl_file'] = options.furl_file | |
157 | if options.logfile is not None: |
|
161 | if options.logfile is not None: | |
158 | kernel_config['engine']['logfile'] = options.logfile |
|
162 | kernel_config['engine']['logfile'] = options.logfile | |
159 | if options.mpi is not None: |
|
163 | if options.mpi is not None: | |
160 | kernel_config['mpi']['default'] = options.mpi |
|
164 | kernel_config['mpi']['default'] = options.mpi | |
161 |
|
165 | |||
162 |
|
166 | |||
163 | def main(): |
|
167 | def main(): | |
164 | """ |
|
168 | """ | |
165 | After creating the configuration information, start the engine. |
|
169 | After creating the configuration information, start the engine. | |
166 | """ |
|
170 | """ | |
167 | init_config() |
|
171 | init_config() | |
168 | start_engine() |
|
172 | start_engine() | |
169 |
|
173 | |||
170 |
|
174 | |||
171 | if __name__ == "__main__": |
|
175 | if __name__ == "__main__": | |
172 | main() |
|
176 | main() |
@@ -1,33 +1,32 b'' | |||||
1 | include README_Windows.txt |
|
|||
2 | include win32_manual_post_install.py |
|
|||
3 | include ipython.py |
|
1 | include ipython.py | |
4 | include setupbase.py |
|
2 | include setupbase.py | |
|
3 | include setupegg.py | |||
5 |
|
4 | |||
6 | graft scripts |
|
5 | graft scripts | |
7 |
|
6 | |||
8 | graft setupext |
|
7 | graft setupext | |
9 |
|
8 | |||
10 | graft IPython/UserConfig |
|
9 | graft IPython/UserConfig | |
11 |
|
10 | |||
12 | graft IPython/kernel |
|
11 | graft IPython/kernel | |
13 | graft IPython/config |
|
12 | graft IPython/config | |
14 | graft IPython/testing |
|
13 | graft IPython/testing | |
15 | graft IPython/tools |
|
14 | graft IPython/tools | |
16 |
|
15 | |||
17 | recursive-include IPython/Extensions igrid_help* |
|
16 | recursive-include IPython/Extensions igrid_help* | |
18 |
|
17 | |||
19 | graft docs |
|
18 | graft docs | |
20 | exclude docs/\#* |
|
19 | exclude docs/\#* | |
21 | exclude docs/man/*.1 |
|
20 | exclude docs/man/*.1 | |
22 |
|
21 | |||
23 | # docs subdirs we want to skip |
|
22 | # docs subdirs we want to skip | |
24 | prune docs/attic |
|
23 | prune docs/attic | |
25 | prune docs/build |
|
24 | prune docs/build | |
26 |
|
25 | |||
27 | global-exclude *~ |
|
26 | global-exclude *~ | |
28 | global-exclude *.flc |
|
27 | global-exclude *.flc | |
29 | global-exclude *.pyc |
|
28 | global-exclude *.pyc | |
30 | global-exclude .dircopy.log |
|
29 | global-exclude .dircopy.log | |
31 | global-exclude .svn |
|
30 | global-exclude .svn | |
32 | global-exclude .bzr |
|
31 | global-exclude .bzr | |
33 | global-exclude .hgignore |
|
32 | global-exclude .hgignore |
@@ -1,360 +1,393 b'' | |||||
1 | .. _changes: |
|
1 | .. _changes: | |
2 |
|
2 | |||
3 | ========== |
|
3 | ========== | |
4 | What's new |
|
4 | What's new | |
5 | ========== |
|
5 | ========== | |
6 |
|
6 | |||
7 | .. contents:: |
|
7 | .. contents:: | |
8 | .. |
|
8 | .. | |
9 | 1 Release 0.9.1 |
|
9 | 1 Release 0.9.1 | |
10 | 2 Release 0.9 |
|
10 | 2 Release 0.9 | |
11 | 2.1 New features |
|
11 | 2.1 New features | |
12 | 2.2 Bug fixes |
|
12 | 2.2 Bug fixes | |
13 | 2.3 Backwards incompatible changes |
|
13 | 2.3 Backwards incompatible changes | |
14 | 2.4 Changes merged in from IPython1 |
|
14 | 2.4 Changes merged in from IPython1 | |
15 | 2.4.1 New features |
|
15 | 2.4.1 New features | |
16 | 2.4.2 Bug fixes |
|
16 | 2.4.2 Bug fixes | |
17 | 2.4.3 Backwards incompatible changes |
|
17 | 2.4.3 Backwards incompatible changes | |
18 | 3 Release 0.8.4 |
|
18 | 3 Release 0.8.4 | |
19 | 4 Release 0.8.3 |
|
19 | 4 Release 0.8.3 | |
20 | 5 Release 0.8.2 |
|
20 | 5 Release 0.8.2 | |
21 | 6 Older releases |
|
21 | 6 Older releases | |
22 | .. |
|
22 | .. | |
23 |
|
23 | |||
24 |
Release |
|
24 | Release dev | |
25 | =========== |
|
25 | =========== | |
26 |
|
26 | |||
|
27 | New features | |||
|
28 | ------------ | |||
|
29 | ||||
|
30 | * The wonderful TextMate editor can now be used with %edit on OS X. Thanks | |||
|
31 | to Matt Foster for this patch. | |||
|
32 | ||||
|
33 | * Fully refactored :command:`ipcluster` command line program for starting | |||
|
34 | IPython clusters. This new version is a complete rewrite and 1) is fully | |||
|
35 | cross platform (we now use Twisted's process management), 2) has much | |||
|
36 | improved performance, 3) uses subcommands for different types of clusters, | |||
|
37 | 4) uses argparse for parsing command line options, 5) has better support | |||
|
38 | for starting clusters using :command:`mpirun`, 6) has experimental support | |||
|
39 | for starting engines using PBS. However, this new version of ipcluster | |||
|
40 | should be considered a technology preview. We plan on changing the API | |||
|
41 | in significant ways before it is final. | |||
|
42 | ||||
|
43 | * The :mod:`argparse` module has been added to :mod:`IPython.external`. | |||
|
44 | ||||
|
45 | * Fully description of the security model added to the docs. | |||
|
46 | ||||
27 | * cd completer: show bookmarks if no other completions are available. |
|
47 | * cd completer: show bookmarks if no other completions are available. | |
28 |
|
48 | |||
29 | * Remove ipy_leo.py. "easy_install ipython-extension" to get it. |
|
|||
30 | (done to decouple it from ipython release cycle) |
|
|||
31 |
|
||||
32 | * sh profile: easy way to give 'title' to prompt: assign to variable |
|
49 | * sh profile: easy way to give 'title' to prompt: assign to variable | |
33 | '_prompt_title'. It looks like this:: |
|
50 | '_prompt_title'. It looks like this:: | |
34 |
|
51 | |||
35 | [~]|1> _prompt_title = 'sudo!' |
|
52 | [~]|1> _prompt_title = 'sudo!' | |
36 | sudo![~]|2> |
|
53 | sudo![~]|2> | |
37 |
|
54 | |||
|
55 | * %edit: If you do '%edit pasted_block', pasted_block | |||
|
56 | variable gets updated with new data (so repeated | |||
|
57 | editing makes sense) | |||
|
58 | ||||
|
59 | Bug fixes | |||
|
60 | --------- | |||
|
61 | ||||
|
62 | * The ipengine and ipcontroller scripts now handle missing furl files | |||
|
63 | more gracefully by giving better error messages. | |||
|
64 | ||||
38 | * %rehashx: Aliases no longer contain dots. python3.0 binary |
|
65 | * %rehashx: Aliases no longer contain dots. python3.0 binary | |
39 | will create alias python30. Fixes: |
|
66 | will create alias python30. Fixes: | |
40 | #259716 "commands with dots in them don't work" |
|
67 | #259716 "commands with dots in them don't work" | |
41 |
|
68 | |||
42 | * %cpaste: %cpaste -r repeats the last pasted block. |
|
69 | * %cpaste: %cpaste -r repeats the last pasted block. | |
43 | The block is assigned to pasted_block even if code |
|
70 | The block is assigned to pasted_block even if code | |
44 | raises exception. |
|
71 | raises exception. | |
45 |
|
72 | |||
46 | * %edit: If you do '%edit pasted_block', pasted_block |
|
73 | Backwards incompatible changes | |
47 | variable gets updated with new data (so repeated |
|
74 | ------------------------------ | |
48 | editing makes sense) |
|
75 | ||
|
76 | * The controller now has a ``-r`` flag that needs to be used if you want to | |||
|
77 | reuse existing furl files. Otherwise they are deleted (the default). | |||
|
78 | ||||
|
79 | * Remove ipy_leo.py. "easy_install ipython-extension" to get it. | |||
|
80 | (done to decouple it from ipython release cycle) | |||
|
81 | ||||
49 |
|
82 | |||
50 |
|
83 | |||
51 | Release 0.9.1 |
|
84 | Release 0.9.1 | |
52 | ============= |
|
85 | ============= | |
53 |
|
86 | |||
54 | This release was quickly made to restore compatibility with Python 2.4, which |
|
87 | This release was quickly made to restore compatibility with Python 2.4, which | |
55 | version 0.9 accidentally broke. No new features were introduced, other than |
|
88 | version 0.9 accidentally broke. No new features were introduced, other than | |
56 | some additional testing support for internal use. |
|
89 | some additional testing support for internal use. | |
57 |
|
90 | |||
58 |
|
91 | |||
59 | Release 0.9 |
|
92 | Release 0.9 | |
60 | =========== |
|
93 | =========== | |
61 |
|
94 | |||
62 | New features |
|
95 | New features | |
63 | ------------ |
|
96 | ------------ | |
64 |
|
97 | |||
65 |
* All furl files and security certificates are now put in a read-only |
|
98 | * All furl files and security certificates are now put in a read-only | |
66 | named ~./ipython/security. |
|
99 | directory named ~./ipython/security. | |
67 |
|
100 | |||
68 | * A single function :func:`get_ipython_dir`, in :mod:`IPython.genutils` that |
|
101 | * A single function :func:`get_ipython_dir`, in :mod:`IPython.genutils` that | |
69 | determines the user's IPython directory in a robust manner. |
|
102 | determines the user's IPython directory in a robust manner. | |
70 |
|
103 | |||
71 |
* Laurent's WX application has been given a top-level script called |
|
104 | * Laurent's WX application has been given a top-level script called | |
72 |
and it has received numerous fixes. |
|
105 | ipython-wx, and it has received numerous fixes. We expect this code to be | |
73 | architecturally better integrated with Gael's WX 'ipython widget' over the |
|
106 | architecturally better integrated with Gael's WX 'ipython widget' over the | |
74 | next few releases. |
|
107 | next few releases. | |
75 |
|
108 | |||
76 | * The Editor synchronization work by Vivian De Smedt has been merged in. This |
|
109 | * The Editor synchronization work by Vivian De Smedt has been merged in. This | |
77 | code adds a number of new editor hooks to synchronize with editors under |
|
110 | code adds a number of new editor hooks to synchronize with editors under | |
78 | Windows. |
|
111 | Windows. | |
79 |
|
112 | |||
80 | * A new, still experimental but highly functional, WX shell by Gael Varoquaux. |
|
113 | * A new, still experimental but highly functional, WX shell by Gael Varoquaux. | |
81 | This work was sponsored by Enthought, and while it's still very new, it is |
|
114 | This work was sponsored by Enthought, and while it's still very new, it is | |
82 | based on a more cleanly organized arhictecture of the various IPython |
|
115 | based on a more cleanly organized arhictecture of the various IPython | |
83 |
components. |
|
116 | components. We will continue to develop this over the next few releases as a | |
84 | model for GUI components that use IPython. |
|
117 | model for GUI components that use IPython. | |
85 |
|
118 | |||
86 | * Another GUI frontend, Cocoa based (Cocoa is the OSX native GUI framework), |
|
119 | * Another GUI frontend, Cocoa based (Cocoa is the OSX native GUI framework), | |
87 | authored by Barry Wark. Currently the WX and the Cocoa ones have slightly |
|
120 | authored by Barry Wark. Currently the WX and the Cocoa ones have slightly | |
88 | different internal organizations, but the whole team is working on finding |
|
121 | different internal organizations, but the whole team is working on finding | |
89 | what the right abstraction points are for a unified codebase. |
|
122 | what the right abstraction points are for a unified codebase. | |
90 |
|
123 | |||
91 | * As part of the frontend work, Barry Wark also implemented an experimental |
|
124 | * As part of the frontend work, Barry Wark also implemented an experimental | |
92 | event notification system that various ipython components can use. In the |
|
125 | event notification system that various ipython components can use. In the | |
93 | next release the implications and use patterns of this system regarding the |
|
126 | next release the implications and use patterns of this system regarding the | |
94 | various GUI options will be worked out. |
|
127 | various GUI options will be worked out. | |
95 |
|
128 | |||
96 | * IPython finally has a full test system, that can test docstrings with |
|
129 | * IPython finally has a full test system, that can test docstrings with | |
97 | IPython-specific functionality. There are still a few pieces missing for it |
|
130 | IPython-specific functionality. There are still a few pieces missing for it | |
98 | to be widely accessible to all users (so they can run the test suite at any |
|
131 | to be widely accessible to all users (so they can run the test suite at any | |
99 | time and report problems), but it now works for the developers. We are |
|
132 | time and report problems), but it now works for the developers. We are | |
100 | working hard on continuing to improve it, as this was probably IPython's |
|
133 | working hard on continuing to improve it, as this was probably IPython's | |
101 | major Achilles heel (the lack of proper test coverage made it effectively |
|
134 | major Achilles heel (the lack of proper test coverage made it effectively | |
102 | impossible to do large-scale refactoring). The full test suite can now |
|
135 | impossible to do large-scale refactoring). The full test suite can now | |
103 | be run using the :command:`iptest` command line program. |
|
136 | be run using the :command:`iptest` command line program. | |
104 |
|
137 | |||
105 | * The notion of a task has been completely reworked. An `ITask` interface has |
|
138 | * The notion of a task has been completely reworked. An `ITask` interface has | |
106 | been created. This interface defines the methods that tasks need to |
|
139 | been created. This interface defines the methods that tasks need to | |
107 | implement. These methods are now responsible for things like submitting |
|
140 | implement. These methods are now responsible for things like submitting | |
108 | tasks and processing results. There are two basic task types: |
|
141 | tasks and processing results. There are two basic task types: | |
109 | :class:`IPython.kernel.task.StringTask` (this is the old `Task` object, but |
|
142 | :class:`IPython.kernel.task.StringTask` (this is the old `Task` object, but | |
110 | renamed) and the new :class:`IPython.kernel.task.MapTask`, which is based on |
|
143 | renamed) and the new :class:`IPython.kernel.task.MapTask`, which is based on | |
111 | a function. |
|
144 | a function. | |
112 |
|
145 | |||
113 | * A new interface, :class:`IPython.kernel.mapper.IMapper` has been defined to |
|
146 | * A new interface, :class:`IPython.kernel.mapper.IMapper` has been defined to | |
114 | standardize the idea of a `map` method. This interface has a single `map` |
|
147 | standardize the idea of a `map` method. This interface has a single `map` | |
115 | method that has the same syntax as the built-in `map`. We have also defined |
|
148 | method that has the same syntax as the built-in `map`. We have also defined | |
116 | a `mapper` factory interface that creates objects that implement |
|
149 | a `mapper` factory interface that creates objects that implement | |
117 | :class:`IPython.kernel.mapper.IMapper` for different controllers. Both the |
|
150 | :class:`IPython.kernel.mapper.IMapper` for different controllers. Both the | |
118 | multiengine and task controller now have mapping capabilties. |
|
151 | multiengine and task controller now have mapping capabilties. | |
119 |
|
152 | |||
120 | * The parallel function capabilities have been reworks. The major changes are |
|
153 | * The parallel function capabilities have been reworks. The major changes are | |
121 | that i) there is now an `@parallel` magic that creates parallel functions, |
|
154 | that i) there is now an `@parallel` magic that creates parallel functions, | |
122 | ii) the syntax for mulitple variable follows that of `map`, iii) both the |
|
155 | ii) the syntax for mulitple variable follows that of `map`, iii) both the | |
123 | multiengine and task controller now have a parallel function implementation. |
|
156 | multiengine and task controller now have a parallel function implementation. | |
124 |
|
157 | |||
125 | * All of the parallel computing capabilities from `ipython1-dev` have been |
|
158 | * All of the parallel computing capabilities from `ipython1-dev` have been | |
126 | merged into IPython proper. This resulted in the following new subpackages: |
|
159 | merged into IPython proper. This resulted in the following new subpackages: | |
127 | :mod:`IPython.kernel`, :mod:`IPython.kernel.core`, :mod:`IPython.config`, |
|
160 | :mod:`IPython.kernel`, :mod:`IPython.kernel.core`, :mod:`IPython.config`, | |
128 | :mod:`IPython.tools` and :mod:`IPython.testing`. |
|
161 | :mod:`IPython.tools` and :mod:`IPython.testing`. | |
129 |
|
162 | |||
130 | * As part of merging in the `ipython1-dev` stuff, the `setup.py` script and |
|
163 | * As part of merging in the `ipython1-dev` stuff, the `setup.py` script and | |
131 | friends have been completely refactored. Now we are checking for |
|
164 | friends have been completely refactored. Now we are checking for | |
132 | dependencies using the approach that matplotlib uses. |
|
165 | dependencies using the approach that matplotlib uses. | |
133 |
|
166 | |||
134 |
* The documentation has been completely reorganized to accept the |
|
167 | * The documentation has been completely reorganized to accept the | |
135 | from `ipython1-dev`. |
|
168 | documentation from `ipython1-dev`. | |
136 |
|
169 | |||
137 | * We have switched to using Foolscap for all of our network protocols in |
|
170 | * We have switched to using Foolscap for all of our network protocols in | |
138 | :mod:`IPython.kernel`. This gives us secure connections that are both |
|
171 | :mod:`IPython.kernel`. This gives us secure connections that are both | |
139 | encrypted and authenticated. |
|
172 | encrypted and authenticated. | |
140 |
|
173 | |||
141 | * We have a brand new `COPYING.txt` files that describes the IPython license |
|
174 | * We have a brand new `COPYING.txt` files that describes the IPython license | |
142 |
and copyright. |
|
175 | and copyright. The biggest change is that we are putting "The IPython | |
143 |
Development Team" as the copyright holder. |
|
176 | Development Team" as the copyright holder. We give more details about | |
144 |
exactly what this means in this file. |
|
177 | exactly what this means in this file. All developer should read this and use | |
145 | the new banner in all IPython source code files. |
|
178 | the new banner in all IPython source code files. | |
146 |
|
179 | |||
147 | * sh profile: ./foo runs foo as system command, no need to do !./foo anymore |
|
180 | * sh profile: ./foo runs foo as system command, no need to do !./foo anymore | |
148 |
|
181 | |||
149 | * String lists now support ``sort(field, nums = True)`` method (to easily sort |
|
182 | * String lists now support ``sort(field, nums = True)`` method (to easily sort | |
150 | system command output). Try it with ``a = !ls -l ; a.sort(1, nums=1)``. |
|
183 | system command output). Try it with ``a = !ls -l ; a.sort(1, nums=1)``. | |
151 |
|
184 | |||
152 | * '%cpaste foo' now assigns the pasted block as string list, instead of string |
|
185 | * '%cpaste foo' now assigns the pasted block as string list, instead of string | |
153 |
|
186 | |||
154 | * The ipcluster script now run by default with no security. This is done |
|
187 | * The ipcluster script now run by default with no security. This is done | |
155 | because the main usage of the script is for starting things on localhost. |
|
188 | because the main usage of the script is for starting things on localhost. | |
156 | Eventually when ipcluster is able to start things on other hosts, we will put |
|
189 | Eventually when ipcluster is able to start things on other hosts, we will put | |
157 | security back. |
|
190 | security back. | |
158 |
|
191 | |||
159 | * 'cd --foo' searches directory history for string foo, and jumps to that dir. |
|
192 | * 'cd --foo' searches directory history for string foo, and jumps to that dir. | |
160 | Last part of dir name is checked first. If no matches for that are found, |
|
193 | Last part of dir name is checked first. If no matches for that are found, | |
161 | look at the whole path. |
|
194 | look at the whole path. | |
162 |
|
195 | |||
163 |
|
196 | |||
164 | Bug fixes |
|
197 | Bug fixes | |
165 | --------- |
|
198 | --------- | |
166 |
|
199 | |||
167 | * The Windows installer has been fixed. Now all IPython scripts have ``.bat`` |
|
200 | * The Windows installer has been fixed. Now all IPython scripts have ``.bat`` | |
168 | versions created. Also, the Start Menu shortcuts have been updated. |
|
201 | versions created. Also, the Start Menu shortcuts have been updated. | |
169 |
|
202 | |||
170 | * The colors escapes in the multiengine client are now turned off on win32 as |
|
203 | * The colors escapes in the multiengine client are now turned off on win32 as | |
171 | they don't print correctly. |
|
204 | they don't print correctly. | |
172 |
|
205 | |||
173 | * The :mod:`IPython.kernel.scripts.ipengine` script was exec'ing |
|
206 | * The :mod:`IPython.kernel.scripts.ipengine` script was exec'ing | |
174 | mpi_import_statement incorrectly, which was leading the engine to crash when |
|
207 | mpi_import_statement incorrectly, which was leading the engine to crash when | |
175 | mpi was enabled. |
|
208 | mpi was enabled. | |
176 |
|
209 | |||
177 | * A few subpackages had missing ``__init__.py`` files. |
|
210 | * A few subpackages had missing ``__init__.py`` files. | |
178 |
|
211 | |||
179 | * The documentation is only created if Sphinx is found. Previously, the |
|
212 | * The documentation is only created if Sphinx is found. Previously, the | |
180 | ``setup.py`` script would fail if it was missing. |
|
213 | ``setup.py`` script would fail if it was missing. | |
181 |
|
214 | |||
182 | * Greedy ``cd`` completion has been disabled again (it was enabled in 0.8.4) as |
|
215 | * Greedy ``cd`` completion has been disabled again (it was enabled in 0.8.4) as | |
183 | it caused problems on certain platforms. |
|
216 | it caused problems on certain platforms. | |
184 |
|
217 | |||
185 |
|
218 | |||
186 | Backwards incompatible changes |
|
219 | Backwards incompatible changes | |
187 | ------------------------------ |
|
220 | ------------------------------ | |
188 |
|
221 | |||
189 | * The ``clusterfile`` options of the :command:`ipcluster` command has been |
|
222 | * The ``clusterfile`` options of the :command:`ipcluster` command has been | |
190 | removed as it was not working and it will be replaced soon by something much |
|
223 | removed as it was not working and it will be replaced soon by something much | |
191 | more robust. |
|
224 | more robust. | |
192 |
|
225 | |||
193 | * The :mod:`IPython.kernel` configuration now properly find the user's |
|
226 | * The :mod:`IPython.kernel` configuration now properly find the user's | |
194 | IPython directory. |
|
227 | IPython directory. | |
195 |
|
228 | |||
196 | * In ipapi, the :func:`make_user_ns` function has been replaced with |
|
229 | * In ipapi, the :func:`make_user_ns` function has been replaced with | |
197 | :func:`make_user_namespaces`, to support dict subclasses in namespace |
|
230 | :func:`make_user_namespaces`, to support dict subclasses in namespace | |
198 | creation. |
|
231 | creation. | |
199 |
|
232 | |||
200 | * :class:`IPython.kernel.client.Task` has been renamed |
|
233 | * :class:`IPython.kernel.client.Task` has been renamed | |
201 | :class:`IPython.kernel.client.StringTask` to make way for new task types. |
|
234 | :class:`IPython.kernel.client.StringTask` to make way for new task types. | |
202 |
|
235 | |||
203 | * The keyword argument `style` has been renamed `dist` in `scatter`, `gather` |
|
236 | * The keyword argument `style` has been renamed `dist` in `scatter`, `gather` | |
204 | and `map`. |
|
237 | and `map`. | |
205 |
|
238 | |||
206 | * Renamed the values that the rename `dist` keyword argument can have from |
|
239 | * Renamed the values that the rename `dist` keyword argument can have from | |
207 | `'basic'` to `'b'`. |
|
240 | `'basic'` to `'b'`. | |
208 |
|
241 | |||
209 | * IPython has a larger set of dependencies if you want all of its capabilities. |
|
242 | * IPython has a larger set of dependencies if you want all of its capabilities. | |
210 | See the `setup.py` script for details. |
|
243 | See the `setup.py` script for details. | |
211 |
|
244 | |||
212 | * The constructors for :class:`IPython.kernel.client.MultiEngineClient` and |
|
245 | * The constructors for :class:`IPython.kernel.client.MultiEngineClient` and | |
213 | :class:`IPython.kernel.client.TaskClient` no longer take the (ip,port) tuple. |
|
246 | :class:`IPython.kernel.client.TaskClient` no longer take the (ip,port) tuple. | |
214 | Instead they take the filename of a file that contains the FURL for that |
|
247 | Instead they take the filename of a file that contains the FURL for that | |
215 | client. If the FURL file is in your IPYTHONDIR, it will be found automatically |
|
248 | client. If the FURL file is in your IPYTHONDIR, it will be found automatically | |
216 | and the constructor can be left empty. |
|
249 | and the constructor can be left empty. | |
217 |
|
250 | |||
218 | * The asynchronous clients in :mod:`IPython.kernel.asyncclient` are now created |
|
251 | * The asynchronous clients in :mod:`IPython.kernel.asyncclient` are now created | |
219 | using the factory functions :func:`get_multiengine_client` and |
|
252 | using the factory functions :func:`get_multiengine_client` and | |
220 | :func:`get_task_client`. These return a `Deferred` to the actual client. |
|
253 | :func:`get_task_client`. These return a `Deferred` to the actual client. | |
221 |
|
254 | |||
222 | * The command line options to `ipcontroller` and `ipengine` have changed to |
|
255 | * The command line options to `ipcontroller` and `ipengine` have changed to | |
223 | reflect the new Foolscap network protocol and the FURL files. Please see the |
|
256 | reflect the new Foolscap network protocol and the FURL files. Please see the | |
224 | help for these scripts for details. |
|
257 | help for these scripts for details. | |
225 |
|
258 | |||
226 | * The configuration files for the kernel have changed because of the Foolscap |
|
259 | * The configuration files for the kernel have changed because of the Foolscap | |
227 | stuff. If you were using custom config files before, you should delete them |
|
260 | stuff. If you were using custom config files before, you should delete them | |
228 | and regenerate new ones. |
|
261 | and regenerate new ones. | |
229 |
|
262 | |||
230 | Changes merged in from IPython1 |
|
263 | Changes merged in from IPython1 | |
231 | ------------------------------- |
|
264 | ------------------------------- | |
232 |
|
265 | |||
233 | New features |
|
266 | New features | |
234 | ............ |
|
267 | ............ | |
235 |
|
268 | |||
236 | * Much improved ``setup.py`` and ``setupegg.py`` scripts. Because Twisted and |
|
269 | * Much improved ``setup.py`` and ``setupegg.py`` scripts. Because Twisted and | |
237 | zope.interface are now easy installable, we can declare them as dependencies |
|
270 | zope.interface are now easy installable, we can declare them as dependencies | |
238 | in our setupegg.py script. |
|
271 | in our setupegg.py script. | |
239 |
|
272 | |||
240 | * IPython is now compatible with Twisted 2.5.0 and 8.x. |
|
273 | * IPython is now compatible with Twisted 2.5.0 and 8.x. | |
241 |
|
274 | |||
242 | * Added a new example of how to use :mod:`ipython1.kernel.asynclient`. |
|
275 | * Added a new example of how to use :mod:`ipython1.kernel.asynclient`. | |
243 |
|
276 | |||
244 | * Initial draft of a process daemon in :mod:`ipython1.daemon`. This has not |
|
277 | * Initial draft of a process daemon in :mod:`ipython1.daemon`. This has not | |
245 | been merged into IPython and is still in `ipython1-dev`. |
|
278 | been merged into IPython and is still in `ipython1-dev`. | |
246 |
|
279 | |||
247 | * The ``TaskController`` now has methods for getting the queue status. |
|
280 | * The ``TaskController`` now has methods for getting the queue status. | |
248 |
|
281 | |||
249 | * The ``TaskResult`` objects not have information about how long the task |
|
282 | * The ``TaskResult`` objects not have information about how long the task | |
250 | took to run. |
|
283 | took to run. | |
251 |
|
284 | |||
252 | * We are attaching additional attributes to exceptions ``(_ipython_*)`` that |
|
285 | * We are attaching additional attributes to exceptions ``(_ipython_*)`` that | |
253 | we use to carry additional info around. |
|
286 | we use to carry additional info around. | |
254 |
|
287 | |||
255 | * New top-level module :mod:`asyncclient` that has asynchronous versions (that |
|
288 | * New top-level module :mod:`asyncclient` that has asynchronous versions (that | |
256 | return deferreds) of the client classes. This is designed to users who want |
|
289 | return deferreds) of the client classes. This is designed to users who want | |
257 | to run their own Twisted reactor. |
|
290 | to run their own Twisted reactor. | |
258 |
|
291 | |||
259 | * All the clients in :mod:`client` are now based on Twisted. This is done by |
|
292 | * All the clients in :mod:`client` are now based on Twisted. This is done by | |
260 | running the Twisted reactor in a separate thread and using the |
|
293 | running the Twisted reactor in a separate thread and using the | |
261 | :func:`blockingCallFromThread` function that is in recent versions of Twisted. |
|
294 | :func:`blockingCallFromThread` function that is in recent versions of Twisted. | |
262 |
|
295 | |||
263 | * Functions can now be pushed/pulled to/from engines using |
|
296 | * Functions can now be pushed/pulled to/from engines using | |
264 | :meth:`MultiEngineClient.push_function` and |
|
297 | :meth:`MultiEngineClient.push_function` and | |
265 | :meth:`MultiEngineClient.pull_function`. |
|
298 | :meth:`MultiEngineClient.pull_function`. | |
266 |
|
299 | |||
267 | * Gather/scatter are now implemented in the client to reduce the work load |
|
300 | * Gather/scatter are now implemented in the client to reduce the work load | |
268 | of the controller and improve performance. |
|
301 | of the controller and improve performance. | |
269 |
|
302 | |||
270 | * Complete rewrite of the IPython docuementation. All of the documentation |
|
303 | * Complete rewrite of the IPython docuementation. All of the documentation | |
271 | from the IPython website has been moved into docs/source as restructured |
|
304 | from the IPython website has been moved into docs/source as restructured | |
272 | text documents. PDF and HTML documentation are being generated using |
|
305 | text documents. PDF and HTML documentation are being generated using | |
273 | Sphinx. |
|
306 | Sphinx. | |
274 |
|
307 | |||
275 | * New developer oriented documentation: development guidelines and roadmap. |
|
308 | * New developer oriented documentation: development guidelines and roadmap. | |
276 |
|
309 | |||
277 | * Traditional ``ChangeLog`` has been changed to a more useful ``changes.txt`` |
|
310 | * Traditional ``ChangeLog`` has been changed to a more useful ``changes.txt`` | |
278 | file that is organized by release and is meant to provide something more |
|
311 | file that is organized by release and is meant to provide something more | |
279 | relevant for users. |
|
312 | relevant for users. | |
280 |
|
313 | |||
281 | Bug fixes |
|
314 | Bug fixes | |
282 | ......... |
|
315 | ......... | |
283 |
|
316 | |||
284 | * Created a proper ``MANIFEST.in`` file to create source distributions. |
|
317 | * Created a proper ``MANIFEST.in`` file to create source distributions. | |
285 |
|
318 | |||
286 | * Fixed a bug in the ``MultiEngine`` interface. Previously, multi-engine |
|
319 | * Fixed a bug in the ``MultiEngine`` interface. Previously, multi-engine | |
287 | actions were being collected with a :class:`DeferredList` with |
|
320 | actions were being collected with a :class:`DeferredList` with | |
288 | ``fireononeerrback=1``. This meant that methods were returning |
|
321 | ``fireononeerrback=1``. This meant that methods were returning | |
289 | before all engines had given their results. This was causing extremely odd |
|
322 | before all engines had given their results. This was causing extremely odd | |
290 | bugs in certain cases. To fix this problem, we have 1) set |
|
323 | bugs in certain cases. To fix this problem, we have 1) set | |
291 | ``fireononeerrback=0`` to make sure all results (or exceptions) are in |
|
324 | ``fireononeerrback=0`` to make sure all results (or exceptions) are in | |
292 | before returning and 2) introduced a :exc:`CompositeError` exception |
|
325 | before returning and 2) introduced a :exc:`CompositeError` exception | |
293 | that wraps all of the engine exceptions. This is a huge change as it means |
|
326 | that wraps all of the engine exceptions. This is a huge change as it means | |
294 | that users will have to catch :exc:`CompositeError` rather than the actual |
|
327 | that users will have to catch :exc:`CompositeError` rather than the actual | |
295 | exception. |
|
328 | exception. | |
296 |
|
329 | |||
297 | Backwards incompatible changes |
|
330 | Backwards incompatible changes | |
298 | .............................. |
|
331 | .............................. | |
299 |
|
332 | |||
300 | * All names have been renamed to conform to the lowercase_with_underscore |
|
333 | * All names have been renamed to conform to the lowercase_with_underscore | |
301 | convention. This will require users to change references to all names like |
|
334 | convention. This will require users to change references to all names like | |
302 | ``queueStatus`` to ``queue_status``. |
|
335 | ``queueStatus`` to ``queue_status``. | |
303 |
|
336 | |||
304 | * Previously, methods like :meth:`MultiEngineClient.push` and |
|
337 | * Previously, methods like :meth:`MultiEngineClient.push` and | |
305 | :meth:`MultiEngineClient.push` used ``*args`` and ``**kwargs``. This was |
|
338 | :meth:`MultiEngineClient.push` used ``*args`` and ``**kwargs``. This was | |
306 | becoming a problem as we weren't able to introduce new keyword arguments into |
|
339 | becoming a problem as we weren't able to introduce new keyword arguments into | |
307 | the API. Now these methods simple take a dict or sequence. This has also |
|
340 | the API. Now these methods simple take a dict or sequence. This has also | |
308 | allowed us to get rid of the ``*All`` methods like :meth:`pushAll` and |
|
341 | allowed us to get rid of the ``*All`` methods like :meth:`pushAll` and | |
309 | :meth:`pullAll`. These things are now handled with the ``targets`` keyword |
|
342 | :meth:`pullAll`. These things are now handled with the ``targets`` keyword | |
310 | argument that defaults to ``'all'``. |
|
343 | argument that defaults to ``'all'``. | |
311 |
|
344 | |||
312 | * The :attr:`MultiEngineClient.magicTargets` has been renamed to |
|
345 | * The :attr:`MultiEngineClient.magicTargets` has been renamed to | |
313 | :attr:`MultiEngineClient.targets`. |
|
346 | :attr:`MultiEngineClient.targets`. | |
314 |
|
347 | |||
315 | * All methods in the MultiEngine interface now accept the optional keyword |
|
348 | * All methods in the MultiEngine interface now accept the optional keyword | |
316 | argument ``block``. |
|
349 | argument ``block``. | |
317 |
|
350 | |||
318 | * Renamed :class:`RemoteController` to :class:`MultiEngineClient` and |
|
351 | * Renamed :class:`RemoteController` to :class:`MultiEngineClient` and | |
319 | :class:`TaskController` to :class:`TaskClient`. |
|
352 | :class:`TaskController` to :class:`TaskClient`. | |
320 |
|
353 | |||
321 | * Renamed the top-level module from :mod:`api` to :mod:`client`. |
|
354 | * Renamed the top-level module from :mod:`api` to :mod:`client`. | |
322 |
|
355 | |||
323 | * Most methods in the multiengine interface now raise a :exc:`CompositeError` |
|
356 | * Most methods in the multiengine interface now raise a :exc:`CompositeError` | |
324 | exception that wraps the user's exceptions, rather than just raising the raw |
|
357 | exception that wraps the user's exceptions, rather than just raising the raw | |
325 | user's exception. |
|
358 | user's exception. | |
326 |
|
359 | |||
327 | * Changed the ``setupNS`` and ``resultNames`` in the ``Task`` class to ``push`` |
|
360 | * Changed the ``setupNS`` and ``resultNames`` in the ``Task`` class to ``push`` | |
328 | and ``pull``. |
|
361 | and ``pull``. | |
329 |
|
362 | |||
330 |
|
363 | |||
331 | Release 0.8.4 |
|
364 | Release 0.8.4 | |
332 | ============= |
|
365 | ============= | |
333 |
|
366 | |||
334 | This was a quick release to fix an unfortunate bug that slipped into the 0.8.3 |
|
367 | This was a quick release to fix an unfortunate bug that slipped into the 0.8.3 | |
335 | release. The ``--twisted`` option was disabled, as it turned out to be broken |
|
368 | release. The ``--twisted`` option was disabled, as it turned out to be broken | |
336 | across several platforms. |
|
369 | across several platforms. | |
337 |
|
370 | |||
338 |
|
371 | |||
339 | Release 0.8.3 |
|
372 | Release 0.8.3 | |
340 | ============= |
|
373 | ============= | |
341 |
|
374 | |||
342 | * pydb is now disabled by default (due to %run -d problems). You can enable |
|
375 | * pydb is now disabled by default (due to %run -d problems). You can enable | |
343 | it by passing -pydb command line argument to IPython. Note that setting |
|
376 | it by passing -pydb command line argument to IPython. Note that setting | |
344 | it in config file won't work. |
|
377 | it in config file won't work. | |
345 |
|
378 | |||
346 |
|
379 | |||
347 | Release 0.8.2 |
|
380 | Release 0.8.2 | |
348 | ============= |
|
381 | ============= | |
349 |
|
382 | |||
350 | * %pushd/%popd behave differently; now "pushd /foo" pushes CURRENT directory |
|
383 | * %pushd/%popd behave differently; now "pushd /foo" pushes CURRENT directory | |
351 | and jumps to /foo. The current behaviour is closer to the documented |
|
384 | and jumps to /foo. The current behaviour is closer to the documented | |
352 | behaviour, and should not trip anyone. |
|
385 | behaviour, and should not trip anyone. | |
353 |
|
386 | |||
354 |
|
387 | |||
355 | Older releases |
|
388 | Older releases | |
356 | ============== |
|
389 | ============== | |
357 |
|
390 | |||
358 | Changes in earlier releases of IPython are described in the older file |
|
391 | Changes in earlier releases of IPython are described in the older file | |
359 | ``ChangeLog``. Please refer to this document for details. |
|
392 | ``ChangeLog``. Please refer to this document for details. | |
360 |
|
393 |
@@ -1,10 +1,10 b'' | |||||
1 | =============================== |
|
1 | =============================== | |
2 | Configuration and customization |
|
2 | Configuration and customization | |
3 | =============================== |
|
3 | =============================== | |
4 |
|
4 | |||
5 | .. toctree:: |
|
5 | .. toctree:: | |
6 |
:maxdepth: |
|
6 | :maxdepth: 2 | |
7 |
|
7 | |||
8 | initial_config.txt |
|
8 | initial_config.txt | |
9 | customization.txt |
|
9 | customization.txt | |
10 | new_config.txt |
|
10 | new_config.txt |
@@ -1,446 +1,310 b'' | |||||
1 | .. _development: |
|
1 | .. _development: | |
2 |
|
2 | |||
3 | ============================== |
|
3 | ============================== | |
4 | IPython development guidelines |
|
4 | IPython development guidelines | |
5 | ============================== |
|
5 | ============================== | |
6 |
|
6 | |||
7 |
|
7 | |||
8 | Overview |
|
8 | Overview | |
9 | ======== |
|
9 | ======== | |
10 |
|
10 | |||
11 | IPython is the next generation of IPython. It is named such for two reasons: |
|
11 | This document describes IPython from the perspective of developers. Most | |
12 |
|
12 | importantly, it gives information for people who want to contribute to the | ||
13 | - Eventually, IPython will become IPython version 1.0. |
|
13 | development of IPython. So if you want to help out, read on! | |
14 | - This new code base needs to be able to co-exist with the existing IPython until |
|
14 | ||
15 | it is a full replacement for it. Thus we needed a different name. We couldn't |
|
15 | How to contribute to IPython | |
16 | use ``ipython`` (lowercase) as some files systems are case insensitive. |
|
16 | ============================ | |
17 |
|
17 | |||
18 | There are two, no three, main goals of the IPython effort: |
|
18 | IPython development is done using Bazaar [Bazaar]_ and Launchpad [Launchpad]_. | |
19 |
|
19 | This makes it easy for people to contribute to the development of IPython. | ||
20 | 1. Clean up the existing codebase and write lots of tests. |
|
20 | Here is a sketch of how to get going. | |
21 | 2. Separate the core functionality of IPython from the terminal to enable IPython |
|
|||
22 | to be used from within a variety of GUI applications. |
|
|||
23 | 3. Implement a system for interactive parallel computing. |
|
|||
24 |
|
||||
25 | While the third goal may seem a bit unrelated to the main focus of IPython, it |
|
|||
26 | turns out that the technologies required for this goal are nearly identical |
|
|||
27 | with those required for goal two. This is the main reason the interactive |
|
|||
28 | parallel computing capabilities are being put into IPython proper. Currently |
|
|||
29 | the third of these goals is furthest along. |
|
|||
30 |
|
||||
31 | This document describes IPython from the perspective of developers. |
|
|||
32 |
|
||||
33 |
|
||||
34 | Project organization |
|
|||
35 | ==================== |
|
|||
36 |
|
||||
37 | Subpackages |
|
|||
38 | ----------- |
|
|||
39 |
|
||||
40 | IPython is organized into semi self-contained subpackages. Each of the |
|
|||
41 | subpackages will have its own: |
|
|||
42 |
|
||||
43 | - **Dependencies**. One of the most important things to keep in mind in |
|
|||
44 | partitioning code amongst subpackages, is that they should be used to cleanly |
|
|||
45 | encapsulate dependencies. |
|
|||
46 |
|
||||
47 | - **Tests**. Each subpackage shoud have its own ``tests`` subdirectory that |
|
|||
48 | contains all of the tests for that package. For information about writing |
|
|||
49 | tests for IPython, see the `Testing System`_ section of this document. |
|
|||
50 |
|
||||
51 | - **Configuration**. Each subpackage should have its own ``config`` |
|
|||
52 | subdirectory that contains the configuration information for the components |
|
|||
53 | of the subpackage. For information about how the IPython configuration |
|
|||
54 | system works, see the `Configuration System`_ section of this document. |
|
|||
55 |
|
||||
56 | - **Scripts**. Each subpackage should have its own ``scripts`` subdirectory |
|
|||
57 | that contains all of the command line scripts associated with the subpackage. |
|
|||
58 |
|
||||
59 | Installation and dependencies |
|
|||
60 | ----------------------------- |
|
|||
61 |
|
||||
62 | IPython will not use `setuptools`_ for installation. Instead, we will use |
|
|||
63 | standard ``setup.py`` scripts that use `distutils`_. While there are a number a |
|
|||
64 | extremely nice features that `setuptools`_ has (like namespace packages), the |
|
|||
65 | current implementation of `setuptools`_ has performance problems, particularly |
|
|||
66 | on shared file systems. In particular, when Python packages are installed on |
|
|||
67 | NSF file systems, import times become much too long (up towards 10 seconds). |
|
|||
68 |
|
||||
69 | Because IPython is being used extensively in the context of high performance |
|
|||
70 | computing, where performance is critical but shared file systems are common, we |
|
|||
71 | feel these performance hits are not acceptable. Thus, until the performance |
|
|||
72 | problems associated with `setuptools`_ are addressed, we will stick with plain |
|
|||
73 | `distutils`_. We are hopeful that these problems will be addressed and that we |
|
|||
74 | will eventually begin using `setuptools`_. Because of this, we are trying to |
|
|||
75 | organize IPython in a way that will make the eventual transition to |
|
|||
76 | `setuptools`_ as painless as possible. |
|
|||
77 |
|
||||
78 | Because we will be using `distutils`_, there will be no method for |
|
|||
79 | automatically installing dependencies. Instead, we are following the approach |
|
|||
80 | of `Matplotlib`_ which can be summarized as follows: |
|
|||
81 |
|
||||
82 | - Distinguish between required and optional dependencies. However, the required |
|
|||
83 | dependencies for IPython should be only the Python standard library. |
|
|||
84 |
|
||||
85 | - Upon installation check to see which optional dependencies are present and |
|
|||
86 | tell the user which parts of IPython need which optional dependencies. |
|
|||
87 |
|
||||
88 | It is absolutely critical that each subpackage of IPython has a clearly |
|
|||
89 | specified set of dependencies and that dependencies are not carelessly |
|
|||
90 | inherited from other IPython subpackages. Furthermore, tests that have certain |
|
|||
91 | dependencies should not fail if those dependencies are not present. Instead |
|
|||
92 | they should be skipped and print a message. |
|
|||
93 |
|
||||
94 | .. _setuptools: http://peak.telecommunity.com/DevCenter/setuptools |
|
|||
95 | .. _distutils: http://docs.python.org/lib/module-distutils.html |
|
|||
96 | .. _Matplotlib: http://matplotlib.sourceforge.net/ |
|
|||
97 |
|
||||
98 | Specific subpackages |
|
|||
99 | -------------------- |
|
|||
100 |
|
||||
101 | ``core`` |
|
|||
102 | This is the core functionality of IPython that is independent of the |
|
|||
103 | terminal, network and GUIs. Most of the code that is in the current |
|
|||
104 | IPython trunk will be refactored, cleaned up and moved here. |
|
|||
105 |
|
||||
106 | ``kernel`` |
|
|||
107 | The enables the IPython core to be expose to a the network. This is |
|
|||
108 | also where all of the parallel computing capabilities are to be found. |
|
|||
109 |
|
||||
110 | ``config`` |
|
|||
111 | The configuration package used by IPython. |
|
|||
112 |
|
21 | |||
113 | ``frontends`` |
|
22 | Install Bazaar and create a Launchpad account | |
114 | The various frontends for IPython. A frontend is the end-user application |
|
23 | --------------------------------------------- | |
115 | that exposes the capabilities of IPython to the user. The most basic |
|
|||
116 | frontend will simply be a terminal based application that looks just like |
|
|||
117 | today 's IPython. Other frontends will likely be more powerful and based |
|
|||
118 | on GUI toolkits. |
|
|||
119 |
|
24 | |||
120 | ``notebook`` |
|
25 | First make sure you have installed Bazaar (see their `website | |
121 | An application that allows users to work with IPython notebooks. |
|
26 | <http://bazaar-vcs.org/>`_). To see that Bazaar is installed and knows about | |
|
27 | you, try the following:: | |||
122 |
|
28 | |||
123 | ``tools`` |
|
29 | $ bzr whoami | |
124 | This is where general utilities go. |
|
30 | Joe Coder <jcoder@gmail.com> | |
125 |
|
31 | |||
|
32 | This should display your name and email. Next, you will want to create an | |||
|
33 | account on the `Launchpad website <http://www.launchpad.net>`_ and setup your | |||
|
34 | ssh keys. For more information of setting up your ssh keys, see `this link | |||
|
35 | <https://help.launchpad.net/YourAccount/CreatingAnSSHKeyPair>`_. | |||
126 |
|
36 | |||
127 | Version control |
|
37 | Get the main IPython branch from Launchpad | |
128 | =============== |
|
38 | ------------------------------------------ | |
129 |
|
39 | |||
130 | In the past, IPython development has been done using `Subversion`__. Recently, |
|
40 | Now, you can get a copy of the main IPython development branch (we call this | |
131 | we made the transition to using `Bazaar`__ and `Launchpad`__. This makes it |
|
41 | the "trunk"):: | |
132 | much easier for people to contribute code to IPython. Here is a sketch of how |
|
|||
133 | to use Bazaar for IPython development. First, you should install Bazaar. |
|
|||
134 | After you have done that, make sure that it is working by getting the latest |
|
|||
135 | main branch of IPython:: |
|
|||
136 |
|
42 | |||
137 | $ bzr branch lp:ipython |
|
43 | $ bzr branch lp:ipython | |
138 |
|
44 | |||
139 | Now you can create a new branch for you to do your work in:: |
|
45 | Create a working branch | |
|
46 | ----------------------- | |||
|
47 | ||||
|
48 | When working on IPython, you won't actually make edits directly to the | |||
|
49 | :file:`lp:ipython` branch. Instead, you will create a separate branch for your | |||
|
50 | changes. For now, let's assume you want to do your work in a branch named | |||
|
51 | "ipython-mybranch". Create this branch by doing:: | |||
140 |
|
52 | |||
141 | $ bzr branch ipython ipython-mybranch |
|
53 | $ bzr branch ipython ipython-mybranch | |
142 |
|
54 | |||
143 | The typical work cycle in this branch will be to make changes in |
|
55 | When you actually create a branch, you will want to give it a name that | |
144 | ``ipython-mybranch`` and then commit those changes using the commit command:: |
|
56 | reflects the nature of the work that you will be doing in it, like | |
|
57 | "install-docs-update". | |||
|
58 | ||||
|
59 | Make edits in your working branch | |||
|
60 | --------------------------------- | |||
|
61 | ||||
|
62 | Now you are ready to actually make edits in your :file:`ipython-mybranch` | |||
|
63 | branch. Before doing this, it is helpful to install this branch so you can | |||
|
64 | test your changes as you work. This is easiest if you have setuptools | |||
|
65 | installed. Then, just do:: | |||
|
66 | ||||
|
67 | $ cd ipython-mybranch | |||
|
68 | $ python setupegg.py develop | |||
|
69 | ||||
|
70 | Now, make some changes. After a while, you will want to commit your changes. | |||
|
71 | This let's Bazaar know that you like the changes you have made and gives you | |||
|
72 | an opportunity to keep a nice record of what you have done. This looks like | |||
|
73 | this:: | |||
145 |
|
74 | |||
146 | $ ...do work in ipython-mybranch... |
|
75 | $ ...do work in ipython-mybranch... | |
147 | $ bzr ci -m "the commit message goes here" |
|
76 | $ bzr commit -m "the commit message goes here" | |
148 |
|
77 | |||
149 | Please note that since we now don't use an old-style linear ChangeLog (that |
|
78 | Please note that since we now don't use an old-style linear ChangeLog (that | |
150 | tends to cause problems with distributed version control systems), you should |
|
79 | tends to cause problems with distributed version control systems), you should | |
151 | ensure that your log messages are reasonably detailed. Use a docstring-like |
|
80 | ensure that your log messages are reasonably detailed. Use a docstring-like | |
152 | approach in the commit messages (including the second line being left |
|
81 | approach in the commit messages (including the second line being left | |
153 | *blank*):: |
|
82 | *blank*):: | |
154 |
|
83 | |||
155 | Single line summary of changes being committed. |
|
84 | Single line summary of changes being committed. | |
156 |
|
85 | |||
157 |
|
|
86 | * more details when warranted ... | |
158 |
|
|
87 | * including crediting outside contributors if they sent the | |
159 | code/bug/idea! |
|
88 | code/bug/idea! | |
160 |
|
89 | |||
161 | If we couple this with a policy of making single commits for each reasonably |
|
90 | As you work, you will repeat this edit/commit cycle many times. If you work on | |
162 | atomic change, the bzr log should give an excellent view of the project, and |
|
91 | your branch for a long time, you will also want to get the latest changes from | |
163 | the `--short` log option becomes a nice summary. |
|
92 | the :file:`lp:ipython` branch. This can be done with the following sequence of | |
|
93 | commands:: | |||
164 |
|
94 | |||
165 | While working with this branch, it is a good idea to merge in changes that have |
|
95 | $ ls | |
166 | been made upstream in the parent branch. This can be done by doing:: |
|
96 | ipython | |
167 |
|
97 | ipython-mybranch | ||
168 | $ bzr pull |
|
|||
169 |
|
98 | |||
170 | If this command shows that the branches have diverged, then you should do a |
|
99 | $ cd ipython | |
171 | merge instead:: |
|
100 | $ bzr pull | |
|
101 | $ cd ../ipython-mybranch | |||
|
102 | $ bzr merge ../ipython | |||
|
103 | $ bzr commit -m "Merging changes from trunk" | |||
172 |
|
104 | |||
173 | $ bzr merge lp:ipython |
|
105 | Along the way, you should also run the IPython test suite. You can do this using the :command:`iptest` command:: | |
174 |
|
106 | |||
175 | If you want others to be able to see your branch, you can create an account |
|
107 | $ cd | |
176 | with launchpad and push the branch to your own workspace:: |
|
108 | $ iptest | |
177 |
|
109 | |||
178 | $ bzr push bzr+ssh://<me>@bazaar.launchpad.net/~<me>/+junk/ipython-mybranch |
|
110 | The :command:`iptest` command will also pick up and run any tests you have written. | |
179 |
|
111 | |||
180 | Finally, once the work in your branch is done, you can merge your changes back |
|
112 | Post your branch and request a code review | |
181 | into the `ipython` branch by using merge:: |
|
113 | ------------------------------------------ | |
182 |
|
114 | |||
183 | $ cd ipython |
|
115 | Once you are done with your edits, you should post your branch on Launchpad so | |
184 | $ merge ../ipython-mybranch |
|
116 | that other IPython developers can review the changes and help you merge your | |
185 | [resolve any conflicts] |
|
117 | changes into the main development branch. To post your branch on Launchpad, | |
186 | $ bzr ci -m "Fixing that bug" |
|
118 | do:: | |
187 | $ bzr push |
|
119 | ||
|
120 | $ cd ipython-mybranch | |||
|
121 | $ bzr push lp:~yourusername/ipython/ipython-mybranch | |||
|
122 | ||||
|
123 | Then, go to the `IPython Launchpad site <www.launchpad.net/ipython>`_, and you | |||
|
124 | should see your branch under the "Code" tab. If you click on your branch, you | |||
|
125 | can provide a short description of the branch as well as mark its status. Most | |||
|
126 | importantly, you should click the link that reads "Propose for merging into | |||
|
127 | another branch". What does this do? | |||
188 |
|
128 | |||
189 | But this will require you to have write permissions to the `ipython` branch. |
|
129 | This let's the other IPython developers know that your branch is ready to be | |
190 | It you don't you can tell one of the IPython devs about your branch and they |
|
130 | reviewed and merged into the main development branch. During this review | |
191 | can do the merge for you. |
|
131 | process, other developers will give you feedback and help you get your code | |
|
132 | ready to be merged. What types of things will we be looking for: | |||
192 |
|
133 | |||
193 | More information about Bazaar workflows can be found `here`__. |
|
134 | * All code is documented. | |
|
135 | * All code has tests. | |||
|
136 | * The entire IPython test suite passes. | |||
194 |
|
137 | |||
195 | .. __: http://subversion.tigris.org/ |
|
138 | Once your changes have been reviewed and approved, someone will merge them | |
196 | .. __: http://bazaar-vcs.org/ |
|
139 | into the main development branch. | |
197 | .. __: http://www.launchpad.net/ipython |
|
|||
198 | .. __: http://doc.bazaar-vcs.org/bzr.dev/en/user-guide/index.html |
|
|||
199 |
|
140 | |||
200 | Documentation |
|
141 | Documentation | |
201 | ============= |
|
142 | ============= | |
202 |
|
143 | |||
203 | Standalone documentation |
|
144 | Standalone documentation | |
204 | ------------------------ |
|
145 | ------------------------ | |
205 |
|
146 | |||
206 | All standalone documentation should be written in plain text (``.txt``) files |
|
147 | All standalone documentation should be written in plain text (``.txt``) files | |
207 |
using |
|
148 | using reStructuredText [reStructuredText]_ for markup and formatting. All such | |
208 |
should be placed in |
|
149 | documentation should be placed in directory :file:`docs/source` of the IPython | |
209 | tree. Or, when appropriate, a suitably named subdirectory should be used. The |
|
150 | source tree. The documentation in this location will serve as the main source | |
210 | documentation in this location will serve as the main source for IPython |
|
151 | for IPython documentation and all existing documentation should be converted | |
211 | documentation and all existing documentation should be converted to this |
|
152 | to this format. | |
212 | format. |
|
|||
213 |
|
153 | |||
214 | In the future, the text files in the ``docs`` directory will be used to |
|
154 | To build the final documentation, we use Sphinx [Sphinx]_. Once you have Sphinx installed, you can build the html docs yourself by doing:: | |
215 | generate all forms of documentation for IPython. This include documentation on |
|
|||
216 | the IPython website as well as *pdf* documentation. |
|
|||
217 |
|
155 | |||
218 | .. _reStructuredText: http://docutils.sourceforge.net/rst.html |
|
156 | $ cd ipython-mybranch/docs | |
|
157 | $ make html | |||
219 |
|
158 | |||
220 | Docstring format |
|
159 | Docstring format | |
221 | ---------------- |
|
160 | ---------------- | |
222 |
|
161 | |||
223 |
Good docstrings are very important. All new code |
|
162 | Good docstrings are very important. All new code should have docstrings that | |
224 | generating API docs, so we will follow the `Epydoc`_ conventions. More |
|
163 | are formatted using reStructuredText for markup and formatting, since it is | |
225 | specifically, we will use `reStructuredText`_ for markup and formatting, since |
|
164 | understood by a wide variety of tools. Details about using reStructuredText | |
226 | it is understood by a wide variety of tools. This means that if in the future |
|
165 | for docstrings can be found `here | |
227 | we have any reason to change from `Epydoc`_ to something else, we'll have fewer |
|
|||
228 | transition pains. |
|
|||
229 |
|
||||
230 | Details about using `reStructuredText`_ for docstrings can be found `here |
|
|||
231 | <http://epydoc.sourceforge.net/manual-othermarkup.html>`_. |
|
166 | <http://epydoc.sourceforge.net/manual-othermarkup.html>`_. | |
232 |
|
167 | |||
233 | .. _Epydoc: http://epydoc.sourceforge.net/ |
|
|||
234 |
|
||||
235 | Additional PEPs of interest regarding documentation of code: |
|
168 | Additional PEPs of interest regarding documentation of code: | |
236 |
|
169 | |||
237 |
|
|
170 | * `Docstring Conventions <http://www.python.org/peps/pep-0257.html>`_ | |
238 |
|
|
171 | * `Docstring Processing System Framework <http://www.python.org/peps/pep-0256.html>`_ | |
239 |
|
|
172 | * `Docutils Design Specification <http://www.python.org/peps/pep-0258.html>`_ | |
240 |
|
173 | |||
241 |
|
174 | |||
242 | Coding conventions |
|
175 | Coding conventions | |
243 | ================== |
|
176 | ================== | |
244 |
|
177 | |||
245 | General |
|
178 | General | |
246 | ------- |
|
179 | ------- | |
247 |
|
180 | |||
248 | In general, we'll try to follow the standard Python style conventions as |
|
181 | In general, we'll try to follow the standard Python style conventions as | |
249 | described here: |
|
182 | described here: | |
250 |
|
183 | |||
251 |
|
|
184 | * `Style Guide for Python Code <http://www.python.org/peps/pep-0008.html>`_ | |
252 |
|
185 | |||
253 |
|
186 | |||
254 | Other comments: |
|
187 | Other comments: | |
255 |
|
188 | |||
256 |
|
|
189 | * In a large file, top level classes and functions should be | |
257 | separated by 2-3 lines to make it easier to separate them visually. |
|
190 | separated by 2-3 lines to make it easier to separate them visually. | |
258 |
|
|
191 | * Use 4 spaces for indentation. | |
259 |
|
|
192 | * Keep the ordering of methods the same in classes that have the same | |
260 | methods. This is particularly true for classes that implement |
|
193 | methods. This is particularly true for classes that implement an interface. | |
261 | similar interfaces and for interfaces that are similar. |
|
|||
262 |
|
194 | |||
263 | Naming conventions |
|
195 | Naming conventions | |
264 | ------------------ |
|
196 | ------------------ | |
265 |
|
197 | |||
266 | In terms of naming conventions, we'll follow the guidelines from the `Style |
|
198 | In terms of naming conventions, we'll follow the guidelines from the `Style | |
267 | Guide for Python Code`_. |
|
199 | Guide for Python Code`_. | |
268 |
|
200 | |||
269 | For all new IPython code (and much existing code is being refactored), we'll use: |
|
201 | For all new IPython code (and much existing code is being refactored), we'll use: | |
270 |
|
202 | |||
271 |
|
|
203 | * All ``lowercase`` module names. | |
272 |
|
204 | |||
273 |
|
|
205 | * ``CamelCase`` for class names. | |
274 |
|
206 | |||
275 |
|
|
207 | * ``lowercase_with_underscores`` for methods, functions, variables and | |
276 | attributes. |
|
208 | attributes. | |
277 |
|
209 | |||
278 | This may be confusing as most of the existing IPython codebase uses a different |
|
210 | There are, however, some important exceptions to these rules. In some cases, | |
279 | convention (``lowerCamelCase`` for methods and attributes). Slowly, we will |
|
|||
280 | move IPython over to the new convention, providing shadow names for backward |
|
|||
281 | compatibility in public interfaces. |
|
|||
282 |
|
||||
283 | There are, however, some important exceptions to these rules. In some cases, |
|
|||
284 | IPython code will interface with packages (Twisted, Wx, Qt) that use other |
|
211 | IPython code will interface with packages (Twisted, Wx, Qt) that use other | |
285 |
conventions. |
|
212 | conventions. At some level this makes it impossible to adhere to our own | |
286 |
standards at all times. |
|
213 | standards at all times. In particular, when subclassing classes that use other | |
287 |
naming conventions, you must follow their naming conventions. |
|
214 | naming conventions, you must follow their naming conventions. To deal with | |
288 | cases like this, we propose the following policy: |
|
215 | cases like this, we propose the following policy: | |
289 |
|
216 | |||
290 |
|
|
217 | * If you are subclassing a class that uses different conventions, use its | |
291 | naming conventions throughout your subclass. Thus, if you are creating a |
|
218 | naming conventions throughout your subclass. Thus, if you are creating a | |
292 | Twisted Protocol class, used Twisted's |
|
219 | Twisted Protocol class, used Twisted's | |
293 | ``namingSchemeForMethodsAndAttributes.`` |
|
220 | ``namingSchemeForMethodsAndAttributes.`` | |
294 |
|
221 | |||
295 |
|
|
222 | * All IPython's official interfaces should use our conventions. In some cases | |
296 | this will mean that you need to provide shadow names (first implement |
|
223 | this will mean that you need to provide shadow names (first implement | |
297 | ``fooBar`` and then ``foo_bar = fooBar``). We want to avoid this at all |
|
224 | ``fooBar`` and then ``foo_bar = fooBar``). We want to avoid this at all | |
298 | costs, but it will probably be necessary at times. But, please use this |
|
225 | costs, but it will probably be necessary at times. But, please use this | |
299 | sparingly! |
|
226 | sparingly! | |
300 |
|
227 | |||
301 | Implementation-specific *private* methods will use |
|
228 | Implementation-specific *private* methods will use | |
302 |
``_single_underscore_prefix``. |
|
229 | ``_single_underscore_prefix``. Names with a leading double underscore will | |
303 | *only* be used in special cases, as they makes subclassing difficult (such |
|
230 | *only* be used in special cases, as they makes subclassing difficult (such | |
304 | names are not easily seen by child classes). |
|
231 | names are not easily seen by child classes). | |
305 |
|
232 | |||
306 | Occasionally some run-in lowercase names are used, but mostly for very short |
|
233 | Occasionally some run-in lowercase names are used, but mostly for very short | |
307 | names or where we are implementing methods very similar to existing ones in a |
|
234 | names or where we are implementing methods very similar to existing ones in a | |
308 | base class (like ``runlines()`` where ``runsource()`` and ``runcode()`` had |
|
235 | base class (like ``runlines()`` where ``runsource()`` and ``runcode()`` had | |
309 | established precedent). |
|
236 | established precedent). | |
310 |
|
237 | |||
311 | The old IPython codebase has a big mix of classes and modules prefixed with an |
|
238 | The old IPython codebase has a big mix of classes and modules prefixed with an | |
312 | explicit ``IP``. In Python this is mostly unnecessary, redundant and frowned |
|
239 | explicit ``IP``. In Python this is mostly unnecessary, redundant and frowned | |
313 | upon, as namespaces offer cleaner prefixing. The only case where this approach |
|
240 | upon, as namespaces offer cleaner prefixing. The only case where this approach | |
314 | is justified is for classes which are expected to be imported into external |
|
241 | is justified is for classes which are expected to be imported into external | |
315 | namespaces and a very generic name (like Shell) is too likely to clash with |
|
242 | namespaces and a very generic name (like Shell) is too likely to clash with | |
316 | something else. We'll need to revisit this issue as we clean up and refactor |
|
243 | something else. We'll need to revisit this issue as we clean up and refactor | |
317 | the code, but in general we should remove as many unnecessary ``IP``/``ip`` |
|
244 | the code, but in general we should remove as many unnecessary ``IP``/``ip`` | |
318 | prefixes as possible. However, if a prefix seems absolutely necessary the more |
|
245 | prefixes as possible. However, if a prefix seems absolutely necessary the more | |
319 | specific ``IPY`` or ``ipy`` are preferred. |
|
246 | specific ``IPY`` or ``ipy`` are preferred. | |
320 |
|
247 | |||
321 | .. _devel_testing: |
|
248 | .. _devel_testing: | |
322 |
|
249 | |||
323 | Testing system |
|
250 | Testing system | |
324 | ============== |
|
251 | ============== | |
325 |
|
252 | |||
326 |
It is extremely important that all code contributed to IPython has tests. |
|
253 | It is extremely important that all code contributed to IPython has tests. | |
327 |
should be written as unittests, doctests or as entities that the |
|
254 | Tests should be written as unittests, doctests or as entities that the Nose | |
328 |
testing package will find. Regardless of how the tests are written, we |
|
255 | [Nose]_ testing package will find. Regardless of how the tests are written, we | |
329 |
|
|
256 | will use Nose for discovering and running the tests. Nose will be required to | |
330 | the IPython test suite, but will not be required to simply use IPython. |
|
257 | run the IPython test suite, but will not be required to simply use IPython. | |
331 |
|
258 | |||
332 | .. _Nose: http://code.google.com/p/python-nose/ |
|
259 | Tests of Twisted using code need to follow two additional guidelines: | |
333 |
|
260 | |||
334 |
|
|
261 | 1. Twisted using tests should be written by subclassing the :class:`TestCase` | |
335 |
|
|
262 | class that comes with :mod:`twisted.trial.unittest`. | |
336 | done, `Nose`_ will be able to run the tests and the twisted reactor will be |
|
|||
337 | handled correctly. |
|
|||
338 |
|
263 | |||
339 | .. __: http://www.twistedmatrix.com |
|
264 | 2. All :class:`Deferred` instances that are created in the test must be | |
|
265 | properly chained and the final one *must* be the return value of the test | |||
|
266 | method. | |||
340 |
|
267 | |||
341 | Each subpackage in IPython should have its own ``tests`` directory that |
|
268 | When these two things are done, Nose will be able to run the tests and the | |
|
269 | twisted reactor will be handled correctly. | |||
|
270 | ||||
|
271 | Each subpackage in IPython should have its own :file:`tests` directory that | |||
342 | contains all of the tests for that subpackage. This allows each subpackage to |
|
272 | contains all of the tests for that subpackage. This allows each subpackage to | |
343 | be self-contained. If a subpackage has any dependencies beyond the Python |
|
273 | be self-contained. If a subpackage has any dependencies beyond the Python | |
344 | standard library, the tests for that subpackage should be skipped if the |
|
274 | standard library, the tests for that subpackage should be skipped if the | |
345 | dependencies are not found. This is very important so users don't get tests |
|
275 | dependencies are not found. This is very important so users don't get tests | |
346 | failing simply because they don't have dependencies. |
|
276 | failing simply because they don't have dependencies. | |
347 |
|
277 | |||
348 | We also need to look into use Noses ability to tag tests to allow a more |
|
278 | To run the IPython test suite, use the :command:`iptest` command that is installed with IPython:: | |
349 | modular approach of running tests. |
|
|||
350 |
|
279 | |||
351 | .. _devel_config: |
|
280 | $ iptest | |
352 |
|
281 | |||
353 | Configuration system |
|
282 | This command runs Nose with the proper options and extensions. | |
354 | ==================== |
|
|||
355 |
|
||||
356 | IPython uses `.ini`_ files for configuration purposes. This represents a huge |
|
|||
357 | improvement over the configuration system used in IPython. IPython works with |
|
|||
358 | these files using the `ConfigObj`_ package, which IPython includes as |
|
|||
359 | ``ipython1/external/configobj.py``. |
|
|||
360 |
|
||||
361 | Currently, we are using raw `ConfigObj`_ objects themselves. Each subpackage of |
|
|||
362 | IPython should contain a ``config`` subdirectory that contains all of the |
|
|||
363 | configuration information for the subpackage. To see how configuration |
|
|||
364 | information is defined (along with defaults) see at the examples in |
|
|||
365 | ``ipython1/kernel/config`` and ``ipython1/core/config``. Likewise, to see how |
|
|||
366 | the configuration information is used, see examples in |
|
|||
367 | ``ipython1/kernel/scripts/ipengine.py``. |
|
|||
368 |
|
||||
369 | Eventually, we will add a new layer on top of the raw `ConfigObj`_ objects. We |
|
|||
370 | are calling this new layer, ``tconfig``, as it will use a `Traits`_-like |
|
|||
371 | validation model. We won't actually use `Traits`_, but will implement |
|
|||
372 | something similar in pure Python. But, even in this new system, we will still |
|
|||
373 | use `ConfigObj`_ and `.ini`_ files underneath the hood. Talk to Fernando if you |
|
|||
374 | are interested in working on this part of IPython. The current prototype of |
|
|||
375 | ``tconfig`` is located in the IPython sandbox. |
|
|||
376 |
|
||||
377 | .. _.ini: http://docs.python.org/lib/module-ConfigParser.html |
|
|||
378 | .. _ConfigObj: http://www.voidspace.org.uk/python/configobj.html |
|
|||
379 | .. _Traits: http://code.enthought.com/traits/ |
|
|||
380 |
|
||||
381 |
|
||||
382 | Installation and testing scenarios |
|
|||
383 | ================================== |
|
|||
384 |
|
||||
385 | This section outlines the various scenarios that we need to test before we |
|
|||
386 | release an IPython version. These scenarios represent different ways of |
|
|||
387 | installing IPython and its dependencies. |
|
|||
388 |
|
||||
389 | Installation scenarios under Linux and OS X |
|
|||
390 | ------------------------------------------- |
|
|||
391 |
|
||||
392 | 1. Install from tarball using ``python setup.py install``. |
|
|||
393 | a. With only readline+nose dependencies installed. |
|
|||
394 | b. With all dependencies installed (readline, zope.interface, Twisted, |
|
|||
395 | foolscap, Sphinx, nose, pyOpenSSL). |
|
|||
396 |
|
||||
397 | 2. Install using easy_install. |
|
|||
398 |
|
||||
399 | a. With only readline+nose dependencies installed. |
|
|||
400 | i. Default dependencies: ``easy_install ipython-0.9.beta3-py2.5.egg`` |
|
|||
401 | ii. Optional dependency sets: ``easy_install -f ipython-0.9.beta3-py2.5.egg IPython[kernel,doc,test,security]`` |
|
|||
402 |
|
||||
403 | b. With all dependencies already installed. |
|
|||
404 |
|
||||
405 |
|
||||
406 | Installation scenarios under Win32 |
|
|||
407 | ---------------------------------- |
|
|||
408 |
|
||||
409 | 1. Install everything from .exe installers |
|
|||
410 | 2. easy_install? |
|
|||
411 |
|
||||
412 |
|
||||
413 | Tests to run for these scenarios |
|
|||
414 | -------------------------------- |
|
|||
415 |
|
||||
416 | 1. Run the full test suite. |
|
|||
417 | 2. Start a controller and engines and try a few things by hand. |
|
|||
418 | a. Using ipcluster. |
|
|||
419 | b. Using ipcontroller/ipengine by hand. |
|
|||
420 |
|
||||
421 | 3. Run a few of the parallel examples. |
|
|||
422 | 4. Try the kernel with and without security with and without PyOpenSSL |
|
|||
423 | installed. |
|
|||
424 | 5. Beat on the IPython terminal a bunch. |
|
|||
425 | 6. Make sure that furl files are being put in proper locations. |
|
|||
426 |
|
283 | |||
|
284 | .. _devel_config: | |||
427 |
|
285 | |||
428 | Release checklist |
|
286 | Release checklist | |
429 | ================= |
|
287 | ================= | |
430 |
|
288 | |||
431 | Most of the release process is automated by the :file:`release` script in the |
|
289 | Most of the release process is automated by the :file:`release` script in the | |
432 | :file:`tools` directory. This is just a handy reminder for the release manager. |
|
290 | :file:`tools` directory. This is just a handy reminder for the release manager. | |
433 |
|
291 | |||
434 | #. Run the release script, which makes the tar.gz, eggs and Win32 .exe |
|
292 | #. Run the release script, which makes the tar.gz, eggs and Win32 .exe | |
435 | installer. It posts them to the site and registers the release with PyPI. |
|
293 | installer. It posts them to the site and registers the release with PyPI. | |
436 |
|
294 | |||
437 |
#. Updating the website with announcements and links to the updated |
|
295 | #. Updating the website with announcements and links to the updated | |
438 |
in html form. |
|
296 | changes.txt in html form. Remember to put a short note both on the news | |
439 |
and on |
|
297 | page of the site and on Launcphad. | |
440 |
|
298 | |||
441 | #. Drafting a short release announcement with i) highlights and ii) a link to |
|
299 | #. Drafting a short release announcement with i) highlights and ii) a link to | |
442 | the html changes.txt. |
|
300 | the html changes.txt. | |
443 |
|
301 | |||
444 | #. Make sure that the released version of the docs is live on the site. |
|
302 | #. Make sure that the released version of the docs is live on the site. | |
445 |
|
303 | |||
446 | #. Celebrate! |
|
304 | #. Celebrate! | |
|
305 | ||||
|
306 | .. [Bazaar] Bazaar. http://bazaar-vcs.org/ | |||
|
307 | .. [Launchpad] Launchpad. http://www.launchpad.net/ipython | |||
|
308 | .. [reStructuredText] reStructuredText. http://docutils.sourceforge.net/rst.html | |||
|
309 | .. [Sphinx] Sphinx. http://sphinx.pocoo.org/ | |||
|
310 | .. [Nose] Nose: a discovery based unittest extension. http://code.google.com/p/python-nose/ |
@@ -1,10 +1,11 b'' | |||||
1 | ================== |
|
1 | ================== | |
2 | Development |
|
2 | Development | |
3 | ================== |
|
3 | ================== | |
4 |
|
4 | |||
5 | .. toctree:: |
|
5 | .. toctree:: | |
6 | :maxdepth: 2 |
|
6 | :maxdepth: 2 | |
7 |
|
7 | |||
8 | development.txt |
|
8 | development.txt | |
9 | roadmap.txt |
|
9 | roadmap.txt | |
10 | notification_blueprint.txt |
|
10 | notification_blueprint.txt | |
|
11 | config_blueprint.txt |
@@ -1,49 +1,83 b'' | |||||
1 | .. _notification: |
|
1 | .. _notification: | |
2 |
|
2 | |||
3 | ========================================== |
|
3 | ========================================== | |
4 | IPython.kernel.core.notification blueprint |
|
4 | IPython.kernel.core.notification blueprint | |
5 | ========================================== |
|
5 | ========================================== | |
6 |
|
6 | |||
7 | Overview |
|
7 | Overview | |
8 | ======== |
|
8 | ======== | |
9 | The :mod:`IPython.kernel.core.notification` module will provide a simple implementation of a notification center and support for the observer pattern within the :mod:`IPython.kernel.core`. The main intended use case is to provide notification of Interpreter events to an observing frontend during the execution of a single block of code. |
|
9 | ||
|
10 | The :mod:`IPython.kernel.core.notification` module will provide a simple | |||
|
11 | implementation of a notification center and support for the observer pattern | |||
|
12 | within the :mod:`IPython.kernel.core`. The main intended use case is to | |||
|
13 | provide notification of Interpreter events to an observing frontend during the | |||
|
14 | execution of a single block of code. | |||
10 |
|
15 | |||
11 | Functional Requirements |
|
16 | Functional Requirements | |
12 | ======================= |
|
17 | ======================= | |
|
18 | ||||
13 | The notification center must: |
|
19 | The notification center must: | |
14 | * Provide synchronous notification of events to all registered observers. |
|
20 | ||
15 | * Provide typed or labeled notification types |
|
21 | * Provide synchronous notification of events to all registered observers. | |
16 | * Allow observers to register callbacks for individual or all notification types |
|
22 | ||
17 | * Allow observers to register callbacks for events from individual or all notifying objects |
|
23 | * Provide typed or labeled notification types. | |
18 | * Notification to the observer consists of the notification type, notifying object and user-supplied extra information [implementation: as keyword parameters to the registered callback] |
|
24 | ||
19 | * Perform as O(1) in the case of no registered observers. |
|
25 | * Allow observers to register callbacks for individual or all notification | |
20 | * Permit out-of-process or cross-network extension. |
|
26 | types. | |
|
27 | ||||
|
28 | * Allow observers to register callbacks for events from individual or all | |||
|
29 | notifying objects. | |||
|
30 | ||||
|
31 | * Notification to the observer consists of the notification type, notifying | |||
|
32 | object and user-supplied extra information [implementation: as keyword | |||
|
33 | parameters to the registered callback]. | |||
|
34 | ||||
|
35 | * Perform as O(1) in the case of no registered observers. | |||
|
36 | ||||
|
37 | * Permit out-of-process or cross-network extension. | |||
21 |
|
38 | |||
22 | What's not included |
|
39 | What's not included | |
23 | ============================================================== |
|
40 | =================== | |
|
41 | ||||
24 | As written, the :mod:`IPython.kernel.core.notificaiton` module does not: |
|
42 | As written, the :mod:`IPython.kernel.core.notificaiton` module does not: | |
25 | * Provide out-of-process or network notifications [these should be handled by a separate, Twisted aware module in :mod:`IPython.kernel`]. |
|
43 | ||
26 | * Provide zope.interface-style interfaces for the notification system [these should also be provided by the :mod:`IPython.kernel` module] |
|
44 | * Provide out-of-process or network notifications (these should be handled by | |
|
45 | a separate, Twisted aware module in :mod:`IPython.kernel`). | |||
|
46 | ||||
|
47 | * Provide zope.interface-style interfaces for the notification system (these | |||
|
48 | should also be provided by the :mod:`IPython.kernel` module). | |||
27 |
|
49 | |||
28 | Use Cases |
|
50 | Use Cases | |
29 | ========= |
|
51 | ========= | |
|
52 | ||||
30 | The following use cases describe the main intended uses of the notificaiton module and illustrate the main success scenario for each use case: |
|
53 | The following use cases describe the main intended uses of the notificaiton module and illustrate the main success scenario for each use case: | |
31 |
|
54 | |||
32 | 1. Dwight Schroot is writing a frontend for the IPython project. His frontend is stuck in the stone age and must communicate synchronously with an IPython.kernel.core.Interpreter instance. Because code is executed in blocks by the Interpreter, Dwight's UI freezes every time he executes a long block of code. To keep track of the progress of his long running block, Dwight adds the following code to his frontend's set-up code:: |
|
55 | 1. Dwight Schroot is writing a frontend for the IPython project. His frontend is stuck in the stone age and must communicate synchronously with an IPython.kernel.core.Interpreter instance. Because code is executed in blocks by the Interpreter, Dwight's UI freezes every time he executes a long block of code. To keep track of the progress of his long running block, Dwight adds the following code to his frontend's set-up code:: | |
33 |
|
56 | |||
34 | from IPython.kernel.core.notification import NotificationCenter |
|
57 | from IPython.kernel.core.notification import NotificationCenter | |
35 | center = NotificationCenter.sharedNotificationCenter |
|
58 | center = NotificationCenter.sharedNotificationCenter | |
36 | center.registerObserver(self, type=IPython.kernel.core.Interpreter.STDOUT_NOTIFICATION_TYPE, notifying_object=self.interpreter, callback=self.stdout_notification) |
|
59 | center.registerObserver(self, type=IPython.kernel.core.Interpreter.STDOUT_NOTIFICATION_TYPE, notifying_object=self.interpreter, callback=self.stdout_notification) | |
37 |
|
60 | |||
38 | and elsewhere in his front end:: |
|
61 | and elsewhere in his front end:: | |
39 |
|
62 | |||
40 | def stdout_notification(self, type, notifying_object, out_string=None): |
|
63 | def stdout_notification(self, type, notifying_object, out_string=None): | |
41 | self.writeStdOut(out_string) |
|
64 | self.writeStdOut(out_string) | |
42 |
|
65 | |||
43 | If everything works, the Interpreter will (according to its published API) fire a notification via the :data:`IPython.kernel.core.notification.sharedCenter` of type :const:`STD_OUT_NOTIFICATION_TYPE` before writing anything to stdout [it's up to the Intereter implementation to figure out when to do this]. The notificaiton center will then call the registered callbacks for that event type (in this case, Dwight's frontend's stdout_notification method). Again, according to its API, the Interpreter provides an additional keyword argument when firing the notificaiton of out_string, a copy of the string it will write to stdout. |
|
66 | If everything works, the Interpreter will (according to its published API) | |
|
67 | fire a notification via the | |||
|
68 | :data:`IPython.kernel.core.notification.sharedCenter` of type | |||
|
69 | :const:`STD_OUT_NOTIFICATION_TYPE` before writing anything to stdout [it's up | |||
|
70 | to the Intereter implementation to figure out when to do this]. The | |||
|
71 | notificaiton center will then call the registered callbacks for that event | |||
|
72 | type (in this case, Dwight's frontend's stdout_notification method). Again, | |||
|
73 | according to its API, the Interpreter provides an additional keyword argument | |||
|
74 | when firing the notificaiton of out_string, a copy of the string it will write | |||
|
75 | to stdout. | |||
44 |
|
76 | |||
45 |
|
|
77 | Like magic, Dwight's frontend is able to provide output, even during | |
|
78 | long-running calculations. Now if Jim could just convince Dwight to use | |||
|
79 | Twisted... | |||
46 |
|
80 | |||
47 | 2. Boss Hog is writing a frontend for the IPython project. Because Boss Hog is stuck in the stone age, his frontend will be written in a new Fortran-like dialect of python and will run only from the command line. Because he doesn't need any fancy notification system and is used to worrying about every cycle on his rat-wheel powered mini, Boss Hog is adamant that the new notification system not produce any performance penalty. As they say in Hazard county, there's no such thing as a free lunch. If he wanted zero overhead, he should have kept using IPython 0.8. Instead, those tricky Duke boys slide in a suped-up bridge-out jumpin' awkwardly confederate-lovin' notification module that imparts only a constant (and small) performance penalty when the Interpreter (or any other object) fires an event for which there are no registered observers. Of course, the same notificaiton-enabled Interpreter can then be used in frontends that require notifications, thus saving the IPython project from a nasty civil war. |
|
81 | 2. Boss Hog is writing a frontend for the IPython project. Because Boss Hog is stuck in the stone age, his frontend will be written in a new Fortran-like dialect of python and will run only from the command line. Because he doesn't need any fancy notification system and is used to worrying about every cycle on his rat-wheel powered mini, Boss Hog is adamant that the new notification system not produce any performance penalty. As they say in Hazard county, there's no such thing as a free lunch. If he wanted zero overhead, he should have kept using IPython 0.8. Instead, those tricky Duke boys slide in a suped-up bridge-out jumpin' awkwardly confederate-lovin' notification module that imparts only a constant (and small) performance penalty when the Interpreter (or any other object) fires an event for which there are no registered observers. Of course, the same notificaiton-enabled Interpreter can then be used in frontends that require notifications, thus saving the IPython project from a nasty civil war. | |
48 |
|
82 | |||
49 | 3. Barry is wrting a frontend for the IPython project. Because Barry's front end is the *new hotness*, it uses an asynchronous event model to communicate with a Twisted :mod:`~IPython.kernel.engineservice` that communicates with the IPython :class:`~IPython.kernel.core.interpreter.Interpreter`. Using the :mod:`IPython.kernel.notification` module, an asynchronous wrapper on the :mod:`IPython.kernel.core.notification` module, Barry's frontend can register for notifications from the interpreter that are delivered asynchronously. Even if Barry's frontend is running on a separate process or even host from the Interpreter, the notifications are delivered, as if by dark and twisted magic. Just like Dwight's frontend, Barry's frontend can now recieve notifications of e.g. writing to stdout/stderr, opening/closing an external file, an exception in the executing code, etc. No newline at end of file |
|
83 | 3. Barry is wrting a frontend for the IPython project. Because Barry's front end is the *new hotness*, it uses an asynchronous event model to communicate with a Twisted :mod:`~IPython.kernel.engineservice` that communicates with the IPython :class:`~IPython.kernel.core.interpreter.Interpreter`. Using the :mod:`IPython.kernel.notification` module, an asynchronous wrapper on the :mod:`IPython.kernel.core.notification` module, Barry's frontend can register for notifications from the interpreter that are delivered asynchronously. Even if Barry's frontend is running on a separate process or even host from the Interpreter, the notifications are delivered, as if by dark and twisted magic. Just like Dwight's frontend, Barry's frontend can now recieve notifications of e.g. writing to stdout/stderr, opening/closing an external file, an exception in the executing code, etc. |
@@ -1,107 +1,81 b'' | |||||
1 | .. _roadmap: |
|
1 | .. _roadmap: | |
2 |
|
2 | |||
3 | =================== |
|
3 | =================== | |
4 | Development roadmap |
|
4 | Development roadmap | |
5 | =================== |
|
5 | =================== | |
6 |
|
6 | |||
7 | .. contents:: |
|
|||
8 |
|
||||
9 | IPython is an ambitious project that is still under heavy development. However, we want IPython to become useful to as many people as possible, as quickly as possible. To help us accomplish this, we are laying out a roadmap of where we are headed and what needs to happen to get there. Hopefully, this will help the IPython developers figure out the best things to work on for each upcoming release. |
|
7 | IPython is an ambitious project that is still under heavy development. However, we want IPython to become useful to as many people as possible, as quickly as possible. To help us accomplish this, we are laying out a roadmap of where we are headed and what needs to happen to get there. Hopefully, this will help the IPython developers figure out the best things to work on for each upcoming release. | |
10 |
|
8 | |||
11 | Speaking of releases, we are going to begin releasing a new version of IPython every four weeks. We are hoping that a regular release schedule, along with a clear roadmap of where we are headed will propel the project forward. |
|
9 | Work targeted to particular releases | |
12 |
|
10 | ==================================== | ||
13 | Where are we headed |
|
|||
14 | =================== |
|
|||
15 |
|
||||
16 | Our goal with IPython is simple: to provide a *powerful*, *robust* and *easy to use* framework for parallel computing. While there are other secondary goals you will hear us talking about at various times, this is the primary goal of IPython that frames the roadmap. |
|
|||
17 |
|
||||
18 | Steps along the way |
|
|||
19 | =================== |
|
|||
20 |
|
||||
21 | Here we describe the various things that we need to work on to accomplish this goal. |
|
|||
22 |
|
||||
23 | Setting up for regular release schedule |
|
|||
24 | --------------------------------------- |
|
|||
25 |
|
||||
26 | We would like to begin to release IPython regularly (probably a 4 week release cycle). To get ready for this, we need to revisit the development guidelines and put in information about releasing IPython. |
|
|||
27 |
|
11 | |||
28 | Process startup and management |
|
12 | Release 0.10 | |
29 | ------------------------------ |
|
13 | ------------ | |
30 |
|
14 | |||
31 | IPython is implemented using a distributed set of processes that communicate using TCP/IP network channels. Currently, users have to start each of the various processes separately using command line scripts. This is both difficult and error prone. Furthermore, there are a number of things that often need to be managed once the processes have been started, such as the sending of signals and the shutting down and cleaning up of processes. |
|
15 | * Initial refactor of :command:`ipcluster`. | |
32 |
|
16 | |||
33 | We need to build a system that makes it trivial for users to start and manage IPython processes. This system should have the following properties: |
|
17 | * Better TextMate integration. | |
34 |
|
18 | |||
35 | * It should possible to do everything through an extremely simple API that users |
|
19 | * Merge in the daemon branch. | |
36 | can call from their own Python script. No shell commands should be needed. |
|
|||
37 |
|
||||
38 | * This simple API should be configured using standard .ini files. |
|
|||
39 |
|
20 | |||
40 | * The system should make it possible to start processes using a number of different |
|
21 | Release 0.11 | |
41 | approaches: SSH, PBS/Torque, Xgrid, Windows Server, mpirun, etc. |
|
22 | ------------ | |
42 |
|
||||
43 | * The controller and engine processes should each have a daemon for monitoring, |
|
|||
44 | signaling and clean up. |
|
|||
45 |
|
||||
46 | * The system should be secure. |
|
|||
47 |
|
23 | |||
48 | * The system should work under all the major operating systems, including |
|
24 | * Refactor the configuration system and command line options for | |
49 | Windows. |
|
25 | :command:`ipengine` and :command:`ipcontroller`. This will include the | |
|
26 | creation of cluster directories that encapsulate all the configuration | |||
|
27 | files, log files and security related files for a particular cluster. | |||
50 |
|
28 | |||
51 | Initial work has begun on the daemon infrastructure, and some of the needed logic is contained in the ipcluster script. |
|
29 | * Refactor :command:`ipcluster` to support the new configuration system. | |
52 |
|
30 | |||
53 | Ease of use/high-level approaches to parallelism |
|
31 | * Refactor the daemon stuff to support the new configuration system. | |
54 | ------------------------------------------------ |
|
|||
55 |
|
32 | |||
56 | While our current API for clients is well designed, we can still do a lot better in designing a user-facing API that is super simple. The main goal here is that it should take *almost no extra code* for users to get their code running in parallel. For this to be possible, we need to tie into Python's standard idioms that enable efficient coding. The biggest ones we are looking at are using context managers (i.e., Python 2.5's ``with`` statement) and decorators. Initial work on this front has begun, but more work is needed. |
|
33 | * Merge back in the core of the notebook. | |
57 |
|
34 | |||
58 | We also need to think about new models for expressing parallelism. This is fun work as most of the foundation has already been established. |
|
35 | Release 0.12 | |
|
36 | ------------ | |||
59 |
|
37 | |||
60 | Security |
|
38 | * Fully integrate process startup with the daemons for full process | |
61 | -------- |
|
39 | management. | |
62 |
|
40 | |||
63 | Currently, IPython has no built in security or security model. Because we would like IPython to be usable on public computer systems and over wide area networks, we need to come up with a robust solution for security. Here are some of the specific things that need to be included: |
|
41 | * Make the capabilites of :command:`ipcluster` available from simple Python | |
|
42 | classes. | |||
64 |
|
43 | |||
65 | * User authentication between all processes (engines, controller and clients). |
|
44 | Major areas of work | |
|
45 | =================== | |||
66 |
|
46 | |||
67 | * Optional TSL/SSL based encryption of all communication channels. |
|
47 | Refactoring the main IPython core | |
|
48 | --------------------------------- | |||
68 |
|
49 | |||
69 | * A good way of picking network ports so multiple users on the same system can |
|
50 | Process management for :mod:`IPython.kernel` | |
70 | run their own controller and engines without interfering with those of others. |
|
51 | -------------------------------------------- | |
71 |
|
||||
72 | * A clear model for security that enables users to evaluate the security risks |
|
|||
73 | associated with using IPython in various manners. |
|
|||
74 |
|
52 | |||
75 | For the implementation of this, we plan on using Twisted's support for SSL and authentication. One things that we really should look at is the `Foolscap`_ network protocol, which provides many of these things out of the box. |
|
53 | Configuration system | |
|
54 | -------------------- | |||
76 |
|
55 | |||
77 | .. _Foolscap: http://foolscap.lothar.com/trac |
|
56 | Performance problems | |
|
57 | -------------------- | |||
78 |
|
58 | |||
79 | The security work needs to be done in conjunction with other network protocol stuff. |
|
59 | Currently, we have a number of performance issues that are waiting to bite users: | |
80 |
|
60 | |||
81 | As of the 0.9 release of IPython, we are using Foolscap and we have implemented |
|
61 | * The controller stores a large amount of state in Python dictionaries. Under | |
82 | a full security model. |
|
62 | heavy usage, these dicts with get very large, causing memory usage problems. | |
|
63 | We need to develop more scalable solutions to this problem, such as using a | |||
|
64 | sqlite database to store this state. This will also help the controller to | |||
|
65 | be more fault tolerant. | |||
83 |
|
66 | |||
84 | Latent performance issues |
|
67 | * We currently don't have a good way of handling large objects in the | |
85 | ------------------------- |
|
68 | controller. The biggest problem is that because we don't have any way of | |
|
69 | streaming objects, we get lots of temporary copies in the low-level buffers. | |||
|
70 | We need to implement a better serialization approach and true streaming | |||
|
71 | support. | |||
86 |
|
72 | |||
87 | Currently, we have a number of performance issues that are waiting to bite users: |
|
73 | * The controller currently unpickles and repickles objects. We need to use the | |
|
74 | [push|pull]_serialized methods instead. | |||
88 |
|
75 | |||
89 | * The controller store a large amount of state in Python dictionaries. Under heavy |
|
76 | * Currently the controller is a bottleneck. The best approach for this is to | |
90 | usage, these dicts with get very large, causing memory usage problems. We need to |
|
77 | separate the controller itself into multiple processes, one for the core | |
91 | develop more scalable solutions to this problem, such as using a sqlite database |
|
78 | controller and one each for the controller interfaces. | |
92 | to store this state. This will also help the controller to be more fault tolerant. |
|
|||
93 | * Currently, the client to controller connections are done through XML-RPC using |
|
|||
94 | HTTP 1.0. This is very inefficient as XML-RPC is a very verbose protocol and |
|
|||
95 | each request must be handled with a new connection. We need to move these network |
|
|||
96 | connections over to PB or Foolscap. Done! |
|
|||
97 | * We currently don't have a good way of handling large objects in the controller. |
|
|||
98 | The biggest problem is that because we don't have any way of streaming objects, |
|
|||
99 | we get lots of temporary copies in the low-level buffers. We need to implement |
|
|||
100 | a better serialization approach and true streaming support. |
|
|||
101 | * The controller currently unpickles and repickles objects. We need to use the |
|
|||
102 | [push|pull]_serialized methods instead. |
|
|||
103 | * Currently the controller is a bottleneck. We need the ability to scale the |
|
|||
104 | controller by aggregating multiple controllers into one effective controller. |
|
|||
105 |
|
79 | |||
106 |
|
80 | |||
107 |
|
81 |
@@ -1,32 +1,30 b'' | |||||
1 | ===================== |
|
1 | ===================== | |
2 | IPython Documentation |
|
2 | IPython Documentation | |
3 | ===================== |
|
3 | ===================== | |
4 |
|
4 | |||
5 | .. htmlonly:: |
|
5 | .. htmlonly:: | |
6 |
|
6 | |||
7 | :Release: |release| |
|
7 | :Release: |release| | |
8 | :Date: |today| |
|
8 | :Date: |today| | |
9 |
|
9 | |||
10 | Contents: |
|
10 | Contents: | |
11 |
|
11 | |||
12 | .. toctree:: |
|
12 | .. toctree:: | |
13 | :maxdepth: 2 |
|
13 | :maxdepth: 2 | |
14 |
|
14 | |||
15 | overview.txt |
|
15 | overview.txt | |
16 | install/index.txt |
|
16 | install/index.txt | |
17 | interactive/index.txt |
|
17 | interactive/index.txt | |
18 | parallel/index.txt |
|
18 | parallel/index.txt | |
19 | config/index.txt |
|
19 | config/index.txt | |
20 | changes.txt |
|
20 | changes.txt | |
21 | development/index.txt |
|
21 | development/index.txt | |
22 | faq.txt |
|
22 | faq.txt | |
23 | history.txt |
|
23 | history.txt | |
24 | license_and_copyright.txt |
|
24 | license_and_copyright.txt | |
25 | credits.txt |
|
25 | credits.txt | |
26 |
|
26 | |||
27 |
|
||||
28 | .. htmlonly:: |
|
27 | .. htmlonly:: | |
29 |
|
28 | * :ref:`genindex` | ||
30 |
* :ref:` |
|
29 | * :ref:`modindex` | |
31 |
* :ref:` |
|
30 | * :ref:`search` | |
32 | * :ref:`search` |
|
@@ -1,191 +1,217 b'' | |||||
1 | Overview |
|
1 | Overview | |
2 | ======== |
|
2 | ======== | |
3 |
|
3 | |||
4 | This document describes the steps required to install IPython. IPython is organized into a number of subpackages, each of which has its own dependencies. All of the subpackages come with IPython, so you don't need to download and install them separately. However, to use a given subpackage, you will need to install all of its dependencies. |
|
4 | This document describes the steps required to install IPython. IPython is organized into a number of subpackages, each of which has its own dependencies. All of the subpackages come with IPython, so you don't need to download and install them separately. However, to use a given subpackage, you will need to install all of its dependencies. | |
5 |
|
5 | |||
6 |
|
6 | |||
7 | Please let us know if you have problems installing IPython or any of its |
|
7 | Please let us know if you have problems installing IPython or any of its | |
8 | dependencies. IPython requires Python version 2.4 or greater. We have not tested |
|
8 | dependencies. IPython requires Python version 2.4 or greater. We have not tested | |
9 | IPython with the upcoming 2.6 or 3.0 versions. |
|
9 | IPython with the upcoming 2.6 or 3.0 versions. | |
10 |
|
10 | |||
11 | .. warning:: |
|
11 | .. warning:: | |
12 |
|
12 | |||
13 | IPython will not work with Python 2.3 or below. |
|
13 | IPython will not work with Python 2.3 or below. | |
14 |
|
14 | |||
15 | Some of the installation approaches use the :mod:`setuptools` package and its :command:`easy_install` command line program. In many scenarios, this provides the most simple method of installing IPython and its dependencies. It is not required though. More information about :mod:`setuptools` can be found on its website. |
|
15 | Some of the installation approaches use the :mod:`setuptools` package and its :command:`easy_install` command line program. In many scenarios, this provides the most simple method of installing IPython and its dependencies. It is not required though. More information about :mod:`setuptools` can be found on its website. | |
16 |
|
16 | |||
17 | More general information about installing Python packages can be found in Python's documentation at http://www.python.org/doc/. |
|
17 | More general information about installing Python packages can be found in Python's documentation at http://www.python.org/doc/. | |
18 |
|
18 | |||
|
19 | Quickstart | |||
|
20 | ========== | |||
|
21 | ||||
|
22 | If you have :mod:`setuptools` installed and you are on OS X or Linux (not Windows), the following will download and install IPython *and* the main optional dependencies:: | |||
|
23 | ||||
|
24 | $ easy_install ipython[kernel,security,test] | |||
|
25 | ||||
|
26 | This will get Twisted, zope.interface and Foolscap, which are needed for IPython's parallel computing features as well as the nose package, which will enable you to run IPython's test suite. To run IPython's test suite, use the :command:`iptest` command:: | |||
|
27 | ||||
|
28 | $ iptest | |||
|
29 | ||||
|
30 | Read on for more specific details and instructions for Windows. | |||
|
31 | ||||
19 | Installing IPython itself |
|
32 | Installing IPython itself | |
20 | ========================= |
|
33 | ========================= | |
21 |
|
34 | |||
22 | Given a properly built Python, the basic interactive IPython shell will work with no external dependencies. However, some Python distributions (particularly on Windows and OS X), don't come with a working :mod:`readline` module. The IPython shell will work without :mod:`readline`, but will lack many features that users depend on, such as tab completion and command line editing. See below for details of how to make sure you have a working :mod:`readline`. |
|
35 | Given a properly built Python, the basic interactive IPython shell will work with no external dependencies. However, some Python distributions (particularly on Windows and OS X), don't come with a working :mod:`readline` module. The IPython shell will work without :mod:`readline`, but will lack many features that users depend on, such as tab completion and command line editing. See below for details of how to make sure you have a working :mod:`readline`. | |
23 |
|
36 | |||
24 | Installation using easy_install |
|
37 | Installation using easy_install | |
25 | ------------------------------- |
|
38 | ------------------------------- | |
26 |
|
39 | |||
27 | If you have :mod:`setuptools` installed, the easiest way of getting IPython is to simple use :command:`easy_install`:: |
|
40 | If you have :mod:`setuptools` installed, the easiest way of getting IPython is to simple use :command:`easy_install`:: | |
28 |
|
41 | |||
29 |
$ easy_install |
|
42 | $ easy_install ipython | |
30 |
|
43 | |||
31 | That's it. |
|
44 | That's it. | |
32 |
|
45 | |||
33 | Installation from source |
|
46 | Installation from source | |
34 | ------------------------ |
|
47 | ------------------------ | |
35 |
|
48 | |||
36 | If you don't want to use :command:`easy_install`, or don't have it installed, just grab the latest stable build of IPython from `here <http://ipython.scipy.org/dist/>`_. Then do the following:: |
|
49 | If you don't want to use :command:`easy_install`, or don't have it installed, just grab the latest stable build of IPython from `here <http://ipython.scipy.org/dist/>`_. Then do the following:: | |
37 |
|
50 | |||
38 | $ tar -xzf ipython.tar.gz |
|
51 | $ tar -xzf ipython.tar.gz | |
39 | $ cd ipython |
|
52 | $ cd ipython | |
40 | $ python setup.py install |
|
53 | $ python setup.py install | |
41 |
|
54 | |||
42 | If you are installing to a location (like ``/usr/local``) that requires higher permissions, you may need to run the last command with :command:`sudo`. |
|
55 | If you are installing to a location (like ``/usr/local``) that requires higher permissions, you may need to run the last command with :command:`sudo`. | |
43 |
|
56 | |||
44 | Windows |
|
57 | Windows | |
45 | ------- |
|
58 | ------- | |
46 |
|
59 | |||
47 | There are a few caveats for Windows users. The main issue is that a basic ``python setup.py install`` approach won't create ``.bat`` file or Start Menu shortcuts, which most users want. To get an installation with these, there are two choices: |
|
60 | There are a few caveats for Windows users. The main issue is that a basic ``python setup.py install`` approach won't create ``.bat`` file or Start Menu shortcuts, which most users want. To get an installation with these, there are two choices: | |
48 |
|
61 | |||
49 | 1. Install using :command:`easy_install`. |
|
62 | 1. Install using :command:`easy_install`. | |
50 |
|
63 | |||
51 | 2. Install using our binary ``.exe`` Windows installer, which can be found at `here <http://ipython.scipy.org/dist/>`_ |
|
64 | 2. Install using our binary ``.exe`` Windows installer, which can be found at `here <http://ipython.scipy.org/dist/>`_ | |
52 |
|
65 | |||
53 | 3. Install from source, but using :mod:`setuptools` (``python setupegg.py install``). |
|
66 | 3. Install from source, but using :mod:`setuptools` (``python setupegg.py install``). | |
54 |
|
67 | |||
55 | Installing the development version |
|
68 | Installing the development version | |
56 | ---------------------------------- |
|
69 | ---------------------------------- | |
57 |
|
70 | |||
58 | It is also possible to install the development version of IPython from our `Bazaar <http://bazaar-vcs.org/>`_ source code |
|
71 | It is also possible to install the development version of IPython from our `Bazaar <http://bazaar-vcs.org/>`_ source code | |
59 | repository. To do this you will need to have Bazaar installed on your system. Then just do:: |
|
72 | repository. To do this you will need to have Bazaar installed on your system. Then just do:: | |
60 |
|
73 | |||
61 | $ bzr branch lp:ipython |
|
74 | $ bzr branch lp:ipython | |
62 | $ cd ipython |
|
75 | $ cd ipython | |
63 | $ python setup.py install |
|
76 | $ python setup.py install | |
64 |
|
77 | |||
65 | Again, this last step on Windows won't create ``.bat`` files or Start Menu shortcuts, so you will have to use one of the other approaches listed above. |
|
78 | Again, this last step on Windows won't create ``.bat`` files or Start Menu shortcuts, so you will have to use one of the other approaches listed above. | |
66 |
|
79 | |||
67 | Some users want to be able to follow the development branch as it changes. If you have :mod:`setuptools` installed, this is easy. Simply replace the last step by:: |
|
80 | Some users want to be able to follow the development branch as it changes. If you have :mod:`setuptools` installed, this is easy. Simply replace the last step by:: | |
68 |
|
81 | |||
69 | $ python setupegg.py develop |
|
82 | $ python setupegg.py develop | |
70 |
|
83 | |||
71 | This creates links in the right places and installs the command line script to the appropriate places. Then, if you want to update your IPython at any time, just do:: |
|
84 | This creates links in the right places and installs the command line script to the appropriate places. Then, if you want to update your IPython at any time, just do:: | |
72 |
|
85 | |||
73 | $ bzr pull |
|
86 | $ bzr pull | |
74 |
|
87 | |||
75 | Basic optional dependencies |
|
88 | Basic optional dependencies | |
76 | =========================== |
|
89 | =========================== | |
77 |
|
90 | |||
78 | There are a number of basic optional dependencies that most users will want to get. These are: |
|
91 | There are a number of basic optional dependencies that most users will want to get. These are: | |
79 |
|
92 | |||
80 | * readline (for command line editing, tab completion, etc.) |
|
93 | * readline (for command line editing, tab completion, etc.) | |
81 | * nose (to run the IPython test suite) |
|
94 | * nose (to run the IPython test suite) | |
82 | * pexpect (to use things like irunner) |
|
95 | * pexpect (to use things like irunner) | |
83 |
|
96 | |||
84 | If you are comfortable installing these things yourself, have at it, otherwise read on for more details. |
|
97 | If you are comfortable installing these things yourself, have at it, otherwise read on for more details. | |
85 |
|
98 | |||
86 | readline |
|
99 | readline | |
87 | -------- |
|
100 | -------- | |
88 |
|
101 | |||
89 | In principle, all Python distributions should come with a working :mod:`readline` module. But, reality is not quite that simple. There are two common situations where you won't have a working :mod:`readline` module: |
|
102 | In principle, all Python distributions should come with a working :mod:`readline` module. But, reality is not quite that simple. There are two common situations where you won't have a working :mod:`readline` module: | |
90 |
|
103 | |||
91 | * If you are using the built-in Python on Mac OS X. |
|
104 | * If you are using the built-in Python on Mac OS X. | |
92 |
|
105 | |||
93 | * If you are running Windows, which doesn't have a :mod:`readline` module. |
|
106 | * If you are running Windows, which doesn't have a :mod:`readline` module. | |
94 |
|
107 | |||
95 | On OS X, the built-in Python doesn't not have :mod:`readline` because of license issues. Starting with OS X 10.5 (Leopard), Apple's built-in Python has a BSD-licensed not-quite-compatible readline replacement. As of IPython 0.9, many of the issues related to the differences between readline and libedit have been resolved. For many users, libedit may be sufficient. |
|
108 | On OS X, the built-in Python doesn't not have :mod:`readline` because of license issues. Starting with OS X 10.5 (Leopard), Apple's built-in Python has a BSD-licensed not-quite-compatible readline replacement. As of IPython 0.9, many of the issues related to the differences between readline and libedit have been resolved. For many users, libedit may be sufficient. | |
96 |
|
109 | |||
97 | Most users on OS X will want to get the full :mod:`readline` module. To get a working :mod:`readline` module, just do (with :mod:`setuptools` installed):: |
|
110 | Most users on OS X will want to get the full :mod:`readline` module. To get a working :mod:`readline` module, just do (with :mod:`setuptools` installed):: | |
98 |
|
111 | |||
99 | $ easy_install readline |
|
112 | $ easy_install readline | |
100 |
|
113 | |||
101 | .. note: |
|
114 | .. note: | |
102 |
|
115 | |||
103 | Other Python distributions on OS X (such as fink, MacPorts and the |
|
116 | Other Python distributions on OS X (such as fink, MacPorts and the | |
104 | official python.org binaries) already have readline installed so |
|
117 | official python.org binaries) already have readline installed so | |
105 | you don't have to do this step. |
|
118 | you don't have to do this step. | |
106 |
|
119 | |||
107 | If needed, the readline egg can be build and installed from source (see the wiki page at http://ipython.scipy.org/moin/InstallationOSXLeopard). |
|
120 | If needed, the readline egg can be build and installed from source (see the wiki page at http://ipython.scipy.org/moin/InstallationOSXLeopard). | |
108 |
|
121 | |||
109 | On Windows, you will need the PyReadline module. PyReadline is a separate, Windows only implementation of readline that uses native Windows calls through :mod:`ctypes`. The easiest way of installing PyReadline is you use the binary installer available `here <http://ipython.scipy.org/dist/>`_. The :mod:`ctypes` module, which comes with Python 2.5 and greater, is required by PyReadline. It is available for Python 2.4 at http://python.net/crew/theller/ctypes. |
|
122 | On Windows, you will need the PyReadline module. PyReadline is a separate, | |
|
123 | Windows only implementation of readline that uses native Windows calls through | |||
|
124 | :mod:`ctypes`. The easiest way of installing PyReadline is you use the binary | |||
|
125 | installer available `here <http://ipython.scipy.org/dist/>`_. The | |||
|
126 | :mod:`ctypes` module, which comes with Python 2.5 and greater, is required by | |||
|
127 | PyReadline. It is available for Python 2.4 at | |||
|
128 | http://python.net/crew/theller/ctypes. | |||
110 |
|
129 | |||
111 | nose |
|
130 | nose | |
112 | ---- |
|
131 | ---- | |
113 |
|
132 | |||
114 | To run the IPython test suite you will need the :mod:`nose` package. Nose provides a great way of sniffing out and running all of the IPython tests. The simplest way of getting nose, is to use :command:`easy_install`:: |
|
133 | To run the IPython test suite you will need the :mod:`nose` package. Nose provides a great way of sniffing out and running all of the IPython tests. The simplest way of getting nose, is to use :command:`easy_install`:: | |
115 |
|
134 | |||
116 | $ easy_install nose |
|
135 | $ easy_install nose | |
117 |
|
136 | |||
118 | Another way of getting this is to do:: |
|
137 | Another way of getting this is to do:: | |
119 |
|
138 | |||
120 |
$ easy_install |
|
139 | $ easy_install ipython[test] | |
121 |
|
140 | |||
122 | For more installation options, see the `nose website <http://somethingaboutorange.com/mrl/projects/nose/>`_. Once you have nose installed, you can run IPython's test suite using the iptest command:: |
|
141 | For more installation options, see the `nose website <http://somethingaboutorange.com/mrl/projects/nose/>`_. Once you have nose installed, you can run IPython's test suite using the iptest command:: | |
123 |
|
142 | |||
124 | $ iptest |
|
143 | $ iptest | |
125 |
|
144 | |||
126 |
|
145 | |||
127 | pexpect |
|
146 | pexpect | |
128 | ------- |
|
147 | ------- | |
129 |
|
148 | |||
130 | The `pexpect <http://www.noah.org/wiki/Pexpect>`_ package is used in IPython's :command:`irunner` script. On Unix platforms (including OS X), just do:: |
|
149 | The `pexpect <http://www.noah.org/wiki/Pexpect>`_ package is used in IPython's :command:`irunner` script. On Unix platforms (including OS X), just do:: | |
131 |
|
150 | |||
132 | $ easy_install pexpect |
|
151 | $ easy_install pexpect | |
133 |
|
152 | |||
134 | Windows users are out of luck as pexpect does not run there. |
|
153 | Windows users are out of luck as pexpect does not run there. | |
135 |
|
154 | |||
136 | Dependencies for IPython.kernel (parallel computing) |
|
155 | Dependencies for IPython.kernel (parallel computing) | |
137 | ==================================================== |
|
156 | ==================================================== | |
138 |
|
157 | |||
139 | The IPython kernel provides a nice architecture for parallel computing. The main focus of this architecture is on interactive parallel computing. These features require a number of additional packages: |
|
158 | The IPython kernel provides a nice architecture for parallel computing. The main focus of this architecture is on interactive parallel computing. These features require a number of additional packages: | |
140 |
|
159 | |||
141 | * zope.interface (yep, we use interfaces) |
|
160 | * zope.interface (yep, we use interfaces) | |
142 | * Twisted (asynchronous networking framework) |
|
161 | * Twisted (asynchronous networking framework) | |
143 | * Foolscap (a nice, secure network protocol) |
|
162 | * Foolscap (a nice, secure network protocol) | |
144 | * pyOpenSSL (security for network connections) |
|
163 | * pyOpenSSL (security for network connections) | |
145 |
|
164 | |||
146 | On a Unix style platform (including OS X), if you want to use :mod:`setuptools`, you can just do:: |
|
165 | On a Unix style platform (including OS X), if you want to use :mod:`setuptools`, you can just do:: | |
147 |
|
166 | |||
148 |
$ easy_install |
|
167 | $ easy_install ipython[kernel] # the first three | |
149 |
$ easy_install |
|
168 | $ easy_install ipython[security] # pyOpenSSL | |
150 |
|
169 | |||
151 | zope.interface and Twisted |
|
170 | zope.interface and Twisted | |
152 | -------------------------- |
|
171 | -------------------------- | |
153 |
|
172 | |||
154 | On Unix style platforms (including OS X), the simplest way of getting the these is to use :command:`easy_install`:: |
|
173 | Twisted [Twisted]_ and zope.interface [ZopeInterface]_ are used for networking related things. On Unix | |
|
174 | style platforms (including OS X), the simplest way of getting the these is to | |||
|
175 | use :command:`easy_install`:: | |||
155 |
|
176 | |||
156 | $ easy_install zope.interface |
|
177 | $ easy_install zope.interface | |
157 | $ easy_install Twisted |
|
178 | $ easy_install Twisted | |
158 |
|
179 | |||
159 | Of course, you can also download the source tarballs from the `Twisted website <twistedmatrix.org>`_ and the `zope.interface page at PyPI <http://pypi.python.org/pypi/zope.interface>`_ and do the usual ``python setup.py install`` if you prefer. |
|
180 | Of course, you can also download the source tarballs from the `Twisted website <twistedmatrix.org>`_ and the `zope.interface page at PyPI <http://pypi.python.org/pypi/zope.interface>`_ and do the usual ``python setup.py install`` if you prefer. | |
160 |
|
181 | |||
161 | Windows is a bit different. For zope.interface and Twisted, simply get the latest binary ``.exe`` installer from the Twisted website. This installer includes both zope.interface and Twisted and should just work. |
|
182 | Windows is a bit different. For zope.interface and Twisted, simply get the latest binary ``.exe`` installer from the Twisted website. This installer includes both zope.interface and Twisted and should just work. | |
162 |
|
183 | |||
163 | Foolscap |
|
184 | Foolscap | |
164 | -------- |
|
185 | -------- | |
165 |
|
186 | |||
166 | Foolscap uses Twisted to provide a very nice secure RPC protocol that we use to implement our parallel computing features. |
|
187 | Foolscap [Foolscap]_ uses Twisted to provide a very nice secure RPC protocol that we use to implement our parallel computing features. | |
167 |
|
188 | |||
168 | On all platforms a simple:: |
|
189 | On all platforms a simple:: | |
169 |
|
190 | |||
170 | $ easy_install foolscap |
|
191 | $ easy_install foolscap | |
171 |
|
192 | |||
172 | should work. You can also download the source tarballs from the `Foolscap website <http://foolscap.lothar.com/trac>`_ and do ``python setup.py install`` if you prefer. |
|
193 | should work. You can also download the source tarballs from the `Foolscap website <http://foolscap.lothar.com/trac>`_ and do ``python setup.py install`` if you prefer. | |
173 |
|
194 | |||
174 | pyOpenSSL |
|
195 | pyOpenSSL | |
175 | --------- |
|
196 | --------- | |
176 |
|
197 | |||
177 | IPython requires an older version of pyOpenSSL (0.6 rather than the current 0.7). There are a couple of options for getting this: |
|
198 | IPython requires an older version of pyOpenSSL [pyOpenSSL]_ (0.6 rather than the current 0.7). There are a couple of options for getting this: | |
178 |
|
199 | |||
179 | 1. Most Linux distributions have packages for pyOpenSSL. |
|
200 | 1. Most Linux distributions have packages for pyOpenSSL. | |
180 | 2. The built-in Python 2.5 on OS X 10.5 already has it installed. |
|
201 | 2. The built-in Python 2.5 on OS X 10.5 already has it installed. | |
181 | 3. There are source tarballs on the pyOpenSSL website. On Unix-like |
|
202 | 3. There are source tarballs on the pyOpenSSL website. On Unix-like | |
182 | platforms, these can be built using ``python seutp.py install``. |
|
203 | platforms, these can be built using ``python seutp.py install``. | |
183 | 4. There is also a binary ``.exe`` Windows installer on the `pyOpenSSL website <http://pyopenssl.sourceforge.net/>`_. |
|
204 | 4. There is also a binary ``.exe`` Windows installer on the `pyOpenSSL website <http://pyopenssl.sourceforge.net/>`_. | |
184 |
|
205 | |||
185 | Dependencies for IPython.frontend (the IPython GUI) |
|
206 | Dependencies for IPython.frontend (the IPython GUI) | |
186 | =================================================== |
|
207 | =================================================== | |
187 |
|
208 | |||
188 | wxPython |
|
209 | wxPython | |
189 | -------- |
|
210 | -------- | |
190 |
|
211 | |||
191 |
Starting with IPython 0.9, IPython has a new IPython.frontend package that has a nice wxPython based IPython GUI. As you would expect, this GUI requires wxPython. Most Linux distributions have wxPython packages available and the built-in Python on OS X comes with wxPython preinstalled. For Windows, a binary installer is available on the `wxPython website <http://www.wxpython.org/>`_. |
|
212 | Starting with IPython 0.9, IPython has a new IPython.frontend package that has a nice wxPython based IPython GUI. As you would expect, this GUI requires wxPython. Most Linux distributions have wxPython packages available and the built-in Python on OS X comes with wxPython preinstalled. For Windows, a binary installer is available on the `wxPython website <http://www.wxpython.org/>`_. | |
|
213 | ||||
|
214 | .. [Twisted] Twisted matrix. http://twistedmatrix.org | |||
|
215 | .. [ZopeInterface] http://pypi.python.org/pypi/zope.interface | |||
|
216 | .. [Foolscap] Foolscap network protocol. http://foolscap.lothar.com/trac | |||
|
217 | .. [pyOpenSSL] pyOpenSSL. http://pyopenssl.sourceforge.net No newline at end of file |
@@ -1,11 +1,11 b'' | |||||
1 | ================================== |
|
1 | ================================== | |
2 | Using IPython for interactive work |
|
2 | Using IPython for interactive work | |
3 | ================================== |
|
3 | ================================== | |
4 |
|
4 | |||
5 | .. toctree:: |
|
5 | .. toctree:: | |
6 |
:maxdepth: |
|
6 | :maxdepth: 2 | |
7 |
|
7 | |||
8 | tutorial.txt |
|
8 | tutorial.txt | |
9 | reference.txt |
|
9 | reference.txt | |
10 | shell.txt |
|
10 | shell.txt | |
11 | extension_api.txt |
|
11 | extension_api.txt |
@@ -1,3200 +1,3194 b'' | |||||
1 | .. IPython documentation master file, created by sphinx-quickstart.py on Mon Mar 24 17:01:34 2008. |
|
|||
2 | You can adapt this file completely to your liking, but it should at least |
|
|||
3 | contain the root 'toctree' directive. |
|
|||
4 |
|
||||
5 | ================= |
|
1 | ================= | |
6 | IPython reference |
|
2 | IPython reference | |
7 | ================= |
|
3 | ================= | |
8 |
|
4 | |||
9 | .. contents:: |
|
|||
10 |
|
||||
11 | .. _command_line_options: |
|
5 | .. _command_line_options: | |
12 |
|
6 | |||
13 | Command-line usage |
|
7 | Command-line usage | |
14 | ================== |
|
8 | ================== | |
15 |
|
9 | |||
16 | You start IPython with the command:: |
|
10 | You start IPython with the command:: | |
17 |
|
11 | |||
18 | $ ipython [options] files |
|
12 | $ ipython [options] files | |
19 |
|
13 | |||
20 | If invoked with no options, it executes all the files listed in sequence |
|
14 | If invoked with no options, it executes all the files listed in sequence | |
21 | and drops you into the interpreter while still acknowledging any options |
|
15 | and drops you into the interpreter while still acknowledging any options | |
22 | you may have set in your ipythonrc file. This behavior is different from |
|
16 | you may have set in your ipythonrc file. This behavior is different from | |
23 | standard Python, which when called as python -i will only execute one |
|
17 | standard Python, which when called as python -i will only execute one | |
24 | file and ignore your configuration setup. |
|
18 | file and ignore your configuration setup. | |
25 |
|
19 | |||
26 | Please note that some of the configuration options are not available at |
|
20 | Please note that some of the configuration options are not available at | |
27 | the command line, simply because they are not practical here. Look into |
|
21 | the command line, simply because they are not practical here. Look into | |
28 | your ipythonrc configuration file for details on those. This file |
|
22 | your ipythonrc configuration file for details on those. This file | |
29 | typically installed in the $HOME/.ipython directory. For Windows users, |
|
23 | typically installed in the $HOME/.ipython directory. For Windows users, | |
30 | $HOME resolves to C:\\Documents and Settings\\YourUserName in most |
|
24 | $HOME resolves to C:\\Documents and Settings\\YourUserName in most | |
31 | instances. In the rest of this text, we will refer to this directory as |
|
25 | instances. In the rest of this text, we will refer to this directory as | |
32 | IPYTHONDIR. |
|
26 | IPYTHONDIR. | |
33 |
|
27 | |||
34 | .. _Threading options: |
|
28 | .. _Threading options: | |
35 |
|
29 | |||
36 |
|
30 | |||
37 | Special Threading Options |
|
31 | Special Threading Options | |
38 | ------------------------- |
|
32 | ------------------------- | |
39 |
|
33 | |||
40 | The following special options are ONLY valid at the beginning of the |
|
34 | The following special options are ONLY valid at the beginning of the | |
41 | command line, and not later. This is because they control the initial- |
|
35 | command line, and not later. This is because they control the initial- | |
42 | ization of ipython itself, before the normal option-handling mechanism |
|
36 | ization of ipython itself, before the normal option-handling mechanism | |
43 | is active. |
|
37 | is active. | |
44 |
|
38 | |||
45 | -gthread, -qthread, -q4thread, -wthread, -pylab: |
|
39 | -gthread, -qthread, -q4thread, -wthread, -pylab: | |
46 | Only one of these can be given, and it can only be given as |
|
40 | Only one of these can be given, and it can only be given as | |
47 | the first option passed to IPython (it will have no effect in |
|
41 | the first option passed to IPython (it will have no effect in | |
48 | any other position). They provide threading support for the |
|
42 | any other position). They provide threading support for the | |
49 | GTK, Qt (versions 3 and 4) and WXPython toolkits, and for the |
|
43 | GTK, Qt (versions 3 and 4) and WXPython toolkits, and for the | |
50 | matplotlib library. |
|
44 | matplotlib library. | |
51 |
|
45 | |||
52 | With any of the first four options, IPython starts running a |
|
46 | With any of the first four options, IPython starts running a | |
53 | separate thread for the graphical toolkit's operation, so that |
|
47 | separate thread for the graphical toolkit's operation, so that | |
54 | you can open and control graphical elements from within an |
|
48 | you can open and control graphical elements from within an | |
55 | IPython command line, without blocking. All four provide |
|
49 | IPython command line, without blocking. All four provide | |
56 | essentially the same functionality, respectively for GTK, Qt3, |
|
50 | essentially the same functionality, respectively for GTK, Qt3, | |
57 | Qt4 and WXWidgets (via their Python interfaces). |
|
51 | Qt4 and WXWidgets (via their Python interfaces). | |
58 |
|
52 | |||
59 | Note that with -wthread, you can additionally use the |
|
53 | Note that with -wthread, you can additionally use the | |
60 | -wxversion option to request a specific version of wx to be |
|
54 | -wxversion option to request a specific version of wx to be | |
61 | used. This requires that you have the wxversion Python module |
|
55 | used. This requires that you have the wxversion Python module | |
62 | installed, which is part of recent wxPython distributions. |
|
56 | installed, which is part of recent wxPython distributions. | |
63 |
|
57 | |||
64 | If -pylab is given, IPython loads special support for the mat |
|
58 | If -pylab is given, IPython loads special support for the mat | |
65 | plotlib library (http://matplotlib.sourceforge.net), allowing |
|
59 | plotlib library (http://matplotlib.sourceforge.net), allowing | |
66 | interactive usage of any of its backends as defined in the |
|
60 | interactive usage of any of its backends as defined in the | |
67 | user's ~/.matplotlib/matplotlibrc file. It automatically |
|
61 | user's ~/.matplotlib/matplotlibrc file. It automatically | |
68 | activates GTK, Qt or WX threading for IPyhton if the choice of |
|
62 | activates GTK, Qt or WX threading for IPyhton if the choice of | |
69 | matplotlib backend requires it. It also modifies the %run |
|
63 | matplotlib backend requires it. It also modifies the %run | |
70 | command to correctly execute (without blocking) any |
|
64 | command to correctly execute (without blocking) any | |
71 | matplotlib-based script which calls show() at the end. |
|
65 | matplotlib-based script which calls show() at the end. | |
72 |
|
66 | |||
73 | -tk |
|
67 | -tk | |
74 | The -g/q/q4/wthread options, and -pylab (if matplotlib is |
|
68 | The -g/q/q4/wthread options, and -pylab (if matplotlib is | |
75 | configured to use GTK, Qt3, Qt4 or WX), will normally block Tk |
|
69 | configured to use GTK, Qt3, Qt4 or WX), will normally block Tk | |
76 | graphical interfaces. This means that when either GTK, Qt or WX |
|
70 | graphical interfaces. This means that when either GTK, Qt or WX | |
77 | threading is active, any attempt to open a Tk GUI will result in a |
|
71 | threading is active, any attempt to open a Tk GUI will result in a | |
78 | dead window, and possibly cause the Python interpreter to crash. |
|
72 | dead window, and possibly cause the Python interpreter to crash. | |
79 | An extra option, -tk, is available to address this issue. It can |
|
73 | An extra option, -tk, is available to address this issue. It can | |
80 | only be given as a second option after any of the above (-gthread, |
|
74 | only be given as a second option after any of the above (-gthread, | |
81 | -wthread or -pylab). |
|
75 | -wthread or -pylab). | |
82 |
|
76 | |||
83 | If -tk is given, IPython will try to coordinate Tk threading |
|
77 | If -tk is given, IPython will try to coordinate Tk threading | |
84 | with GTK, Qt or WX. This is however potentially unreliable, and |
|
78 | with GTK, Qt or WX. This is however potentially unreliable, and | |
85 | you will have to test on your platform and Python configuration to |
|
79 | you will have to test on your platform and Python configuration to | |
86 | determine whether it works for you. Debian users have reported |
|
80 | determine whether it works for you. Debian users have reported | |
87 | success, apparently due to the fact that Debian builds all of Tcl, |
|
81 | success, apparently due to the fact that Debian builds all of Tcl, | |
88 | Tk, Tkinter and Python with pthreads support. Under other Linux |
|
82 | Tk, Tkinter and Python with pthreads support. Under other Linux | |
89 | environments (such as Fedora Core 2/3), this option has caused |
|
83 | environments (such as Fedora Core 2/3), this option has caused | |
90 | random crashes and lockups of the Python interpreter. Under other |
|
84 | random crashes and lockups of the Python interpreter. Under other | |
91 | operating systems (Mac OSX and Windows), you'll need to try it to |
|
85 | operating systems (Mac OSX and Windows), you'll need to try it to | |
92 | find out, since currently no user reports are available. |
|
86 | find out, since currently no user reports are available. | |
93 |
|
87 | |||
94 | There is unfortunately no way for IPython to determine at run time |
|
88 | There is unfortunately no way for IPython to determine at run time | |
95 | whether -tk will work reliably or not, so you will need to do some |
|
89 | whether -tk will work reliably or not, so you will need to do some | |
96 | experiments before relying on it for regular work. |
|
90 | experiments before relying on it for regular work. | |
97 |
|
91 | |||
98 |
|
92 | |||
99 |
|
93 | |||
100 | Regular Options |
|
94 | Regular Options | |
101 | --------------- |
|
95 | --------------- | |
102 |
|
96 | |||
103 | After the above threading options have been given, regular options can |
|
97 | After the above threading options have been given, regular options can | |
104 | follow in any order. All options can be abbreviated to their shortest |
|
98 | follow in any order. All options can be abbreviated to their shortest | |
105 | non-ambiguous form and are case-sensitive. One or two dashes can be |
|
99 | non-ambiguous form and are case-sensitive. One or two dashes can be | |
106 | used. Some options have an alternate short form, indicated after a ``|``. |
|
100 | used. Some options have an alternate short form, indicated after a ``|``. | |
107 |
|
101 | |||
108 | Most options can also be set from your ipythonrc configuration file. See |
|
102 | Most options can also be set from your ipythonrc configuration file. See | |
109 | the provided example for more details on what the options do. Options |
|
103 | the provided example for more details on what the options do. Options | |
110 | given at the command line override the values set in the ipythonrc file. |
|
104 | given at the command line override the values set in the ipythonrc file. | |
111 |
|
105 | |||
112 | All options with a [no] prepended can be specified in negated form |
|
106 | All options with a [no] prepended can be specified in negated form | |
113 | (-nooption instead of -option) to turn the feature off. |
|
107 | (-nooption instead of -option) to turn the feature off. | |
114 |
|
108 | |||
115 | -help print a help message and exit. |
|
109 | -help print a help message and exit. | |
116 |
|
110 | |||
117 | -pylab |
|
111 | -pylab | |
118 | this can only be given as the first option passed to IPython |
|
112 | this can only be given as the first option passed to IPython | |
119 | (it will have no effect in any other position). It adds |
|
113 | (it will have no effect in any other position). It adds | |
120 | special support for the matplotlib library |
|
114 | special support for the matplotlib library | |
121 | (http://matplotlib.sourceforge.ne), allowing interactive usage |
|
115 | (http://matplotlib.sourceforge.ne), allowing interactive usage | |
122 | of any of its backends as defined in the user's .matplotlibrc |
|
116 | of any of its backends as defined in the user's .matplotlibrc | |
123 | file. It automatically activates GTK or WX threading for |
|
117 | file. It automatically activates GTK or WX threading for | |
124 | IPyhton if the choice of matplotlib backend requires it. It |
|
118 | IPyhton if the choice of matplotlib backend requires it. It | |
125 | also modifies the %run command to correctly execute (without |
|
119 | also modifies the %run command to correctly execute (without | |
126 | blocking) any matplotlib-based script which calls show() at |
|
120 | blocking) any matplotlib-based script which calls show() at | |
127 | the end. See `Matplotlib support`_ for more details. |
|
121 | the end. See `Matplotlib support`_ for more details. | |
128 |
|
122 | |||
129 | -autocall <val> |
|
123 | -autocall <val> | |
130 | Make IPython automatically call any callable object even if you |
|
124 | Make IPython automatically call any callable object even if you | |
131 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
125 | didn't type explicit parentheses. For example, 'str 43' becomes | |
132 | 'str(43)' automatically. The value can be '0' to disable the feature, |
|
126 | 'str(43)' automatically. The value can be '0' to disable the feature, | |
133 | '1' for smart autocall, where it is not applied if there are no more |
|
127 | '1' for smart autocall, where it is not applied if there are no more | |
134 | arguments on the line, and '2' for full autocall, where all callable |
|
128 | arguments on the line, and '2' for full autocall, where all callable | |
135 | objects are automatically called (even if no arguments are |
|
129 | objects are automatically called (even if no arguments are | |
136 | present). The default is '1'. |
|
130 | present). The default is '1'. | |
137 |
|
131 | |||
138 | -[no]autoindent |
|
132 | -[no]autoindent | |
139 | Turn automatic indentation on/off. |
|
133 | Turn automatic indentation on/off. | |
140 |
|
134 | |||
141 | -[no]automagic |
|
135 | -[no]automagic | |
142 | make magic commands automatic (without needing their first character |
|
136 | make magic commands automatic (without needing their first character | |
143 | to be %). Type %magic at the IPython prompt for more information. |
|
137 | to be %). Type %magic at the IPython prompt for more information. | |
144 |
|
138 | |||
145 | -[no]autoedit_syntax |
|
139 | -[no]autoedit_syntax | |
146 | When a syntax error occurs after editing a file, automatically |
|
140 | When a syntax error occurs after editing a file, automatically | |
147 | open the file to the trouble causing line for convenient |
|
141 | open the file to the trouble causing line for convenient | |
148 | fixing. |
|
142 | fixing. | |
149 |
|
143 | |||
150 | -[no]banner Print the initial information banner (default on). |
|
144 | -[no]banner Print the initial information banner (default on). | |
151 |
|
145 | |||
152 | -c <command> |
|
146 | -c <command> | |
153 | execute the given command string. This is similar to the -c |
|
147 | execute the given command string. This is similar to the -c | |
154 | option in the normal Python interpreter. |
|
148 | option in the normal Python interpreter. | |
155 |
|
149 | |||
156 | -cache_size, cs <n> |
|
150 | -cache_size, cs <n> | |
157 | size of the output cache (maximum number of entries to hold in |
|
151 | size of the output cache (maximum number of entries to hold in | |
158 | memory). The default is 1000, you can change it permanently in your |
|
152 | memory). The default is 1000, you can change it permanently in your | |
159 | config file. Setting it to 0 completely disables the caching system, |
|
153 | config file. Setting it to 0 completely disables the caching system, | |
160 | and the minimum value accepted is 20 (if you provide a value less than |
|
154 | and the minimum value accepted is 20 (if you provide a value less than | |
161 | 20, it is reset to 0 and a warning is issued) This limit is defined |
|
155 | 20, it is reset to 0 and a warning is issued) This limit is defined | |
162 | because otherwise you'll spend more time re-flushing a too small cache |
|
156 | because otherwise you'll spend more time re-flushing a too small cache | |
163 | than working. |
|
157 | than working. | |
164 |
|
158 | |||
165 | -classic, cl |
|
159 | -classic, cl | |
166 | Gives IPython a similar feel to the classic Python |
|
160 | Gives IPython a similar feel to the classic Python | |
167 | prompt. |
|
161 | prompt. | |
168 |
|
162 | |||
169 | -colors <scheme> |
|
163 | -colors <scheme> | |
170 | Color scheme for prompts and exception reporting. Currently |
|
164 | Color scheme for prompts and exception reporting. Currently | |
171 | implemented: NoColor, Linux and LightBG. |
|
165 | implemented: NoColor, Linux and LightBG. | |
172 |
|
166 | |||
173 | -[no]color_info |
|
167 | -[no]color_info | |
174 | IPython can display information about objects via a set of functions, |
|
168 | IPython can display information about objects via a set of functions, | |
175 | and optionally can use colors for this, syntax highlighting source |
|
169 | and optionally can use colors for this, syntax highlighting source | |
176 | code and various other elements. However, because this information is |
|
170 | code and various other elements. However, because this information is | |
177 | passed through a pager (like 'less') and many pagers get confused with |
|
171 | passed through a pager (like 'less') and many pagers get confused with | |
178 | color codes, this option is off by default. You can test it and turn |
|
172 | color codes, this option is off by default. You can test it and turn | |
179 | it on permanently in your ipythonrc file if it works for you. As a |
|
173 | it on permanently in your ipythonrc file if it works for you. As a | |
180 | reference, the 'less' pager supplied with Mandrake 8.2 works ok, but |
|
174 | reference, the 'less' pager supplied with Mandrake 8.2 works ok, but | |
181 | that in RedHat 7.2 doesn't. |
|
175 | that in RedHat 7.2 doesn't. | |
182 |
|
176 | |||
183 | Test it and turn it on permanently if it works with your |
|
177 | Test it and turn it on permanently if it works with your | |
184 | system. The magic function %color_info allows you to toggle this |
|
178 | system. The magic function %color_info allows you to toggle this | |
185 | interactively for testing. |
|
179 | interactively for testing. | |
186 |
|
180 | |||
187 | -[no]debug |
|
181 | -[no]debug | |
188 | Show information about the loading process. Very useful to pin down |
|
182 | Show information about the loading process. Very useful to pin down | |
189 | problems with your configuration files or to get details about |
|
183 | problems with your configuration files or to get details about | |
190 | session restores. |
|
184 | session restores. | |
191 |
|
185 | |||
192 | -[no]deep_reload: |
|
186 | -[no]deep_reload: | |
193 | IPython can use the deep_reload module which reloads changes in |
|
187 | IPython can use the deep_reload module which reloads changes in | |
194 | modules recursively (it replaces the reload() function, so you don't |
|
188 | modules recursively (it replaces the reload() function, so you don't | |
195 | need to change anything to use it). deep_reload() forces a full |
|
189 | need to change anything to use it). deep_reload() forces a full | |
196 | reload of modules whose code may have changed, which the default |
|
190 | reload of modules whose code may have changed, which the default | |
197 | reload() function does not. |
|
191 | reload() function does not. | |
198 |
|
192 | |||
199 | When deep_reload is off, IPython will use the normal reload(), |
|
193 | When deep_reload is off, IPython will use the normal reload(), | |
200 | but deep_reload will still be available as dreload(). This |
|
194 | but deep_reload will still be available as dreload(). This | |
201 | feature is off by default [which means that you have both |
|
195 | feature is off by default [which means that you have both | |
202 | normal reload() and dreload()]. |
|
196 | normal reload() and dreload()]. | |
203 |
|
197 | |||
204 | -editor <name> |
|
198 | -editor <name> | |
205 | Which editor to use with the %edit command. By default, |
|
199 | Which editor to use with the %edit command. By default, | |
206 | IPython will honor your EDITOR environment variable (if not |
|
200 | IPython will honor your EDITOR environment variable (if not | |
207 | set, vi is the Unix default and notepad the Windows one). |
|
201 | set, vi is the Unix default and notepad the Windows one). | |
208 | Since this editor is invoked on the fly by IPython and is |
|
202 | Since this editor is invoked on the fly by IPython and is | |
209 | meant for editing small code snippets, you may want to use a |
|
203 | meant for editing small code snippets, you may want to use a | |
210 | small, lightweight editor here (in case your default EDITOR is |
|
204 | small, lightweight editor here (in case your default EDITOR is | |
211 | something like Emacs). |
|
205 | something like Emacs). | |
212 |
|
206 | |||
213 | -ipythondir <name> |
|
207 | -ipythondir <name> | |
214 | name of your IPython configuration directory IPYTHONDIR. This |
|
208 | name of your IPython configuration directory IPYTHONDIR. This | |
215 | can also be specified through the environment variable |
|
209 | can also be specified through the environment variable | |
216 | IPYTHONDIR. |
|
210 | IPYTHONDIR. | |
217 |
|
211 | |||
218 | -log, l |
|
212 | -log, l | |
219 | generate a log file of all input. The file is named |
|
213 | generate a log file of all input. The file is named | |
220 | ipython_log.py in your current directory (which prevents logs |
|
214 | ipython_log.py in your current directory (which prevents logs | |
221 | from multiple IPython sessions from trampling each other). You |
|
215 | from multiple IPython sessions from trampling each other). You | |
222 | can use this to later restore a session by loading your |
|
216 | can use this to later restore a session by loading your | |
223 | logfile as a file to be executed with option -logplay (see |
|
217 | logfile as a file to be executed with option -logplay (see | |
224 | below). |
|
218 | below). | |
225 |
|
219 | |||
226 | -logfile, lf <name> specify the name of your logfile. |
|
220 | -logfile, lf <name> specify the name of your logfile. | |
227 |
|
221 | |||
228 | -logplay, lp <name> |
|
222 | -logplay, lp <name> | |
229 |
|
223 | |||
230 | you can replay a previous log. For restoring a session as close as |
|
224 | you can replay a previous log. For restoring a session as close as | |
231 | possible to the state you left it in, use this option (don't just run |
|
225 | possible to the state you left it in, use this option (don't just run | |
232 | the logfile). With -logplay, IPython will try to reconstruct the |
|
226 | the logfile). With -logplay, IPython will try to reconstruct the | |
233 | previous working environment in full, not just execute the commands in |
|
227 | previous working environment in full, not just execute the commands in | |
234 | the logfile. |
|
228 | the logfile. | |
235 |
|
229 | |||
236 | When a session is restored, logging is automatically turned on |
|
230 | When a session is restored, logging is automatically turned on | |
237 | again with the name of the logfile it was invoked with (it is |
|
231 | again with the name of the logfile it was invoked with (it is | |
238 | read from the log header). So once you've turned logging on for |
|
232 | read from the log header). So once you've turned logging on for | |
239 | a session, you can quit IPython and reload it as many times as |
|
233 | a session, you can quit IPython and reload it as many times as | |
240 | you want and it will continue to log its history and restore |
|
234 | you want and it will continue to log its history and restore | |
241 | from the beginning every time. |
|
235 | from the beginning every time. | |
242 |
|
236 | |||
243 | Caveats: there are limitations in this option. The history |
|
237 | Caveats: there are limitations in this option. The history | |
244 | variables _i*,_* and _dh don't get restored properly. In the |
|
238 | variables _i*,_* and _dh don't get restored properly. In the | |
245 | future we will try to implement full session saving by writing |
|
239 | future we will try to implement full session saving by writing | |
246 | and retrieving a 'snapshot' of the memory state of IPython. But |
|
240 | and retrieving a 'snapshot' of the memory state of IPython. But | |
247 | our first attempts failed because of inherent limitations of |
|
241 | our first attempts failed because of inherent limitations of | |
248 | Python's Pickle module, so this may have to wait. |
|
242 | Python's Pickle module, so this may have to wait. | |
249 |
|
243 | |||
250 | -[no]messages |
|
244 | -[no]messages | |
251 | Print messages which IPython collects about its startup |
|
245 | Print messages which IPython collects about its startup | |
252 | process (default on). |
|
246 | process (default on). | |
253 |
|
247 | |||
254 | -[no]pdb |
|
248 | -[no]pdb | |
255 | Automatically call the pdb debugger after every uncaught |
|
249 | Automatically call the pdb debugger after every uncaught | |
256 | exception. If you are used to debugging using pdb, this puts |
|
250 | exception. If you are used to debugging using pdb, this puts | |
257 | you automatically inside of it after any call (either in |
|
251 | you automatically inside of it after any call (either in | |
258 | IPython or in code called by it) which triggers an exception |
|
252 | IPython or in code called by it) which triggers an exception | |
259 | which goes uncaught. |
|
253 | which goes uncaught. | |
260 |
|
254 | |||
261 | -pydb |
|
255 | -pydb | |
262 | Makes IPython use the third party "pydb" package as debugger, |
|
256 | Makes IPython use the third party "pydb" package as debugger, | |
263 | instead of pdb. Requires that pydb is installed. |
|
257 | instead of pdb. Requires that pydb is installed. | |
264 |
|
258 | |||
265 | -[no]pprint |
|
259 | -[no]pprint | |
266 | ipython can optionally use the pprint (pretty printer) module |
|
260 | ipython can optionally use the pprint (pretty printer) module | |
267 | for displaying results. pprint tends to give a nicer display |
|
261 | for displaying results. pprint tends to give a nicer display | |
268 | of nested data structures. If you like it, you can turn it on |
|
262 | of nested data structures. If you like it, you can turn it on | |
269 | permanently in your config file (default off). |
|
263 | permanently in your config file (default off). | |
270 |
|
264 | |||
271 | -profile, p <name> |
|
265 | -profile, p <name> | |
272 |
|
266 | |||
273 | assume that your config file is ipythonrc-<name> or |
|
267 | assume that your config file is ipythonrc-<name> or | |
274 | ipy_profile_<name>.py (looks in current dir first, then in |
|
268 | ipy_profile_<name>.py (looks in current dir first, then in | |
275 | IPYTHONDIR). This is a quick way to keep and load multiple |
|
269 | IPYTHONDIR). This is a quick way to keep and load multiple | |
276 | config files for different tasks, especially if you use the |
|
270 | config files for different tasks, especially if you use the | |
277 | include option of config files. You can keep a basic |
|
271 | include option of config files. You can keep a basic | |
278 | IPYTHONDIR/ipythonrc file and then have other 'profiles' which |
|
272 | IPYTHONDIR/ipythonrc file and then have other 'profiles' which | |
279 | include this one and load extra things for particular |
|
273 | include this one and load extra things for particular | |
280 | tasks. For example: |
|
274 | tasks. For example: | |
281 |
|
275 | |||
282 | 1. $HOME/.ipython/ipythonrc : load basic things you always want. |
|
276 | 1. $HOME/.ipython/ipythonrc : load basic things you always want. | |
283 | 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules. |
|
277 | 2. $HOME/.ipython/ipythonrc-math : load (1) and basic math-related modules. | |
284 | 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules. |
|
278 | 3. $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and plotting modules. | |
285 |
|
279 | |||
286 | Since it is possible to create an endless loop by having |
|
280 | Since it is possible to create an endless loop by having | |
287 | circular file inclusions, IPython will stop if it reaches 15 |
|
281 | circular file inclusions, IPython will stop if it reaches 15 | |
288 | recursive inclusions. |
|
282 | recursive inclusions. | |
289 |
|
283 | |||
290 | -prompt_in1, pi1 <string> |
|
284 | -prompt_in1, pi1 <string> | |
291 |
|
285 | |||
292 | Specify the string used for input prompts. Note that if you are using |
|
286 | Specify the string used for input prompts. Note that if you are using | |
293 | numbered prompts, the number is represented with a '\#' in the |
|
287 | numbered prompts, the number is represented with a '\#' in the | |
294 | string. Don't forget to quote strings with spaces embedded in |
|
288 | string. Don't forget to quote strings with spaces embedded in | |
295 | them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>` |
|
289 | them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>` | |
296 | discusses in detail all the available escapes to customize your |
|
290 | discusses in detail all the available escapes to customize your | |
297 | prompts. |
|
291 | prompts. | |
298 |
|
292 | |||
299 | -prompt_in2, pi2 <string> |
|
293 | -prompt_in2, pi2 <string> | |
300 | Similar to the previous option, but used for the continuation |
|
294 | Similar to the previous option, but used for the continuation | |
301 | prompts. The special sequence '\D' is similar to '\#', but |
|
295 | prompts. The special sequence '\D' is similar to '\#', but | |
302 | with all digits replaced dots (so you can have your |
|
296 | with all digits replaced dots (so you can have your | |
303 | continuation prompt aligned with your input prompt). Default: |
|
297 | continuation prompt aligned with your input prompt). Default: | |
304 | ' .\D.:' (note three spaces at the start for alignment with |
|
298 | ' .\D.:' (note three spaces at the start for alignment with | |
305 | 'In [\#]'). |
|
299 | 'In [\#]'). | |
306 |
|
300 | |||
307 | -prompt_out,po <string> |
|
301 | -prompt_out,po <string> | |
308 | String used for output prompts, also uses numbers like |
|
302 | String used for output prompts, also uses numbers like | |
309 | prompt_in1. Default: 'Out[\#]:' |
|
303 | prompt_in1. Default: 'Out[\#]:' | |
310 |
|
304 | |||
311 | -quick start in bare bones mode (no config file loaded). |
|
305 | -quick start in bare bones mode (no config file loaded). | |
312 |
|
306 | |||
313 | -rcfile <name> |
|
307 | -rcfile <name> | |
314 | name of your IPython resource configuration file. Normally |
|
308 | name of your IPython resource configuration file. Normally | |
315 | IPython loads ipythonrc (from current directory) or |
|
309 | IPython loads ipythonrc (from current directory) or | |
316 | IPYTHONDIR/ipythonrc. |
|
310 | IPYTHONDIR/ipythonrc. | |
317 |
|
311 | |||
318 | If the loading of your config file fails, IPython starts with |
|
312 | If the loading of your config file fails, IPython starts with | |
319 | a bare bones configuration (no modules loaded at all). |
|
313 | a bare bones configuration (no modules loaded at all). | |
320 |
|
314 | |||
321 | -[no]readline |
|
315 | -[no]readline | |
322 | use the readline library, which is needed to support name |
|
316 | use the readline library, which is needed to support name | |
323 | completion and command history, among other things. It is |
|
317 | completion and command history, among other things. It is | |
324 | enabled by default, but may cause problems for users of |
|
318 | enabled by default, but may cause problems for users of | |
325 | X/Emacs in Python comint or shell buffers. |
|
319 | X/Emacs in Python comint or shell buffers. | |
326 |
|
320 | |||
327 | Note that X/Emacs 'eterm' buffers (opened with M-x term) support |
|
321 | Note that X/Emacs 'eterm' buffers (opened with M-x term) support | |
328 | IPython's readline and syntax coloring fine, only 'emacs' (M-x |
|
322 | IPython's readline and syntax coloring fine, only 'emacs' (M-x | |
329 | shell and C-c !) buffers do not. |
|
323 | shell and C-c !) buffers do not. | |
330 |
|
324 | |||
331 | -screen_length, sl <n> |
|
325 | -screen_length, sl <n> | |
332 | number of lines of your screen. This is used to control |
|
326 | number of lines of your screen. This is used to control | |
333 | printing of very long strings. Strings longer than this number |
|
327 | printing of very long strings. Strings longer than this number | |
334 | of lines will be sent through a pager instead of directly |
|
328 | of lines will be sent through a pager instead of directly | |
335 | printed. |
|
329 | printed. | |
336 |
|
330 | |||
337 | The default value for this is 0, which means IPython will |
|
331 | The default value for this is 0, which means IPython will | |
338 | auto-detect your screen size every time it needs to print certain |
|
332 | auto-detect your screen size every time it needs to print certain | |
339 | potentially long strings (this doesn't change the behavior of the |
|
333 | potentially long strings (this doesn't change the behavior of the | |
340 | 'print' keyword, it's only triggered internally). If for some |
|
334 | 'print' keyword, it's only triggered internally). If for some | |
341 | reason this isn't working well (it needs curses support), specify |
|
335 | reason this isn't working well (it needs curses support), specify | |
342 | it yourself. Otherwise don't change the default. |
|
336 | it yourself. Otherwise don't change the default. | |
343 |
|
337 | |||
344 | -separate_in, si <string> |
|
338 | -separate_in, si <string> | |
345 |
|
339 | |||
346 | separator before input prompts. |
|
340 | separator before input prompts. | |
347 | Default: '\n' |
|
341 | Default: '\n' | |
348 |
|
342 | |||
349 | -separate_out, so <string> |
|
343 | -separate_out, so <string> | |
350 | separator before output prompts. |
|
344 | separator before output prompts. | |
351 | Default: nothing. |
|
345 | Default: nothing. | |
352 |
|
346 | |||
353 | -separate_out2, so2 |
|
347 | -separate_out2, so2 | |
354 | separator after output prompts. |
|
348 | separator after output prompts. | |
355 | Default: nothing. |
|
349 | Default: nothing. | |
356 | For these three options, use the value 0 to specify no separator. |
|
350 | For these three options, use the value 0 to specify no separator. | |
357 |
|
351 | |||
358 | -nosep |
|
352 | -nosep | |
359 | shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 |
|
353 | shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 | |
360 | 0'. Simply removes all input/output separators. |
|
354 | 0'. Simply removes all input/output separators. | |
361 |
|
355 | |||
362 | -upgrade |
|
356 | -upgrade | |
363 | allows you to upgrade your IPYTHONDIR configuration when you |
|
357 | allows you to upgrade your IPYTHONDIR configuration when you | |
364 | install a new version of IPython. Since new versions may |
|
358 | install a new version of IPython. Since new versions may | |
365 | include new command line options or example files, this copies |
|
359 | include new command line options or example files, this copies | |
366 | updated ipythonrc-type files. However, it backs up (with a |
|
360 | updated ipythonrc-type files. However, it backs up (with a | |
367 | .old extension) all files which it overwrites so that you can |
|
361 | .old extension) all files which it overwrites so that you can | |
368 | merge back any customizations you might have in your personal |
|
362 | merge back any customizations you might have in your personal | |
369 | files. Note that you should probably use %upgrade instead, |
|
363 | files. Note that you should probably use %upgrade instead, | |
370 | it's a safer alternative. |
|
364 | it's a safer alternative. | |
371 |
|
365 | |||
372 |
|
366 | |||
373 | -Version print version information and exit. |
|
367 | -Version print version information and exit. | |
374 |
|
368 | |||
375 | -wxversion <string> |
|
369 | -wxversion <string> | |
376 | Select a specific version of wxPython (used in conjunction |
|
370 | Select a specific version of wxPython (used in conjunction | |
377 | with -wthread). Requires the wxversion module, part of recent |
|
371 | with -wthread). Requires the wxversion module, part of recent | |
378 | wxPython distributions |
|
372 | wxPython distributions | |
379 |
|
373 | |||
380 | -xmode <modename> |
|
374 | -xmode <modename> | |
381 |
|
375 | |||
382 | Mode for exception reporting. |
|
376 | Mode for exception reporting. | |
383 |
|
377 | |||
384 | Valid modes: Plain, Context and Verbose. |
|
378 | Valid modes: Plain, Context and Verbose. | |
385 |
|
379 | |||
386 | * Plain: similar to python's normal traceback printing. |
|
380 | * Plain: similar to python's normal traceback printing. | |
387 | * Context: prints 5 lines of context source code around each |
|
381 | * Context: prints 5 lines of context source code around each | |
388 | line in the traceback. |
|
382 | line in the traceback. | |
389 | * Verbose: similar to Context, but additionally prints the |
|
383 | * Verbose: similar to Context, but additionally prints the | |
390 | variables currently visible where the exception happened |
|
384 | variables currently visible where the exception happened | |
391 | (shortening their strings if too long). This can potentially be |
|
385 | (shortening their strings if too long). This can potentially be | |
392 | very slow, if you happen to have a huge data structure whose |
|
386 | very slow, if you happen to have a huge data structure whose | |
393 | string representation is complex to compute. Your computer may |
|
387 | string representation is complex to compute. Your computer may | |
394 | appear to freeze for a while with cpu usage at 100%. If this |
|
388 | appear to freeze for a while with cpu usage at 100%. If this | |
395 | occurs, you can cancel the traceback with Ctrl-C (maybe hitting it |
|
389 | occurs, you can cancel the traceback with Ctrl-C (maybe hitting it | |
396 | more than once). |
|
390 | more than once). | |
397 |
|
391 | |||
398 | Interactive use |
|
392 | Interactive use | |
399 | =============== |
|
393 | =============== | |
400 |
|
394 | |||
401 | Warning: IPython relies on the existence of a global variable called |
|
395 | Warning: IPython relies on the existence of a global variable called | |
402 | _ip which controls the shell itself. If you redefine _ip to anything, |
|
396 | _ip which controls the shell itself. If you redefine _ip to anything, | |
403 | bizarre behavior will quickly occur. |
|
397 | bizarre behavior will quickly occur. | |
404 |
|
398 | |||
405 | Other than the above warning, IPython is meant to work as a drop-in |
|
399 | Other than the above warning, IPython is meant to work as a drop-in | |
406 | replacement for the standard interactive interpreter. As such, any code |
|
400 | replacement for the standard interactive interpreter. As such, any code | |
407 | which is valid python should execute normally under IPython (cases where |
|
401 | which is valid python should execute normally under IPython (cases where | |
408 | this is not true should be reported as bugs). It does, however, offer |
|
402 | this is not true should be reported as bugs). It does, however, offer | |
409 | many features which are not available at a standard python prompt. What |
|
403 | many features which are not available at a standard python prompt. What | |
410 | follows is a list of these. |
|
404 | follows is a list of these. | |
411 |
|
405 | |||
412 |
|
406 | |||
413 | Caution for Windows users |
|
407 | Caution for Windows users | |
414 | ------------------------- |
|
408 | ------------------------- | |
415 |
|
409 | |||
416 | Windows, unfortunately, uses the '\' character as a path |
|
410 | Windows, unfortunately, uses the '\' character as a path | |
417 | separator. This is a terrible choice, because '\' also represents the |
|
411 | separator. This is a terrible choice, because '\' also represents the | |
418 | escape character in most modern programming languages, including |
|
412 | escape character in most modern programming languages, including | |
419 | Python. For this reason, using '/' character is recommended if you |
|
413 | Python. For this reason, using '/' character is recommended if you | |
420 | have problems with ``\``. However, in Windows commands '/' flags |
|
414 | have problems with ``\``. However, in Windows commands '/' flags | |
421 | options, so you can not use it for the root directory. This means that |
|
415 | options, so you can not use it for the root directory. This means that | |
422 | paths beginning at the root must be typed in a contrived manner like: |
|
416 | paths beginning at the root must be typed in a contrived manner like: | |
423 | ``%copy \opt/foo/bar.txt \tmp`` |
|
417 | ``%copy \opt/foo/bar.txt \tmp`` | |
424 |
|
418 | |||
425 | .. _magic: |
|
419 | .. _magic: | |
426 |
|
420 | |||
427 | Magic command system |
|
421 | Magic command system | |
428 | -------------------- |
|
422 | -------------------- | |
429 |
|
423 | |||
430 | IPython will treat any line whose first character is a % as a special |
|
424 | IPython will treat any line whose first character is a % as a special | |
431 | call to a 'magic' function. These allow you to control the behavior of |
|
425 | call to a 'magic' function. These allow you to control the behavior of | |
432 | IPython itself, plus a lot of system-type features. They are all |
|
426 | IPython itself, plus a lot of system-type features. They are all | |
433 | prefixed with a % character, but parameters are given without |
|
427 | prefixed with a % character, but parameters are given without | |
434 | parentheses or quotes. |
|
428 | parentheses or quotes. | |
435 |
|
429 | |||
436 | Example: typing '%cd mydir' (without the quotes) changes you working |
|
430 | Example: typing '%cd mydir' (without the quotes) changes you working | |
437 | directory to 'mydir', if it exists. |
|
431 | directory to 'mydir', if it exists. | |
438 |
|
432 | |||
439 | If you have 'automagic' enabled (in your ipythonrc file, via the command |
|
433 | If you have 'automagic' enabled (in your ipythonrc file, via the command | |
440 | line option -automagic or with the %automagic function), you don't need |
|
434 | line option -automagic or with the %automagic function), you don't need | |
441 | to type in the % explicitly. IPython will scan its internal list of |
|
435 | to type in the % explicitly. IPython will scan its internal list of | |
442 | magic functions and call one if it exists. With automagic on you can |
|
436 | magic functions and call one if it exists. With automagic on you can | |
443 | then just type 'cd mydir' to go to directory 'mydir'. The automagic |
|
437 | then just type 'cd mydir' to go to directory 'mydir'. The automagic | |
444 | system has the lowest possible precedence in name searches, so defining |
|
438 | system has the lowest possible precedence in name searches, so defining | |
445 | an identifier with the same name as an existing magic function will |
|
439 | an identifier with the same name as an existing magic function will | |
446 | shadow it for automagic use. You can still access the shadowed magic |
|
440 | shadow it for automagic use. You can still access the shadowed magic | |
447 | function by explicitly using the % character at the beginning of the line. |
|
441 | function by explicitly using the % character at the beginning of the line. | |
448 |
|
442 | |||
449 | An example (with automagic on) should clarify all this:: |
|
443 | An example (with automagic on) should clarify all this:: | |
450 |
|
444 | |||
451 | In [1]: cd ipython # %cd is called by automagic |
|
445 | In [1]: cd ipython # %cd is called by automagic | |
452 |
|
446 | |||
453 | /home/fperez/ipython |
|
447 | /home/fperez/ipython | |
454 |
|
448 | |||
455 | In [2]: cd=1 # now cd is just a variable |
|
449 | In [2]: cd=1 # now cd is just a variable | |
456 |
|
450 | |||
457 | In [3]: cd .. # and doesn't work as a function anymore |
|
451 | In [3]: cd .. # and doesn't work as a function anymore | |
458 |
|
452 | |||
459 | ------------------------------ |
|
453 | ------------------------------ | |
460 |
|
454 | |||
461 | File "<console>", line 1 |
|
455 | File "<console>", line 1 | |
462 |
|
456 | |||
463 | cd .. |
|
457 | cd .. | |
464 |
|
458 | |||
465 | ^ |
|
459 | ^ | |
466 |
|
460 | |||
467 | SyntaxError: invalid syntax |
|
461 | SyntaxError: invalid syntax | |
468 |
|
462 | |||
469 | In [4]: %cd .. # but %cd always works |
|
463 | In [4]: %cd .. # but %cd always works | |
470 |
|
464 | |||
471 | /home/fperez |
|
465 | /home/fperez | |
472 |
|
466 | |||
473 | In [5]: del cd # if you remove the cd variable |
|
467 | In [5]: del cd # if you remove the cd variable | |
474 |
|
468 | |||
475 | In [6]: cd ipython # automagic can work again |
|
469 | In [6]: cd ipython # automagic can work again | |
476 |
|
470 | |||
477 | /home/fperez/ipython |
|
471 | /home/fperez/ipython | |
478 |
|
472 | |||
479 | You can define your own magic functions to extend the system. The |
|
473 | You can define your own magic functions to extend the system. The | |
480 | following example defines a new magic command, %impall:: |
|
474 | following example defines a new magic command, %impall:: | |
481 |
|
475 | |||
482 | import IPython.ipapi |
|
476 | import IPython.ipapi | |
483 |
|
477 | |||
484 | ip = IPython.ipapi.get() |
|
478 | ip = IPython.ipapi.get() | |
485 |
|
479 | |||
486 | def doimp(self, arg): |
|
480 | def doimp(self, arg): | |
487 |
|
481 | |||
488 | ip = self.api |
|
482 | ip = self.api | |
489 |
|
483 | |||
490 | ip.ex("import %s; reload(%s); from %s import *" % ( |
|
484 | ip.ex("import %s; reload(%s); from %s import *" % ( | |
491 |
|
485 | |||
492 | arg,arg,arg) |
|
486 | arg,arg,arg) | |
493 |
|
487 | |||
494 | ) |
|
488 | ) | |
495 |
|
489 | |||
496 | ip.expose_magic('impall', doimp) |
|
490 | ip.expose_magic('impall', doimp) | |
497 |
|
491 | |||
498 | You can also define your own aliased names for magic functions. In your |
|
492 | You can also define your own aliased names for magic functions. In your | |
499 | ipythonrc file, placing a line like: |
|
493 | ipythonrc file, placing a line like: | |
500 |
|
494 | |||
501 | execute __IP.magic_cl = __IP.magic_clear |
|
495 | execute __IP.magic_cl = __IP.magic_clear | |
502 |
|
496 | |||
503 | will define %cl as a new name for %clear. |
|
497 | will define %cl as a new name for %clear. | |
504 |
|
498 | |||
505 | Type %magic for more information, including a list of all available |
|
499 | Type %magic for more information, including a list of all available | |
506 | magic functions at any time and their docstrings. You can also type |
|
500 | magic functions at any time and their docstrings. You can also type | |
507 | %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for |
|
501 | %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for | |
508 | information on the '?' system) to get information about any particular |
|
502 | information on the '?' system) to get information about any particular | |
509 | magic function you are interested in. |
|
503 | magic function you are interested in. | |
510 |
|
504 | |||
511 |
|
505 | |||
512 | Magic commands |
|
506 | Magic commands | |
513 | -------------- |
|
507 | -------------- | |
514 |
|
508 | |||
515 | The rest of this section is automatically generated for each release |
|
509 | The rest of this section is automatically generated for each release | |
516 | from the docstrings in the IPython code. Therefore the formatting is |
|
510 | from the docstrings in the IPython code. Therefore the formatting is | |
517 | somewhat minimal, but this method has the advantage of having |
|
511 | somewhat minimal, but this method has the advantage of having | |
518 | information always in sync with the code. |
|
512 | information always in sync with the code. | |
519 |
|
513 | |||
520 | A list of all the magic commands available in IPython's default |
|
514 | A list of all the magic commands available in IPython's default | |
521 | installation follows. This is similar to what you'll see by simply |
|
515 | installation follows. This is similar to what you'll see by simply | |
522 | typing %magic at the prompt, but that will also give you information |
|
516 | typing %magic at the prompt, but that will also give you information | |
523 | about magic commands you may have added as part of your personal |
|
517 | about magic commands you may have added as part of your personal | |
524 | customizations. |
|
518 | customizations. | |
525 |
|
519 | |||
526 | .. magic_start |
|
520 | .. magic_start | |
527 |
|
521 | |||
528 | **%Exit**:: |
|
522 | **%Exit**:: | |
529 |
|
523 | |||
530 | Exit IPython without confirmation. |
|
524 | Exit IPython without confirmation. | |
531 |
|
525 | |||
532 | **%Pprint**:: |
|
526 | **%Pprint**:: | |
533 |
|
527 | |||
534 | Toggle pretty printing on/off. |
|
528 | Toggle pretty printing on/off. | |
535 |
|
529 | |||
536 | **%alias**:: |
|
530 | **%alias**:: | |
537 |
|
531 | |||
538 | Define an alias for a system command. |
|
532 | Define an alias for a system command. | |
539 |
|
533 | |||
540 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
534 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
541 |
|
535 | |||
542 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
536 | Then, typing 'alias_name params' will execute the system command 'cmd | |
543 | params' (from your underlying operating system). |
|
537 | params' (from your underlying operating system). | |
544 |
|
538 | |||
545 | Aliases have lower precedence than magic functions and Python normal |
|
539 | Aliases have lower precedence than magic functions and Python normal | |
546 | variables, so if 'foo' is both a Python variable and an alias, the |
|
540 | variables, so if 'foo' is both a Python variable and an alias, the | |
547 | alias can not be executed until 'del foo' removes the Python variable. |
|
541 | alias can not be executed until 'del foo' removes the Python variable. | |
548 |
|
542 | |||
549 | You can use the %l specifier in an alias definition to represent the |
|
543 | You can use the %l specifier in an alias definition to represent the | |
550 | whole line when the alias is called. For example: |
|
544 | whole line when the alias is called. For example: | |
551 |
|
545 | |||
552 | In [2]: alias all echo "Input in brackets: <%l>"\ |
|
546 | In [2]: alias all echo "Input in brackets: <%l>"\ | |
553 | In [3]: all hello world\ |
|
547 | In [3]: all hello world\ | |
554 | Input in brackets: <hello world> |
|
548 | Input in brackets: <hello world> | |
555 |
|
549 | |||
556 | You can also define aliases with parameters using %s specifiers (one |
|
550 | You can also define aliases with parameters using %s specifiers (one | |
557 | per parameter): |
|
551 | per parameter): | |
558 |
|
552 | |||
559 | In [1]: alias parts echo first %s second %s\ |
|
553 | In [1]: alias parts echo first %s second %s\ | |
560 | In [2]: %parts A B\ |
|
554 | In [2]: %parts A B\ | |
561 | first A second B\ |
|
555 | first A second B\ | |
562 | In [3]: %parts A\ |
|
556 | In [3]: %parts A\ | |
563 | Incorrect number of arguments: 2 expected.\ |
|
557 | Incorrect number of arguments: 2 expected.\ | |
564 | parts is an alias to: 'echo first %s second %s' |
|
558 | parts is an alias to: 'echo first %s second %s' | |
565 |
|
559 | |||
566 | Note that %l and %s are mutually exclusive. You can only use one or |
|
560 | Note that %l and %s are mutually exclusive. You can only use one or | |
567 | the other in your aliases. |
|
561 | the other in your aliases. | |
568 |
|
562 | |||
569 | Aliases expand Python variables just like system calls using ! or !! |
|
563 | Aliases expand Python variables just like system calls using ! or !! | |
570 | do: all expressions prefixed with '$' get expanded. For details of |
|
564 | do: all expressions prefixed with '$' get expanded. For details of | |
571 | the semantic rules, see PEP-215: |
|
565 | the semantic rules, see PEP-215: | |
572 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
566 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
573 | IPython for variable expansion. If you want to access a true shell |
|
567 | IPython for variable expansion. If you want to access a true shell | |
574 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
568 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
575 |
|
569 | |||
576 | In [6]: alias show echo\ |
|
570 | In [6]: alias show echo\ | |
577 | In [7]: PATH='A Python string'\ |
|
571 | In [7]: PATH='A Python string'\ | |
578 | In [8]: show $PATH\ |
|
572 | In [8]: show $PATH\ | |
579 | A Python string\ |
|
573 | A Python string\ | |
580 | In [9]: show $$PATH\ |
|
574 | In [9]: show $$PATH\ | |
581 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
575 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
582 |
|
576 | |||
583 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
577 | You can use the alias facility to acess all of $PATH. See the %rehash | |
584 | and %rehashx functions, which automatically create aliases for the |
|
578 | and %rehashx functions, which automatically create aliases for the | |
585 | contents of your $PATH. |
|
579 | contents of your $PATH. | |
586 |
|
580 | |||
587 | If called with no parameters, %alias prints the current alias table. |
|
581 | If called with no parameters, %alias prints the current alias table. | |
588 |
|
582 | |||
589 | **%autocall**:: |
|
583 | **%autocall**:: | |
590 |
|
584 | |||
591 | Make functions callable without having to type parentheses. |
|
585 | Make functions callable without having to type parentheses. | |
592 |
|
586 | |||
593 | Usage: |
|
587 | Usage: | |
594 |
|
588 | |||
595 | %autocall [mode] |
|
589 | %autocall [mode] | |
596 |
|
590 | |||
597 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
591 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
598 | value is toggled on and off (remembering the previous state). |
|
592 | value is toggled on and off (remembering the previous state). | |
599 |
|
593 | |||
600 | In more detail, these values mean: |
|
594 | In more detail, these values mean: | |
601 |
|
595 | |||
602 | 0 -> fully disabled |
|
596 | 0 -> fully disabled | |
603 |
|
597 | |||
604 | 1 -> active, but do not apply if there are no arguments on the line. |
|
598 | 1 -> active, but do not apply if there are no arguments on the line. | |
605 |
|
599 | |||
606 | In this mode, you get: |
|
600 | In this mode, you get: | |
607 |
|
601 | |||
608 | In [1]: callable |
|
602 | In [1]: callable | |
609 | Out[1]: <built-in function callable> |
|
603 | Out[1]: <built-in function callable> | |
610 |
|
604 | |||
611 | In [2]: callable 'hello' |
|
605 | In [2]: callable 'hello' | |
612 | ------> callable('hello') |
|
606 | ------> callable('hello') | |
613 | Out[2]: False |
|
607 | Out[2]: False | |
614 |
|
608 | |||
615 | 2 -> Active always. Even if no arguments are present, the callable |
|
609 | 2 -> Active always. Even if no arguments are present, the callable | |
616 | object is called: |
|
610 | object is called: | |
617 |
|
611 | |||
618 | In [4]: callable |
|
612 | In [4]: callable | |
619 | ------> callable() |
|
613 | ------> callable() | |
620 |
|
614 | |||
621 | Note that even with autocall off, you can still use '/' at the start of |
|
615 | Note that even with autocall off, you can still use '/' at the start of | |
622 | a line to treat the first argument on the command line as a function |
|
616 | a line to treat the first argument on the command line as a function | |
623 | and add parentheses to it: |
|
617 | and add parentheses to it: | |
624 |
|
618 | |||
625 | In [8]: /str 43 |
|
619 | In [8]: /str 43 | |
626 | ------> str(43) |
|
620 | ------> str(43) | |
627 | Out[8]: '43' |
|
621 | Out[8]: '43' | |
628 |
|
622 | |||
629 | **%autoindent**:: |
|
623 | **%autoindent**:: | |
630 |
|
624 | |||
631 | Toggle autoindent on/off (if available). |
|
625 | Toggle autoindent on/off (if available). | |
632 |
|
626 | |||
633 | **%automagic**:: |
|
627 | **%automagic**:: | |
634 |
|
628 | |||
635 | Make magic functions callable without having to type the initial %. |
|
629 | Make magic functions callable without having to type the initial %. | |
636 |
|
630 | |||
637 | Without argumentsl toggles on/off (when off, you must call it as |
|
631 | Without argumentsl toggles on/off (when off, you must call it as | |
638 | %automagic, of course). With arguments it sets the value, and you can |
|
632 | %automagic, of course). With arguments it sets the value, and you can | |
639 | use any of (case insensitive): |
|
633 | use any of (case insensitive): | |
640 |
|
634 | |||
641 | - on,1,True: to activate |
|
635 | - on,1,True: to activate | |
642 |
|
636 | |||
643 | - off,0,False: to deactivate. |
|
637 | - off,0,False: to deactivate. | |
644 |
|
638 | |||
645 | Note that magic functions have lowest priority, so if there's a |
|
639 | Note that magic functions have lowest priority, so if there's a | |
646 | variable whose name collides with that of a magic fn, automagic won't |
|
640 | variable whose name collides with that of a magic fn, automagic won't | |
647 | work for that function (you get the variable instead). However, if you |
|
641 | work for that function (you get the variable instead). However, if you | |
648 | delete the variable (del var), the previously shadowed magic function |
|
642 | delete the variable (del var), the previously shadowed magic function | |
649 | becomes visible to automagic again. |
|
643 | becomes visible to automagic again. | |
650 |
|
644 | |||
651 | **%bg**:: |
|
645 | **%bg**:: | |
652 |
|
646 | |||
653 | Run a job in the background, in a separate thread. |
|
647 | Run a job in the background, in a separate thread. | |
654 |
|
648 | |||
655 | For example, |
|
649 | For example, | |
656 |
|
650 | |||
657 | %bg myfunc(x,y,z=1) |
|
651 | %bg myfunc(x,y,z=1) | |
658 |
|
652 | |||
659 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
653 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
660 | execution starts, a message will be printed indicating the job |
|
654 | execution starts, a message will be printed indicating the job | |
661 | number. If your job number is 5, you can use |
|
655 | number. If your job number is 5, you can use | |
662 |
|
656 | |||
663 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
657 | myvar = jobs.result(5) or myvar = jobs[5].result | |
664 |
|
658 | |||
665 | to assign this result to variable 'myvar'. |
|
659 | to assign this result to variable 'myvar'. | |
666 |
|
660 | |||
667 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
661 | IPython has a job manager, accessible via the 'jobs' object. You can | |
668 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
662 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
669 | its attributes. All attributes not starting with an underscore are |
|
663 | its attributes. All attributes not starting with an underscore are | |
670 | meant for public use. |
|
664 | meant for public use. | |
671 |
|
665 | |||
672 | In particular, look at the jobs.new() method, which is used to create |
|
666 | In particular, look at the jobs.new() method, which is used to create | |
673 | new jobs. This magic %bg function is just a convenience wrapper |
|
667 | new jobs. This magic %bg function is just a convenience wrapper | |
674 | around jobs.new(), for expression-based jobs. If you want to create a |
|
668 | around jobs.new(), for expression-based jobs. If you want to create a | |
675 | new job with an explicit function object and arguments, you must call |
|
669 | new job with an explicit function object and arguments, you must call | |
676 | jobs.new() directly. |
|
670 | jobs.new() directly. | |
677 |
|
671 | |||
678 | The jobs.new docstring also describes in detail several important |
|
672 | The jobs.new docstring also describes in detail several important | |
679 | caveats associated with a thread-based model for background job |
|
673 | caveats associated with a thread-based model for background job | |
680 | execution. Type jobs.new? for details. |
|
674 | execution. Type jobs.new? for details. | |
681 |
|
675 | |||
682 | You can check the status of all jobs with jobs.status(). |
|
676 | You can check the status of all jobs with jobs.status(). | |
683 |
|
677 | |||
684 | The jobs variable is set by IPython into the Python builtin namespace. |
|
678 | The jobs variable is set by IPython into the Python builtin namespace. | |
685 | If you ever declare a variable named 'jobs', you will shadow this |
|
679 | If you ever declare a variable named 'jobs', you will shadow this | |
686 | name. You can either delete your global jobs variable to regain |
|
680 | name. You can either delete your global jobs variable to regain | |
687 | access to the job manager, or make a new name and assign it manually |
|
681 | access to the job manager, or make a new name and assign it manually | |
688 | to the manager (stored in IPython's namespace). For example, to |
|
682 | to the manager (stored in IPython's namespace). For example, to | |
689 | assign the job manager to the Jobs name, use: |
|
683 | assign the job manager to the Jobs name, use: | |
690 |
|
684 | |||
691 | Jobs = __builtins__.jobs |
|
685 | Jobs = __builtins__.jobs | |
692 |
|
686 | |||
693 | **%bookmark**:: |
|
687 | **%bookmark**:: | |
694 |
|
688 | |||
695 | Manage IPython's bookmark system. |
|
689 | Manage IPython's bookmark system. | |
696 |
|
690 | |||
697 | %bookmark <name> - set bookmark to current dir |
|
691 | %bookmark <name> - set bookmark to current dir | |
698 | %bookmark <name> <dir> - set bookmark to <dir> |
|
692 | %bookmark <name> <dir> - set bookmark to <dir> | |
699 | %bookmark -l - list all bookmarks |
|
693 | %bookmark -l - list all bookmarks | |
700 | %bookmark -d <name> - remove bookmark |
|
694 | %bookmark -d <name> - remove bookmark | |
701 | %bookmark -r - remove all bookmarks |
|
695 | %bookmark -r - remove all bookmarks | |
702 |
|
696 | |||
703 | You can later on access a bookmarked folder with: |
|
697 | You can later on access a bookmarked folder with: | |
704 | %cd -b <name> |
|
698 | %cd -b <name> | |
705 | or simply '%cd <name>' if there is no directory called <name> AND |
|
699 | or simply '%cd <name>' if there is no directory called <name> AND | |
706 | there is such a bookmark defined. |
|
700 | there is such a bookmark defined. | |
707 |
|
701 | |||
708 | Your bookmarks persist through IPython sessions, but they are |
|
702 | Your bookmarks persist through IPython sessions, but they are | |
709 | associated with each profile. |
|
703 | associated with each profile. | |
710 |
|
704 | |||
711 | **%cd**:: |
|
705 | **%cd**:: | |
712 |
|
706 | |||
713 | Change the current working directory. |
|
707 | Change the current working directory. | |
714 |
|
708 | |||
715 | This command automatically maintains an internal list of directories |
|
709 | This command automatically maintains an internal list of directories | |
716 | you visit during your IPython session, in the variable _dh. The |
|
710 | you visit during your IPython session, in the variable _dh. The | |
717 | command %dhist shows this history nicely formatted. You can also |
|
711 | command %dhist shows this history nicely formatted. You can also | |
718 | do 'cd -<tab>' to see directory history conveniently. |
|
712 | do 'cd -<tab>' to see directory history conveniently. | |
719 |
|
713 | |||
720 | Usage: |
|
714 | Usage: | |
721 |
|
715 | |||
722 | cd 'dir': changes to directory 'dir'. |
|
716 | cd 'dir': changes to directory 'dir'. | |
723 |
|
717 | |||
724 | cd -: changes to the last visited directory. |
|
718 | cd -: changes to the last visited directory. | |
725 |
|
719 | |||
726 | cd -<n>: changes to the n-th directory in the directory history. |
|
720 | cd -<n>: changes to the n-th directory in the directory history. | |
727 |
|
721 | |||
728 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
722 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
729 | (note: cd <bookmark_name> is enough if there is no |
|
723 | (note: cd <bookmark_name> is enough if there is no | |
730 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
724 | directory <bookmark_name>, but a bookmark with the name exists.) | |
731 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
725 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
732 |
|
726 | |||
733 | Options: |
|
727 | Options: | |
734 |
|
728 | |||
735 | -q: quiet. Do not print the working directory after the cd command is |
|
729 | -q: quiet. Do not print the working directory after the cd command is | |
736 | executed. By default IPython's cd command does print this directory, |
|
730 | executed. By default IPython's cd command does print this directory, | |
737 | since the default prompts do not display path information. |
|
731 | since the default prompts do not display path information. | |
738 |
|
732 | |||
739 | Note that !cd doesn't work for this purpose because the shell where |
|
733 | Note that !cd doesn't work for this purpose because the shell where | |
740 | !command runs is immediately discarded after executing 'command'. |
|
734 | !command runs is immediately discarded after executing 'command'. | |
741 |
|
735 | |||
742 | **%clear**:: |
|
736 | **%clear**:: | |
743 |
|
737 | |||
744 | Clear various data (e.g. stored history data) |
|
738 | Clear various data (e.g. stored history data) | |
745 |
|
739 | |||
746 | %clear out - clear output history |
|
740 | %clear out - clear output history | |
747 | %clear in - clear input history |
|
741 | %clear in - clear input history | |
748 | %clear shadow_compress - Compresses shadow history (to speed up ipython) |
|
742 | %clear shadow_compress - Compresses shadow history (to speed up ipython) | |
749 | %clear shadow_nuke - permanently erase all entries in shadow history |
|
743 | %clear shadow_nuke - permanently erase all entries in shadow history | |
750 | %clear dhist - clear dir history |
|
744 | %clear dhist - clear dir history | |
751 |
|
745 | |||
752 | **%color_info**:: |
|
746 | **%color_info**:: | |
753 |
|
747 | |||
754 | Toggle color_info. |
|
748 | Toggle color_info. | |
755 |
|
749 | |||
756 | The color_info configuration parameter controls whether colors are |
|
750 | The color_info configuration parameter controls whether colors are | |
757 | used for displaying object details (by things like %psource, %pfile or |
|
751 | used for displaying object details (by things like %psource, %pfile or | |
758 | the '?' system). This function toggles this value with each call. |
|
752 | the '?' system). This function toggles this value with each call. | |
759 |
|
753 | |||
760 | Note that unless you have a fairly recent pager (less works better |
|
754 | Note that unless you have a fairly recent pager (less works better | |
761 | than more) in your system, using colored object information displays |
|
755 | than more) in your system, using colored object information displays | |
762 | will not work properly. Test it and see. |
|
756 | will not work properly. Test it and see. | |
763 |
|
757 | |||
764 | **%colors**:: |
|
758 | **%colors**:: | |
765 |
|
759 | |||
766 | Switch color scheme for prompts, info system and exception handlers. |
|
760 | Switch color scheme for prompts, info system and exception handlers. | |
767 |
|
761 | |||
768 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
762 | Currently implemented schemes: NoColor, Linux, LightBG. | |
769 |
|
763 | |||
770 | Color scheme names are not case-sensitive. |
|
764 | Color scheme names are not case-sensitive. | |
771 |
|
765 | |||
772 | **%cpaste**:: |
|
766 | **%cpaste**:: | |
773 |
|
767 | |||
774 | Allows you to paste & execute a pre-formatted code block from clipboard |
|
768 | Allows you to paste & execute a pre-formatted code block from clipboard | |
775 |
|
769 | |||
776 | You must terminate the block with '--' (two minus-signs) alone on the |
|
770 | You must terminate the block with '--' (two minus-signs) alone on the | |
777 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
771 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
778 | is the new sentinel for this operation) |
|
772 | is the new sentinel for this operation) | |
779 |
|
773 | |||
780 | The block is dedented prior to execution to enable execution of method |
|
774 | The block is dedented prior to execution to enable execution of method | |
781 | definitions. '>' and '+' characters at the beginning of a line are |
|
775 | definitions. '>' and '+' characters at the beginning of a line are | |
782 | ignored, to allow pasting directly from e-mails or diff files. The |
|
776 | ignored, to allow pasting directly from e-mails or diff files. The | |
783 | executed block is also assigned to variable named 'pasted_block' for |
|
777 | executed block is also assigned to variable named 'pasted_block' for | |
784 | later editing with '%edit pasted_block'. |
|
778 | later editing with '%edit pasted_block'. | |
785 |
|
779 | |||
786 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
780 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
787 | This assigns the pasted block to variable 'foo' as string, without |
|
781 | This assigns the pasted block to variable 'foo' as string, without | |
788 | dedenting or executing it. |
|
782 | dedenting or executing it. | |
789 |
|
783 | |||
790 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
784 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
791 | Just press enter and type -- (and press enter again) and the block |
|
785 | Just press enter and type -- (and press enter again) and the block | |
792 | will be what was just pasted. |
|
786 | will be what was just pasted. | |
793 |
|
787 | |||
794 | IPython statements (magics, shell escapes) are not supported (yet). |
|
788 | IPython statements (magics, shell escapes) are not supported (yet). | |
795 |
|
789 | |||
796 | **%debug**:: |
|
790 | **%debug**:: | |
797 |
|
791 | |||
798 | Activate the interactive debugger in post-mortem mode. |
|
792 | Activate the interactive debugger in post-mortem mode. | |
799 |
|
793 | |||
800 | If an exception has just occurred, this lets you inspect its stack |
|
794 | If an exception has just occurred, this lets you inspect its stack | |
801 | frames interactively. Note that this will always work only on the last |
|
795 | frames interactively. Note that this will always work only on the last | |
802 | traceback that occurred, so you must call this quickly after an |
|
796 | traceback that occurred, so you must call this quickly after an | |
803 | exception that you wish to inspect has fired, because if another one |
|
797 | exception that you wish to inspect has fired, because if another one | |
804 | occurs, it clobbers the previous one. |
|
798 | occurs, it clobbers the previous one. | |
805 |
|
799 | |||
806 | If you want IPython to automatically do this on every exception, see |
|
800 | If you want IPython to automatically do this on every exception, see | |
807 | the %pdb magic for more details. |
|
801 | the %pdb magic for more details. | |
808 |
|
802 | |||
809 | **%dhist**:: |
|
803 | **%dhist**:: | |
810 |
|
804 | |||
811 | Print your history of visited directories. |
|
805 | Print your history of visited directories. | |
812 |
|
806 | |||
813 | %dhist -> print full history\ |
|
807 | %dhist -> print full history\ | |
814 | %dhist n -> print last n entries only\ |
|
808 | %dhist n -> print last n entries only\ | |
815 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\ |
|
809 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\ | |
816 |
|
810 | |||
817 | This history is automatically maintained by the %cd command, and |
|
811 | This history is automatically maintained by the %cd command, and | |
818 | always available as the global list variable _dh. You can use %cd -<n> |
|
812 | always available as the global list variable _dh. You can use %cd -<n> | |
819 | to go to directory number <n>. |
|
813 | to go to directory number <n>. | |
820 |
|
814 | |||
821 | Note that most of time, you should view directory history by entering |
|
815 | Note that most of time, you should view directory history by entering | |
822 | cd -<TAB>. |
|
816 | cd -<TAB>. | |
823 |
|
817 | |||
824 | **%dirs**:: |
|
818 | **%dirs**:: | |
825 |
|
819 | |||
826 | Return the current directory stack. |
|
820 | Return the current directory stack. | |
827 |
|
821 | |||
828 | **%doctest_mode**:: |
|
822 | **%doctest_mode**:: | |
829 |
|
823 | |||
830 | Toggle doctest mode on and off. |
|
824 | Toggle doctest mode on and off. | |
831 |
|
825 | |||
832 | This mode allows you to toggle the prompt behavior between normal |
|
826 | This mode allows you to toggle the prompt behavior between normal | |
833 | IPython prompts and ones that are as similar to the default IPython |
|
827 | IPython prompts and ones that are as similar to the default IPython | |
834 | interpreter as possible. |
|
828 | interpreter as possible. | |
835 |
|
829 | |||
836 | It also supports the pasting of code snippets that have leading '>>>' |
|
830 | It also supports the pasting of code snippets that have leading '>>>' | |
837 | and '...' prompts in them. This means that you can paste doctests from |
|
831 | and '...' prompts in them. This means that you can paste doctests from | |
838 | files or docstrings (even if they have leading whitespace), and the |
|
832 | files or docstrings (even if they have leading whitespace), and the | |
839 | code will execute correctly. You can then use '%history -tn' to see |
|
833 | code will execute correctly. You can then use '%history -tn' to see | |
840 | the translated history without line numbers; this will give you the |
|
834 | the translated history without line numbers; this will give you the | |
841 | input after removal of all the leading prompts and whitespace, which |
|
835 | input after removal of all the leading prompts and whitespace, which | |
842 | can be pasted back into an editor. |
|
836 | can be pasted back into an editor. | |
843 |
|
837 | |||
844 | With these features, you can switch into this mode easily whenever you |
|
838 | With these features, you can switch into this mode easily whenever you | |
845 | need to do testing and changes to doctests, without having to leave |
|
839 | need to do testing and changes to doctests, without having to leave | |
846 | your existing IPython session. |
|
840 | your existing IPython session. | |
847 |
|
841 | |||
848 | **%ed**:: |
|
842 | **%ed**:: | |
849 |
|
843 | |||
850 | Alias to %edit. |
|
844 | Alias to %edit. | |
851 |
|
845 | |||
852 | **%edit**:: |
|
846 | **%edit**:: | |
853 |
|
847 | |||
854 | Bring up an editor and execute the resulting code. |
|
848 | Bring up an editor and execute the resulting code. | |
855 |
|
849 | |||
856 | Usage: |
|
850 | Usage: | |
857 | %edit [options] [args] |
|
851 | %edit [options] [args] | |
858 |
|
852 | |||
859 | %edit runs IPython's editor hook. The default version of this hook is |
|
853 | %edit runs IPython's editor hook. The default version of this hook is | |
860 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
854 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
861 | environment variable $EDITOR. If this isn't found, it will default to |
|
855 | environment variable $EDITOR. If this isn't found, it will default to | |
862 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
856 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
863 | docstring for how to change the editor hook. |
|
857 | docstring for how to change the editor hook. | |
864 |
|
858 | |||
865 | You can also set the value of this editor via the command line option |
|
859 | You can also set the value of this editor via the command line option | |
866 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
860 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
867 | specifically for IPython an editor different from your typical default |
|
861 | specifically for IPython an editor different from your typical default | |
868 | (and for Windows users who typically don't set environment variables). |
|
862 | (and for Windows users who typically don't set environment variables). | |
869 |
|
863 | |||
870 | This command allows you to conveniently edit multi-line code right in |
|
864 | This command allows you to conveniently edit multi-line code right in | |
871 | your IPython session. |
|
865 | your IPython session. | |
872 |
|
866 | |||
873 | If called without arguments, %edit opens up an empty editor with a |
|
867 | If called without arguments, %edit opens up an empty editor with a | |
874 | temporary file and will execute the contents of this file when you |
|
868 | temporary file and will execute the contents of this file when you | |
875 | close it (don't forget to save it!). |
|
869 | close it (don't forget to save it!). | |
876 |
|
870 | |||
877 |
|
871 | |||
878 | Options: |
|
872 | Options: | |
879 |
|
873 | |||
880 | -n <number>: open the editor at a specified line number. By default, |
|
874 | -n <number>: open the editor at a specified line number. By default, | |
881 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
875 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
882 | you can configure this by providing your own modified hook if your |
|
876 | you can configure this by providing your own modified hook if your | |
883 | favorite editor supports line-number specifications with a different |
|
877 | favorite editor supports line-number specifications with a different | |
884 | syntax. |
|
878 | syntax. | |
885 |
|
879 | |||
886 | -p: this will call the editor with the same data as the previous time |
|
880 | -p: this will call the editor with the same data as the previous time | |
887 | it was used, regardless of how long ago (in your current session) it |
|
881 | it was used, regardless of how long ago (in your current session) it | |
888 | was. |
|
882 | was. | |
889 |
|
883 | |||
890 | -r: use 'raw' input. This option only applies to input taken from the |
|
884 | -r: use 'raw' input. This option only applies to input taken from the | |
891 | user's history. By default, the 'processed' history is used, so that |
|
885 | user's history. By default, the 'processed' history is used, so that | |
892 | magics are loaded in their transformed version to valid Python. If |
|
886 | magics are loaded in their transformed version to valid Python. If | |
893 | this option is given, the raw input as typed as the command line is |
|
887 | this option is given, the raw input as typed as the command line is | |
894 | used instead. When you exit the editor, it will be executed by |
|
888 | used instead. When you exit the editor, it will be executed by | |
895 | IPython's own processor. |
|
889 | IPython's own processor. | |
896 |
|
890 | |||
897 | -x: do not execute the edited code immediately upon exit. This is |
|
891 | -x: do not execute the edited code immediately upon exit. This is | |
898 | mainly useful if you are editing programs which need to be called with |
|
892 | mainly useful if you are editing programs which need to be called with | |
899 | command line arguments, which you can then do using %run. |
|
893 | command line arguments, which you can then do using %run. | |
900 |
|
894 | |||
901 |
|
895 | |||
902 | Arguments: |
|
896 | Arguments: | |
903 |
|
897 | |||
904 | If arguments are given, the following possibilites exist: |
|
898 | If arguments are given, the following possibilites exist: | |
905 |
|
899 | |||
906 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
900 | - The arguments are numbers or pairs of colon-separated numbers (like | |
907 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
901 | 1 4:8 9). These are interpreted as lines of previous input to be | |
908 | loaded into the editor. The syntax is the same of the %macro command. |
|
902 | loaded into the editor. The syntax is the same of the %macro command. | |
909 |
|
903 | |||
910 | - If the argument doesn't start with a number, it is evaluated as a |
|
904 | - If the argument doesn't start with a number, it is evaluated as a | |
911 | variable and its contents loaded into the editor. You can thus edit |
|
905 | variable and its contents loaded into the editor. You can thus edit | |
912 | any string which contains python code (including the result of |
|
906 | any string which contains python code (including the result of | |
913 | previous edits). |
|
907 | previous edits). | |
914 |
|
908 | |||
915 | - If the argument is the name of an object (other than a string), |
|
909 | - If the argument is the name of an object (other than a string), | |
916 | IPython will try to locate the file where it was defined and open the |
|
910 | IPython will try to locate the file where it was defined and open the | |
917 | editor at the point where it is defined. You can use `%edit function` |
|
911 | editor at the point where it is defined. You can use `%edit function` | |
918 | to load an editor exactly at the point where 'function' is defined, |
|
912 | to load an editor exactly at the point where 'function' is defined, | |
919 | edit it and have the file be executed automatically. |
|
913 | edit it and have the file be executed automatically. | |
920 |
|
914 | |||
921 | If the object is a macro (see %macro for details), this opens up your |
|
915 | If the object is a macro (see %macro for details), this opens up your | |
922 | specified editor with a temporary file containing the macro's data. |
|
916 | specified editor with a temporary file containing the macro's data. | |
923 | Upon exit, the macro is reloaded with the contents of the file. |
|
917 | Upon exit, the macro is reloaded with the contents of the file. | |
924 |
|
918 | |||
925 | Note: opening at an exact line is only supported under Unix, and some |
|
919 | Note: opening at an exact line is only supported under Unix, and some | |
926 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
920 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
927 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
921 | '+NUMBER' parameter necessary for this feature. Good editors like | |
928 | (X)Emacs, vi, jed, pico and joe all do. |
|
922 | (X)Emacs, vi, jed, pico and joe all do. | |
929 |
|
923 | |||
930 | - If the argument is not found as a variable, IPython will look for a |
|
924 | - If the argument is not found as a variable, IPython will look for a | |
931 | file with that name (adding .py if necessary) and load it into the |
|
925 | file with that name (adding .py if necessary) and load it into the | |
932 | editor. It will execute its contents with execfile() when you exit, |
|
926 | editor. It will execute its contents with execfile() when you exit, | |
933 | loading any code in the file into your interactive namespace. |
|
927 | loading any code in the file into your interactive namespace. | |
934 |
|
928 | |||
935 | After executing your code, %edit will return as output the code you |
|
929 | After executing your code, %edit will return as output the code you | |
936 | typed in the editor (except when it was an existing file). This way |
|
930 | typed in the editor (except when it was an existing file). This way | |
937 | you can reload the code in further invocations of %edit as a variable, |
|
931 | you can reload the code in further invocations of %edit as a variable, | |
938 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
932 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
939 | the output. |
|
933 | the output. | |
940 |
|
934 | |||
941 | Note that %edit is also available through the alias %ed. |
|
935 | Note that %edit is also available through the alias %ed. | |
942 |
|
936 | |||
943 | This is an example of creating a simple function inside the editor and |
|
937 | This is an example of creating a simple function inside the editor and | |
944 | then modifying it. First, start up the editor: |
|
938 | then modifying it. First, start up the editor: | |
945 |
|
939 | |||
946 | In [1]: ed\ |
|
940 | In [1]: ed\ | |
947 | Editing... done. Executing edited code...\ |
|
941 | Editing... done. Executing edited code...\ | |
948 | Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n' |
|
942 | Out[1]: 'def foo():\n print "foo() was defined in an editing session"\n' | |
949 |
|
943 | |||
950 | We can then call the function foo(): |
|
944 | We can then call the function foo(): | |
951 |
|
945 | |||
952 | In [2]: foo()\ |
|
946 | In [2]: foo()\ | |
953 | foo() was defined in an editing session |
|
947 | foo() was defined in an editing session | |
954 |
|
948 | |||
955 | Now we edit foo. IPython automatically loads the editor with the |
|
949 | Now we edit foo. IPython automatically loads the editor with the | |
956 | (temporary) file where foo() was previously defined: |
|
950 | (temporary) file where foo() was previously defined: | |
957 |
|
951 | |||
958 | In [3]: ed foo\ |
|
952 | In [3]: ed foo\ | |
959 | Editing... done. Executing edited code... |
|
953 | Editing... done. Executing edited code... | |
960 |
|
954 | |||
961 | And if we call foo() again we get the modified version: |
|
955 | And if we call foo() again we get the modified version: | |
962 |
|
956 | |||
963 | In [4]: foo()\ |
|
957 | In [4]: foo()\ | |
964 | foo() has now been changed! |
|
958 | foo() has now been changed! | |
965 |
|
959 | |||
966 | Here is an example of how to edit a code snippet successive |
|
960 | Here is an example of how to edit a code snippet successive | |
967 | times. First we call the editor: |
|
961 | times. First we call the editor: | |
968 |
|
962 | |||
969 | In [8]: ed\ |
|
963 | In [8]: ed\ | |
970 | Editing... done. Executing edited code...\ |
|
964 | Editing... done. Executing edited code...\ | |
971 | hello\ |
|
965 | hello\ | |
972 | Out[8]: "print 'hello'\n" |
|
966 | Out[8]: "print 'hello'\n" | |
973 |
|
967 | |||
974 | Now we call it again with the previous output (stored in _): |
|
968 | Now we call it again with the previous output (stored in _): | |
975 |
|
969 | |||
976 | In [9]: ed _\ |
|
970 | In [9]: ed _\ | |
977 | Editing... done. Executing edited code...\ |
|
971 | Editing... done. Executing edited code...\ | |
978 | hello world\ |
|
972 | hello world\ | |
979 | Out[9]: "print 'hello world'\n" |
|
973 | Out[9]: "print 'hello world'\n" | |
980 |
|
974 | |||
981 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
975 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
982 |
|
976 | |||
983 | In [10]: ed _8\ |
|
977 | In [10]: ed _8\ | |
984 | Editing... done. Executing edited code...\ |
|
978 | Editing... done. Executing edited code...\ | |
985 | hello again\ |
|
979 | hello again\ | |
986 | Out[10]: "print 'hello again'\n" |
|
980 | Out[10]: "print 'hello again'\n" | |
987 |
|
981 | |||
988 |
|
982 | |||
989 | Changing the default editor hook: |
|
983 | Changing the default editor hook: | |
990 |
|
984 | |||
991 | If you wish to write your own editor hook, you can put it in a |
|
985 | If you wish to write your own editor hook, you can put it in a | |
992 | configuration file which you load at startup time. The default hook |
|
986 | configuration file which you load at startup time. The default hook | |
993 | is defined in the IPython.hooks module, and you can use that as a |
|
987 | is defined in the IPython.hooks module, and you can use that as a | |
994 | starting example for further modifications. That file also has |
|
988 | starting example for further modifications. That file also has | |
995 | general instructions on how to set a new hook for use once you've |
|
989 | general instructions on how to set a new hook for use once you've | |
996 | defined it. |
|
990 | defined it. | |
997 |
|
991 | |||
998 | **%env**:: |
|
992 | **%env**:: | |
999 |
|
993 | |||
1000 | List environment variables. |
|
994 | List environment variables. | |
1001 |
|
995 | |||
1002 | **%exit**:: |
|
996 | **%exit**:: | |
1003 |
|
997 | |||
1004 | Exit IPython, confirming if configured to do so. |
|
998 | Exit IPython, confirming if configured to do so. | |
1005 |
|
999 | |||
1006 | You can configure whether IPython asks for confirmation upon exit by |
|
1000 | You can configure whether IPython asks for confirmation upon exit by | |
1007 | setting the confirm_exit flag in the ipythonrc file. |
|
1001 | setting the confirm_exit flag in the ipythonrc file. | |
1008 |
|
1002 | |||
1009 | **%hist**:: |
|
1003 | **%hist**:: | |
1010 |
|
1004 | |||
1011 | Alternate name for %history. |
|
1005 | Alternate name for %history. | |
1012 |
|
1006 | |||
1013 | **%history**:: |
|
1007 | **%history**:: | |
1014 |
|
1008 | |||
1015 | Print input history (_i<n> variables), with most recent last. |
|
1009 | Print input history (_i<n> variables), with most recent last. | |
1016 |
|
1010 | |||
1017 | %history -> print at most 40 inputs (some may be multi-line)\ |
|
1011 | %history -> print at most 40 inputs (some may be multi-line)\ | |
1018 | %history n -> print at most n inputs\ |
|
1012 | %history n -> print at most n inputs\ | |
1019 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\ |
|
1013 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\ | |
1020 |
|
1014 | |||
1021 | Each input's number <n> is shown, and is accessible as the |
|
1015 | Each input's number <n> is shown, and is accessible as the | |
1022 | automatically generated variable _i<n>. Multi-line statements are |
|
1016 | automatically generated variable _i<n>. Multi-line statements are | |
1023 | printed starting at a new line for easy copy/paste. |
|
1017 | printed starting at a new line for easy copy/paste. | |
1024 |
|
1018 | |||
1025 |
|
1019 | |||
1026 | Options: |
|
1020 | Options: | |
1027 |
|
1021 | |||
1028 | -n: do NOT print line numbers. This is useful if you want to get a |
|
1022 | -n: do NOT print line numbers. This is useful if you want to get a | |
1029 | printout of many lines which can be directly pasted into a text |
|
1023 | printout of many lines which can be directly pasted into a text | |
1030 | editor. |
|
1024 | editor. | |
1031 |
|
1025 | |||
1032 | This feature is only available if numbered prompts are in use. |
|
1026 | This feature is only available if numbered prompts are in use. | |
1033 |
|
1027 | |||
1034 | -t: (default) print the 'translated' history, as IPython understands it. |
|
1028 | -t: (default) print the 'translated' history, as IPython understands it. | |
1035 | IPython filters your input and converts it all into valid Python source |
|
1029 | IPython filters your input and converts it all into valid Python source | |
1036 | before executing it (things like magics or aliases are turned into |
|
1030 | before executing it (things like magics or aliases are turned into | |
1037 | function calls, for example). With this option, you'll see the native |
|
1031 | function calls, for example). With this option, you'll see the native | |
1038 | history instead of the user-entered version: '%cd /' will be seen as |
|
1032 | history instead of the user-entered version: '%cd /' will be seen as | |
1039 | '_ip.magic("%cd /")' instead of '%cd /'. |
|
1033 | '_ip.magic("%cd /")' instead of '%cd /'. | |
1040 |
|
1034 | |||
1041 | -r: print the 'raw' history, i.e. the actual commands you typed. |
|
1035 | -r: print the 'raw' history, i.e. the actual commands you typed. | |
1042 |
|
1036 | |||
1043 | -g: treat the arg as a pattern to grep for in (full) history. |
|
1037 | -g: treat the arg as a pattern to grep for in (full) history. | |
1044 | This includes the "shadow history" (almost all commands ever written). |
|
1038 | This includes the "shadow history" (almost all commands ever written). | |
1045 | Use '%hist -g' to show full shadow history (may be very long). |
|
1039 | Use '%hist -g' to show full shadow history (may be very long). | |
1046 | In shadow history, every index nuwber starts with 0. |
|
1040 | In shadow history, every index nuwber starts with 0. | |
1047 |
|
1041 | |||
1048 | -f FILENAME: instead of printing the output to the screen, redirect it to |
|
1042 | -f FILENAME: instead of printing the output to the screen, redirect it to | |
1049 | the given file. The file is always overwritten, though IPython asks for |
|
1043 | the given file. The file is always overwritten, though IPython asks for | |
1050 | confirmation first if it already exists. |
|
1044 | confirmation first if it already exists. | |
1051 |
|
1045 | |||
1052 | **%logoff**:: |
|
1046 | **%logoff**:: | |
1053 |
|
1047 | |||
1054 | Temporarily stop logging. |
|
1048 | Temporarily stop logging. | |
1055 |
|
1049 | |||
1056 | You must have previously started logging. |
|
1050 | You must have previously started logging. | |
1057 |
|
1051 | |||
1058 | **%logon**:: |
|
1052 | **%logon**:: | |
1059 |
|
1053 | |||
1060 | Restart logging. |
|
1054 | Restart logging. | |
1061 |
|
1055 | |||
1062 | This function is for restarting logging which you've temporarily |
|
1056 | This function is for restarting logging which you've temporarily | |
1063 | stopped with %logoff. For starting logging for the first time, you |
|
1057 | stopped with %logoff. For starting logging for the first time, you | |
1064 | must use the %logstart function, which allows you to specify an |
|
1058 | must use the %logstart function, which allows you to specify an | |
1065 | optional log filename. |
|
1059 | optional log filename. | |
1066 |
|
1060 | |||
1067 | **%logstart**:: |
|
1061 | **%logstart**:: | |
1068 |
|
1062 | |||
1069 | Start logging anywhere in a session. |
|
1063 | Start logging anywhere in a session. | |
1070 |
|
1064 | |||
1071 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1065 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1072 |
|
1066 | |||
1073 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1067 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1074 | current directory, in 'rotate' mode (see below). |
|
1068 | current directory, in 'rotate' mode (see below). | |
1075 |
|
1069 | |||
1076 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1070 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1077 | history up to that point and then continues logging. |
|
1071 | history up to that point and then continues logging. | |
1078 |
|
1072 | |||
1079 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1073 | %logstart takes a second optional parameter: logging mode. This can be one | |
1080 | of (note that the modes are given unquoted):\ |
|
1074 | of (note that the modes are given unquoted):\ | |
1081 | append: well, that says it.\ |
|
1075 | append: well, that says it.\ | |
1082 | backup: rename (if exists) to name~ and start name.\ |
|
1076 | backup: rename (if exists) to name~ and start name.\ | |
1083 | global: single logfile in your home dir, appended to.\ |
|
1077 | global: single logfile in your home dir, appended to.\ | |
1084 | over : overwrite existing log.\ |
|
1078 | over : overwrite existing log.\ | |
1085 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1079 | rotate: create rotating logs name.1~, name.2~, etc. | |
1086 |
|
1080 | |||
1087 | Options: |
|
1081 | Options: | |
1088 |
|
1082 | |||
1089 | -o: log also IPython's output. In this mode, all commands which |
|
1083 | -o: log also IPython's output. In this mode, all commands which | |
1090 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1084 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1091 | their corresponding input line. The output lines are always |
|
1085 | their corresponding input line. The output lines are always | |
1092 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1086 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1093 | Python code. |
|
1087 | Python code. | |
1094 |
|
1088 | |||
1095 | Since this marker is always the same, filtering only the output from |
|
1089 | Since this marker is always the same, filtering only the output from | |
1096 | a log is very easy, using for example a simple awk call: |
|
1090 | a log is very easy, using for example a simple awk call: | |
1097 |
|
1091 | |||
1098 | awk -F'#\[Out\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1092 | awk -F'#\[Out\]# ' '{if($2) {print $2}}' ipython_log.py | |
1099 |
|
1093 | |||
1100 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1094 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1101 | input, so that user lines are logged in their final form, converted |
|
1095 | input, so that user lines are logged in their final form, converted | |
1102 | into valid Python. For example, %Exit is logged as |
|
1096 | into valid Python. For example, %Exit is logged as | |
1103 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1097 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1104 | exactly as typed, with no transformations applied. |
|
1098 | exactly as typed, with no transformations applied. | |
1105 |
|
1099 | |||
1106 | -t: put timestamps before each input line logged (these are put in |
|
1100 | -t: put timestamps before each input line logged (these are put in | |
1107 | comments). |
|
1101 | comments). | |
1108 |
|
1102 | |||
1109 | **%logstate**:: |
|
1103 | **%logstate**:: | |
1110 |
|
1104 | |||
1111 | Print the status of the logging system. |
|
1105 | Print the status of the logging system. | |
1112 |
|
1106 | |||
1113 | **%logstop**:: |
|
1107 | **%logstop**:: | |
1114 |
|
1108 | |||
1115 | Fully stop logging and close log file. |
|
1109 | Fully stop logging and close log file. | |
1116 |
|
1110 | |||
1117 | In order to start logging again, a new %logstart call needs to be made, |
|
1111 | In order to start logging again, a new %logstart call needs to be made, | |
1118 | possibly (though not necessarily) with a new filename, mode and other |
|
1112 | possibly (though not necessarily) with a new filename, mode and other | |
1119 | options. |
|
1113 | options. | |
1120 |
|
1114 | |||
1121 | **%lsmagic**:: |
|
1115 | **%lsmagic**:: | |
1122 |
|
1116 | |||
1123 | List currently available magic functions. |
|
1117 | List currently available magic functions. | |
1124 |
|
1118 | |||
1125 | **%macro**:: |
|
1119 | **%macro**:: | |
1126 |
|
1120 | |||
1127 | Define a set of input lines as a macro for future re-execution. |
|
1121 | Define a set of input lines as a macro for future re-execution. | |
1128 |
|
1122 | |||
1129 | Usage:\ |
|
1123 | Usage:\ | |
1130 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1124 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1131 |
|
1125 | |||
1132 | Options: |
|
1126 | Options: | |
1133 |
|
1127 | |||
1134 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1128 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1135 | so that magics are loaded in their transformed version to valid |
|
1129 | so that magics are loaded in their transformed version to valid | |
1136 | Python. If this option is given, the raw input as typed as the |
|
1130 | Python. If this option is given, the raw input as typed as the | |
1137 | command line is used instead. |
|
1131 | command line is used instead. | |
1138 |
|
1132 | |||
1139 | This will define a global variable called `name` which is a string |
|
1133 | This will define a global variable called `name` which is a string | |
1140 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1134 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1141 | above) from your input history into a single string. This variable |
|
1135 | above) from your input history into a single string. This variable | |
1142 | acts like an automatic function which re-executes those lines as if |
|
1136 | acts like an automatic function which re-executes those lines as if | |
1143 | you had typed them. You just type 'name' at the prompt and the code |
|
1137 | you had typed them. You just type 'name' at the prompt and the code | |
1144 | executes. |
|
1138 | executes. | |
1145 |
|
1139 | |||
1146 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1140 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1147 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1141 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1148 | using the lines numbered 5,6 and 7. |
|
1142 | using the lines numbered 5,6 and 7. | |
1149 |
|
1143 | |||
1150 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1144 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1151 | notation, where N:M means numbers N through M-1. |
|
1145 | notation, where N:M means numbers N through M-1. | |
1152 |
|
1146 | |||
1153 | For example, if your history contains (%hist prints it): |
|
1147 | For example, if your history contains (%hist prints it): | |
1154 |
|
1148 | |||
1155 | 44: x=1\ |
|
1149 | 44: x=1\ | |
1156 | 45: y=3\ |
|
1150 | 45: y=3\ | |
1157 | 46: z=x+y\ |
|
1151 | 46: z=x+y\ | |
1158 | 47: print x\ |
|
1152 | 47: print x\ | |
1159 | 48: a=5\ |
|
1153 | 48: a=5\ | |
1160 | 49: print 'x',x,'y',y\ |
|
1154 | 49: print 'x',x,'y',y\ | |
1161 |
|
1155 | |||
1162 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1156 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1163 | called my_macro with: |
|
1157 | called my_macro with: | |
1164 |
|
1158 | |||
1165 | In [51]: %macro my_macro 44-47 49 |
|
1159 | In [51]: %macro my_macro 44-47 49 | |
1166 |
|
1160 | |||
1167 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1161 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1168 | in one pass. |
|
1162 | in one pass. | |
1169 |
|
1163 | |||
1170 | You don't need to give the line-numbers in order, and any given line |
|
1164 | You don't need to give the line-numbers in order, and any given line | |
1171 | number can appear multiple times. You can assemble macros with any |
|
1165 | number can appear multiple times. You can assemble macros with any | |
1172 | lines from your input history in any order. |
|
1166 | lines from your input history in any order. | |
1173 |
|
1167 | |||
1174 | The macro is a simple object which holds its value in an attribute, |
|
1168 | The macro is a simple object which holds its value in an attribute, | |
1175 | but IPython's display system checks for macros and executes them as |
|
1169 | but IPython's display system checks for macros and executes them as | |
1176 | code instead of printing them when you type their name. |
|
1170 | code instead of printing them when you type their name. | |
1177 |
|
1171 | |||
1178 | You can view a macro's contents by explicitly printing it with: |
|
1172 | You can view a macro's contents by explicitly printing it with: | |
1179 |
|
1173 | |||
1180 | 'print macro_name'. |
|
1174 | 'print macro_name'. | |
1181 |
|
1175 | |||
1182 | For one-off cases which DON'T contain magic function calls in them you |
|
1176 | For one-off cases which DON'T contain magic function calls in them you | |
1183 | can obtain similar results by explicitly executing slices from your |
|
1177 | can obtain similar results by explicitly executing slices from your | |
1184 | input history with: |
|
1178 | input history with: | |
1185 |
|
1179 | |||
1186 | In [60]: exec In[44:48]+In[49] |
|
1180 | In [60]: exec In[44:48]+In[49] | |
1187 |
|
1181 | |||
1188 | **%magic**:: |
|
1182 | **%magic**:: | |
1189 |
|
1183 | |||
1190 | Print information about the magic function system. |
|
1184 | Print information about the magic function system. | |
1191 |
|
1185 | |||
1192 | **%mglob**:: |
|
1186 | **%mglob**:: | |
1193 |
|
1187 | |||
1194 | This program allows specifying filenames with "mglob" mechanism. |
|
1188 | This program allows specifying filenames with "mglob" mechanism. | |
1195 | Supported syntax in globs (wilcard matching patterns):: |
|
1189 | Supported syntax in globs (wilcard matching patterns):: | |
1196 |
|
1190 | |||
1197 | *.cpp ?ellowo* |
|
1191 | *.cpp ?ellowo* | |
1198 | - obvious. Differs from normal glob in that dirs are not included. |
|
1192 | - obvious. Differs from normal glob in that dirs are not included. | |
1199 | Unix users might want to write this as: "*.cpp" "?ellowo*" |
|
1193 | Unix users might want to write this as: "*.cpp" "?ellowo*" | |
1200 | rec:/usr/share=*.txt,*.doc |
|
1194 | rec:/usr/share=*.txt,*.doc | |
1201 | - get all *.txt and *.doc under /usr/share, |
|
1195 | - get all *.txt and *.doc under /usr/share, | |
1202 | recursively |
|
1196 | recursively | |
1203 | rec:/usr/share |
|
1197 | rec:/usr/share | |
1204 | - All files under /usr/share, recursively |
|
1198 | - All files under /usr/share, recursively | |
1205 | rec:*.py |
|
1199 | rec:*.py | |
1206 | - All .py files under current working dir, recursively |
|
1200 | - All .py files under current working dir, recursively | |
1207 | foo |
|
1201 | foo | |
1208 | - File or dir foo |
|
1202 | - File or dir foo | |
1209 | !*.bak readme* |
|
1203 | !*.bak readme* | |
1210 | - readme*, exclude files ending with .bak |
|
1204 | - readme*, exclude files ending with .bak | |
1211 | !.svn/ !.hg/ !*_Data/ rec:. |
|
1205 | !.svn/ !.hg/ !*_Data/ rec:. | |
1212 | - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse. |
|
1206 | - Skip .svn, .hg, foo_Data dirs (and their subdirs) in recurse. | |
1213 | Trailing / is the key, \ does not work! |
|
1207 | Trailing / is the key, \ does not work! | |
1214 | dir:foo |
|
1208 | dir:foo | |
1215 | - the directory foo if it exists (not files in foo) |
|
1209 | - the directory foo if it exists (not files in foo) | |
1216 | dir:* |
|
1210 | dir:* | |
1217 | - all directories in current folder |
|
1211 | - all directories in current folder | |
1218 | foo.py bar.* !h* rec:*.py |
|
1212 | foo.py bar.* !h* rec:*.py | |
1219 | - Obvious. !h* exclusion only applies for rec:*.py. |
|
1213 | - Obvious. !h* exclusion only applies for rec:*.py. | |
1220 | foo.py is *not* included twice. |
|
1214 | foo.py is *not* included twice. | |
1221 | @filelist.txt |
|
1215 | @filelist.txt | |
1222 | - All files listed in 'filelist.txt' file, on separate lines. |
|
1216 | - All files listed in 'filelist.txt' file, on separate lines. | |
1223 |
|
1217 | |||
1224 | **%page**:: |
|
1218 | **%page**:: | |
1225 |
|
1219 | |||
1226 | Pretty print the object and display it through a pager. |
|
1220 | Pretty print the object and display it through a pager. | |
1227 |
|
1221 | |||
1228 | %page [options] OBJECT |
|
1222 | %page [options] OBJECT | |
1229 |
|
1223 | |||
1230 | If no object is given, use _ (last output). |
|
1224 | If no object is given, use _ (last output). | |
1231 |
|
1225 | |||
1232 | Options: |
|
1226 | Options: | |
1233 |
|
1227 | |||
1234 | -r: page str(object), don't pretty-print it. |
|
1228 | -r: page str(object), don't pretty-print it. | |
1235 |
|
1229 | |||
1236 | **%pdb**:: |
|
1230 | **%pdb**:: | |
1237 |
|
1231 | |||
1238 | Control the automatic calling of the pdb interactive debugger. |
|
1232 | Control the automatic calling of the pdb interactive debugger. | |
1239 |
|
1233 | |||
1240 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1234 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1241 | argument it works as a toggle. |
|
1235 | argument it works as a toggle. | |
1242 |
|
1236 | |||
1243 | When an exception is triggered, IPython can optionally call the |
|
1237 | When an exception is triggered, IPython can optionally call the | |
1244 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1238 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1245 | this feature on and off. |
|
1239 | this feature on and off. | |
1246 |
|
1240 | |||
1247 | The initial state of this feature is set in your ipythonrc |
|
1241 | The initial state of this feature is set in your ipythonrc | |
1248 | configuration file (the variable is called 'pdb'). |
|
1242 | configuration file (the variable is called 'pdb'). | |
1249 |
|
1243 | |||
1250 | If you want to just activate the debugger AFTER an exception has fired, |
|
1244 | If you want to just activate the debugger AFTER an exception has fired, | |
1251 | without having to type '%pdb on' and rerunning your code, you can use |
|
1245 | without having to type '%pdb on' and rerunning your code, you can use | |
1252 | the %debug magic. |
|
1246 | the %debug magic. | |
1253 |
|
1247 | |||
1254 | **%pdef**:: |
|
1248 | **%pdef**:: | |
1255 |
|
1249 | |||
1256 | Print the definition header for any callable object. |
|
1250 | Print the definition header for any callable object. | |
1257 |
|
1251 | |||
1258 | If the object is a class, print the constructor information. |
|
1252 | If the object is a class, print the constructor information. | |
1259 |
|
1253 | |||
1260 | **%pdoc**:: |
|
1254 | **%pdoc**:: | |
1261 |
|
1255 | |||
1262 | Print the docstring for an object. |
|
1256 | Print the docstring for an object. | |
1263 |
|
1257 | |||
1264 | If the given object is a class, it will print both the class and the |
|
1258 | If the given object is a class, it will print both the class and the | |
1265 | constructor docstrings. |
|
1259 | constructor docstrings. | |
1266 |
|
1260 | |||
1267 | **%pfile**:: |
|
1261 | **%pfile**:: | |
1268 |
|
1262 | |||
1269 | Print (or run through pager) the file where an object is defined. |
|
1263 | Print (or run through pager) the file where an object is defined. | |
1270 |
|
1264 | |||
1271 | The file opens at the line where the object definition begins. IPython |
|
1265 | The file opens at the line where the object definition begins. IPython | |
1272 | will honor the environment variable PAGER if set, and otherwise will |
|
1266 | will honor the environment variable PAGER if set, and otherwise will | |
1273 | do its best to print the file in a convenient form. |
|
1267 | do its best to print the file in a convenient form. | |
1274 |
|
1268 | |||
1275 | If the given argument is not an object currently defined, IPython will |
|
1269 | If the given argument is not an object currently defined, IPython will | |
1276 | try to interpret it as a filename (automatically adding a .py extension |
|
1270 | try to interpret it as a filename (automatically adding a .py extension | |
1277 | if needed). You can thus use %pfile as a syntax highlighting code |
|
1271 | if needed). You can thus use %pfile as a syntax highlighting code | |
1278 | viewer. |
|
1272 | viewer. | |
1279 |
|
1273 | |||
1280 | **%pinfo**:: |
|
1274 | **%pinfo**:: | |
1281 |
|
1275 | |||
1282 | Provide detailed information about an object. |
|
1276 | Provide detailed information about an object. | |
1283 |
|
1277 | |||
1284 | '%pinfo object' is just a synonym for object? or ?object. |
|
1278 | '%pinfo object' is just a synonym for object? or ?object. | |
1285 |
|
1279 | |||
1286 | **%popd**:: |
|
1280 | **%popd**:: | |
1287 |
|
1281 | |||
1288 | Change to directory popped off the top of the stack. |
|
1282 | Change to directory popped off the top of the stack. | |
1289 |
|
1283 | |||
1290 | **%profile**:: |
|
1284 | **%profile**:: | |
1291 |
|
1285 | |||
1292 | Print your currently active IPyhton profile. |
|
1286 | Print your currently active IPyhton profile. | |
1293 |
|
1287 | |||
1294 | **%prun**:: |
|
1288 | **%prun**:: | |
1295 |
|
1289 | |||
1296 | Run a statement through the python code profiler. |
|
1290 | Run a statement through the python code profiler. | |
1297 |
|
1291 | |||
1298 | Usage:\ |
|
1292 | Usage:\ | |
1299 | %prun [options] statement |
|
1293 | %prun [options] statement | |
1300 |
|
1294 | |||
1301 | The given statement (which doesn't require quote marks) is run via the |
|
1295 | The given statement (which doesn't require quote marks) is run via the | |
1302 | python profiler in a manner similar to the profile.run() function. |
|
1296 | python profiler in a manner similar to the profile.run() function. | |
1303 | Namespaces are internally managed to work correctly; profile.run |
|
1297 | Namespaces are internally managed to work correctly; profile.run | |
1304 | cannot be used in IPython because it makes certain assumptions about |
|
1298 | cannot be used in IPython because it makes certain assumptions about | |
1305 | namespaces which do not hold under IPython. |
|
1299 | namespaces which do not hold under IPython. | |
1306 |
|
1300 | |||
1307 | Options: |
|
1301 | Options: | |
1308 |
|
1302 | |||
1309 | -l <limit>: you can place restrictions on what or how much of the |
|
1303 | -l <limit>: you can place restrictions on what or how much of the | |
1310 | profile gets printed. The limit value can be: |
|
1304 | profile gets printed. The limit value can be: | |
1311 |
|
1305 | |||
1312 | * A string: only information for function names containing this string |
|
1306 | * A string: only information for function names containing this string | |
1313 | is printed. |
|
1307 | is printed. | |
1314 |
|
1308 | |||
1315 | * An integer: only these many lines are printed. |
|
1309 | * An integer: only these many lines are printed. | |
1316 |
|
1310 | |||
1317 | * A float (between 0 and 1): this fraction of the report is printed |
|
1311 | * A float (between 0 and 1): this fraction of the report is printed | |
1318 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1312 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1319 |
|
1313 | |||
1320 | You can combine several limits with repeated use of the option. For |
|
1314 | You can combine several limits with repeated use of the option. For | |
1321 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1315 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1322 | information about class constructors. |
|
1316 | information about class constructors. | |
1323 |
|
1317 | |||
1324 | -r: return the pstats.Stats object generated by the profiling. This |
|
1318 | -r: return the pstats.Stats object generated by the profiling. This | |
1325 | object has all the information about the profile in it, and you can |
|
1319 | object has all the information about the profile in it, and you can | |
1326 | later use it for further analysis or in other functions. |
|
1320 | later use it for further analysis or in other functions. | |
1327 |
|
1321 | |||
1328 | -s <key>: sort profile by given key. You can provide more than one key |
|
1322 | -s <key>: sort profile by given key. You can provide more than one key | |
1329 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1323 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1330 | default sorting key is 'time'. |
|
1324 | default sorting key is 'time'. | |
1331 |
|
1325 | |||
1332 | The following is copied verbatim from the profile documentation |
|
1326 | The following is copied verbatim from the profile documentation | |
1333 | referenced below: |
|
1327 | referenced below: | |
1334 |
|
1328 | |||
1335 | When more than one key is provided, additional keys are used as |
|
1329 | When more than one key is provided, additional keys are used as | |
1336 | secondary criteria when the there is equality in all keys selected |
|
1330 | secondary criteria when the there is equality in all keys selected | |
1337 | before them. |
|
1331 | before them. | |
1338 |
|
1332 | |||
1339 | Abbreviations can be used for any key names, as long as the |
|
1333 | Abbreviations can be used for any key names, as long as the | |
1340 | abbreviation is unambiguous. The following are the keys currently |
|
1334 | abbreviation is unambiguous. The following are the keys currently | |
1341 | defined: |
|
1335 | defined: | |
1342 |
|
1336 | |||
1343 | Valid Arg Meaning\ |
|
1337 | Valid Arg Meaning\ | |
1344 | "calls" call count\ |
|
1338 | "calls" call count\ | |
1345 | "cumulative" cumulative time\ |
|
1339 | "cumulative" cumulative time\ | |
1346 | "file" file name\ |
|
1340 | "file" file name\ | |
1347 | "module" file name\ |
|
1341 | "module" file name\ | |
1348 | "pcalls" primitive call count\ |
|
1342 | "pcalls" primitive call count\ | |
1349 | "line" line number\ |
|
1343 | "line" line number\ | |
1350 | "name" function name\ |
|
1344 | "name" function name\ | |
1351 | "nfl" name/file/line\ |
|
1345 | "nfl" name/file/line\ | |
1352 | "stdname" standard name\ |
|
1346 | "stdname" standard name\ | |
1353 | "time" internal time |
|
1347 | "time" internal time | |
1354 |
|
1348 | |||
1355 | Note that all sorts on statistics are in descending order (placing |
|
1349 | Note that all sorts on statistics are in descending order (placing | |
1356 | most time consuming items first), where as name, file, and line number |
|
1350 | most time consuming items first), where as name, file, and line number | |
1357 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1351 | searches are in ascending order (i.e., alphabetical). The subtle | |
1358 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1352 | distinction between "nfl" and "stdname" is that the standard name is a | |
1359 | sort of the name as printed, which means that the embedded line |
|
1353 | sort of the name as printed, which means that the embedded line | |
1360 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1354 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1361 | would (if the file names were the same) appear in the string order |
|
1355 | would (if the file names were the same) appear in the string order | |
1362 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1356 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1363 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1357 | line numbers. In fact, sort_stats("nfl") is the same as | |
1364 | sort_stats("name", "file", "line"). |
|
1358 | sort_stats("name", "file", "line"). | |
1365 |
|
1359 | |||
1366 | -T <filename>: save profile results as shown on screen to a text |
|
1360 | -T <filename>: save profile results as shown on screen to a text | |
1367 | file. The profile is still shown on screen. |
|
1361 | file. The profile is still shown on screen. | |
1368 |
|
1362 | |||
1369 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1363 | -D <filename>: save (via dump_stats) profile statistics to given | |
1370 | filename. This data is in a format understod by the pstats module, and |
|
1364 | filename. This data is in a format understod by the pstats module, and | |
1371 | is generated by a call to the dump_stats() method of profile |
|
1365 | is generated by a call to the dump_stats() method of profile | |
1372 | objects. The profile is still shown on screen. |
|
1366 | objects. The profile is still shown on screen. | |
1373 |
|
1367 | |||
1374 | If you want to run complete programs under the profiler's control, use |
|
1368 | If you want to run complete programs under the profiler's control, use | |
1375 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1369 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1376 | contains profiler specific options as described here. |
|
1370 | contains profiler specific options as described here. | |
1377 |
|
1371 | |||
1378 | You can read the complete documentation for the profile module with:\ |
|
1372 | You can read the complete documentation for the profile module with:\ | |
1379 | In [1]: import profile; profile.help() |
|
1373 | In [1]: import profile; profile.help() | |
1380 |
|
1374 | |||
1381 | **%psearch**:: |
|
1375 | **%psearch**:: | |
1382 |
|
1376 | |||
1383 | Search for object in namespaces by wildcard. |
|
1377 | Search for object in namespaces by wildcard. | |
1384 |
|
1378 | |||
1385 | %psearch [options] PATTERN [OBJECT TYPE] |
|
1379 | %psearch [options] PATTERN [OBJECT TYPE] | |
1386 |
|
1380 | |||
1387 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
1381 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
1388 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
1382 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
1389 | rest of the command line must be unchanged (options come first), so |
|
1383 | rest of the command line must be unchanged (options come first), so | |
1390 | for example the following forms are equivalent |
|
1384 | for example the following forms are equivalent | |
1391 |
|
1385 | |||
1392 | %psearch -i a* function |
|
1386 | %psearch -i a* function | |
1393 | -i a* function? |
|
1387 | -i a* function? | |
1394 | ?-i a* function |
|
1388 | ?-i a* function | |
1395 |
|
1389 | |||
1396 | Arguments: |
|
1390 | Arguments: | |
1397 |
|
1391 | |||
1398 | PATTERN |
|
1392 | PATTERN | |
1399 |
|
1393 | |||
1400 | where PATTERN is a string containing * as a wildcard similar to its |
|
1394 | where PATTERN is a string containing * as a wildcard similar to its | |
1401 | use in a shell. The pattern is matched in all namespaces on the |
|
1395 | use in a shell. The pattern is matched in all namespaces on the | |
1402 | search path. By default objects starting with a single _ are not |
|
1396 | search path. By default objects starting with a single _ are not | |
1403 | matched, many IPython generated objects have a single |
|
1397 | matched, many IPython generated objects have a single | |
1404 | underscore. The default is case insensitive matching. Matching is |
|
1398 | underscore. The default is case insensitive matching. Matching is | |
1405 | also done on the attributes of objects and not only on the objects |
|
1399 | also done on the attributes of objects and not only on the objects | |
1406 | in a module. |
|
1400 | in a module. | |
1407 |
|
1401 | |||
1408 | [OBJECT TYPE] |
|
1402 | [OBJECT TYPE] | |
1409 |
|
1403 | |||
1410 | Is the name of a python type from the types module. The name is |
|
1404 | Is the name of a python type from the types module. The name is | |
1411 | given in lowercase without the ending type, ex. StringType is |
|
1405 | given in lowercase without the ending type, ex. StringType is | |
1412 | written string. By adding a type here only objects matching the |
|
1406 | written string. By adding a type here only objects matching the | |
1413 | given type are matched. Using all here makes the pattern match all |
|
1407 | given type are matched. Using all here makes the pattern match all | |
1414 | types (this is the default). |
|
1408 | types (this is the default). | |
1415 |
|
1409 | |||
1416 | Options: |
|
1410 | Options: | |
1417 |
|
1411 | |||
1418 | -a: makes the pattern match even objects whose names start with a |
|
1412 | -a: makes the pattern match even objects whose names start with a | |
1419 | single underscore. These names are normally ommitted from the |
|
1413 | single underscore. These names are normally ommitted from the | |
1420 | search. |
|
1414 | search. | |
1421 |
|
1415 | |||
1422 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
1416 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
1423 | these options is given, the default is read from your ipythonrc |
|
1417 | these options is given, the default is read from your ipythonrc | |
1424 | file. The option name which sets this value is |
|
1418 | file. The option name which sets this value is | |
1425 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
1419 | 'wildcards_case_sensitive'. If this option is not specified in your | |
1426 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
1420 | ipythonrc file, IPython's internal default is to do a case sensitive | |
1427 | search. |
|
1421 | search. | |
1428 |
|
1422 | |||
1429 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
1423 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
1430 | specifiy can be searched in any of the following namespaces: |
|
1424 | specifiy can be searched in any of the following namespaces: | |
1431 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
1425 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
1432 | 'builtin' and 'user' are the search defaults. Note that you should |
|
1426 | 'builtin' and 'user' are the search defaults. Note that you should | |
1433 | not use quotes when specifying namespaces. |
|
1427 | not use quotes when specifying namespaces. | |
1434 |
|
1428 | |||
1435 | 'Builtin' contains the python module builtin, 'user' contains all |
|
1429 | 'Builtin' contains the python module builtin, 'user' contains all | |
1436 | user data, 'alias' only contain the shell aliases and no python |
|
1430 | user data, 'alias' only contain the shell aliases and no python | |
1437 | objects, 'internal' contains objects used by IPython. The |
|
1431 | objects, 'internal' contains objects used by IPython. The | |
1438 | 'user_global' namespace is only used by embedded IPython instances, |
|
1432 | 'user_global' namespace is only used by embedded IPython instances, | |
1439 | and it contains module-level globals. You can add namespaces to the |
|
1433 | and it contains module-level globals. You can add namespaces to the | |
1440 | search with -s or exclude them with -e (these options can be given |
|
1434 | search with -s or exclude them with -e (these options can be given | |
1441 | more than once). |
|
1435 | more than once). | |
1442 |
|
1436 | |||
1443 | Examples: |
|
1437 | Examples: | |
1444 |
|
1438 | |||
1445 | %psearch a* -> objects beginning with an a |
|
1439 | %psearch a* -> objects beginning with an a | |
1446 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
1440 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
1447 | %psearch a* function -> all functions beginning with an a |
|
1441 | %psearch a* function -> all functions beginning with an a | |
1448 | %psearch re.e* -> objects beginning with an e in module re |
|
1442 | %psearch re.e* -> objects beginning with an e in module re | |
1449 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
1443 | %psearch r*.e* -> objects that start with e in modules starting in r | |
1450 | %psearch r*.* string -> all strings in modules beginning with r |
|
1444 | %psearch r*.* string -> all strings in modules beginning with r | |
1451 |
|
1445 | |||
1452 | Case sensitve search: |
|
1446 | Case sensitve search: | |
1453 |
|
1447 | |||
1454 | %psearch -c a* list all object beginning with lower case a |
|
1448 | %psearch -c a* list all object beginning with lower case a | |
1455 |
|
1449 | |||
1456 | Show objects beginning with a single _: |
|
1450 | Show objects beginning with a single _: | |
1457 |
|
1451 | |||
1458 | %psearch -a _* list objects beginning with a single underscore |
|
1452 | %psearch -a _* list objects beginning with a single underscore | |
1459 |
|
1453 | |||
1460 | **%psource**:: |
|
1454 | **%psource**:: | |
1461 |
|
1455 | |||
1462 | Print (or run through pager) the source code for an object. |
|
1456 | Print (or run through pager) the source code for an object. | |
1463 |
|
1457 | |||
1464 | **%pushd**:: |
|
1458 | **%pushd**:: | |
1465 |
|
1459 | |||
1466 | Place the current dir on stack and change directory. |
|
1460 | Place the current dir on stack and change directory. | |
1467 |
|
1461 | |||
1468 | Usage:\ |
|
1462 | Usage:\ | |
1469 | %pushd ['dirname'] |
|
1463 | %pushd ['dirname'] | |
1470 |
|
1464 | |||
1471 | **%pwd**:: |
|
1465 | **%pwd**:: | |
1472 |
|
1466 | |||
1473 | Return the current working directory path. |
|
1467 | Return the current working directory path. | |
1474 |
|
1468 | |||
1475 | **%pycat**:: |
|
1469 | **%pycat**:: | |
1476 |
|
1470 | |||
1477 | Show a syntax-highlighted file through a pager. |
|
1471 | Show a syntax-highlighted file through a pager. | |
1478 |
|
1472 | |||
1479 | This magic is similar to the cat utility, but it will assume the file |
|
1473 | This magic is similar to the cat utility, but it will assume the file | |
1480 | to be Python source and will show it with syntax highlighting. |
|
1474 | to be Python source and will show it with syntax highlighting. | |
1481 |
|
1475 | |||
1482 | **%quickref**:: |
|
1476 | **%quickref**:: | |
1483 |
|
1477 | |||
1484 | Show a quick reference sheet |
|
1478 | Show a quick reference sheet | |
1485 |
|
1479 | |||
1486 | **%quit**:: |
|
1480 | **%quit**:: | |
1487 |
|
1481 | |||
1488 | Exit IPython, confirming if configured to do so (like %exit) |
|
1482 | Exit IPython, confirming if configured to do so (like %exit) | |
1489 |
|
1483 | |||
1490 | **%r**:: |
|
1484 | **%r**:: | |
1491 |
|
1485 | |||
1492 | Repeat previous input. |
|
1486 | Repeat previous input. | |
1493 |
|
1487 | |||
1494 | Note: Consider using the more powerfull %rep instead! |
|
1488 | Note: Consider using the more powerfull %rep instead! | |
1495 |
|
1489 | |||
1496 | If given an argument, repeats the previous command which starts with |
|
1490 | If given an argument, repeats the previous command which starts with | |
1497 | the same string, otherwise it just repeats the previous input. |
|
1491 | the same string, otherwise it just repeats the previous input. | |
1498 |
|
1492 | |||
1499 | Shell escaped commands (with ! as first character) are not recognized |
|
1493 | Shell escaped commands (with ! as first character) are not recognized | |
1500 | by this system, only pure python code and magic commands. |
|
1494 | by this system, only pure python code and magic commands. | |
1501 |
|
1495 | |||
1502 | **%rehashdir**:: |
|
1496 | **%rehashdir**:: | |
1503 |
|
1497 | |||
1504 | Add executables in all specified dirs to alias table |
|
1498 | Add executables in all specified dirs to alias table | |
1505 |
|
1499 | |||
1506 | Usage: |
|
1500 | Usage: | |
1507 |
|
1501 | |||
1508 | %rehashdir c:/bin;c:/tools |
|
1502 | %rehashdir c:/bin;c:/tools | |
1509 | - Add all executables under c:/bin and c:/tools to alias table, in |
|
1503 | - Add all executables under c:/bin and c:/tools to alias table, in | |
1510 | order to make them directly executable from any directory. |
|
1504 | order to make them directly executable from any directory. | |
1511 |
|
1505 | |||
1512 | Without arguments, add all executables in current directory. |
|
1506 | Without arguments, add all executables in current directory. | |
1513 |
|
1507 | |||
1514 | **%rehashx**:: |
|
1508 | **%rehashx**:: | |
1515 |
|
1509 | |||
1516 | Update the alias table with all executable files in $PATH. |
|
1510 | Update the alias table with all executable files in $PATH. | |
1517 |
|
1511 | |||
1518 | This version explicitly checks that every entry in $PATH is a file |
|
1512 | This version explicitly checks that every entry in $PATH is a file | |
1519 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
1513 | with execute access (os.X_OK), so it is much slower than %rehash. | |
1520 |
|
1514 | |||
1521 | Under Windows, it checks executability as a match agains a |
|
1515 | Under Windows, it checks executability as a match agains a | |
1522 | '|'-separated string of extensions, stored in the IPython config |
|
1516 | '|'-separated string of extensions, stored in the IPython config | |
1523 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
1517 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
1524 |
|
1518 | |||
1525 | This function also resets the root module cache of module completer, |
|
1519 | This function also resets the root module cache of module completer, | |
1526 | used on slow filesystems. |
|
1520 | used on slow filesystems. | |
1527 |
|
1521 | |||
1528 | **%rep**:: |
|
1522 | **%rep**:: | |
1529 |
|
1523 | |||
1530 | Repeat a command, or get command to input line for editing |
|
1524 | Repeat a command, or get command to input line for editing | |
1531 |
|
1525 | |||
1532 | - %rep (no arguments): |
|
1526 | - %rep (no arguments): | |
1533 |
|
1527 | |||
1534 | Place a string version of last computation result (stored in the special '_' |
|
1528 | Place a string version of last computation result (stored in the special '_' | |
1535 | variable) to the next input prompt. Allows you to create elaborate command |
|
1529 | variable) to the next input prompt. Allows you to create elaborate command | |
1536 | lines without using copy-paste:: |
|
1530 | lines without using copy-paste:: | |
1537 |
|
1531 | |||
1538 | $ l = ["hei", "vaan"] |
|
1532 | $ l = ["hei", "vaan"] | |
1539 | $ "".join(l) |
|
1533 | $ "".join(l) | |
1540 | ==> heivaan |
|
1534 | ==> heivaan | |
1541 | $ %rep |
|
1535 | $ %rep | |
1542 | $ heivaan_ <== cursor blinking |
|
1536 | $ heivaan_ <== cursor blinking | |
1543 |
|
1537 | |||
1544 | %rep 45 |
|
1538 | %rep 45 | |
1545 |
|
1539 | |||
1546 | Place history line 45 to next input prompt. Use %hist to find out the |
|
1540 | Place history line 45 to next input prompt. Use %hist to find out the | |
1547 | number. |
|
1541 | number. | |
1548 |
|
1542 | |||
1549 | %rep 1-4 6-7 3 |
|
1543 | %rep 1-4 6-7 3 | |
1550 |
|
1544 | |||
1551 | Repeat the specified lines immediately. Input slice syntax is the same as |
|
1545 | Repeat the specified lines immediately. Input slice syntax is the same as | |
1552 | in %macro and %save. |
|
1546 | in %macro and %save. | |
1553 |
|
1547 | |||
1554 | %rep foo |
|
1548 | %rep foo | |
1555 |
|
1549 | |||
1556 | Place the most recent line that has the substring "foo" to next input. |
|
1550 | Place the most recent line that has the substring "foo" to next input. | |
1557 | (e.g. 'svn ci -m foobar'). |
|
1551 | (e.g. 'svn ci -m foobar'). | |
1558 |
|
1552 | |||
1559 | **%reset**:: |
|
1553 | **%reset**:: | |
1560 |
|
1554 | |||
1561 | Resets the namespace by removing all names defined by the user. |
|
1555 | Resets the namespace by removing all names defined by the user. | |
1562 |
|
1556 | |||
1563 | Input/Output history are left around in case you need them. |
|
1557 | Input/Output history are left around in case you need them. | |
1564 |
|
1558 | |||
1565 | **%run**:: |
|
1559 | **%run**:: | |
1566 |
|
1560 | |||
1567 | Run the named file inside IPython as a program. |
|
1561 | Run the named file inside IPython as a program. | |
1568 |
|
1562 | |||
1569 | Usage:\ |
|
1563 | Usage:\ | |
1570 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1564 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1571 |
|
1565 | |||
1572 | Parameters after the filename are passed as command-line arguments to |
|
1566 | Parameters after the filename are passed as command-line arguments to | |
1573 | the program (put in sys.argv). Then, control returns to IPython's |
|
1567 | the program (put in sys.argv). Then, control returns to IPython's | |
1574 | prompt. |
|
1568 | prompt. | |
1575 |
|
1569 | |||
1576 | This is similar to running at a system prompt:\ |
|
1570 | This is similar to running at a system prompt:\ | |
1577 | $ python file args\ |
|
1571 | $ python file args\ | |
1578 | but with the advantage of giving you IPython's tracebacks, and of |
|
1572 | but with the advantage of giving you IPython's tracebacks, and of | |
1579 | loading all variables into your interactive namespace for further use |
|
1573 | loading all variables into your interactive namespace for further use | |
1580 | (unless -p is used, see below). |
|
1574 | (unless -p is used, see below). | |
1581 |
|
1575 | |||
1582 | The file is executed in a namespace initially consisting only of |
|
1576 | The file is executed in a namespace initially consisting only of | |
1583 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1577 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1584 | sees its environment as if it were being run as a stand-alone program |
|
1578 | sees its environment as if it were being run as a stand-alone program | |
1585 | (except for sharing global objects such as previously imported |
|
1579 | (except for sharing global objects such as previously imported | |
1586 | modules). But after execution, the IPython interactive namespace gets |
|
1580 | modules). But after execution, the IPython interactive namespace gets | |
1587 | updated with all variables defined in the program (except for __name__ |
|
1581 | updated with all variables defined in the program (except for __name__ | |
1588 | and sys.argv). This allows for very convenient loading of code for |
|
1582 | and sys.argv). This allows for very convenient loading of code for | |
1589 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1583 | interactive work, while giving each program a 'clean sheet' to run in. | |
1590 |
|
1584 | |||
1591 | Options: |
|
1585 | Options: | |
1592 |
|
1586 | |||
1593 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1587 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1594 | without extension (as python does under import). This allows running |
|
1588 | without extension (as python does under import). This allows running | |
1595 | scripts and reloading the definitions in them without calling code |
|
1589 | scripts and reloading the definitions in them without calling code | |
1596 | protected by an ' if __name__ == "__main__" ' clause. |
|
1590 | protected by an ' if __name__ == "__main__" ' clause. | |
1597 |
|
1591 | |||
1598 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1592 | -i: run the file in IPython's namespace instead of an empty one. This | |
1599 | is useful if you are experimenting with code written in a text editor |
|
1593 | is useful if you are experimenting with code written in a text editor | |
1600 | which depends on variables defined interactively. |
|
1594 | which depends on variables defined interactively. | |
1601 |
|
1595 | |||
1602 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1596 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1603 | being run. This is particularly useful if IPython is being used to |
|
1597 | being run. This is particularly useful if IPython is being used to | |
1604 | run unittests, which always exit with a sys.exit() call. In such |
|
1598 | run unittests, which always exit with a sys.exit() call. In such | |
1605 | cases you are interested in the output of the test results, not in |
|
1599 | cases you are interested in the output of the test results, not in | |
1606 | seeing a traceback of the unittest module. |
|
1600 | seeing a traceback of the unittest module. | |
1607 |
|
1601 | |||
1608 | -t: print timing information at the end of the run. IPython will give |
|
1602 | -t: print timing information at the end of the run. IPython will give | |
1609 | you an estimated CPU time consumption for your script, which under |
|
1603 | you an estimated CPU time consumption for your script, which under | |
1610 | Unix uses the resource module to avoid the wraparound problems of |
|
1604 | Unix uses the resource module to avoid the wraparound problems of | |
1611 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1605 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1612 | is also given (for Windows platforms this is reported as 0.0). |
|
1606 | is also given (for Windows platforms this is reported as 0.0). | |
1613 |
|
1607 | |||
1614 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1608 | If -t is given, an additional -N<N> option can be given, where <N> | |
1615 | must be an integer indicating how many times you want the script to |
|
1609 | must be an integer indicating how many times you want the script to | |
1616 | run. The final timing report will include total and per run results. |
|
1610 | run. The final timing report will include total and per run results. | |
1617 |
|
1611 | |||
1618 | For example (testing the script uniq_stable.py): |
|
1612 | For example (testing the script uniq_stable.py): | |
1619 |
|
1613 | |||
1620 | In [1]: run -t uniq_stable |
|
1614 | In [1]: run -t uniq_stable | |
1621 |
|
1615 | |||
1622 | IPython CPU timings (estimated):\ |
|
1616 | IPython CPU timings (estimated):\ | |
1623 | User : 0.19597 s.\ |
|
1617 | User : 0.19597 s.\ | |
1624 | System: 0.0 s.\ |
|
1618 | System: 0.0 s.\ | |
1625 |
|
1619 | |||
1626 | In [2]: run -t -N5 uniq_stable |
|
1620 | In [2]: run -t -N5 uniq_stable | |
1627 |
|
1621 | |||
1628 | IPython CPU timings (estimated):\ |
|
1622 | IPython CPU timings (estimated):\ | |
1629 | Total runs performed: 5\ |
|
1623 | Total runs performed: 5\ | |
1630 | Times : Total Per run\ |
|
1624 | Times : Total Per run\ | |
1631 | User : 0.910862 s, 0.1821724 s.\ |
|
1625 | User : 0.910862 s, 0.1821724 s.\ | |
1632 | System: 0.0 s, 0.0 s. |
|
1626 | System: 0.0 s, 0.0 s. | |
1633 |
|
1627 | |||
1634 | -d: run your program under the control of pdb, the Python debugger. |
|
1628 | -d: run your program under the control of pdb, the Python debugger. | |
1635 | This allows you to execute your program step by step, watch variables, |
|
1629 | This allows you to execute your program step by step, watch variables, | |
1636 | etc. Internally, what IPython does is similar to calling: |
|
1630 | etc. Internally, what IPython does is similar to calling: | |
1637 |
|
1631 | |||
1638 | pdb.run('execfile("YOURFILENAME")') |
|
1632 | pdb.run('execfile("YOURFILENAME")') | |
1639 |
|
1633 | |||
1640 | with a breakpoint set on line 1 of your file. You can change the line |
|
1634 | with a breakpoint set on line 1 of your file. You can change the line | |
1641 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1635 | number for this automatic breakpoint to be <N> by using the -bN option | |
1642 | (where N must be an integer). For example: |
|
1636 | (where N must be an integer). For example: | |
1643 |
|
1637 | |||
1644 | %run -d -b40 myscript |
|
1638 | %run -d -b40 myscript | |
1645 |
|
1639 | |||
1646 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1640 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1647 | the first breakpoint must be set on a line which actually does |
|
1641 | the first breakpoint must be set on a line which actually does | |
1648 | something (not a comment or docstring) for it to stop execution. |
|
1642 | something (not a comment or docstring) for it to stop execution. | |
1649 |
|
1643 | |||
1650 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1644 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1651 | first enter 'c' (without qoutes) to start execution up to the first |
|
1645 | first enter 'c' (without qoutes) to start execution up to the first | |
1652 | breakpoint. |
|
1646 | breakpoint. | |
1653 |
|
1647 | |||
1654 | Entering 'help' gives information about the use of the debugger. You |
|
1648 | Entering 'help' gives information about the use of the debugger. You | |
1655 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1649 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1656 | at a prompt. |
|
1650 | at a prompt. | |
1657 |
|
1651 | |||
1658 | -p: run program under the control of the Python profiler module (which |
|
1652 | -p: run program under the control of the Python profiler module (which | |
1659 | prints a detailed report of execution times, function calls, etc). |
|
1653 | prints a detailed report of execution times, function calls, etc). | |
1660 |
|
1654 | |||
1661 | You can pass other options after -p which affect the behavior of the |
|
1655 | You can pass other options after -p which affect the behavior of the | |
1662 | profiler itself. See the docs for %prun for details. |
|
1656 | profiler itself. See the docs for %prun for details. | |
1663 |
|
1657 | |||
1664 | In this mode, the program's variables do NOT propagate back to the |
|
1658 | In this mode, the program's variables do NOT propagate back to the | |
1665 | IPython interactive namespace (because they remain in the namespace |
|
1659 | IPython interactive namespace (because they remain in the namespace | |
1666 | where the profiler executes them). |
|
1660 | where the profiler executes them). | |
1667 |
|
1661 | |||
1668 | Internally this triggers a call to %prun, see its documentation for |
|
1662 | Internally this triggers a call to %prun, see its documentation for | |
1669 | details on the options available specifically for profiling. |
|
1663 | details on the options available specifically for profiling. | |
1670 |
|
1664 | |||
1671 | There is one special usage for which the text above doesn't apply: |
|
1665 | There is one special usage for which the text above doesn't apply: | |
1672 | if the filename ends with .ipy, the file is run as ipython script, |
|
1666 | if the filename ends with .ipy, the file is run as ipython script, | |
1673 | just as if the commands were written on IPython prompt. |
|
1667 | just as if the commands were written on IPython prompt. | |
1674 |
|
1668 | |||
1675 | **%runlog**:: |
|
1669 | **%runlog**:: | |
1676 |
|
1670 | |||
1677 | Run files as logs. |
|
1671 | Run files as logs. | |
1678 |
|
1672 | |||
1679 | Usage:\ |
|
1673 | Usage:\ | |
1680 | %runlog file1 file2 ... |
|
1674 | %runlog file1 file2 ... | |
1681 |
|
1675 | |||
1682 | Run the named files (treating them as log files) in sequence inside |
|
1676 | Run the named files (treating them as log files) in sequence inside | |
1683 | the interpreter, and return to the prompt. This is much slower than |
|
1677 | the interpreter, and return to the prompt. This is much slower than | |
1684 | %run because each line is executed in a try/except block, but it |
|
1678 | %run because each line is executed in a try/except block, but it | |
1685 | allows running files with syntax errors in them. |
|
1679 | allows running files with syntax errors in them. | |
1686 |
|
1680 | |||
1687 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1681 | Normally IPython will guess when a file is one of its own logfiles, so | |
1688 | you can typically use %run even for logs. This shorthand allows you to |
|
1682 | you can typically use %run even for logs. This shorthand allows you to | |
1689 | force any file to be treated as a log file. |
|
1683 | force any file to be treated as a log file. | |
1690 |
|
1684 | |||
1691 | **%save**:: |
|
1685 | **%save**:: | |
1692 |
|
1686 | |||
1693 | Save a set of lines to a given filename. |
|
1687 | Save a set of lines to a given filename. | |
1694 |
|
1688 | |||
1695 | Usage:\ |
|
1689 | Usage:\ | |
1696 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1690 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
1697 |
|
1691 | |||
1698 | Options: |
|
1692 | Options: | |
1699 |
|
1693 | |||
1700 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1694 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1701 | so that magics are loaded in their transformed version to valid |
|
1695 | so that magics are loaded in their transformed version to valid | |
1702 | Python. If this option is given, the raw input as typed as the |
|
1696 | Python. If this option is given, the raw input as typed as the | |
1703 | command line is used instead. |
|
1697 | command line is used instead. | |
1704 |
|
1698 | |||
1705 | This function uses the same syntax as %macro for line extraction, but |
|
1699 | This function uses the same syntax as %macro for line extraction, but | |
1706 | instead of creating a macro it saves the resulting string to the |
|
1700 | instead of creating a macro it saves the resulting string to the | |
1707 | filename you specify. |
|
1701 | filename you specify. | |
1708 |
|
1702 | |||
1709 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1703 | It adds a '.py' extension to the file if you don't do so yourself, and | |
1710 | it asks for confirmation before overwriting existing files. |
|
1704 | it asks for confirmation before overwriting existing files. | |
1711 |
|
1705 | |||
1712 | **%sc**:: |
|
1706 | **%sc**:: | |
1713 |
|
1707 | |||
1714 | Shell capture - execute a shell command and capture its output. |
|
1708 | Shell capture - execute a shell command and capture its output. | |
1715 |
|
1709 | |||
1716 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
1710 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
1717 |
|
1711 | |||
1718 | You should use the form 'var = !command' instead. Example: |
|
1712 | You should use the form 'var = !command' instead. Example: | |
1719 |
|
1713 | |||
1720 | "%sc -l myfiles = ls ~" should now be written as |
|
1714 | "%sc -l myfiles = ls ~" should now be written as | |
1721 |
|
1715 | |||
1722 | "myfiles = !ls ~" |
|
1716 | "myfiles = !ls ~" | |
1723 |
|
1717 | |||
1724 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
1718 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
1725 | below. |
|
1719 | below. | |
1726 |
|
1720 | |||
1727 | -- |
|
1721 | -- | |
1728 | %sc [options] varname=command |
|
1722 | %sc [options] varname=command | |
1729 |
|
1723 | |||
1730 | IPython will run the given command using commands.getoutput(), and |
|
1724 | IPython will run the given command using commands.getoutput(), and | |
1731 | will then update the user's interactive namespace with a variable |
|
1725 | will then update the user's interactive namespace with a variable | |
1732 | called varname, containing the value of the call. Your command can |
|
1726 | called varname, containing the value of the call. Your command can | |
1733 | contain shell wildcards, pipes, etc. |
|
1727 | contain shell wildcards, pipes, etc. | |
1734 |
|
1728 | |||
1735 | The '=' sign in the syntax is mandatory, and the variable name you |
|
1729 | The '=' sign in the syntax is mandatory, and the variable name you | |
1736 | supply must follow Python's standard conventions for valid names. |
|
1730 | supply must follow Python's standard conventions for valid names. | |
1737 |
|
1731 | |||
1738 | (A special format without variable name exists for internal use) |
|
1732 | (A special format without variable name exists for internal use) | |
1739 |
|
1733 | |||
1740 | Options: |
|
1734 | Options: | |
1741 |
|
1735 | |||
1742 | -l: list output. Split the output on newlines into a list before |
|
1736 | -l: list output. Split the output on newlines into a list before | |
1743 | assigning it to the given variable. By default the output is stored |
|
1737 | assigning it to the given variable. By default the output is stored | |
1744 | as a single string. |
|
1738 | as a single string. | |
1745 |
|
1739 | |||
1746 | -v: verbose. Print the contents of the variable. |
|
1740 | -v: verbose. Print the contents of the variable. | |
1747 |
|
1741 | |||
1748 | In most cases you should not need to split as a list, because the |
|
1742 | In most cases you should not need to split as a list, because the | |
1749 | returned value is a special type of string which can automatically |
|
1743 | returned value is a special type of string which can automatically | |
1750 | provide its contents either as a list (split on newlines) or as a |
|
1744 | provide its contents either as a list (split on newlines) or as a | |
1751 | space-separated string. These are convenient, respectively, either |
|
1745 | space-separated string. These are convenient, respectively, either | |
1752 | for sequential processing or to be passed to a shell command. |
|
1746 | for sequential processing or to be passed to a shell command. | |
1753 |
|
1747 | |||
1754 | For example: |
|
1748 | For example: | |
1755 |
|
1749 | |||
1756 | # Capture into variable a |
|
1750 | # Capture into variable a | |
1757 | In [9]: sc a=ls *py |
|
1751 | In [9]: sc a=ls *py | |
1758 |
|
1752 | |||
1759 | # a is a string with embedded newlines |
|
1753 | # a is a string with embedded newlines | |
1760 | In [10]: a |
|
1754 | In [10]: a | |
1761 | Out[10]: 'setup.py win32_manual_post_install.py' |
|
1755 | Out[10]: 'setup.py win32_manual_post_install.py' | |
1762 |
|
1756 | |||
1763 | # which can be seen as a list: |
|
1757 | # which can be seen as a list: | |
1764 | In [11]: a.l |
|
1758 | In [11]: a.l | |
1765 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
1759 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] | |
1766 |
|
1760 | |||
1767 | # or as a whitespace-separated string: |
|
1761 | # or as a whitespace-separated string: | |
1768 | In [12]: a.s |
|
1762 | In [12]: a.s | |
1769 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
1763 | Out[12]: 'setup.py win32_manual_post_install.py' | |
1770 |
|
1764 | |||
1771 | # a.s is useful to pass as a single command line: |
|
1765 | # a.s is useful to pass as a single command line: | |
1772 | In [13]: !wc -l $a.s |
|
1766 | In [13]: !wc -l $a.s | |
1773 | 146 setup.py |
|
1767 | 146 setup.py | |
1774 | 130 win32_manual_post_install.py |
|
1768 | 130 win32_manual_post_install.py | |
1775 | 276 total |
|
1769 | 276 total | |
1776 |
|
1770 | |||
1777 | # while the list form is useful to loop over: |
|
1771 | # while the list form is useful to loop over: | |
1778 | In [14]: for f in a.l: |
|
1772 | In [14]: for f in a.l: | |
1779 | ....: !wc -l $f |
|
1773 | ....: !wc -l $f | |
1780 | ....: |
|
1774 | ....: | |
1781 | 146 setup.py |
|
1775 | 146 setup.py | |
1782 | 130 win32_manual_post_install.py |
|
1776 | 130 win32_manual_post_install.py | |
1783 |
|
1777 | |||
1784 | Similiarly, the lists returned by the -l option are also special, in |
|
1778 | Similiarly, the lists returned by the -l option are also special, in | |
1785 | the sense that you can equally invoke the .s attribute on them to |
|
1779 | the sense that you can equally invoke the .s attribute on them to | |
1786 | automatically get a whitespace-separated string from their contents: |
|
1780 | automatically get a whitespace-separated string from their contents: | |
1787 |
|
1781 | |||
1788 | In [1]: sc -l b=ls *py |
|
1782 | In [1]: sc -l b=ls *py | |
1789 |
|
1783 | |||
1790 | In [2]: b |
|
1784 | In [2]: b | |
1791 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
1785 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] | |
1792 |
|
1786 | |||
1793 | In [3]: b.s |
|
1787 | In [3]: b.s | |
1794 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
1788 | Out[3]: 'setup.py win32_manual_post_install.py' | |
1795 |
|
1789 | |||
1796 | In summary, both the lists and strings used for ouptut capture have |
|
1790 | In summary, both the lists and strings used for ouptut capture have | |
1797 | the following special attributes: |
|
1791 | the following special attributes: | |
1798 |
|
1792 | |||
1799 | .l (or .list) : value as list. |
|
1793 | .l (or .list) : value as list. | |
1800 | .n (or .nlstr): value as newline-separated string. |
|
1794 | .n (or .nlstr): value as newline-separated string. | |
1801 | .s (or .spstr): value as space-separated string. |
|
1795 | .s (or .spstr): value as space-separated string. | |
1802 |
|
1796 | |||
1803 | **%store**:: |
|
1797 | **%store**:: | |
1804 |
|
1798 | |||
1805 | Lightweight persistence for python variables. |
|
1799 | Lightweight persistence for python variables. | |
1806 |
|
1800 | |||
1807 | Example: |
|
1801 | Example: | |
1808 |
|
1802 | |||
1809 | ville@badger[~]|1> A = ['hello',10,'world']\ |
|
1803 | ville@badger[~]|1> A = ['hello',10,'world']\ | |
1810 | ville@badger[~]|2> %store A\ |
|
1804 | ville@badger[~]|2> %store A\ | |
1811 | ville@badger[~]|3> Exit |
|
1805 | ville@badger[~]|3> Exit | |
1812 |
|
1806 | |||
1813 | (IPython session is closed and started again...) |
|
1807 | (IPython session is closed and started again...) | |
1814 |
|
1808 | |||
1815 | ville@badger:~$ ipython -p pysh\ |
|
1809 | ville@badger:~$ ipython -p pysh\ | |
1816 | ville@badger[~]|1> print A |
|
1810 | ville@badger[~]|1> print A | |
1817 |
|
1811 | |||
1818 | ['hello', 10, 'world'] |
|
1812 | ['hello', 10, 'world'] | |
1819 |
|
1813 | |||
1820 | Usage: |
|
1814 | Usage: | |
1821 |
|
1815 | |||
1822 | %store - Show list of all variables and their current values\ |
|
1816 | %store - Show list of all variables and their current values\ | |
1823 | %store <var> - Store the *current* value of the variable to disk\ |
|
1817 | %store <var> - Store the *current* value of the variable to disk\ | |
1824 | %store -d <var> - Remove the variable and its value from storage\ |
|
1818 | %store -d <var> - Remove the variable and its value from storage\ | |
1825 | %store -z - Remove all variables from storage\ |
|
1819 | %store -z - Remove all variables from storage\ | |
1826 | %store -r - Refresh all variables from store (delete current vals)\ |
|
1820 | %store -r - Refresh all variables from store (delete current vals)\ | |
1827 | %store foo >a.txt - Store value of foo to new file a.txt\ |
|
1821 | %store foo >a.txt - Store value of foo to new file a.txt\ | |
1828 | %store foo >>a.txt - Append value of foo to file a.txt\ |
|
1822 | %store foo >>a.txt - Append value of foo to file a.txt\ | |
1829 |
|
1823 | |||
1830 | It should be noted that if you change the value of a variable, you |
|
1824 | It should be noted that if you change the value of a variable, you | |
1831 | need to %store it again if you want to persist the new value. |
|
1825 | need to %store it again if you want to persist the new value. | |
1832 |
|
1826 | |||
1833 | Note also that the variables will need to be pickleable; most basic |
|
1827 | Note also that the variables will need to be pickleable; most basic | |
1834 | python types can be safely %stored. |
|
1828 | python types can be safely %stored. | |
1835 |
|
1829 | |||
1836 | Also aliases can be %store'd across sessions. |
|
1830 | Also aliases can be %store'd across sessions. | |
1837 |
|
1831 | |||
1838 | **%sx**:: |
|
1832 | **%sx**:: | |
1839 |
|
1833 | |||
1840 | Shell execute - run a shell command and capture its output. |
|
1834 | Shell execute - run a shell command and capture its output. | |
1841 |
|
1835 | |||
1842 | %sx command |
|
1836 | %sx command | |
1843 |
|
1837 | |||
1844 | IPython will run the given command using commands.getoutput(), and |
|
1838 | IPython will run the given command using commands.getoutput(), and | |
1845 | return the result formatted as a list (split on '\n'). Since the |
|
1839 | return the result formatted as a list (split on '\n'). Since the | |
1846 | output is _returned_, it will be stored in ipython's regular output |
|
1840 | output is _returned_, it will be stored in ipython's regular output | |
1847 | cache Out[N] and in the '_N' automatic variables. |
|
1841 | cache Out[N] and in the '_N' automatic variables. | |
1848 |
|
1842 | |||
1849 | Notes: |
|
1843 | Notes: | |
1850 |
|
1844 | |||
1851 | 1) If an input line begins with '!!', then %sx is automatically |
|
1845 | 1) If an input line begins with '!!', then %sx is automatically | |
1852 | invoked. That is, while: |
|
1846 | invoked. That is, while: | |
1853 | !ls |
|
1847 | !ls | |
1854 | causes ipython to simply issue system('ls'), typing |
|
1848 | causes ipython to simply issue system('ls'), typing | |
1855 | !!ls |
|
1849 | !!ls | |
1856 | is a shorthand equivalent to: |
|
1850 | is a shorthand equivalent to: | |
1857 | %sx ls |
|
1851 | %sx ls | |
1858 |
|
1852 | |||
1859 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
1853 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
1860 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
1854 | like '%sc -l'. The reason for this is to make it as easy as possible | |
1861 | to process line-oriented shell output via further python commands. |
|
1855 | to process line-oriented shell output via further python commands. | |
1862 | %sc is meant to provide much finer control, but requires more |
|
1856 | %sc is meant to provide much finer control, but requires more | |
1863 | typing. |
|
1857 | typing. | |
1864 |
|
1858 | |||
1865 | 3) Just like %sc -l, this is a list with special attributes: |
|
1859 | 3) Just like %sc -l, this is a list with special attributes: | |
1866 |
|
1860 | |||
1867 | .l (or .list) : value as list. |
|
1861 | .l (or .list) : value as list. | |
1868 | .n (or .nlstr): value as newline-separated string. |
|
1862 | .n (or .nlstr): value as newline-separated string. | |
1869 | .s (or .spstr): value as whitespace-separated string. |
|
1863 | .s (or .spstr): value as whitespace-separated string. | |
1870 |
|
1864 | |||
1871 | This is very useful when trying to use such lists as arguments to |
|
1865 | This is very useful when trying to use such lists as arguments to | |
1872 | system commands. |
|
1866 | system commands. | |
1873 |
|
1867 | |||
1874 | **%system_verbose**:: |
|
1868 | **%system_verbose**:: | |
1875 |
|
1869 | |||
1876 | Set verbose printing of system calls. |
|
1870 | Set verbose printing of system calls. | |
1877 |
|
1871 | |||
1878 | If called without an argument, act as a toggle |
|
1872 | If called without an argument, act as a toggle | |
1879 |
|
1873 | |||
1880 | **%time**:: |
|
1874 | **%time**:: | |
1881 |
|
1875 | |||
1882 | Time execution of a Python statement or expression. |
|
1876 | Time execution of a Python statement or expression. | |
1883 |
|
1877 | |||
1884 | The CPU and wall clock times are printed, and the value of the |
|
1878 | The CPU and wall clock times are printed, and the value of the | |
1885 | expression (if any) is returned. Note that under Win32, system time |
|
1879 | expression (if any) is returned. Note that under Win32, system time | |
1886 | is always reported as 0, since it can not be measured. |
|
1880 | is always reported as 0, since it can not be measured. | |
1887 |
|
1881 | |||
1888 | This function provides very basic timing functionality. In Python |
|
1882 | This function provides very basic timing functionality. In Python | |
1889 | 2.3, the timeit module offers more control and sophistication, so this |
|
1883 | 2.3, the timeit module offers more control and sophistication, so this | |
1890 | could be rewritten to use it (patches welcome). |
|
1884 | could be rewritten to use it (patches welcome). | |
1891 |
|
1885 | |||
1892 | Some examples: |
|
1886 | Some examples: | |
1893 |
|
1887 | |||
1894 | In [1]: time 2**128 |
|
1888 | In [1]: time 2**128 | |
1895 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1889 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1896 | Wall time: 0.00 |
|
1890 | Wall time: 0.00 | |
1897 | Out[1]: 340282366920938463463374607431768211456L |
|
1891 | Out[1]: 340282366920938463463374607431768211456L | |
1898 |
|
1892 | |||
1899 | In [2]: n = 1000000 |
|
1893 | In [2]: n = 1000000 | |
1900 |
|
1894 | |||
1901 | In [3]: time sum(range(n)) |
|
1895 | In [3]: time sum(range(n)) | |
1902 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1896 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1903 | Wall time: 1.37 |
|
1897 | Wall time: 1.37 | |
1904 | Out[3]: 499999500000L |
|
1898 | Out[3]: 499999500000L | |
1905 |
|
1899 | |||
1906 | In [4]: time print 'hello world' |
|
1900 | In [4]: time print 'hello world' | |
1907 | hello world |
|
1901 | hello world | |
1908 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1902 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1909 | Wall time: 0.00 |
|
1903 | Wall time: 0.00 | |
1910 |
|
1904 | |||
1911 | Note that the time needed by Python to compile the given expression |
|
1905 | Note that the time needed by Python to compile the given expression | |
1912 | will be reported if it is more than 0.1s. In this example, the |
|
1906 | will be reported if it is more than 0.1s. In this example, the | |
1913 | actual exponentiation is done by Python at compilation time, so while |
|
1907 | actual exponentiation is done by Python at compilation time, so while | |
1914 | the expression can take a noticeable amount of time to compute, that |
|
1908 | the expression can take a noticeable amount of time to compute, that | |
1915 | time is purely due to the compilation: |
|
1909 | time is purely due to the compilation: | |
1916 |
|
1910 | |||
1917 | In [5]: time 3**9999; |
|
1911 | In [5]: time 3**9999; | |
1918 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1912 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1919 | Wall time: 0.00 s |
|
1913 | Wall time: 0.00 s | |
1920 |
|
1914 | |||
1921 | In [6]: time 3**999999; |
|
1915 | In [6]: time 3**999999; | |
1922 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1916 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1923 | Wall time: 0.00 s |
|
1917 | Wall time: 0.00 s | |
1924 | Compiler : 0.78 s |
|
1918 | Compiler : 0.78 s | |
1925 |
|
1919 | |||
1926 | **%timeit**:: |
|
1920 | **%timeit**:: | |
1927 |
|
1921 | |||
1928 | Time execution of a Python statement or expression |
|
1922 | Time execution of a Python statement or expression | |
1929 |
|
1923 | |||
1930 | Usage:\ |
|
1924 | Usage:\ | |
1931 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1925 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1932 |
|
1926 | |||
1933 | Time execution of a Python statement or expression using the timeit |
|
1927 | Time execution of a Python statement or expression using the timeit | |
1934 | module. |
|
1928 | module. | |
1935 |
|
1929 | |||
1936 | Options: |
|
1930 | Options: | |
1937 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1931 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1938 | is not given, a fitting value is chosen. |
|
1932 | is not given, a fitting value is chosen. | |
1939 |
|
1933 | |||
1940 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1934 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1941 | Default: 3 |
|
1935 | Default: 3 | |
1942 |
|
1936 | |||
1943 | -t: use time.time to measure the time, which is the default on Unix. |
|
1937 | -t: use time.time to measure the time, which is the default on Unix. | |
1944 | This function measures wall time. |
|
1938 | This function measures wall time. | |
1945 |
|
1939 | |||
1946 | -c: use time.clock to measure the time, which is the default on |
|
1940 | -c: use time.clock to measure the time, which is the default on | |
1947 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1941 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1948 | instead and returns the CPU user time. |
|
1942 | instead and returns the CPU user time. | |
1949 |
|
1943 | |||
1950 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1944 | -p<P>: use a precision of <P> digits to display the timing result. | |
1951 | Default: 3 |
|
1945 | Default: 3 | |
1952 |
|
1946 | |||
1953 |
|
1947 | |||
1954 | Examples:\ |
|
1948 | Examples:\ | |
1955 | In [1]: %timeit pass |
|
1949 | In [1]: %timeit pass | |
1956 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1950 | 10000000 loops, best of 3: 53.3 ns per loop | |
1957 |
|
1951 | |||
1958 | In [2]: u = None |
|
1952 | In [2]: u = None | |
1959 |
|
1953 | |||
1960 | In [3]: %timeit u is None |
|
1954 | In [3]: %timeit u is None | |
1961 | 10000000 loops, best of 3: 184 ns per loop |
|
1955 | 10000000 loops, best of 3: 184 ns per loop | |
1962 |
|
1956 | |||
1963 | In [4]: %timeit -r 4 u == None |
|
1957 | In [4]: %timeit -r 4 u == None | |
1964 | 1000000 loops, best of 4: 242 ns per loop |
|
1958 | 1000000 loops, best of 4: 242 ns per loop | |
1965 |
|
1959 | |||
1966 | In [5]: import time |
|
1960 | In [5]: import time | |
1967 |
|
1961 | |||
1968 | In [6]: %timeit -n1 time.sleep(2) |
|
1962 | In [6]: %timeit -n1 time.sleep(2) | |
1969 | 1 loops, best of 3: 2 s per loop |
|
1963 | 1 loops, best of 3: 2 s per loop | |
1970 |
|
1964 | |||
1971 |
|
1965 | |||
1972 | The times reported by %timeit will be slightly higher than those |
|
1966 | The times reported by %timeit will be slightly higher than those | |
1973 | reported by the timeit.py script when variables are accessed. This is |
|
1967 | reported by the timeit.py script when variables are accessed. This is | |
1974 | due to the fact that %timeit executes the statement in the namespace |
|
1968 | due to the fact that %timeit executes the statement in the namespace | |
1975 | of the shell, compared with timeit.py, which uses a single setup |
|
1969 | of the shell, compared with timeit.py, which uses a single setup | |
1976 | statement to import function or create variables. Generally, the bias |
|
1970 | statement to import function or create variables. Generally, the bias | |
1977 | does not matter as long as results from timeit.py are not mixed with |
|
1971 | does not matter as long as results from timeit.py are not mixed with | |
1978 | those from %timeit. |
|
1972 | those from %timeit. | |
1979 |
|
1973 | |||
1980 | **%unalias**:: |
|
1974 | **%unalias**:: | |
1981 |
|
1975 | |||
1982 | Remove an alias |
|
1976 | Remove an alias | |
1983 |
|
1977 | |||
1984 | **%upgrade**:: |
|
1978 | **%upgrade**:: | |
1985 |
|
1979 | |||
1986 | Upgrade your IPython installation |
|
1980 | Upgrade your IPython installation | |
1987 |
|
1981 | |||
1988 | This will copy the config files that don't yet exist in your |
|
1982 | This will copy the config files that don't yet exist in your | |
1989 | ipython dir from the system config dir. Use this after upgrading |
|
1983 | ipython dir from the system config dir. Use this after upgrading | |
1990 | IPython if you don't wish to delete your .ipython dir. |
|
1984 | IPython if you don't wish to delete your .ipython dir. | |
1991 |
|
1985 | |||
1992 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
1986 | Call with -nolegacy to get rid of ipythonrc* files (recommended for | |
1993 | new users) |
|
1987 | new users) | |
1994 |
|
1988 | |||
1995 | **%which**:: |
|
1989 | **%which**:: | |
1996 |
|
1990 | |||
1997 | %which <cmd> => search PATH for files matching cmd. Also scans aliases. |
|
1991 | %which <cmd> => search PATH for files matching cmd. Also scans aliases. | |
1998 |
|
1992 | |||
1999 | Traverses PATH and prints all files (not just executables!) that match the |
|
1993 | Traverses PATH and prints all files (not just executables!) that match the | |
2000 | pattern on command line. Probably more useful in finding stuff |
|
1994 | pattern on command line. Probably more useful in finding stuff | |
2001 | interactively than 'which', which only prints the first matching item. |
|
1995 | interactively than 'which', which only prints the first matching item. | |
2002 |
|
1996 | |||
2003 | Also discovers and expands aliases, so you'll see what will be executed |
|
1997 | Also discovers and expands aliases, so you'll see what will be executed | |
2004 | when you call an alias. |
|
1998 | when you call an alias. | |
2005 |
|
1999 | |||
2006 | Example: |
|
2000 | Example: | |
2007 |
|
2001 | |||
2008 | [~]|62> %which d |
|
2002 | [~]|62> %which d | |
2009 | d -> ls -F --color=auto |
|
2003 | d -> ls -F --color=auto | |
2010 | == c:\cygwin\bin\ls.exe |
|
2004 | == c:\cygwin\bin\ls.exe | |
2011 | c:\cygwin\bin\d.exe |
|
2005 | c:\cygwin\bin\d.exe | |
2012 |
|
2006 | |||
2013 | [~]|64> %which diff* |
|
2007 | [~]|64> %which diff* | |
2014 | diff3 -> diff3 |
|
2008 | diff3 -> diff3 | |
2015 | == c:\cygwin\bin\diff3.exe |
|
2009 | == c:\cygwin\bin\diff3.exe | |
2016 | diff -> diff |
|
2010 | diff -> diff | |
2017 | == c:\cygwin\bin\diff.exe |
|
2011 | == c:\cygwin\bin\diff.exe | |
2018 | c:\cygwin\bin\diff.exe |
|
2012 | c:\cygwin\bin\diff.exe | |
2019 | c:\cygwin\bin\diff3.exe |
|
2013 | c:\cygwin\bin\diff3.exe | |
2020 |
|
2014 | |||
2021 | **%who**:: |
|
2015 | **%who**:: | |
2022 |
|
2016 | |||
2023 | Print all interactive variables, with some minimal formatting. |
|
2017 | Print all interactive variables, with some minimal formatting. | |
2024 |
|
2018 | |||
2025 | If any arguments are given, only variables whose type matches one of |
|
2019 | If any arguments are given, only variables whose type matches one of | |
2026 | these are printed. For example: |
|
2020 | these are printed. For example: | |
2027 |
|
2021 | |||
2028 | %who function str |
|
2022 | %who function str | |
2029 |
|
2023 | |||
2030 | will only list functions and strings, excluding all other types of |
|
2024 | will only list functions and strings, excluding all other types of | |
2031 | variables. To find the proper type names, simply use type(var) at a |
|
2025 | variables. To find the proper type names, simply use type(var) at a | |
2032 | command line to see how python prints type names. For example: |
|
2026 | command line to see how python prints type names. For example: | |
2033 |
|
2027 | |||
2034 | In [1]: type('hello')\ |
|
2028 | In [1]: type('hello')\ | |
2035 | Out[1]: <type 'str'> |
|
2029 | Out[1]: <type 'str'> | |
2036 |
|
2030 | |||
2037 | indicates that the type name for strings is 'str'. |
|
2031 | indicates that the type name for strings is 'str'. | |
2038 |
|
2032 | |||
2039 | %who always excludes executed names loaded through your configuration |
|
2033 | %who always excludes executed names loaded through your configuration | |
2040 | file and things which are internal to IPython. |
|
2034 | file and things which are internal to IPython. | |
2041 |
|
2035 | |||
2042 | This is deliberate, as typically you may load many modules and the |
|
2036 | This is deliberate, as typically you may load many modules and the | |
2043 | purpose of %who is to show you only what you've manually defined. |
|
2037 | purpose of %who is to show you only what you've manually defined. | |
2044 |
|
2038 | |||
2045 | **%who_ls**:: |
|
2039 | **%who_ls**:: | |
2046 |
|
2040 | |||
2047 | Return a sorted list of all interactive variables. |
|
2041 | Return a sorted list of all interactive variables. | |
2048 |
|
2042 | |||
2049 | If arguments are given, only variables of types matching these |
|
2043 | If arguments are given, only variables of types matching these | |
2050 | arguments are returned. |
|
2044 | arguments are returned. | |
2051 |
|
2045 | |||
2052 | **%whos**:: |
|
2046 | **%whos**:: | |
2053 |
|
2047 | |||
2054 | Like %who, but gives some extra information about each variable. |
|
2048 | Like %who, but gives some extra information about each variable. | |
2055 |
|
2049 | |||
2056 | The same type filtering of %who can be applied here. |
|
2050 | The same type filtering of %who can be applied here. | |
2057 |
|
2051 | |||
2058 | For all variables, the type is printed. Additionally it prints: |
|
2052 | For all variables, the type is printed. Additionally it prints: | |
2059 |
|
2053 | |||
2060 | - For {},[],(): their length. |
|
2054 | - For {},[],(): their length. | |
2061 |
|
2055 | |||
2062 | - For numpy and Numeric arrays, a summary with shape, number of |
|
2056 | - For numpy and Numeric arrays, a summary with shape, number of | |
2063 | elements, typecode and size in memory. |
|
2057 | elements, typecode and size in memory. | |
2064 |
|
2058 | |||
2065 | - Everything else: a string representation, snipping their middle if |
|
2059 | - Everything else: a string representation, snipping their middle if | |
2066 | too long. |
|
2060 | too long. | |
2067 |
|
2061 | |||
2068 | **%xmode**:: |
|
2062 | **%xmode**:: | |
2069 |
|
2063 | |||
2070 | Switch modes for the exception handlers. |
|
2064 | Switch modes for the exception handlers. | |
2071 |
|
2065 | |||
2072 | Valid modes: Plain, Context and Verbose. |
|
2066 | Valid modes: Plain, Context and Verbose. | |
2073 |
|
2067 | |||
2074 | If called without arguments, acts as a toggle. |
|
2068 | If called without arguments, acts as a toggle. | |
2075 |
|
2069 | |||
2076 | .. magic_end |
|
2070 | .. magic_end | |
2077 |
|
2071 | |||
2078 | Access to the standard Python help |
|
2072 | Access to the standard Python help | |
2079 | ---------------------------------- |
|
2073 | ---------------------------------- | |
2080 |
|
2074 | |||
2081 | As of Python 2.1, a help system is available with access to object docstrings |
|
2075 | As of Python 2.1, a help system is available with access to object docstrings | |
2082 | and the Python manuals. Simply type 'help' (no quotes) to access it. You can |
|
2076 | and the Python manuals. Simply type 'help' (no quotes) to access it. You can | |
2083 | also type help(object) to obtain information about a given object, and |
|
2077 | also type help(object) to obtain information about a given object, and | |
2084 | help('keyword') for information on a keyword. As noted :ref:`here |
|
2078 | help('keyword') for information on a keyword. As noted :ref:`here | |
2085 | <accessing_help>`, you need to properly configure your environment variable |
|
2079 | <accessing_help>`, you need to properly configure your environment variable | |
2086 | PYTHONDOCS for this feature to work correctly. |
|
2080 | PYTHONDOCS for this feature to work correctly. | |
2087 |
|
2081 | |||
2088 | .. _dynamic_object_info: |
|
2082 | .. _dynamic_object_info: | |
2089 |
|
2083 | |||
2090 | Dynamic object information |
|
2084 | Dynamic object information | |
2091 | -------------------------- |
|
2085 | -------------------------- | |
2092 |
|
2086 | |||
2093 | Typing ?word or word? prints detailed information about an object. If |
|
2087 | Typing ?word or word? prints detailed information about an object. If | |
2094 | certain strings in the object are too long (docstrings, code, etc.) they |
|
2088 | certain strings in the object are too long (docstrings, code, etc.) they | |
2095 | get snipped in the center for brevity. This system gives access variable |
|
2089 | get snipped in the center for brevity. This system gives access variable | |
2096 | types and values, full source code for any object (if available), |
|
2090 | types and values, full source code for any object (if available), | |
2097 | function prototypes and other useful information. |
|
2091 | function prototypes and other useful information. | |
2098 |
|
2092 | |||
2099 | Typing ??word or word?? gives access to the full information without |
|
2093 | Typing ??word or word?? gives access to the full information without | |
2100 | snipping long strings. Long strings are sent to the screen through the |
|
2094 | snipping long strings. Long strings are sent to the screen through the | |
2101 | less pager if longer than the screen and printed otherwise. On systems |
|
2095 | less pager if longer than the screen and printed otherwise. On systems | |
2102 | lacking the less command, IPython uses a very basic internal pager. |
|
2096 | lacking the less command, IPython uses a very basic internal pager. | |
2103 |
|
2097 | |||
2104 | The following magic functions are particularly useful for gathering |
|
2098 | The following magic functions are particularly useful for gathering | |
2105 | information about your working environment. You can get more details by |
|
2099 | information about your working environment. You can get more details by | |
2106 | typing %magic or querying them individually (use %function_name? with or |
|
2100 | typing %magic or querying them individually (use %function_name? with or | |
2107 | without the %), this is just a summary: |
|
2101 | without the %), this is just a summary: | |
2108 |
|
2102 | |||
2109 | * **%pdoc <object>**: Print (or run through a pager if too long) the |
|
2103 | * **%pdoc <object>**: Print (or run through a pager if too long) the | |
2110 | docstring for an object. If the given object is a class, it will |
|
2104 | docstring for an object. If the given object is a class, it will | |
2111 | print both the class and the constructor docstrings. |
|
2105 | print both the class and the constructor docstrings. | |
2112 | * **%pdef <object>**: Print the definition header for any callable |
|
2106 | * **%pdef <object>**: Print the definition header for any callable | |
2113 | object. If the object is a class, print the constructor information. |
|
2107 | object. If the object is a class, print the constructor information. | |
2114 | * **%psource <object>**: Print (or run through a pager if too long) |
|
2108 | * **%psource <object>**: Print (or run through a pager if too long) | |
2115 | the source code for an object. |
|
2109 | the source code for an object. | |
2116 | * **%pfile <object>**: Show the entire source file where an object was |
|
2110 | * **%pfile <object>**: Show the entire source file where an object was | |
2117 | defined via a pager, opening it at the line where the object |
|
2111 | defined via a pager, opening it at the line where the object | |
2118 | definition begins. |
|
2112 | definition begins. | |
2119 | * **%who/%whos**: These functions give information about identifiers |
|
2113 | * **%who/%whos**: These functions give information about identifiers | |
2120 | you have defined interactively (not things you loaded or defined |
|
2114 | you have defined interactively (not things you loaded or defined | |
2121 | in your configuration files). %who just prints a list of |
|
2115 | in your configuration files). %who just prints a list of | |
2122 | identifiers and %whos prints a table with some basic details about |
|
2116 | identifiers and %whos prints a table with some basic details about | |
2123 | each identifier. |
|
2117 | each identifier. | |
2124 |
|
2118 | |||
2125 | Note that the dynamic object information functions (?/??, %pdoc, %pfile, |
|
2119 | Note that the dynamic object information functions (?/??, %pdoc, %pfile, | |
2126 | %pdef, %psource) give you access to documentation even on things which |
|
2120 | %pdef, %psource) give you access to documentation even on things which | |
2127 | are not really defined as separate identifiers. Try for example typing |
|
2121 | are not really defined as separate identifiers. Try for example typing | |
2128 | {}.get? or after doing import os, type os.path.abspath??. |
|
2122 | {}.get? or after doing import os, type os.path.abspath??. | |
2129 |
|
2123 | |||
2130 |
|
2124 | |||
2131 | .. _readline: |
|
2125 | .. _readline: | |
2132 |
|
2126 | |||
2133 | Readline-based features |
|
2127 | Readline-based features | |
2134 | ----------------------- |
|
2128 | ----------------------- | |
2135 |
|
2129 | |||
2136 | These features require the GNU readline library, so they won't work if |
|
2130 | These features require the GNU readline library, so they won't work if | |
2137 | your Python installation lacks readline support. We will first describe |
|
2131 | your Python installation lacks readline support. We will first describe | |
2138 | the default behavior IPython uses, and then how to change it to suit |
|
2132 | the default behavior IPython uses, and then how to change it to suit | |
2139 | your preferences. |
|
2133 | your preferences. | |
2140 |
|
2134 | |||
2141 |
|
2135 | |||
2142 | Command line completion |
|
2136 | Command line completion | |
2143 | +++++++++++++++++++++++ |
|
2137 | +++++++++++++++++++++++ | |
2144 |
|
2138 | |||
2145 | At any time, hitting TAB will complete any available python commands or |
|
2139 | At any time, hitting TAB will complete any available python commands or | |
2146 | variable names, and show you a list of the possible completions if |
|
2140 | variable names, and show you a list of the possible completions if | |
2147 | there's no unambiguous one. It will also complete filenames in the |
|
2141 | there's no unambiguous one. It will also complete filenames in the | |
2148 | current directory if no python names match what you've typed so far. |
|
2142 | current directory if no python names match what you've typed so far. | |
2149 |
|
2143 | |||
2150 |
|
2144 | |||
2151 | Search command history |
|
2145 | Search command history | |
2152 | ++++++++++++++++++++++ |
|
2146 | ++++++++++++++++++++++ | |
2153 |
|
2147 | |||
2154 | IPython provides two ways for searching through previous input and thus |
|
2148 | IPython provides two ways for searching through previous input and thus | |
2155 | reduce the need for repetitive typing: |
|
2149 | reduce the need for repetitive typing: | |
2156 |
|
2150 | |||
2157 | 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n |
|
2151 | 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n | |
2158 | (next,down) to search through only the history items that match |
|
2152 | (next,down) to search through only the history items that match | |
2159 | what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank |
|
2153 | what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank | |
2160 | prompt, they just behave like normal arrow keys. |
|
2154 | prompt, they just behave like normal arrow keys. | |
2161 | 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system |
|
2155 | 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system | |
2162 | searches your history for lines that contain what you've typed so |
|
2156 | searches your history for lines that contain what you've typed so | |
2163 | far, completing as much as it can. |
|
2157 | far, completing as much as it can. | |
2164 |
|
2158 | |||
2165 |
|
2159 | |||
2166 | Persistent command history across sessions |
|
2160 | Persistent command history across sessions | |
2167 | ++++++++++++++++++++++++++++++++++++++++++ |
|
2161 | ++++++++++++++++++++++++++++++++++++++++++ | |
2168 |
|
2162 | |||
2169 | IPython will save your input history when it leaves and reload it next |
|
2163 | IPython will save your input history when it leaves and reload it next | |
2170 | time you restart it. By default, the history file is named |
|
2164 | time you restart it. By default, the history file is named | |
2171 | $IPYTHONDIR/history, but if you've loaded a named profile, |
|
2165 | $IPYTHONDIR/history, but if you've loaded a named profile, | |
2172 | '-PROFILE_NAME' is appended to the name. This allows you to keep |
|
2166 | '-PROFILE_NAME' is appended to the name. This allows you to keep | |
2173 | separate histories related to various tasks: commands related to |
|
2167 | separate histories related to various tasks: commands related to | |
2174 | numerical work will not be clobbered by a system shell history, for |
|
2168 | numerical work will not be clobbered by a system shell history, for | |
2175 | example. |
|
2169 | example. | |
2176 |
|
2170 | |||
2177 |
|
2171 | |||
2178 | Autoindent |
|
2172 | Autoindent | |
2179 | ++++++++++ |
|
2173 | ++++++++++ | |
2180 |
|
2174 | |||
2181 | IPython can recognize lines ending in ':' and indent the next line, |
|
2175 | IPython can recognize lines ending in ':' and indent the next line, | |
2182 | while also un-indenting automatically after 'raise' or 'return'. |
|
2176 | while also un-indenting automatically after 'raise' or 'return'. | |
2183 |
|
2177 | |||
2184 | This feature uses the readline library, so it will honor your ~/.inputrc |
|
2178 | This feature uses the readline library, so it will honor your ~/.inputrc | |
2185 | configuration (or whatever file your INPUTRC variable points to). Adding |
|
2179 | configuration (or whatever file your INPUTRC variable points to). Adding | |
2186 | the following lines to your .inputrc file can make indenting/unindenting |
|
2180 | the following lines to your .inputrc file can make indenting/unindenting | |
2187 | more convenient (M-i indents, M-u unindents):: |
|
2181 | more convenient (M-i indents, M-u unindents):: | |
2188 |
|
2182 | |||
2189 | $if Python |
|
2183 | $if Python | |
2190 | "\M-i": " " |
|
2184 | "\M-i": " " | |
2191 | "\M-u": "\d\d\d\d" |
|
2185 | "\M-u": "\d\d\d\d" | |
2192 | $endif |
|
2186 | $endif | |
2193 |
|
2187 | |||
2194 | Note that there are 4 spaces between the quote marks after "M-i" above. |
|
2188 | Note that there are 4 spaces between the quote marks after "M-i" above. | |
2195 |
|
2189 | |||
2196 | Warning: this feature is ON by default, but it can cause problems with |
|
2190 | Warning: this feature is ON by default, but it can cause problems with | |
2197 | the pasting of multi-line indented code (the pasted code gets |
|
2191 | the pasting of multi-line indented code (the pasted code gets | |
2198 | re-indented on each line). A magic function %autoindent allows you to |
|
2192 | re-indented on each line). A magic function %autoindent allows you to | |
2199 | toggle it on/off at runtime. You can also disable it permanently on in |
|
2193 | toggle it on/off at runtime. You can also disable it permanently on in | |
2200 | your ipythonrc file (set autoindent 0). |
|
2194 | your ipythonrc file (set autoindent 0). | |
2201 |
|
2195 | |||
2202 |
|
2196 | |||
2203 | Customizing readline behavior |
|
2197 | Customizing readline behavior | |
2204 | +++++++++++++++++++++++++++++ |
|
2198 | +++++++++++++++++++++++++++++ | |
2205 |
|
2199 | |||
2206 | All these features are based on the GNU readline library, which has an |
|
2200 | All these features are based on the GNU readline library, which has an | |
2207 | extremely customizable interface. Normally, readline is configured via a |
|
2201 | extremely customizable interface. Normally, readline is configured via a | |
2208 | file which defines the behavior of the library; the details of the |
|
2202 | file which defines the behavior of the library; the details of the | |
2209 | syntax for this can be found in the readline documentation available |
|
2203 | syntax for this can be found in the readline documentation available | |
2210 | with your system or on the Internet. IPython doesn't read this file (if |
|
2204 | with your system or on the Internet. IPython doesn't read this file (if | |
2211 | it exists) directly, but it does support passing to readline valid |
|
2205 | it exists) directly, but it does support passing to readline valid | |
2212 | options via a simple interface. In brief, you can customize readline by |
|
2206 | options via a simple interface. In brief, you can customize readline by | |
2213 | setting the following options in your ipythonrc configuration file (note |
|
2207 | setting the following options in your ipythonrc configuration file (note | |
2214 | that these options can not be specified at the command line): |
|
2208 | that these options can not be specified at the command line): | |
2215 |
|
2209 | |||
2216 | * **readline_parse_and_bind**: this option can appear as many times as |
|
2210 | * **readline_parse_and_bind**: this option can appear as many times as | |
2217 | you want, each time defining a string to be executed via a |
|
2211 | you want, each time defining a string to be executed via a | |
2218 | readline.parse_and_bind() command. The syntax for valid commands |
|
2212 | readline.parse_and_bind() command. The syntax for valid commands | |
2219 | of this kind can be found by reading the documentation for the GNU |
|
2213 | of this kind can be found by reading the documentation for the GNU | |
2220 | readline library, as these commands are of the kind which readline |
|
2214 | readline library, as these commands are of the kind which readline | |
2221 | accepts in its configuration file. |
|
2215 | accepts in its configuration file. | |
2222 | * **readline_remove_delims**: a string of characters to be removed |
|
2216 | * **readline_remove_delims**: a string of characters to be removed | |
2223 | from the default word-delimiters list used by readline, so that |
|
2217 | from the default word-delimiters list used by readline, so that | |
2224 | completions may be performed on strings which contain them. Do not |
|
2218 | completions may be performed on strings which contain them. Do not | |
2225 | change the default value unless you know what you're doing. |
|
2219 | change the default value unless you know what you're doing. | |
2226 | * **readline_omit__names**: when tab-completion is enabled, hitting |
|
2220 | * **readline_omit__names**: when tab-completion is enabled, hitting | |
2227 | <tab> after a '.' in a name will complete all attributes of an |
|
2221 | <tab> after a '.' in a name will complete all attributes of an | |
2228 | object, including all the special methods whose names include |
|
2222 | object, including all the special methods whose names include | |
2229 | double underscores (like __getitem__ or __class__). If you'd |
|
2223 | double underscores (like __getitem__ or __class__). If you'd | |
2230 | rather not see these names by default, you can set this option to |
|
2224 | rather not see these names by default, you can set this option to | |
2231 | 1. Note that even when this option is set, you can still see those |
|
2225 | 1. Note that even when this option is set, you can still see those | |
2232 | names by explicitly typing a _ after the period and hitting <tab>: |
|
2226 | names by explicitly typing a _ after the period and hitting <tab>: | |
2233 | 'name._<tab>' will always complete attribute names starting with '_'. |
|
2227 | 'name._<tab>' will always complete attribute names starting with '_'. | |
2234 |
|
2228 | |||
2235 | This option is off by default so that new users see all |
|
2229 | This option is off by default so that new users see all | |
2236 | attributes of any objects they are dealing with. |
|
2230 | attributes of any objects they are dealing with. | |
2237 |
|
2231 | |||
2238 | You will find the default values along with a corresponding detailed |
|
2232 | You will find the default values along with a corresponding detailed | |
2239 | explanation in your ipythonrc file. |
|
2233 | explanation in your ipythonrc file. | |
2240 |
|
2234 | |||
2241 |
|
2235 | |||
2242 | Session logging and restoring |
|
2236 | Session logging and restoring | |
2243 | ----------------------------- |
|
2237 | ----------------------------- | |
2244 |
|
2238 | |||
2245 | You can log all input from a session either by starting IPython with the |
|
2239 | You can log all input from a session either by starting IPython with the | |
2246 | command line switches -log or -logfile (see :ref:`here <command_line_options>`) |
|
2240 | command line switches -log or -logfile (see :ref:`here <command_line_options>`) | |
2247 | or by activating the logging at any moment with the magic function %logstart. |
|
2241 | or by activating the logging at any moment with the magic function %logstart. | |
2248 |
|
2242 | |||
2249 | Log files can later be reloaded with the -logplay option and IPython |
|
2243 | Log files can later be reloaded with the -logplay option and IPython | |
2250 | will attempt to 'replay' the log by executing all the lines in it, thus |
|
2244 | will attempt to 'replay' the log by executing all the lines in it, thus | |
2251 | restoring the state of a previous session. This feature is not quite |
|
2245 | restoring the state of a previous session. This feature is not quite | |
2252 | perfect, but can still be useful in many cases. |
|
2246 | perfect, but can still be useful in many cases. | |
2253 |
|
2247 | |||
2254 | The log files can also be used as a way to have a permanent record of |
|
2248 | The log files can also be used as a way to have a permanent record of | |
2255 | any code you wrote while experimenting. Log files are regular text files |
|
2249 | any code you wrote while experimenting. Log files are regular text files | |
2256 | which you can later open in your favorite text editor to extract code or |
|
2250 | which you can later open in your favorite text editor to extract code or | |
2257 | to 'clean them up' before using them to replay a session. |
|
2251 | to 'clean them up' before using them to replay a session. | |
2258 |
|
2252 | |||
2259 | The %logstart function for activating logging in mid-session is used as |
|
2253 | The %logstart function for activating logging in mid-session is used as | |
2260 | follows: |
|
2254 | follows: | |
2261 |
|
2255 | |||
2262 | %logstart [log_name [log_mode]] |
|
2256 | %logstart [log_name [log_mode]] | |
2263 |
|
2257 | |||
2264 | If no name is given, it defaults to a file named 'log' in your |
|
2258 | If no name is given, it defaults to a file named 'log' in your | |
2265 | IPYTHONDIR directory, in 'rotate' mode (see below). |
|
2259 | IPYTHONDIR directory, in 'rotate' mode (see below). | |
2266 |
|
2260 | |||
2267 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
2261 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
2268 | history up to that point and then continues logging. |
|
2262 | history up to that point and then continues logging. | |
2269 |
|
2263 | |||
2270 | %logstart takes a second optional parameter: logging mode. This can be |
|
2264 | %logstart takes a second optional parameter: logging mode. This can be | |
2271 | one of (note that the modes are given unquoted): |
|
2265 | one of (note that the modes are given unquoted): | |
2272 |
|
2266 | |||
2273 | * [over:] overwrite existing log_name. |
|
2267 | * [over:] overwrite existing log_name. | |
2274 | * [backup:] rename (if exists) to log_name~ and start log_name. |
|
2268 | * [backup:] rename (if exists) to log_name~ and start log_name. | |
2275 | * [append:] well, that says it. |
|
2269 | * [append:] well, that says it. | |
2276 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. |
|
2270 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. | |
2277 |
|
2271 | |||
2278 | The %logoff and %logon functions allow you to temporarily stop and |
|
2272 | The %logoff and %logon functions allow you to temporarily stop and | |
2279 | resume logging to a file which had previously been started with |
|
2273 | resume logging to a file which had previously been started with | |
2280 | %logstart. They will fail (with an explanation) if you try to use them |
|
2274 | %logstart. They will fail (with an explanation) if you try to use them | |
2281 | before logging has been started. |
|
2275 | before logging has been started. | |
2282 |
|
2276 | |||
2283 | .. _system_shell_access: |
|
2277 | .. _system_shell_access: | |
2284 |
|
2278 | |||
2285 | System shell access |
|
2279 | System shell access | |
2286 | ------------------- |
|
2280 | ------------------- | |
2287 |
|
2281 | |||
2288 | Any input line beginning with a ! character is passed verbatim (minus |
|
2282 | Any input line beginning with a ! character is passed verbatim (minus | |
2289 | the !, of course) to the underlying operating system. For example, |
|
2283 | the !, of course) to the underlying operating system. For example, | |
2290 | typing !ls will run 'ls' in the current directory. |
|
2284 | typing !ls will run 'ls' in the current directory. | |
2291 |
|
2285 | |||
2292 | Manual capture of command output |
|
2286 | Manual capture of command output | |
2293 | -------------------------------- |
|
2287 | -------------------------------- | |
2294 |
|
2288 | |||
2295 | If the input line begins with two exclamation marks, !!, the command is |
|
2289 | If the input line begins with two exclamation marks, !!, the command is | |
2296 | executed but its output is captured and returned as a python list, split |
|
2290 | executed but its output is captured and returned as a python list, split | |
2297 | on newlines. Any output sent by the subprocess to standard error is |
|
2291 | on newlines. Any output sent by the subprocess to standard error is | |
2298 | printed separately, so that the resulting list only captures standard |
|
2292 | printed separately, so that the resulting list only captures standard | |
2299 | output. The !! syntax is a shorthand for the %sx magic command. |
|
2293 | output. The !! syntax is a shorthand for the %sx magic command. | |
2300 |
|
2294 | |||
2301 | Finally, the %sc magic (short for 'shell capture') is similar to %sx, |
|
2295 | Finally, the %sc magic (short for 'shell capture') is similar to %sx, | |
2302 | but allowing more fine-grained control of the capture details, and |
|
2296 | but allowing more fine-grained control of the capture details, and | |
2303 | storing the result directly into a named variable. The direct use of |
|
2297 | storing the result directly into a named variable. The direct use of | |
2304 | %sc is now deprecated, and you should ise the ``var = !cmd`` syntax |
|
2298 | %sc is now deprecated, and you should ise the ``var = !cmd`` syntax | |
2305 | instead. |
|
2299 | instead. | |
2306 |
|
2300 | |||
2307 | IPython also allows you to expand the value of python variables when |
|
2301 | IPython also allows you to expand the value of python variables when | |
2308 | making system calls. Any python variable or expression which you prepend |
|
2302 | making system calls. Any python variable or expression which you prepend | |
2309 | with $ will get expanded before the system call is made:: |
|
2303 | with $ will get expanded before the system call is made:: | |
2310 |
|
2304 | |||
2311 | In [1]: pyvar='Hello world' |
|
2305 | In [1]: pyvar='Hello world' | |
2312 | In [2]: !echo "A python variable: $pyvar" |
|
2306 | In [2]: !echo "A python variable: $pyvar" | |
2313 | A python variable: Hello world |
|
2307 | A python variable: Hello world | |
2314 |
|
2308 | |||
2315 | If you want the shell to actually see a literal $, you need to type it |
|
2309 | If you want the shell to actually see a literal $, you need to type it | |
2316 | twice:: |
|
2310 | twice:: | |
2317 |
|
2311 | |||
2318 | In [3]: !echo "A system variable: $$HOME" |
|
2312 | In [3]: !echo "A system variable: $$HOME" | |
2319 | A system variable: /home/fperez |
|
2313 | A system variable: /home/fperez | |
2320 |
|
2314 | |||
2321 | You can pass arbitrary expressions, though you'll need to delimit them |
|
2315 | You can pass arbitrary expressions, though you'll need to delimit them | |
2322 | with {} if there is ambiguity as to the extent of the expression:: |
|
2316 | with {} if there is ambiguity as to the extent of the expression:: | |
2323 |
|
2317 | |||
2324 | In [5]: x=10 |
|
2318 | In [5]: x=10 | |
2325 | In [6]: y=20 |
|
2319 | In [6]: y=20 | |
2326 | In [13]: !echo $x+y |
|
2320 | In [13]: !echo $x+y | |
2327 | 10+y |
|
2321 | 10+y | |
2328 | In [7]: !echo ${x+y} |
|
2322 | In [7]: !echo ${x+y} | |
2329 | 30 |
|
2323 | 30 | |
2330 |
|
2324 | |||
2331 | Even object attributes can be expanded:: |
|
2325 | Even object attributes can be expanded:: | |
2332 |
|
2326 | |||
2333 | In [12]: !echo $sys.argv |
|
2327 | In [12]: !echo $sys.argv | |
2334 | [/home/fperez/usr/bin/ipython] |
|
2328 | [/home/fperez/usr/bin/ipython] | |
2335 |
|
2329 | |||
2336 |
|
2330 | |||
2337 | System command aliases |
|
2331 | System command aliases | |
2338 | ---------------------- |
|
2332 | ---------------------- | |
2339 |
|
2333 | |||
2340 | The %alias magic function and the alias option in the ipythonrc |
|
2334 | The %alias magic function and the alias option in the ipythonrc | |
2341 | configuration file allow you to define magic functions which are in fact |
|
2335 | configuration file allow you to define magic functions which are in fact | |
2342 | system shell commands. These aliases can have parameters. |
|
2336 | system shell commands. These aliases can have parameters. | |
2343 |
|
2337 | |||
2344 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2338 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2345 |
|
2339 | |||
2346 | Then, typing '%alias_name params' will execute the system command 'cmd |
|
2340 | Then, typing '%alias_name params' will execute the system command 'cmd | |
2347 | params' (from your underlying operating system). |
|
2341 | params' (from your underlying operating system). | |
2348 |
|
2342 | |||
2349 | You can also define aliases with parameters using %s specifiers (one per |
|
2343 | You can also define aliases with parameters using %s specifiers (one per | |
2350 | parameter). The following example defines the %parts function as an |
|
2344 | parameter). The following example defines the %parts function as an | |
2351 | alias to the command 'echo first %s second %s' where each %s will be |
|
2345 | alias to the command 'echo first %s second %s' where each %s will be | |
2352 | replaced by a positional parameter to the call to %parts:: |
|
2346 | replaced by a positional parameter to the call to %parts:: | |
2353 |
|
2347 | |||
2354 | In [1]: alias parts echo first %s second %s |
|
2348 | In [1]: alias parts echo first %s second %s | |
2355 | In [2]: %parts A B |
|
2349 | In [2]: %parts A B | |
2356 | first A second B |
|
2350 | first A second B | |
2357 | In [3]: %parts A |
|
2351 | In [3]: %parts A | |
2358 | Incorrect number of arguments: 2 expected. |
|
2352 | Incorrect number of arguments: 2 expected. | |
2359 | parts is an alias to: 'echo first %s second %s' |
|
2353 | parts is an alias to: 'echo first %s second %s' | |
2360 |
|
2354 | |||
2361 | If called with no parameters, %alias prints the table of currently |
|
2355 | If called with no parameters, %alias prints the table of currently | |
2362 | defined aliases. |
|
2356 | defined aliases. | |
2363 |
|
2357 | |||
2364 | The %rehash/rehashx magics allow you to load your entire $PATH as |
|
2358 | The %rehash/rehashx magics allow you to load your entire $PATH as | |
2365 | ipython aliases. See their respective docstrings (or sec. 6.2 |
|
2359 | ipython aliases. See their respective docstrings (or sec. 6.2 | |
2366 | <#sec:magic> for further details). |
|
2360 | <#sec:magic> for further details). | |
2367 |
|
2361 | |||
2368 |
|
2362 | |||
2369 | .. _dreload: |
|
2363 | .. _dreload: | |
2370 |
|
2364 | |||
2371 | Recursive reload |
|
2365 | Recursive reload | |
2372 | ---------------- |
|
2366 | ---------------- | |
2373 |
|
2367 | |||
2374 | The dreload function does a recursive reload of a module: changes made |
|
2368 | The dreload function does a recursive reload of a module: changes made | |
2375 | to the module since you imported will actually be available without |
|
2369 | to the module since you imported will actually be available without | |
2376 | having to exit. |
|
2370 | having to exit. | |
2377 |
|
2371 | |||
2378 |
|
2372 | |||
2379 | Verbose and colored exception traceback printouts |
|
2373 | Verbose and colored exception traceback printouts | |
2380 | ------------------------------------------------- |
|
2374 | ------------------------------------------------- | |
2381 |
|
2375 | |||
2382 | IPython provides the option to see very detailed exception tracebacks, |
|
2376 | IPython provides the option to see very detailed exception tracebacks, | |
2383 | which can be especially useful when debugging large programs. You can |
|
2377 | which can be especially useful when debugging large programs. You can | |
2384 | run any Python file with the %run function to benefit from these |
|
2378 | run any Python file with the %run function to benefit from these | |
2385 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can |
|
2379 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can | |
2386 | be colored (if your terminal supports it) which makes them much easier |
|
2380 | be colored (if your terminal supports it) which makes them much easier | |
2387 | to parse visually. |
|
2381 | to parse visually. | |
2388 |
|
2382 | |||
2389 | See the magic xmode and colors functions for details (just type %magic). |
|
2383 | See the magic xmode and colors functions for details (just type %magic). | |
2390 |
|
2384 | |||
2391 | These features are basically a terminal version of Ka-Ping Yee's cgitb |
|
2385 | These features are basically a terminal version of Ka-Ping Yee's cgitb | |
2392 | module, now part of the standard Python library. |
|
2386 | module, now part of the standard Python library. | |
2393 |
|
2387 | |||
2394 |
|
2388 | |||
2395 | .. _input_caching: |
|
2389 | .. _input_caching: | |
2396 |
|
2390 | |||
2397 | Input caching system |
|
2391 | Input caching system | |
2398 | -------------------- |
|
2392 | -------------------- | |
2399 |
|
2393 | |||
2400 | IPython offers numbered prompts (In/Out) with input and output caching |
|
2394 | IPython offers numbered prompts (In/Out) with input and output caching | |
2401 | (also referred to as 'input history'). All input is saved and can be |
|
2395 | (also referred to as 'input history'). All input is saved and can be | |
2402 | retrieved as variables (besides the usual arrow key recall), in |
|
2396 | retrieved as variables (besides the usual arrow key recall), in | |
2403 | addition to the %rep magic command that brings a history entry |
|
2397 | addition to the %rep magic command that brings a history entry | |
2404 | up for editing on the next command line. |
|
2398 | up for editing on the next command line. | |
2405 |
|
2399 | |||
2406 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
2400 | The following GLOBAL variables always exist (so don't overwrite them!): | |
2407 | _i: stores previous input. _ii: next previous. _iii: next-next previous. |
|
2401 | _i: stores previous input. _ii: next previous. _iii: next-next previous. | |
2408 | _ih : a list of all input _ih[n] is the input from line n and this list |
|
2402 | _ih : a list of all input _ih[n] is the input from line n and this list | |
2409 | is aliased to the global variable In. If you overwrite In with a |
|
2403 | is aliased to the global variable In. If you overwrite In with a | |
2410 | variable of your own, you can remake the assignment to the internal list |
|
2404 | variable of your own, you can remake the assignment to the internal list | |
2411 | with a simple 'In=_ih'. |
|
2405 | with a simple 'In=_ih'. | |
2412 |
|
2406 | |||
2413 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
2407 | Additionally, global variables named _i<n> are dynamically created (<n> | |
2414 | being the prompt counter), such that |
|
2408 | being the prompt counter), such that | |
2415 | _i<n> == _ih[<n>] == In[<n>]. |
|
2409 | _i<n> == _ih[<n>] == In[<n>]. | |
2416 |
|
2410 | |||
2417 | For example, what you typed at prompt 14 is available as _i14, _ih[14] |
|
2411 | For example, what you typed at prompt 14 is available as _i14, _ih[14] | |
2418 | and In[14]. |
|
2412 | and In[14]. | |
2419 |
|
2413 | |||
2420 | This allows you to easily cut and paste multi line interactive prompts |
|
2414 | This allows you to easily cut and paste multi line interactive prompts | |
2421 | by printing them out: they print like a clean string, without prompt |
|
2415 | by printing them out: they print like a clean string, without prompt | |
2422 | characters. You can also manipulate them like regular variables (they |
|
2416 | characters. You can also manipulate them like regular variables (they | |
2423 | are strings), modify or exec them (typing 'exec _i9' will re-execute the |
|
2417 | are strings), modify or exec them (typing 'exec _i9' will re-execute the | |
2424 | contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines |
|
2418 | contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines | |
2425 | 9 through 13 and line 18). |
|
2419 | 9 through 13 and line 18). | |
2426 |
|
2420 | |||
2427 | You can also re-execute multiple lines of input easily by using the |
|
2421 | You can also re-execute multiple lines of input easily by using the | |
2428 | magic %macro function (which automates the process and allows |
|
2422 | magic %macro function (which automates the process and allows | |
2429 | re-execution without having to type 'exec' every time). The macro system |
|
2423 | re-execution without having to type 'exec' every time). The macro system | |
2430 | also allows you to re-execute previous lines which include magic |
|
2424 | also allows you to re-execute previous lines which include magic | |
2431 | function calls (which require special processing). Type %macro? or see |
|
2425 | function calls (which require special processing). Type %macro? or see | |
2432 | sec. 6.2 <#sec:magic> for more details on the macro system. |
|
2426 | sec. 6.2 <#sec:magic> for more details on the macro system. | |
2433 |
|
2427 | |||
2434 | A history function %hist allows you to see any part of your input |
|
2428 | A history function %hist allows you to see any part of your input | |
2435 | history by printing a range of the _i variables. |
|
2429 | history by printing a range of the _i variables. | |
2436 |
|
2430 | |||
2437 | You can also search ('grep') through your history by typing |
|
2431 | You can also search ('grep') through your history by typing | |
2438 | '%hist -g somestring'. This also searches through the so called *shadow history*, |
|
2432 | '%hist -g somestring'. This also searches through the so called *shadow history*, | |
2439 | which remembers all the commands (apart from multiline code blocks) |
|
2433 | which remembers all the commands (apart from multiline code blocks) | |
2440 | you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses |
|
2434 | you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses | |
2441 | etc. You can bring shadow history entries listed by '%hist -g' up for editing |
|
2435 | etc. You can bring shadow history entries listed by '%hist -g' up for editing | |
2442 | (or re-execution by just pressing ENTER) with %rep command. Shadow history |
|
2436 | (or re-execution by just pressing ENTER) with %rep command. Shadow history | |
2443 | entries are not available as _iNUMBER variables, and they are identified by |
|
2437 | entries are not available as _iNUMBER variables, and they are identified by | |
2444 | the '0' prefix in %hist -g output. That is, history entry 12 is a normal |
|
2438 | the '0' prefix in %hist -g output. That is, history entry 12 is a normal | |
2445 | history entry, but 0231 is a shadow history entry. |
|
2439 | history entry, but 0231 is a shadow history entry. | |
2446 |
|
2440 | |||
2447 | Shadow history was added because the readline history is inherently very |
|
2441 | Shadow history was added because the readline history is inherently very | |
2448 | unsafe - if you have multiple IPython sessions open, the last session |
|
2442 | unsafe - if you have multiple IPython sessions open, the last session | |
2449 | to close will overwrite the history of previountly closed session. Likewise, |
|
2443 | to close will overwrite the history of previountly closed session. Likewise, | |
2450 | if a crash occurs, history is never saved, whereas shadow history entries |
|
2444 | if a crash occurs, history is never saved, whereas shadow history entries | |
2451 | are added after entering every command (so a command executed |
|
2445 | are added after entering every command (so a command executed | |
2452 | in another IPython session is immediately available in other IPython |
|
2446 | in another IPython session is immediately available in other IPython | |
2453 | sessions that are open). |
|
2447 | sessions that are open). | |
2454 |
|
2448 | |||
2455 | To conserve space, a command can exist in shadow history only once - it doesn't |
|
2449 | To conserve space, a command can exist in shadow history only once - it doesn't | |
2456 | make sense to store a common line like "cd .." a thousand times. The idea is |
|
2450 | make sense to store a common line like "cd .." a thousand times. The idea is | |
2457 | mainly to provide a reliable place where valuable, hard-to-remember commands can |
|
2451 | mainly to provide a reliable place where valuable, hard-to-remember commands can | |
2458 | always be retrieved, as opposed to providing an exact sequence of commands |
|
2452 | always be retrieved, as opposed to providing an exact sequence of commands | |
2459 | you have entered in actual order. |
|
2453 | you have entered in actual order. | |
2460 |
|
2454 | |||
2461 | Because shadow history has all the commands you have ever executed, |
|
2455 | Because shadow history has all the commands you have ever executed, | |
2462 | time taken by %hist -g will increase oven time. If it ever starts to take |
|
2456 | time taken by %hist -g will increase oven time. If it ever starts to take | |
2463 | too long (or it ends up containing sensitive information like passwords), |
|
2457 | too long (or it ends up containing sensitive information like passwords), | |
2464 | clear the shadow history by `%clear shadow_nuke`. |
|
2458 | clear the shadow history by `%clear shadow_nuke`. | |
2465 |
|
2459 | |||
2466 | Time taken to add entries to shadow history should be negligible, but |
|
2460 | Time taken to add entries to shadow history should be negligible, but | |
2467 | in any case, if you start noticing performance degradation after using |
|
2461 | in any case, if you start noticing performance degradation after using | |
2468 | IPython for a long time (or running a script that floods the shadow history!), |
|
2462 | IPython for a long time (or running a script that floods the shadow history!), | |
2469 | you can 'compress' the shadow history by executing |
|
2463 | you can 'compress' the shadow history by executing | |
2470 | `%clear shadow_compress`. In practice, this should never be necessary |
|
2464 | `%clear shadow_compress`. In practice, this should never be necessary | |
2471 | in normal use. |
|
2465 | in normal use. | |
2472 |
|
2466 | |||
2473 | .. _output_caching: |
|
2467 | .. _output_caching: | |
2474 |
|
2468 | |||
2475 | Output caching system |
|
2469 | Output caching system | |
2476 | --------------------- |
|
2470 | --------------------- | |
2477 |
|
2471 | |||
2478 | For output that is returned from actions, a system similar to the input |
|
2472 | For output that is returned from actions, a system similar to the input | |
2479 | cache exists but using _ instead of _i. Only actions that produce a |
|
2473 | cache exists but using _ instead of _i. Only actions that produce a | |
2480 | result (NOT assignments, for example) are cached. If you are familiar |
|
2474 | result (NOT assignments, for example) are cached. If you are familiar | |
2481 | with Mathematica, IPython's _ variables behave exactly like |
|
2475 | with Mathematica, IPython's _ variables behave exactly like | |
2482 | Mathematica's % variables. |
|
2476 | Mathematica's % variables. | |
2483 |
|
2477 | |||
2484 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
2478 | The following GLOBAL variables always exist (so don't overwrite them!): | |
2485 |
|
2479 | |||
2486 | * [_] (a single underscore) : stores previous output, like Python's |
|
2480 | * [_] (a single underscore) : stores previous output, like Python's | |
2487 | default interpreter. |
|
2481 | default interpreter. | |
2488 | * [__] (two underscores): next previous. |
|
2482 | * [__] (two underscores): next previous. | |
2489 | * [___] (three underscores): next-next previous. |
|
2483 | * [___] (three underscores): next-next previous. | |
2490 |
|
2484 | |||
2491 | Additionally, global variables named _<n> are dynamically created (<n> |
|
2485 | Additionally, global variables named _<n> are dynamically created (<n> | |
2492 | being the prompt counter), such that the result of output <n> is always |
|
2486 | being the prompt counter), such that the result of output <n> is always | |
2493 | available as _<n> (don't use the angle brackets, just the number, e.g. |
|
2487 | available as _<n> (don't use the angle brackets, just the number, e.g. | |
2494 | _21). |
|
2488 | _21). | |
2495 |
|
2489 | |||
2496 | These global variables are all stored in a global dictionary (not a |
|
2490 | These global variables are all stored in a global dictionary (not a | |
2497 | list, since it only has entries for lines which returned a result) |
|
2491 | list, since it only has entries for lines which returned a result) | |
2498 | available under the names _oh and Out (similar to _ih and In). So the |
|
2492 | available under the names _oh and Out (similar to _ih and In). So the | |
2499 | output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you |
|
2493 | output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you | |
2500 | accidentally overwrite the Out variable you can recover it by typing |
|
2494 | accidentally overwrite the Out variable you can recover it by typing | |
2501 | 'Out=_oh' at the prompt. |
|
2495 | 'Out=_oh' at the prompt. | |
2502 |
|
2496 | |||
2503 | This system obviously can potentially put heavy memory demands on your |
|
2497 | This system obviously can potentially put heavy memory demands on your | |
2504 | system, since it prevents Python's garbage collector from removing any |
|
2498 | system, since it prevents Python's garbage collector from removing any | |
2505 | previously computed results. You can control how many results are kept |
|
2499 | previously computed results. You can control how many results are kept | |
2506 | in memory with the option (at the command line or in your ipythonrc |
|
2500 | in memory with the option (at the command line or in your ipythonrc | |
2507 | file) cache_size. If you set it to 0, the whole system is completely |
|
2501 | file) cache_size. If you set it to 0, the whole system is completely | |
2508 | disabled and the prompts revert to the classic '>>>' of normal Python. |
|
2502 | disabled and the prompts revert to the classic '>>>' of normal Python. | |
2509 |
|
2503 | |||
2510 |
|
2504 | |||
2511 | Directory history |
|
2505 | Directory history | |
2512 | ----------------- |
|
2506 | ----------------- | |
2513 |
|
2507 | |||
2514 | Your history of visited directories is kept in the global list _dh, and |
|
2508 | Your history of visited directories is kept in the global list _dh, and | |
2515 | the magic %cd command can be used to go to any entry in that list. The |
|
2509 | the magic %cd command can be used to go to any entry in that list. The | |
2516 | %dhist command allows you to view this history. Do ``cd -<TAB`` to |
|
2510 | %dhist command allows you to view this history. Do ``cd -<TAB`` to | |
2517 | conventiently view the directory history. |
|
2511 | conventiently view the directory history. | |
2518 |
|
2512 | |||
2519 |
|
2513 | |||
2520 | Automatic parentheses and quotes |
|
2514 | Automatic parentheses and quotes | |
2521 | -------------------------------- |
|
2515 | -------------------------------- | |
2522 |
|
2516 | |||
2523 | These features were adapted from Nathan Gray's LazyPython. They are |
|
2517 | These features were adapted from Nathan Gray's LazyPython. They are | |
2524 | meant to allow less typing for common situations. |
|
2518 | meant to allow less typing for common situations. | |
2525 |
|
2519 | |||
2526 |
|
2520 | |||
2527 | Automatic parentheses |
|
2521 | Automatic parentheses | |
2528 | --------------------- |
|
2522 | --------------------- | |
2529 |
|
2523 | |||
2530 | Callable objects (i.e. functions, methods, etc) can be invoked like this |
|
2524 | Callable objects (i.e. functions, methods, etc) can be invoked like this | |
2531 | (notice the commas between the arguments):: |
|
2525 | (notice the commas between the arguments):: | |
2532 |
|
2526 | |||
2533 | >>> callable_ob arg1, arg2, arg3 |
|
2527 | >>> callable_ob arg1, arg2, arg3 | |
2534 |
|
2528 | |||
2535 | and the input will be translated to this:: |
|
2529 | and the input will be translated to this:: | |
2536 |
|
2530 | |||
2537 | -> callable_ob(arg1, arg2, arg3) |
|
2531 | -> callable_ob(arg1, arg2, arg3) | |
2538 |
|
2532 | |||
2539 | You can force automatic parentheses by using '/' as the first character |
|
2533 | You can force automatic parentheses by using '/' as the first character | |
2540 | of a line. For example:: |
|
2534 | of a line. For example:: | |
2541 |
|
2535 | |||
2542 | >>> /globals # becomes 'globals()' |
|
2536 | >>> /globals # becomes 'globals()' | |
2543 |
|
2537 | |||
2544 | Note that the '/' MUST be the first character on the line! This won't work:: |
|
2538 | Note that the '/' MUST be the first character on the line! This won't work:: | |
2545 |
|
2539 | |||
2546 | >>> print /globals # syntax error |
|
2540 | >>> print /globals # syntax error | |
2547 |
|
2541 | |||
2548 | In most cases the automatic algorithm should work, so you should rarely |
|
2542 | In most cases the automatic algorithm should work, so you should rarely | |
2549 | need to explicitly invoke /. One notable exception is if you are trying |
|
2543 | need to explicitly invoke /. One notable exception is if you are trying | |
2550 | to call a function with a list of tuples as arguments (the parenthesis |
|
2544 | to call a function with a list of tuples as arguments (the parenthesis | |
2551 | will confuse IPython):: |
|
2545 | will confuse IPython):: | |
2552 |
|
2546 | |||
2553 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
2547 | In [1]: zip (1,2,3),(4,5,6) # won't work | |
2554 |
|
2548 | |||
2555 | but this will work:: |
|
2549 | but this will work:: | |
2556 |
|
2550 | |||
2557 | In [2]: /zip (1,2,3),(4,5,6) |
|
2551 | In [2]: /zip (1,2,3),(4,5,6) | |
2558 | ---> zip ((1,2,3),(4,5,6)) |
|
2552 | ---> zip ((1,2,3),(4,5,6)) | |
2559 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
2553 | Out[2]= [(1, 4), (2, 5), (3, 6)] | |
2560 |
|
2554 | |||
2561 | IPython tells you that it has altered your command line by displaying |
|
2555 | IPython tells you that it has altered your command line by displaying | |
2562 | the new command line preceded by ->. e.g.:: |
|
2556 | the new command line preceded by ->. e.g.:: | |
2563 |
|
2557 | |||
2564 | In [18]: callable list |
|
2558 | In [18]: callable list | |
2565 | ----> callable (list) |
|
2559 | ----> callable (list) | |
2566 |
|
2560 | |||
2567 |
|
2561 | |||
2568 | Automatic quoting |
|
2562 | Automatic quoting | |
2569 | ----------------- |
|
2563 | ----------------- | |
2570 |
|
2564 | |||
2571 | You can force automatic quoting of a function's arguments by using ',' |
|
2565 | You can force automatic quoting of a function's arguments by using ',' | |
2572 | or ';' as the first character of a line. For example:: |
|
2566 | or ';' as the first character of a line. For example:: | |
2573 |
|
2567 | |||
2574 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
2568 | >>> ,my_function /home/me # becomes my_function("/home/me") | |
2575 |
|
2569 | |||
2576 | If you use ';' instead, the whole argument is quoted as a single string |
|
2570 | If you use ';' instead, the whole argument is quoted as a single string | |
2577 | (while ',' splits on whitespace):: |
|
2571 | (while ',' splits on whitespace):: | |
2578 |
|
2572 | |||
2579 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
2573 | >>> ,my_function a b c # becomes my_function("a","b","c") | |
2580 |
|
2574 | |||
2581 | >>> ;my_function a b c # becomes my_function("a b c") |
|
2575 | >>> ;my_function a b c # becomes my_function("a b c") | |
2582 |
|
2576 | |||
2583 | Note that the ',' or ';' MUST be the first character on the line! This |
|
2577 | Note that the ',' or ';' MUST be the first character on the line! This | |
2584 | won't work:: |
|
2578 | won't work:: | |
2585 |
|
2579 | |||
2586 | >>> x = ,my_function /home/me # syntax error |
|
2580 | >>> x = ,my_function /home/me # syntax error | |
2587 |
|
2581 | |||
2588 | IPython as your default Python environment |
|
2582 | IPython as your default Python environment | |
2589 | ========================================== |
|
2583 | ========================================== | |
2590 |
|
2584 | |||
2591 | Python honors the environment variable PYTHONSTARTUP and will execute at |
|
2585 | Python honors the environment variable PYTHONSTARTUP and will execute at | |
2592 | startup the file referenced by this variable. If you put at the end of |
|
2586 | startup the file referenced by this variable. If you put at the end of | |
2593 | this file the following two lines of code:: |
|
2587 | this file the following two lines of code:: | |
2594 |
|
2588 | |||
2595 | import IPython |
|
2589 | import IPython | |
2596 | IPython.Shell.IPShell().mainloop(sys_exit=1) |
|
2590 | IPython.Shell.IPShell().mainloop(sys_exit=1) | |
2597 |
|
2591 | |||
2598 | then IPython will be your working environment anytime you start Python. |
|
2592 | then IPython will be your working environment anytime you start Python. | |
2599 | The sys_exit=1 is needed to have IPython issue a call to sys.exit() when |
|
2593 | The sys_exit=1 is needed to have IPython issue a call to sys.exit() when | |
2600 | it finishes, otherwise you'll be back at the normal Python '>>>' |
|
2594 | it finishes, otherwise you'll be back at the normal Python '>>>' | |
2601 | prompt. |
|
2595 | prompt. | |
2602 |
|
2596 | |||
2603 | This is probably useful to developers who manage multiple Python |
|
2597 | This is probably useful to developers who manage multiple Python | |
2604 | versions and don't want to have correspondingly multiple IPython |
|
2598 | versions and don't want to have correspondingly multiple IPython | |
2605 | versions. Note that in this mode, there is no way to pass IPython any |
|
2599 | versions. Note that in this mode, there is no way to pass IPython any | |
2606 | command-line options, as those are trapped first by Python itself. |
|
2600 | command-line options, as those are trapped first by Python itself. | |
2607 |
|
2601 | |||
2608 | .. _Embedding: |
|
2602 | .. _Embedding: | |
2609 |
|
2603 | |||
2610 | Embedding IPython |
|
2604 | Embedding IPython | |
2611 | ================= |
|
2605 | ================= | |
2612 |
|
2606 | |||
2613 | It is possible to start an IPython instance inside your own Python |
|
2607 | It is possible to start an IPython instance inside your own Python | |
2614 | programs. This allows you to evaluate dynamically the state of your |
|
2608 | programs. This allows you to evaluate dynamically the state of your | |
2615 | code, operate with your variables, analyze them, etc. Note however that |
|
2609 | code, operate with your variables, analyze them, etc. Note however that | |
2616 | any changes you make to values while in the shell do not propagate back |
|
2610 | any changes you make to values while in the shell do not propagate back | |
2617 | to the running code, so it is safe to modify your values because you |
|
2611 | to the running code, so it is safe to modify your values because you | |
2618 | won't break your code in bizarre ways by doing so. |
|
2612 | won't break your code in bizarre ways by doing so. | |
2619 |
|
2613 | |||
2620 | This feature allows you to easily have a fully functional python |
|
2614 | This feature allows you to easily have a fully functional python | |
2621 | environment for doing object introspection anywhere in your code with a |
|
2615 | environment for doing object introspection anywhere in your code with a | |
2622 | simple function call. In some cases a simple print statement is enough, |
|
2616 | simple function call. In some cases a simple print statement is enough, | |
2623 | but if you need to do more detailed analysis of a code fragment this |
|
2617 | but if you need to do more detailed analysis of a code fragment this | |
2624 | feature can be very valuable. |
|
2618 | feature can be very valuable. | |
2625 |
|
2619 | |||
2626 | It can also be useful in scientific computing situations where it is |
|
2620 | It can also be useful in scientific computing situations where it is | |
2627 | common to need to do some automatic, computationally intensive part and |
|
2621 | common to need to do some automatic, computationally intensive part and | |
2628 | then stop to look at data, plots, etc. |
|
2622 | then stop to look at data, plots, etc. | |
2629 | Opening an IPython instance will give you full access to your data and |
|
2623 | Opening an IPython instance will give you full access to your data and | |
2630 | functions, and you can resume program execution once you are done with |
|
2624 | functions, and you can resume program execution once you are done with | |
2631 | the interactive part (perhaps to stop again later, as many times as |
|
2625 | the interactive part (perhaps to stop again later, as many times as | |
2632 | needed). |
|
2626 | needed). | |
2633 |
|
2627 | |||
2634 | The following code snippet is the bare minimum you need to include in |
|
2628 | The following code snippet is the bare minimum you need to include in | |
2635 | your Python programs for this to work (detailed examples follow later):: |
|
2629 | your Python programs for this to work (detailed examples follow later):: | |
2636 |
|
2630 | |||
2637 | from IPython.Shell import IPShellEmbed |
|
2631 | from IPython.Shell import IPShellEmbed | |
2638 |
|
2632 | |||
2639 | ipshell = IPShellEmbed() |
|
2633 | ipshell = IPShellEmbed() | |
2640 |
|
2634 | |||
2641 | ipshell() # this call anywhere in your program will start IPython |
|
2635 | ipshell() # this call anywhere in your program will start IPython | |
2642 |
|
2636 | |||
2643 | You can run embedded instances even in code which is itself being run at |
|
2637 | You can run embedded instances even in code which is itself being run at | |
2644 | the IPython interactive prompt with '%run <filename>'. Since it's easy |
|
2638 | the IPython interactive prompt with '%run <filename>'. Since it's easy | |
2645 | to get lost as to where you are (in your top-level IPython or in your |
|
2639 | to get lost as to where you are (in your top-level IPython or in your | |
2646 | embedded one), it's a good idea in such cases to set the in/out prompts |
|
2640 | embedded one), it's a good idea in such cases to set the in/out prompts | |
2647 | to something different for the embedded instances. The code examples |
|
2641 | to something different for the embedded instances. The code examples | |
2648 | below illustrate this. |
|
2642 | below illustrate this. | |
2649 |
|
2643 | |||
2650 | You can also have multiple IPython instances in your program and open |
|
2644 | You can also have multiple IPython instances in your program and open | |
2651 | them separately, for example with different options for data |
|
2645 | them separately, for example with different options for data | |
2652 | presentation. If you close and open the same instance multiple times, |
|
2646 | presentation. If you close and open the same instance multiple times, | |
2653 | its prompt counters simply continue from each execution to the next. |
|
2647 | its prompt counters simply continue from each execution to the next. | |
2654 |
|
2648 | |||
2655 | Please look at the docstrings in the Shell.py module for more details on |
|
2649 | Please look at the docstrings in the Shell.py module for more details on | |
2656 | the use of this system. |
|
2650 | the use of this system. | |
2657 |
|
2651 | |||
2658 | The following sample file illustrating how to use the embedding |
|
2652 | The following sample file illustrating how to use the embedding | |
2659 | functionality is provided in the examples directory as example-embed.py. |
|
2653 | functionality is provided in the examples directory as example-embed.py. | |
2660 | It should be fairly self-explanatory:: |
|
2654 | It should be fairly self-explanatory:: | |
2661 |
|
2655 | |||
2662 |
|
2656 | |||
2663 | #!/usr/bin/env python |
|
2657 | #!/usr/bin/env python | |
2664 |
|
2658 | |||
2665 | """An example of how to embed an IPython shell into a running program. |
|
2659 | """An example of how to embed an IPython shell into a running program. | |
2666 |
|
2660 | |||
2667 | Please see the documentation in the IPython.Shell module for more details. |
|
2661 | Please see the documentation in the IPython.Shell module for more details. | |
2668 |
|
2662 | |||
2669 | The accompanying file example-embed-short.py has quick code fragments for |
|
2663 | The accompanying file example-embed-short.py has quick code fragments for | |
2670 | embedding which you can cut and paste in your code once you understand how |
|
2664 | embedding which you can cut and paste in your code once you understand how | |
2671 | things work. |
|
2665 | things work. | |
2672 |
|
2666 | |||
2673 | The code in this file is deliberately extra-verbose, meant for learning.""" |
|
2667 | The code in this file is deliberately extra-verbose, meant for learning.""" | |
2674 |
|
2668 | |||
2675 | # The basics to get you going: |
|
2669 | # The basics to get you going: | |
2676 |
|
2670 | |||
2677 | # IPython sets the __IPYTHON__ variable so you can know if you have nested |
|
2671 | # IPython sets the __IPYTHON__ variable so you can know if you have nested | |
2678 | # copies running. |
|
2672 | # copies running. | |
2679 |
|
2673 | |||
2680 | # Try running this code both at the command line and from inside IPython (with |
|
2674 | # Try running this code both at the command line and from inside IPython (with | |
2681 | # %run example-embed.py) |
|
2675 | # %run example-embed.py) | |
2682 | try: |
|
2676 | try: | |
2683 | __IPYTHON__ |
|
2677 | __IPYTHON__ | |
2684 | except NameError: |
|
2678 | except NameError: | |
2685 | nested = 0 |
|
2679 | nested = 0 | |
2686 | args = [''] |
|
2680 | args = [''] | |
2687 | else: |
|
2681 | else: | |
2688 | print "Running nested copies of IPython." |
|
2682 | print "Running nested copies of IPython." | |
2689 | print "The prompts for the nested copy have been modified" |
|
2683 | print "The prompts for the nested copy have been modified" | |
2690 | nested = 1 |
|
2684 | nested = 1 | |
2691 | # what the embedded instance will see as sys.argv: |
|
2685 | # what the embedded instance will see as sys.argv: | |
2692 | args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ', |
|
2686 | args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ', | |
2693 | '-po','Out<\\#>: ','-nosep'] |
|
2687 | '-po','Out<\\#>: ','-nosep'] | |
2694 |
|
2688 | |||
2695 | # First import the embeddable shell class |
|
2689 | # First import the embeddable shell class | |
2696 | from IPython.Shell import IPShellEmbed |
|
2690 | from IPython.Shell import IPShellEmbed | |
2697 |
|
2691 | |||
2698 | # Now create an instance of the embeddable shell. The first argument is a |
|
2692 | # Now create an instance of the embeddable shell. The first argument is a | |
2699 | # string with options exactly as you would type them if you were starting |
|
2693 | # string with options exactly as you would type them if you were starting | |
2700 | # IPython at the system command line. Any parameters you want to define for |
|
2694 | # IPython at the system command line. Any parameters you want to define for | |
2701 | # configuration can thus be specified here. |
|
2695 | # configuration can thus be specified here. | |
2702 | ipshell = IPShellEmbed(args, |
|
2696 | ipshell = IPShellEmbed(args, | |
2703 | banner = 'Dropping into IPython', |
|
2697 | banner = 'Dropping into IPython', | |
2704 | exit_msg = 'Leaving Interpreter, back to program.') |
|
2698 | exit_msg = 'Leaving Interpreter, back to program.') | |
2705 |
|
2699 | |||
2706 | # Make a second instance, you can have as many as you want. |
|
2700 | # Make a second instance, you can have as many as you want. | |
2707 | if nested: |
|
2701 | if nested: | |
2708 | args[1] = 'In2<\\#>' |
|
2702 | args[1] = 'In2<\\#>' | |
2709 | else: |
|
2703 | else: | |
2710 | args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ', |
|
2704 | args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ', | |
2711 | '-po','Out<\\#>: ','-nosep'] |
|
2705 | '-po','Out<\\#>: ','-nosep'] | |
2712 | ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.') |
|
2706 | ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.') | |
2713 |
|
2707 | |||
2714 | print '\nHello. This is printed from the main controller program.\n' |
|
2708 | print '\nHello. This is printed from the main controller program.\n' | |
2715 |
|
2709 | |||
2716 | # You can then call ipshell() anywhere you need it (with an optional |
|
2710 | # You can then call ipshell() anywhere you need it (with an optional | |
2717 | # message): |
|
2711 | # message): | |
2718 | ipshell('***Called from top level. ' |
|
2712 | ipshell('***Called from top level. ' | |
2719 | 'Hit Ctrl-D to exit interpreter and continue program.\n' |
|
2713 | 'Hit Ctrl-D to exit interpreter and continue program.\n' | |
2720 | 'Note that if you use %kill_embedded, you can fully deactivate\n' |
|
2714 | 'Note that if you use %kill_embedded, you can fully deactivate\n' | |
2721 | 'This embedded instance so it will never turn on again') |
|
2715 | 'This embedded instance so it will never turn on again') | |
2722 |
|
2716 | |||
2723 | print '\nBack in caller program, moving along...\n' |
|
2717 | print '\nBack in caller program, moving along...\n' | |
2724 |
|
2718 | |||
2725 | #--------------------------------------------------------------------------- |
|
2719 | #--------------------------------------------------------------------------- | |
2726 | # More details: |
|
2720 | # More details: | |
2727 |
|
2721 | |||
2728 | # IPShellEmbed instances don't print the standard system banner and |
|
2722 | # IPShellEmbed instances don't print the standard system banner and | |
2729 | # messages. The IPython banner (which actually may contain initialization |
|
2723 | # messages. The IPython banner (which actually may contain initialization | |
2730 | # messages) is available as <instance>.IP.BANNER in case you want it. |
|
2724 | # messages) is available as <instance>.IP.BANNER in case you want it. | |
2731 |
|
2725 | |||
2732 | # IPShellEmbed instances print the following information everytime they |
|
2726 | # IPShellEmbed instances print the following information everytime they | |
2733 | # start: |
|
2727 | # start: | |
2734 |
|
2728 | |||
2735 | # - A global startup banner. |
|
2729 | # - A global startup banner. | |
2736 |
|
2730 | |||
2737 | # - A call-specific header string, which you can use to indicate where in the |
|
2731 | # - A call-specific header string, which you can use to indicate where in the | |
2738 | # execution flow the shell is starting. |
|
2732 | # execution flow the shell is starting. | |
2739 |
|
2733 | |||
2740 | # They also print an exit message every time they exit. |
|
2734 | # They also print an exit message every time they exit. | |
2741 |
|
2735 | |||
2742 | # Both the startup banner and the exit message default to None, and can be set |
|
2736 | # Both the startup banner and the exit message default to None, and can be set | |
2743 | # either at the instance constructor or at any other time with the |
|
2737 | # either at the instance constructor or at any other time with the | |
2744 | # set_banner() and set_exit_msg() methods. |
|
2738 | # set_banner() and set_exit_msg() methods. | |
2745 |
|
2739 | |||
2746 | # The shell instance can be also put in 'dummy' mode globally or on a per-call |
|
2740 | # The shell instance can be also put in 'dummy' mode globally or on a per-call | |
2747 | # basis. This gives you fine control for debugging without having to change |
|
2741 | # basis. This gives you fine control for debugging without having to change | |
2748 | # code all over the place. |
|
2742 | # code all over the place. | |
2749 |
|
2743 | |||
2750 | # The code below illustrates all this. |
|
2744 | # The code below illustrates all this. | |
2751 |
|
2745 | |||
2752 |
|
2746 | |||
2753 | # This is how the global banner and exit_msg can be reset at any point |
|
2747 | # This is how the global banner and exit_msg can be reset at any point | |
2754 | ipshell.set_banner('Entering interpreter - New Banner') |
|
2748 | ipshell.set_banner('Entering interpreter - New Banner') | |
2755 | ipshell.set_exit_msg('Leaving interpreter - New exit_msg') |
|
2749 | ipshell.set_exit_msg('Leaving interpreter - New exit_msg') | |
2756 |
|
2750 | |||
2757 | def foo(m): |
|
2751 | def foo(m): | |
2758 | s = 'spam' |
|
2752 | s = 'spam' | |
2759 | ipshell('***In foo(). Try @whos, or print s or m:') |
|
2753 | ipshell('***In foo(). Try @whos, or print s or m:') | |
2760 | print 'foo says m = ',m |
|
2754 | print 'foo says m = ',m | |
2761 |
|
2755 | |||
2762 | def bar(n): |
|
2756 | def bar(n): | |
2763 | s = 'eggs' |
|
2757 | s = 'eggs' | |
2764 | ipshell('***In bar(). Try @whos, or print s or n:') |
|
2758 | ipshell('***In bar(). Try @whos, or print s or n:') | |
2765 | print 'bar says n = ',n |
|
2759 | print 'bar says n = ',n | |
2766 |
|
2760 | |||
2767 | # Some calls to the above functions which will trigger IPython: |
|
2761 | # Some calls to the above functions which will trigger IPython: | |
2768 | print 'Main program calling foo("eggs")\n' |
|
2762 | print 'Main program calling foo("eggs")\n' | |
2769 | foo('eggs') |
|
2763 | foo('eggs') | |
2770 |
|
2764 | |||
2771 | # The shell can be put in 'dummy' mode where calls to it silently return. This |
|
2765 | # The shell can be put in 'dummy' mode where calls to it silently return. This | |
2772 | # allows you, for example, to globally turn off debugging for a program with a |
|
2766 | # allows you, for example, to globally turn off debugging for a program with a | |
2773 | # single call. |
|
2767 | # single call. | |
2774 | ipshell.set_dummy_mode(1) |
|
2768 | ipshell.set_dummy_mode(1) | |
2775 | print '\nTrying to call IPython which is now "dummy":' |
|
2769 | print '\nTrying to call IPython which is now "dummy":' | |
2776 | ipshell() |
|
2770 | ipshell() | |
2777 | print 'Nothing happened...' |
|
2771 | print 'Nothing happened...' | |
2778 | # The global 'dummy' mode can still be overridden for a single call |
|
2772 | # The global 'dummy' mode can still be overridden for a single call | |
2779 | print '\nOverriding dummy mode manually:' |
|
2773 | print '\nOverriding dummy mode manually:' | |
2780 | ipshell(dummy=0) |
|
2774 | ipshell(dummy=0) | |
2781 |
|
2775 | |||
2782 | # Reactivate the IPython shell |
|
2776 | # Reactivate the IPython shell | |
2783 | ipshell.set_dummy_mode(0) |
|
2777 | ipshell.set_dummy_mode(0) | |
2784 |
|
2778 | |||
2785 | print 'You can even have multiple embedded instances:' |
|
2779 | print 'You can even have multiple embedded instances:' | |
2786 | ipshell2() |
|
2780 | ipshell2() | |
2787 |
|
2781 | |||
2788 | print '\nMain program calling bar("spam")\n' |
|
2782 | print '\nMain program calling bar("spam")\n' | |
2789 | bar('spam') |
|
2783 | bar('spam') | |
2790 |
|
2784 | |||
2791 | print 'Main program finished. Bye!' |
|
2785 | print 'Main program finished. Bye!' | |
2792 |
|
2786 | |||
2793 | #********************** End of file <example-embed.py> *********************** |
|
2787 | #********************** End of file <example-embed.py> *********************** | |
2794 |
|
2788 | |||
2795 | Once you understand how the system functions, you can use the following |
|
2789 | Once you understand how the system functions, you can use the following | |
2796 | code fragments in your programs which are ready for cut and paste:: |
|
2790 | code fragments in your programs which are ready for cut and paste:: | |
2797 |
|
2791 | |||
2798 |
|
2792 | |||
2799 | """Quick code snippets for embedding IPython into other programs. |
|
2793 | """Quick code snippets for embedding IPython into other programs. | |
2800 |
|
2794 | |||
2801 | See example-embed.py for full details, this file has the bare minimum code for |
|
2795 | See example-embed.py for full details, this file has the bare minimum code for | |
2802 | cut and paste use once you understand how to use the system.""" |
|
2796 | cut and paste use once you understand how to use the system.""" | |
2803 |
|
2797 | |||
2804 | #--------------------------------------------------------------------------- |
|
2798 | #--------------------------------------------------------------------------- | |
2805 | # This code loads IPython but modifies a few things if it detects it's running |
|
2799 | # This code loads IPython but modifies a few things if it detects it's running | |
2806 | # embedded in another IPython session (helps avoid confusion) |
|
2800 | # embedded in another IPython session (helps avoid confusion) | |
2807 |
|
2801 | |||
2808 | try: |
|
2802 | try: | |
2809 | __IPYTHON__ |
|
2803 | __IPYTHON__ | |
2810 | except NameError: |
|
2804 | except NameError: | |
2811 | argv = [''] |
|
2805 | argv = [''] | |
2812 | banner = exit_msg = '' |
|
2806 | banner = exit_msg = '' | |
2813 | else: |
|
2807 | else: | |
2814 | # Command-line options for IPython (a list like sys.argv) |
|
2808 | # Command-line options for IPython (a list like sys.argv) | |
2815 | argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:'] |
|
2809 | argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:'] | |
2816 | banner = '*** Nested interpreter ***' |
|
2810 | banner = '*** Nested interpreter ***' | |
2817 | exit_msg = '*** Back in main IPython ***' |
|
2811 | exit_msg = '*** Back in main IPython ***' | |
2818 |
|
2812 | |||
2819 | # First import the embeddable shell class |
|
2813 | # First import the embeddable shell class | |
2820 | from IPython.Shell import IPShellEmbed |
|
2814 | from IPython.Shell import IPShellEmbed | |
2821 | # Now create the IPython shell instance. Put ipshell() anywhere in your code |
|
2815 | # Now create the IPython shell instance. Put ipshell() anywhere in your code | |
2822 | # where you want it to open. |
|
2816 | # where you want it to open. | |
2823 | ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg) |
|
2817 | ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg) | |
2824 |
|
2818 | |||
2825 | #--------------------------------------------------------------------------- |
|
2819 | #--------------------------------------------------------------------------- | |
2826 | # This code will load an embeddable IPython shell always with no changes for |
|
2820 | # This code will load an embeddable IPython shell always with no changes for | |
2827 | # nested embededings. |
|
2821 | # nested embededings. | |
2828 |
|
2822 | |||
2829 | from IPython.Shell import IPShellEmbed |
|
2823 | from IPython.Shell import IPShellEmbed | |
2830 | ipshell = IPShellEmbed() |
|
2824 | ipshell = IPShellEmbed() | |
2831 | # Now ipshell() will open IPython anywhere in the code. |
|
2825 | # Now ipshell() will open IPython anywhere in the code. | |
2832 |
|
2826 | |||
2833 | #--------------------------------------------------------------------------- |
|
2827 | #--------------------------------------------------------------------------- | |
2834 | # This code loads an embeddable shell only if NOT running inside |
|
2828 | # This code loads an embeddable shell only if NOT running inside | |
2835 | # IPython. Inside IPython, the embeddable shell variable ipshell is just a |
|
2829 | # IPython. Inside IPython, the embeddable shell variable ipshell is just a | |
2836 | # dummy function. |
|
2830 | # dummy function. | |
2837 |
|
2831 | |||
2838 | try: |
|
2832 | try: | |
2839 | __IPYTHON__ |
|
2833 | __IPYTHON__ | |
2840 | except NameError: |
|
2834 | except NameError: | |
2841 | from IPython.Shell import IPShellEmbed |
|
2835 | from IPython.Shell import IPShellEmbed | |
2842 | ipshell = IPShellEmbed() |
|
2836 | ipshell = IPShellEmbed() | |
2843 | # Now ipshell() will open IPython anywhere in the code |
|
2837 | # Now ipshell() will open IPython anywhere in the code | |
2844 | else: |
|
2838 | else: | |
2845 | # Define a dummy ipshell() so the same code doesn't crash inside an |
|
2839 | # Define a dummy ipshell() so the same code doesn't crash inside an | |
2846 | # interactive IPython |
|
2840 | # interactive IPython | |
2847 | def ipshell(): pass |
|
2841 | def ipshell(): pass | |
2848 |
|
2842 | |||
2849 | #******************* End of file <example-embed-short.py> ******************** |
|
2843 | #******************* End of file <example-embed-short.py> ******************** | |
2850 |
|
2844 | |||
2851 | Using the Python debugger (pdb) |
|
2845 | Using the Python debugger (pdb) | |
2852 | =============================== |
|
2846 | =============================== | |
2853 |
|
2847 | |||
2854 | Running entire programs via pdb |
|
2848 | Running entire programs via pdb | |
2855 | ------------------------------- |
|
2849 | ------------------------------- | |
2856 |
|
2850 | |||
2857 | pdb, the Python debugger, is a powerful interactive debugger which |
|
2851 | pdb, the Python debugger, is a powerful interactive debugger which | |
2858 | allows you to step through code, set breakpoints, watch variables, |
|
2852 | allows you to step through code, set breakpoints, watch variables, | |
2859 | etc. IPython makes it very easy to start any script under the control |
|
2853 | etc. IPython makes it very easy to start any script under the control | |
2860 | of pdb, regardless of whether you have wrapped it into a 'main()' |
|
2854 | of pdb, regardless of whether you have wrapped it into a 'main()' | |
2861 | function or not. For this, simply type '%run -d myscript' at an |
|
2855 | function or not. For this, simply type '%run -d myscript' at an | |
2862 | IPython prompt. See the %run command's documentation (via '%run?' or |
|
2856 | IPython prompt. See the %run command's documentation (via '%run?' or | |
2863 | in Sec. magic_ for more details, including how to control where pdb |
|
2857 | in Sec. magic_ for more details, including how to control where pdb | |
2864 | will stop execution first. |
|
2858 | will stop execution first. | |
2865 |
|
2859 | |||
2866 | For more information on the use of the pdb debugger, read the included |
|
2860 | For more information on the use of the pdb debugger, read the included | |
2867 | pdb.doc file (part of the standard Python distribution). On a stock |
|
2861 | pdb.doc file (part of the standard Python distribution). On a stock | |
2868 | Linux system it is located at /usr/lib/python2.3/pdb.doc, but the |
|
2862 | Linux system it is located at /usr/lib/python2.3/pdb.doc, but the | |
2869 | easiest way to read it is by using the help() function of the pdb module |
|
2863 | easiest way to read it is by using the help() function of the pdb module | |
2870 | as follows (in an IPython prompt): |
|
2864 | as follows (in an IPython prompt): | |
2871 |
|
2865 | |||
2872 | In [1]: import pdb |
|
2866 | In [1]: import pdb | |
2873 | In [2]: pdb.help() |
|
2867 | In [2]: pdb.help() | |
2874 |
|
2868 | |||
2875 | This will load the pdb.doc document in a file viewer for you automatically. |
|
2869 | This will load the pdb.doc document in a file viewer for you automatically. | |
2876 |
|
2870 | |||
2877 |
|
2871 | |||
2878 | Automatic invocation of pdb on exceptions |
|
2872 | Automatic invocation of pdb on exceptions | |
2879 | ----------------------------------------- |
|
2873 | ----------------------------------------- | |
2880 |
|
2874 | |||
2881 | IPython, if started with the -pdb option (or if the option is set in |
|
2875 | IPython, if started with the -pdb option (or if the option is set in | |
2882 | your rc file) can call the Python pdb debugger every time your code |
|
2876 | your rc file) can call the Python pdb debugger every time your code | |
2883 | triggers an uncaught exception. This feature |
|
2877 | triggers an uncaught exception. This feature | |
2884 | can also be toggled at any time with the %pdb magic command. This can be |
|
2878 | can also be toggled at any time with the %pdb magic command. This can be | |
2885 | extremely useful in order to find the origin of subtle bugs, because pdb |
|
2879 | extremely useful in order to find the origin of subtle bugs, because pdb | |
2886 | opens up at the point in your code which triggered the exception, and |
|
2880 | opens up at the point in your code which triggered the exception, and | |
2887 | while your program is at this point 'dead', all the data is still |
|
2881 | while your program is at this point 'dead', all the data is still | |
2888 | available and you can walk up and down the stack frame and understand |
|
2882 | available and you can walk up and down the stack frame and understand | |
2889 | the origin of the problem. |
|
2883 | the origin of the problem. | |
2890 |
|
2884 | |||
2891 | Furthermore, you can use these debugging facilities both with the |
|
2885 | Furthermore, you can use these debugging facilities both with the | |
2892 | embedded IPython mode and without IPython at all. For an embedded shell |
|
2886 | embedded IPython mode and without IPython at all. For an embedded shell | |
2893 | (see sec. Embedding_), simply call the constructor with |
|
2887 | (see sec. Embedding_), simply call the constructor with | |
2894 | '-pdb' in the argument string and automatically pdb will be called if an |
|
2888 | '-pdb' in the argument string and automatically pdb will be called if an | |
2895 | uncaught exception is triggered by your code. |
|
2889 | uncaught exception is triggered by your code. | |
2896 |
|
2890 | |||
2897 | For stand-alone use of the feature in your programs which do not use |
|
2891 | For stand-alone use of the feature in your programs which do not use | |
2898 | IPython at all, put the following lines toward the top of your 'main' |
|
2892 | IPython at all, put the following lines toward the top of your 'main' | |
2899 | routine:: |
|
2893 | routine:: | |
2900 |
|
2894 | |||
2901 | import sys,IPython.ultraTB |
|
2895 | import sys,IPython.ultraTB | |
2902 | sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose', |
|
2896 | sys.excepthook = IPython.ultraTB.FormattedTB(mode='Verbose', | |
2903 | color_scheme='Linux', call_pdb=1) |
|
2897 | color_scheme='Linux', call_pdb=1) | |
2904 |
|
2898 | |||
2905 | The mode keyword can be either 'Verbose' or 'Plain', giving either very |
|
2899 | The mode keyword can be either 'Verbose' or 'Plain', giving either very | |
2906 | detailed or normal tracebacks respectively. The color_scheme keyword can |
|
2900 | detailed or normal tracebacks respectively. The color_scheme keyword can | |
2907 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same |
|
2901 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same | |
2908 | options which can be set in IPython with -colors and -xmode. |
|
2902 | options which can be set in IPython with -colors and -xmode. | |
2909 |
|
2903 | |||
2910 | This will give any of your programs detailed, colored tracebacks with |
|
2904 | This will give any of your programs detailed, colored tracebacks with | |
2911 | automatic invocation of pdb. |
|
2905 | automatic invocation of pdb. | |
2912 |
|
2906 | |||
2913 |
|
2907 | |||
2914 | Extensions for syntax processing |
|
2908 | Extensions for syntax processing | |
2915 | ================================ |
|
2909 | ================================ | |
2916 |
|
2910 | |||
2917 | This isn't for the faint of heart, because the potential for breaking |
|
2911 | This isn't for the faint of heart, because the potential for breaking | |
2918 | things is quite high. But it can be a very powerful and useful feature. |
|
2912 | things is quite high. But it can be a very powerful and useful feature. | |
2919 | In a nutshell, you can redefine the way IPython processes the user input |
|
2913 | In a nutshell, you can redefine the way IPython processes the user input | |
2920 | line to accept new, special extensions to the syntax without needing to |
|
2914 | line to accept new, special extensions to the syntax without needing to | |
2921 | change any of IPython's own code. |
|
2915 | change any of IPython's own code. | |
2922 |
|
2916 | |||
2923 | In the IPython/Extensions directory you will find some examples |
|
2917 | In the IPython/Extensions directory you will find some examples | |
2924 | supplied, which we will briefly describe now. These can be used 'as is' |
|
2918 | supplied, which we will briefly describe now. These can be used 'as is' | |
2925 | (and both provide very useful functionality), or you can use them as a |
|
2919 | (and both provide very useful functionality), or you can use them as a | |
2926 | starting point for writing your own extensions. |
|
2920 | starting point for writing your own extensions. | |
2927 |
|
2921 | |||
2928 |
|
2922 | |||
2929 | Pasting of code starting with '>>> ' or '... ' |
|
2923 | Pasting of code starting with '>>> ' or '... ' | |
2930 | ---------------------------------------------- |
|
2924 | ---------------------------------------------- | |
2931 |
|
2925 | |||
2932 | In the python tutorial it is common to find code examples which have |
|
2926 | In the python tutorial it is common to find code examples which have | |
2933 | been taken from real python sessions. The problem with those is that all |
|
2927 | been taken from real python sessions. The problem with those is that all | |
2934 | the lines begin with either '>>> ' or '... ', which makes it impossible |
|
2928 | the lines begin with either '>>> ' or '... ', which makes it impossible | |
2935 | to paste them all at once. One must instead do a line by line manual |
|
2929 | to paste them all at once. One must instead do a line by line manual | |
2936 | copying, carefully removing the leading extraneous characters. |
|
2930 | copying, carefully removing the leading extraneous characters. | |
2937 |
|
2931 | |||
2938 | This extension identifies those starting characters and removes them |
|
2932 | This extension identifies those starting characters and removes them | |
2939 | from the input automatically, so that one can paste multi-line examples |
|
2933 | from the input automatically, so that one can paste multi-line examples | |
2940 | directly into IPython, saving a lot of time. Please look at the file |
|
2934 | directly into IPython, saving a lot of time. Please look at the file | |
2941 | InterpreterPasteInput.py in the IPython/Extensions directory for details |
|
2935 | InterpreterPasteInput.py in the IPython/Extensions directory for details | |
2942 | on how this is done. |
|
2936 | on how this is done. | |
2943 |
|
2937 | |||
2944 | IPython comes with a special profile enabling this feature, called |
|
2938 | IPython comes with a special profile enabling this feature, called | |
2945 | tutorial. Simply start IPython via 'ipython -p tutorial' and the feature |
|
2939 | tutorial. Simply start IPython via 'ipython -p tutorial' and the feature | |
2946 | will be available. In a normal IPython session you can activate the |
|
2940 | will be available. In a normal IPython session you can activate the | |
2947 | feature by importing the corresponding module with: |
|
2941 | feature by importing the corresponding module with: | |
2948 | In [1]: import IPython.Extensions.InterpreterPasteInput |
|
2942 | In [1]: import IPython.Extensions.InterpreterPasteInput | |
2949 |
|
2943 | |||
2950 | The following is a 'screenshot' of how things work when this extension |
|
2944 | The following is a 'screenshot' of how things work when this extension | |
2951 | is on, copying an example from the standard tutorial:: |
|
2945 | is on, copying an example from the standard tutorial:: | |
2952 |
|
2946 | |||
2953 | IPython profile: tutorial |
|
2947 | IPython profile: tutorial | |
2954 |
|
2948 | |||
2955 | *** Pasting of code with ">>>" or "..." has been enabled. |
|
2949 | *** Pasting of code with ">>>" or "..." has been enabled. | |
2956 |
|
2950 | |||
2957 | In [1]: >>> def fib2(n): # return Fibonacci series up to n |
|
2951 | In [1]: >>> def fib2(n): # return Fibonacci series up to n | |
2958 | ...: ... """Return a list containing the Fibonacci series up to |
|
2952 | ...: ... """Return a list containing the Fibonacci series up to | |
2959 | n.""" |
|
2953 | n.""" | |
2960 | ...: ... result = [] |
|
2954 | ...: ... result = [] | |
2961 | ...: ... a, b = 0, 1 |
|
2955 | ...: ... a, b = 0, 1 | |
2962 | ...: ... while b < n: |
|
2956 | ...: ... while b < n: | |
2963 | ...: ... result.append(b) # see below |
|
2957 | ...: ... result.append(b) # see below | |
2964 | ...: ... a, b = b, a+b |
|
2958 | ...: ... a, b = b, a+b | |
2965 | ...: ... return result |
|
2959 | ...: ... return result | |
2966 | ...: |
|
2960 | ...: | |
2967 |
|
2961 | |||
2968 | In [2]: fib2(10) |
|
2962 | In [2]: fib2(10) | |
2969 | Out[2]: [1, 1, 2, 3, 5, 8] |
|
2963 | Out[2]: [1, 1, 2, 3, 5, 8] | |
2970 |
|
2964 | |||
2971 | Note that as currently written, this extension does not recognize |
|
2965 | Note that as currently written, this extension does not recognize | |
2972 | IPython's prompts for pasting. Those are more complicated, since the |
|
2966 | IPython's prompts for pasting. Those are more complicated, since the | |
2973 | user can change them very easily, they involve numbers and can vary in |
|
2967 | user can change them very easily, they involve numbers and can vary in | |
2974 | length. One could however extract all the relevant information from the |
|
2968 | length. One could however extract all the relevant information from the | |
2975 | IPython instance and build an appropriate regular expression. This is |
|
2969 | IPython instance and build an appropriate regular expression. This is | |
2976 | left as an exercise for the reader. |
|
2970 | left as an exercise for the reader. | |
2977 |
|
2971 | |||
2978 |
|
2972 | |||
2979 | Input of physical quantities with units |
|
2973 | Input of physical quantities with units | |
2980 | --------------------------------------- |
|
2974 | --------------------------------------- | |
2981 |
|
2975 | |||
2982 | The module PhysicalQInput allows a simplified form of input for physical |
|
2976 | The module PhysicalQInput allows a simplified form of input for physical | |
2983 | quantities with units. This file is meant to be used in conjunction with |
|
2977 | quantities with units. This file is meant to be used in conjunction with | |
2984 | the PhysicalQInteractive module (in the same directory) and |
|
2978 | the PhysicalQInteractive module (in the same directory) and | |
2985 | Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython |
|
2979 | Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython | |
2986 | (http://dirac.cnrs-orleans.fr/ScientificPython/). |
|
2980 | (http://dirac.cnrs-orleans.fr/ScientificPython/). | |
2987 |
|
2981 | |||
2988 | The Physics.PhysicalQuantities module defines PhysicalQuantity objects, |
|
2982 | The Physics.PhysicalQuantities module defines PhysicalQuantity objects, | |
2989 | but these must be declared as instances of a class. For example, to |
|
2983 | but these must be declared as instances of a class. For example, to | |
2990 | define v as a velocity of 3 m/s, normally you would write:: |
|
2984 | define v as a velocity of 3 m/s, normally you would write:: | |
2991 |
|
2985 | |||
2992 | In [1]: v = PhysicalQuantity(3,'m/s') |
|
2986 | In [1]: v = PhysicalQuantity(3,'m/s') | |
2993 |
|
2987 | |||
2994 | Using the PhysicalQ_Input extension this can be input instead as: |
|
2988 | Using the PhysicalQ_Input extension this can be input instead as: | |
2995 | In [1]: v = 3 m/s |
|
2989 | In [1]: v = 3 m/s | |
2996 | which is much more convenient for interactive use (even though it is |
|
2990 | which is much more convenient for interactive use (even though it is | |
2997 | blatantly invalid Python syntax). |
|
2991 | blatantly invalid Python syntax). | |
2998 |
|
2992 | |||
2999 | The physics profile supplied with IPython (enabled via 'ipython -p |
|
2993 | The physics profile supplied with IPython (enabled via 'ipython -p | |
3000 | physics') uses these extensions, which you can also activate with: |
|
2994 | physics') uses these extensions, which you can also activate with: | |
3001 |
|
2995 | |||
3002 | from math import * # math MUST be imported BEFORE PhysicalQInteractive |
|
2996 | from math import * # math MUST be imported BEFORE PhysicalQInteractive | |
3003 | from IPython.Extensions.PhysicalQInteractive import * |
|
2997 | from IPython.Extensions.PhysicalQInteractive import * | |
3004 | import IPython.Extensions.PhysicalQInput |
|
2998 | import IPython.Extensions.PhysicalQInput | |
3005 |
|
2999 | |||
3006 |
|
3000 | |||
3007 | Threading support |
|
3001 | Threading support | |
3008 | ================= |
|
3002 | ================= | |
3009 |
|
3003 | |||
3010 | WARNING: The threading support is still somewhat experimental, and it |
|
3004 | WARNING: The threading support is still somewhat experimental, and it | |
3011 | has only seen reasonable testing under Linux. Threaded code is |
|
3005 | has only seen reasonable testing under Linux. Threaded code is | |
3012 | particularly tricky to debug, and it tends to show extremely |
|
3006 | particularly tricky to debug, and it tends to show extremely | |
3013 | platform-dependent behavior. Since I only have access to Linux machines, |
|
3007 | platform-dependent behavior. Since I only have access to Linux machines, | |
3014 | I will have to rely on user's experiences and assistance for this area |
|
3008 | I will have to rely on user's experiences and assistance for this area | |
3015 | of IPython to improve under other platforms. |
|
3009 | of IPython to improve under other platforms. | |
3016 |
|
3010 | |||
3017 | IPython, via the -gthread , -qthread, -q4thread and -wthread options |
|
3011 | IPython, via the -gthread , -qthread, -q4thread and -wthread options | |
3018 | (described in Sec. `Threading options`_), can run in |
|
3012 | (described in Sec. `Threading options`_), can run in | |
3019 | multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython applications |
|
3013 | multithreaded mode to support pyGTK, Qt3, Qt4 and WXPython applications | |
3020 | respectively. These GUI toolkits need to control the python main loop of |
|
3014 | respectively. These GUI toolkits need to control the python main loop of | |
3021 | execution, so under a normal Python interpreter, starting a pyGTK, Qt3, |
|
3015 | execution, so under a normal Python interpreter, starting a pyGTK, Qt3, | |
3022 | Qt4 or WXPython application will immediately freeze the shell. |
|
3016 | Qt4 or WXPython application will immediately freeze the shell. | |
3023 |
|
3017 | |||
3024 | IPython, with one of these options (you can only use one at a time), |
|
3018 | IPython, with one of these options (you can only use one at a time), | |
3025 | separates the graphical loop and IPython's code execution run into |
|
3019 | separates the graphical loop and IPython's code execution run into | |
3026 | different threads. This allows you to test interactively (with %run, for |
|
3020 | different threads. This allows you to test interactively (with %run, for | |
3027 | example) your GUI code without blocking. |
|
3021 | example) your GUI code without blocking. | |
3028 |
|
3022 | |||
3029 | A nice mini-tutorial on using IPython along with the Qt Designer |
|
3023 | A nice mini-tutorial on using IPython along with the Qt Designer | |
3030 | application is available at the SciPy wiki: |
|
3024 | application is available at the SciPy wiki: | |
3031 | http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer. |
|
3025 | http://www.scipy.org/Cookbook/Matplotlib/Qt_with_IPython_and_Designer. | |
3032 |
|
3026 | |||
3033 |
|
3027 | |||
3034 | Tk issues |
|
3028 | Tk issues | |
3035 | --------- |
|
3029 | --------- | |
3036 |
|
3030 | |||
3037 | As indicated in Sec. `Threading options`_, a special -tk option is |
|
3031 | As indicated in Sec. `Threading options`_, a special -tk option is | |
3038 | provided to try and allow Tk graphical applications to coexist |
|
3032 | provided to try and allow Tk graphical applications to coexist | |
3039 | interactively with WX, Qt or GTK ones. Whether this works at all, |
|
3033 | interactively with WX, Qt or GTK ones. Whether this works at all, | |
3040 | however, is very platform and configuration dependent. Please |
|
3034 | however, is very platform and configuration dependent. Please | |
3041 | experiment with simple test cases before committing to using this |
|
3035 | experiment with simple test cases before committing to using this | |
3042 | combination of Tk and GTK/Qt/WX threading in a production environment. |
|
3036 | combination of Tk and GTK/Qt/WX threading in a production environment. | |
3043 |
|
3037 | |||
3044 |
|
3038 | |||
3045 | I/O pitfalls |
|
3039 | I/O pitfalls | |
3046 | ------------ |
|
3040 | ------------ | |
3047 |
|
3041 | |||
3048 | Be mindful that the Python interpreter switches between threads every |
|
3042 | Be mindful that the Python interpreter switches between threads every | |
3049 | $N$ bytecodes, where the default value as of Python 2.3 is $N=100.$ This |
|
3043 | $N$ bytecodes, where the default value as of Python 2.3 is $N=100.$ This | |
3050 | value can be read by using the sys.getcheckinterval() function, and it |
|
3044 | value can be read by using the sys.getcheckinterval() function, and it | |
3051 | can be reset via sys.setcheckinterval(N). This switching of threads can |
|
3045 | can be reset via sys.setcheckinterval(N). This switching of threads can | |
3052 | cause subtly confusing effects if one of your threads is doing file I/O. |
|
3046 | cause subtly confusing effects if one of your threads is doing file I/O. | |
3053 | In text mode, most systems only flush file buffers when they encounter a |
|
3047 | In text mode, most systems only flush file buffers when they encounter a | |
3054 | '\n'. An instruction as simple as:: |
|
3048 | '\n'. An instruction as simple as:: | |
3055 |
|
3049 | |||
3056 | print >> filehandle, ''hello world'' |
|
3050 | print >> filehandle, ''hello world'' | |
3057 |
|
3051 | |||
3058 | actually consists of several bytecodes, so it is possible that the |
|
3052 | actually consists of several bytecodes, so it is possible that the | |
3059 | newline does not reach your file before the next thread switch. |
|
3053 | newline does not reach your file before the next thread switch. | |
3060 | Similarly, if you are writing to a file in binary mode, the file won't |
|
3054 | Similarly, if you are writing to a file in binary mode, the file won't | |
3061 | be flushed until the buffer fills, and your other thread may see |
|
3055 | be flushed until the buffer fills, and your other thread may see | |
3062 | apparently truncated files. |
|
3056 | apparently truncated files. | |
3063 |
|
3057 | |||
3064 | For this reason, if you are using IPython's thread support and have (for |
|
3058 | For this reason, if you are using IPython's thread support and have (for | |
3065 | example) a GUI application which will read data generated by files |
|
3059 | example) a GUI application which will read data generated by files | |
3066 | written to from the IPython thread, the safest approach is to open all |
|
3060 | written to from the IPython thread, the safest approach is to open all | |
3067 | of your files in unbuffered mode (the third argument to the file/open |
|
3061 | of your files in unbuffered mode (the third argument to the file/open | |
3068 | function is the buffering value):: |
|
3062 | function is the buffering value):: | |
3069 |
|
3063 | |||
3070 | filehandle = open(filename,mode,0) |
|
3064 | filehandle = open(filename,mode,0) | |
3071 |
|
3065 | |||
3072 | This is obviously a brute force way of avoiding race conditions with the |
|
3066 | This is obviously a brute force way of avoiding race conditions with the | |
3073 | file buffering. If you want to do it cleanly, and you have a resource |
|
3067 | file buffering. If you want to do it cleanly, and you have a resource | |
3074 | which is being shared by the interactive IPython loop and your GUI |
|
3068 | which is being shared by the interactive IPython loop and your GUI | |
3075 | thread, you should really handle it with thread locking and |
|
3069 | thread, you should really handle it with thread locking and | |
3076 | syncrhonization properties. The Python documentation discusses these. |
|
3070 | syncrhonization properties. The Python documentation discusses these. | |
3077 |
|
3071 | |||
3078 | .. _interactive_demos: |
|
3072 | .. _interactive_demos: | |
3079 |
|
3073 | |||
3080 | Interactive demos with IPython |
|
3074 | Interactive demos with IPython | |
3081 | ============================== |
|
3075 | ============================== | |
3082 |
|
3076 | |||
3083 | IPython ships with a basic system for running scripts interactively in |
|
3077 | IPython ships with a basic system for running scripts interactively in | |
3084 | sections, useful when presenting code to audiences. A few tags embedded |
|
3078 | sections, useful when presenting code to audiences. A few tags embedded | |
3085 | in comments (so that the script remains valid Python code) divide a file |
|
3079 | in comments (so that the script remains valid Python code) divide a file | |
3086 | into separate blocks, and the demo can be run one block at a time, with |
|
3080 | into separate blocks, and the demo can be run one block at a time, with | |
3087 | IPython printing (with syntax highlighting) the block before executing |
|
3081 | IPython printing (with syntax highlighting) the block before executing | |
3088 | it, and returning to the interactive prompt after each block. The |
|
3082 | it, and returning to the interactive prompt after each block. The | |
3089 | interactive namespace is updated after each block is run with the |
|
3083 | interactive namespace is updated after each block is run with the | |
3090 | contents of the demo's namespace. |
|
3084 | contents of the demo's namespace. | |
3091 |
|
3085 | |||
3092 | This allows you to show a piece of code, run it and then execute |
|
3086 | This allows you to show a piece of code, run it and then execute | |
3093 | interactively commands based on the variables just created. Once you |
|
3087 | interactively commands based on the variables just created. Once you | |
3094 | want to continue, you simply execute the next block of the demo. The |
|
3088 | want to continue, you simply execute the next block of the demo. The | |
3095 | following listing shows the markup necessary for dividing a script into |
|
3089 | following listing shows the markup necessary for dividing a script into | |
3096 | sections for execution as a demo:: |
|
3090 | sections for execution as a demo:: | |
3097 |
|
3091 | |||
3098 |
|
3092 | |||
3099 | """A simple interactive demo to illustrate the use of IPython's Demo class. |
|
3093 | """A simple interactive demo to illustrate the use of IPython's Demo class. | |
3100 |
|
3094 | |||
3101 | Any python script can be run as a demo, but that does little more than showing |
|
3095 | Any python script can be run as a demo, but that does little more than showing | |
3102 | it on-screen, syntax-highlighted in one shot. If you add a little simple |
|
3096 | it on-screen, syntax-highlighted in one shot. If you add a little simple | |
3103 | markup, you can stop at specified intervals and return to the ipython prompt, |
|
3097 | markup, you can stop at specified intervals and return to the ipython prompt, | |
3104 | resuming execution later. |
|
3098 | resuming execution later. | |
3105 | """ |
|
3099 | """ | |
3106 |
|
3100 | |||
3107 | print 'Hello, welcome to an interactive IPython demo.' |
|
3101 | print 'Hello, welcome to an interactive IPython demo.' | |
3108 | print 'Executing this block should require confirmation before proceeding,' |
|
3102 | print 'Executing this block should require confirmation before proceeding,' | |
3109 | print 'unless auto_all has been set to true in the demo object' |
|
3103 | print 'unless auto_all has been set to true in the demo object' | |
3110 |
|
3104 | |||
3111 | # The mark below defines a block boundary, which is a point where IPython will |
|
3105 | # The mark below defines a block boundary, which is a point where IPython will | |
3112 | # stop execution and return to the interactive prompt. |
|
3106 | # stop execution and return to the interactive prompt. | |
3113 | # Note that in actual interactive execution, |
|
3107 | # Note that in actual interactive execution, | |
3114 | # <demo> --- stop --- |
|
3108 | # <demo> --- stop --- | |
3115 |
|
3109 | |||
3116 | x = 1 |
|
3110 | x = 1 | |
3117 | y = 2 |
|
3111 | y = 2 | |
3118 |
|
3112 | |||
3119 | # <demo> --- stop --- |
|
3113 | # <demo> --- stop --- | |
3120 |
|
3114 | |||
3121 | # the mark below makes this block as silent |
|
3115 | # the mark below makes this block as silent | |
3122 | # <demo> silent |
|
3116 | # <demo> silent | |
3123 |
|
3117 | |||
3124 | print 'This is a silent block, which gets executed but not printed.' |
|
3118 | print 'This is a silent block, which gets executed but not printed.' | |
3125 |
|
3119 | |||
3126 | # <demo> --- stop --- |
|
3120 | # <demo> --- stop --- | |
3127 | # <demo> auto |
|
3121 | # <demo> auto | |
3128 | print 'This is an automatic block.' |
|
3122 | print 'This is an automatic block.' | |
3129 | print 'It is executed without asking for confirmation, but printed.' |
|
3123 | print 'It is executed without asking for confirmation, but printed.' | |
3130 | z = x+y |
|
3124 | z = x+y | |
3131 |
|
3125 | |||
3132 | print 'z=',x |
|
3126 | print 'z=',x | |
3133 |
|
3127 | |||
3134 | # <demo> --- stop --- |
|
3128 | # <demo> --- stop --- | |
3135 | # This is just another normal block. |
|
3129 | # This is just another normal block. | |
3136 | print 'z is now:', z |
|
3130 | print 'z is now:', z | |
3137 |
|
3131 | |||
3138 | print 'bye!' |
|
3132 | print 'bye!' | |
3139 |
|
3133 | |||
3140 | In order to run a file as a demo, you must first make a Demo object out |
|
3134 | In order to run a file as a demo, you must first make a Demo object out | |
3141 | of it. If the file is named myscript.py, the following code will make a |
|
3135 | of it. If the file is named myscript.py, the following code will make a | |
3142 | demo:: |
|
3136 | demo:: | |
3143 |
|
3137 | |||
3144 | from IPython.demo import Demo |
|
3138 | from IPython.demo import Demo | |
3145 |
|
3139 | |||
3146 | mydemo = Demo('myscript.py') |
|
3140 | mydemo = Demo('myscript.py') | |
3147 |
|
3141 | |||
3148 | This creates the mydemo object, whose blocks you run one at a time by |
|
3142 | This creates the mydemo object, whose blocks you run one at a time by | |
3149 | simply calling the object with no arguments. If you have autocall active |
|
3143 | simply calling the object with no arguments. If you have autocall active | |
3150 | in IPython (the default), all you need to do is type:: |
|
3144 | in IPython (the default), all you need to do is type:: | |
3151 |
|
3145 | |||
3152 | mydemo |
|
3146 | mydemo | |
3153 |
|
3147 | |||
3154 | and IPython will call it, executing each block. Demo objects can be |
|
3148 | and IPython will call it, executing each block. Demo objects can be | |
3155 | restarted, you can move forward or back skipping blocks, re-execute the |
|
3149 | restarted, you can move forward or back skipping blocks, re-execute the | |
3156 | last block, etc. Simply use the Tab key on a demo object to see its |
|
3150 | last block, etc. Simply use the Tab key on a demo object to see its | |
3157 | methods, and call '?' on them to see their docstrings for more usage |
|
3151 | methods, and call '?' on them to see their docstrings for more usage | |
3158 | details. In addition, the demo module itself contains a comprehensive |
|
3152 | details. In addition, the demo module itself contains a comprehensive | |
3159 | docstring, which you can access via:: |
|
3153 | docstring, which you can access via:: | |
3160 |
|
3154 | |||
3161 | from IPython import demo |
|
3155 | from IPython import demo | |
3162 |
|
3156 | |||
3163 | demo? |
|
3157 | demo? | |
3164 |
|
3158 | |||
3165 | Limitations: It is important to note that these demos are limited to |
|
3159 | Limitations: It is important to note that these demos are limited to | |
3166 | fairly simple uses. In particular, you can not put division marks in |
|
3160 | fairly simple uses. In particular, you can not put division marks in | |
3167 | indented code (loops, if statements, function definitions, etc.) |
|
3161 | indented code (loops, if statements, function definitions, etc.) | |
3168 | Supporting something like this would basically require tracking the |
|
3162 | Supporting something like this would basically require tracking the | |
3169 | internal execution state of the Python interpreter, so only top-level |
|
3163 | internal execution state of the Python interpreter, so only top-level | |
3170 | divisions are allowed. If you want to be able to open an IPython |
|
3164 | divisions are allowed. If you want to be able to open an IPython | |
3171 | instance at an arbitrary point in a program, you can use IPython's |
|
3165 | instance at an arbitrary point in a program, you can use IPython's | |
3172 | embedding facilities, described in detail in Sec. 9 |
|
3166 | embedding facilities, described in detail in Sec. 9 | |
3173 |
|
3167 | |||
3174 |
|
3168 | |||
3175 | .. _Matplotlib support: |
|
3169 | .. _Matplotlib support: | |
3176 |
|
3170 | |||
3177 | Plotting with matplotlib |
|
3171 | Plotting with matplotlib | |
3178 | ======================== |
|
3172 | ======================== | |
3179 |
|
3173 | |||
3180 | The matplotlib library (http://matplotlib.sourceforge.net |
|
3174 | The matplotlib library (http://matplotlib.sourceforge.net | |
3181 | http://matplotlib.sourceforge.net) provides high quality 2D plotting for |
|
3175 | http://matplotlib.sourceforge.net) provides high quality 2D plotting for | |
3182 | Python. Matplotlib can produce plots on screen using a variety of GUI |
|
3176 | Python. Matplotlib can produce plots on screen using a variety of GUI | |
3183 | toolkits, including Tk, GTK and WXPython. It also provides a number of |
|
3177 | toolkits, including Tk, GTK and WXPython. It also provides a number of | |
3184 | commands useful for scientific computing, all with a syntax compatible |
|
3178 | commands useful for scientific computing, all with a syntax compatible | |
3185 | with that of the popular Matlab program. |
|
3179 | with that of the popular Matlab program. | |
3186 |
|
3180 | |||
3187 | IPython accepts the special option -pylab (see :ref:`here |
|
3181 | IPython accepts the special option -pylab (see :ref:`here | |
3188 | <command_line_options>`). This configures it to support matplotlib, honoring |
|
3182 | <command_line_options>`). This configures it to support matplotlib, honoring | |
3189 | the settings in the .matplotlibrc file. IPython will detect the user's choice |
|
3183 | the settings in the .matplotlibrc file. IPython will detect the user's choice | |
3190 | of matplotlib GUI backend, and automatically select the proper threading model |
|
3184 | of matplotlib GUI backend, and automatically select the proper threading model | |
3191 | to prevent blocking. It also sets matplotlib in interactive mode and modifies |
|
3185 | to prevent blocking. It also sets matplotlib in interactive mode and modifies | |
3192 | %run slightly, so that any matplotlib-based script can be executed using %run |
|
3186 | %run slightly, so that any matplotlib-based script can be executed using %run | |
3193 | and the final show() command does not block the interactive shell. |
|
3187 | and the final show() command does not block the interactive shell. | |
3194 |
|
3188 | |||
3195 | The -pylab option must be given first in order for IPython to configure its |
|
3189 | The -pylab option must be given first in order for IPython to configure its | |
3196 | threading mode. However, you can still issue other options afterwards. This |
|
3190 | threading mode. However, you can still issue other options afterwards. This | |
3197 | allows you to have a matplotlib-based environment customized with additional |
|
3191 | allows you to have a matplotlib-based environment customized with additional | |
3198 | modules using the standard IPython profile mechanism (see :ref:`here |
|
3192 | modules using the standard IPython profile mechanism (see :ref:`here | |
3199 | <profiles>`): ``ipython -pylab -p myprofile`` will load the profile defined in |
|
3193 | <profiles>`): ``ipython -pylab -p myprofile`` will load the profile defined in | |
3200 | ipythonrc-myprofile after configuring matplotlib. |
|
3194 | ipythonrc-myprofile after configuring matplotlib. |
@@ -1,317 +1,315 b'' | |||||
1 | .. _tutorial: |
|
1 | .. _tutorial: | |
2 |
|
2 | |||
3 | ====================== |
|
3 | ====================== | |
4 | Quick IPython tutorial |
|
4 | Quick IPython tutorial | |
5 | ====================== |
|
5 | ====================== | |
6 |
|
6 | |||
7 | .. contents:: |
|
|||
8 |
|
||||
9 | IPython can be used as an improved replacement for the Python prompt, |
|
7 | IPython can be used as an improved replacement for the Python prompt, | |
10 | and for that you don't really need to read any more of this manual. But |
|
8 | and for that you don't really need to read any more of this manual. But | |
11 | in this section we'll try to summarize a few tips on how to make the |
|
9 | in this section we'll try to summarize a few tips on how to make the | |
12 | most effective use of it for everyday Python development, highlighting |
|
10 | most effective use of it for everyday Python development, highlighting | |
13 | things you might miss in the rest of the manual (which is getting long). |
|
11 | things you might miss in the rest of the manual (which is getting long). | |
14 | We'll give references to parts in the manual which provide more detail |
|
12 | We'll give references to parts in the manual which provide more detail | |
15 | when appropriate. |
|
13 | when appropriate. | |
16 |
|
14 | |||
17 | The following article by Jeremy Jones provides an introductory tutorial |
|
15 | The following article by Jeremy Jones provides an introductory tutorial | |
18 | about IPython: http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html |
|
16 | about IPython: http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html | |
19 |
|
17 | |||
20 | Highlights |
|
18 | Highlights | |
21 | ========== |
|
19 | ========== | |
22 |
|
20 | |||
23 | Tab completion |
|
21 | Tab completion | |
24 | -------------- |
|
22 | -------------- | |
25 |
|
23 | |||
26 | TAB-completion, especially for attributes, is a convenient way to explore the |
|
24 | TAB-completion, especially for attributes, is a convenient way to explore the | |
27 | structure of any object you're dealing with. Simply type object_name.<TAB> and |
|
25 | structure of any object you're dealing with. Simply type object_name.<TAB> and | |
28 | a list of the object's attributes will be printed (see :ref:`the readline |
|
26 | a list of the object's attributes will be printed (see :ref:`the readline | |
29 | section <readline>` for more). Tab completion also works on file and directory |
|
27 | section <readline>` for more). Tab completion also works on file and directory | |
30 | names, which combined with IPython's alias system allows you to do from within |
|
28 | names, which combined with IPython's alias system allows you to do from within | |
31 | IPython many of the things you normally would need the system shell for. |
|
29 | IPython many of the things you normally would need the system shell for. | |
32 |
|
30 | |||
33 | Explore your objects |
|
31 | Explore your objects | |
34 | -------------------- |
|
32 | -------------------- | |
35 |
|
33 | |||
36 | Typing object_name? will print all sorts of details about any object, |
|
34 | Typing object_name? will print all sorts of details about any object, | |
37 | including docstrings, function definition lines (for call arguments) and |
|
35 | including docstrings, function definition lines (for call arguments) and | |
38 | constructor details for classes. The magic commands %pdoc, %pdef, %psource |
|
36 | constructor details for classes. The magic commands %pdoc, %pdef, %psource | |
39 | and %pfile will respectively print the docstring, function definition line, |
|
37 | and %pfile will respectively print the docstring, function definition line, | |
40 | full source code and the complete file for any object (when they can be |
|
38 | full source code and the complete file for any object (when they can be | |
41 | found). If automagic is on (it is by default), you don't need to type the '%' |
|
39 | found). If automagic is on (it is by default), you don't need to type the '%' | |
42 | explicitly. See :ref:`this section <dynamic_object_info>` for more. |
|
40 | explicitly. See :ref:`this section <dynamic_object_info>` for more. | |
43 |
|
41 | |||
44 | The `%run` magic command |
|
42 | The `%run` magic command | |
45 | ------------------------ |
|
43 | ------------------------ | |
46 |
|
44 | |||
47 | The %run magic command allows you to run any python script and load all of its |
|
45 | The %run magic command allows you to run any python script and load all of its | |
48 | data directly into the interactive namespace. Since the file is re-read from |
|
46 | data directly into the interactive namespace. Since the file is re-read from | |
49 | disk each time, changes you make to it are reflected immediately (in contrast |
|
47 | disk each time, changes you make to it are reflected immediately (in contrast | |
50 | to the behavior of import). I rarely use import for code I am testing, relying |
|
48 | to the behavior of import). I rarely use import for code I am testing, relying | |
51 | on %run instead. See :ref:`this section <magic>` for more on this and other |
|
49 | on %run instead. See :ref:`this section <magic>` for more on this and other | |
52 | magic commands, or type the name of any magic command and ? to get details on |
|
50 | magic commands, or type the name of any magic command and ? to get details on | |
53 | it. See also :ref:`this section <dreload>` for a recursive reload command. %run |
|
51 | it. See also :ref:`this section <dreload>` for a recursive reload command. %run | |
54 | also has special flags for timing the execution of your scripts (-t) and for |
|
52 | also has special flags for timing the execution of your scripts (-t) and for | |
55 | executing them under the control of either Python's pdb debugger (-d) or |
|
53 | executing them under the control of either Python's pdb debugger (-d) or | |
56 | profiler (-p). With all of these, %run can be used as the main tool for |
|
54 | profiler (-p). With all of these, %run can be used as the main tool for | |
57 | efficient interactive development of code which you write in your editor of |
|
55 | efficient interactive development of code which you write in your editor of | |
58 | choice. |
|
56 | choice. | |
59 |
|
57 | |||
60 | Debug a Python script |
|
58 | Debug a Python script | |
61 | --------------------- |
|
59 | --------------------- | |
62 |
|
60 | |||
63 | Use the Python debugger, pdb. The %pdb command allows you to toggle on and off |
|
61 | Use the Python debugger, pdb. The %pdb command allows you to toggle on and off | |
64 | the automatic invocation of an IPython-enhanced pdb debugger (with coloring, |
|
62 | the automatic invocation of an IPython-enhanced pdb debugger (with coloring, | |
65 | tab completion and more) at any uncaught exception. The advantage of this is |
|
63 | tab completion and more) at any uncaught exception. The advantage of this is | |
66 | that pdb starts inside the function where the exception occurred, with all data |
|
64 | that pdb starts inside the function where the exception occurred, with all data | |
67 | still available. You can print variables, see code, execute statements and even |
|
65 | still available. You can print variables, see code, execute statements and even | |
68 | walk up and down the call stack to track down the true source of the problem |
|
66 | walk up and down the call stack to track down the true source of the problem | |
69 | (which often is many layers in the stack above where the exception gets |
|
67 | (which often is many layers in the stack above where the exception gets | |
70 | triggered). Running programs with %run and pdb active can be an efficient to |
|
68 | triggered). Running programs with %run and pdb active can be an efficient to | |
71 | develop and debug code, in many cases eliminating the need for print statements |
|
69 | develop and debug code, in many cases eliminating the need for print statements | |
72 | or external debugging tools. I often simply put a 1/0 in a place where I want |
|
70 | or external debugging tools. I often simply put a 1/0 in a place where I want | |
73 | to take a look so that pdb gets called, quickly view whatever variables I need |
|
71 | to take a look so that pdb gets called, quickly view whatever variables I need | |
74 | to or test various pieces of code and then remove the 1/0. Note also that '%run |
|
72 | to or test various pieces of code and then remove the 1/0. Note also that '%run | |
75 | -d' activates pdb and automatically sets initial breakpoints for you to step |
|
73 | -d' activates pdb and automatically sets initial breakpoints for you to step | |
76 | through your code, watch variables, etc. The :ref:`output caching section |
|
74 | through your code, watch variables, etc. The :ref:`output caching section | |
77 | <output_caching>` has more details. |
|
75 | <output_caching>` has more details. | |
78 |
|
76 | |||
79 | Use the output cache |
|
77 | Use the output cache | |
80 | -------------------- |
|
78 | -------------------- | |
81 |
|
79 | |||
82 | All output results are automatically stored in a global dictionary named Out |
|
80 | All output results are automatically stored in a global dictionary named Out | |
83 | and variables named _1, _2, etc. alias them. For example, the result of input |
|
81 | and variables named _1, _2, etc. alias them. For example, the result of input | |
84 | line 4 is available either as Out[4] or as _4. Additionally, three variables |
|
82 | line 4 is available either as Out[4] or as _4. Additionally, three variables | |
85 | named _, __ and ___ are always kept updated with the for the last three |
|
83 | named _, __ and ___ are always kept updated with the for the last three | |
86 | results. This allows you to recall any previous result and further use it for |
|
84 | results. This allows you to recall any previous result and further use it for | |
87 | new calculations. See :ref:`the output caching section <output_caching>` for |
|
85 | new calculations. See :ref:`the output caching section <output_caching>` for | |
88 | more. |
|
86 | more. | |
89 |
|
87 | |||
90 | Suppress output |
|
88 | Suppress output | |
91 | --------------- |
|
89 | --------------- | |
92 |
|
90 | |||
93 | Put a ';' at the end of a line to suppress the printing of output. This is |
|
91 | Put a ';' at the end of a line to suppress the printing of output. This is | |
94 | useful when doing calculations which generate long output you are not |
|
92 | useful when doing calculations which generate long output you are not | |
95 | interested in seeing. The _* variables and the Out[] list do get updated with |
|
93 | interested in seeing. The _* variables and the Out[] list do get updated with | |
96 | the contents of the output, even if it is not printed. You can thus still |
|
94 | the contents of the output, even if it is not printed. You can thus still | |
97 | access the generated results this way for further processing. |
|
95 | access the generated results this way for further processing. | |
98 |
|
96 | |||
99 | Input cache |
|
97 | Input cache | |
100 | ----------- |
|
98 | ----------- | |
101 |
|
99 | |||
102 | A similar system exists for caching input. All input is stored in a global |
|
100 | A similar system exists for caching input. All input is stored in a global | |
103 | list called In , so you can re-execute lines 22 through 28 plus line 34 by |
|
101 | list called In , so you can re-execute lines 22 through 28 plus line 34 by | |
104 | typing 'exec In[22:29]+In[34]' (using Python slicing notation). If you need |
|
102 | typing 'exec In[22:29]+In[34]' (using Python slicing notation). If you need | |
105 | to execute the same set of lines often, you can assign them to a macro with |
|
103 | to execute the same set of lines often, you can assign them to a macro with | |
106 | the %macro function. See :ref:`here <input_caching>` for more. |
|
104 | the %macro function. See :ref:`here <input_caching>` for more. | |
107 |
|
105 | |||
108 | Use your input history |
|
106 | Use your input history | |
109 | ---------------------- |
|
107 | ---------------------- | |
110 |
|
108 | |||
111 | The %hist command can show you all previous input, without line numbers if |
|
109 | The %hist command can show you all previous input, without line numbers if | |
112 | desired (option -n) so you can directly copy and paste code either back in |
|
110 | desired (option -n) so you can directly copy and paste code either back in | |
113 | IPython or in a text editor. You can also save all your history by turning on |
|
111 | IPython or in a text editor. You can also save all your history by turning on | |
114 | logging via %logstart; these logs can later be either reloaded as IPython |
|
112 | logging via %logstart; these logs can later be either reloaded as IPython | |
115 | sessions or used as code for your programs. |
|
113 | sessions or used as code for your programs. | |
116 |
|
114 | |||
117 | Define your own system aliases |
|
115 | Define your own system aliases | |
118 | ------------------------------ |
|
116 | ------------------------------ | |
119 |
|
117 | |||
120 | Even though IPython gives you access to your system shell via the ! prefix, |
|
118 | Even though IPython gives you access to your system shell via the ! prefix, | |
121 | it is convenient to have aliases to the system commands you use most often. |
|
119 | it is convenient to have aliases to the system commands you use most often. | |
122 | This allows you to work seamlessly from inside IPython with the same commands |
|
120 | This allows you to work seamlessly from inside IPython with the same commands | |
123 | you are used to in your system shell. IPython comes with some pre-defined |
|
121 | you are used to in your system shell. IPython comes with some pre-defined | |
124 | aliases and a complete system for changing directories, both via a stack (see |
|
122 | aliases and a complete system for changing directories, both via a stack (see | |
125 | %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of |
|
123 | %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of | |
126 | visited directories and allows you to go to any previously visited one. |
|
124 | visited directories and allows you to go to any previously visited one. | |
127 |
|
125 | |||
128 | Call system shell commands |
|
126 | Call system shell commands | |
129 | -------------------------- |
|
127 | -------------------------- | |
130 |
|
128 | |||
131 | Use Python to manipulate the results of system commands. The '!!' special |
|
129 | Use Python to manipulate the results of system commands. The '!!' special | |
132 | syntax, and the %sc and %sx magic commands allow you to capture system output |
|
130 | syntax, and the %sc and %sx magic commands allow you to capture system output | |
133 | into Python variables. |
|
131 | into Python variables. | |
134 |
|
132 | |||
135 | Use Python variables when calling the shell |
|
133 | Use Python variables when calling the shell | |
136 | ------------------------------------------- |
|
134 | ------------------------------------------- | |
137 |
|
135 | |||
138 | Expand python variables when calling the shell (either via '!' and '!!' or via |
|
136 | Expand python variables when calling the shell (either via '!' and '!!' or via | |
139 | aliases) by prepending a $ in front of them. You can also expand complete |
|
137 | aliases) by prepending a $ in front of them. You can also expand complete | |
140 | python expressions. See :ref:`our shell section <system_shell_access>` for |
|
138 | python expressions. See :ref:`our shell section <system_shell_access>` for | |
141 | more details. |
|
139 | more details. | |
142 |
|
140 | |||
143 | Use profiles |
|
141 | Use profiles | |
144 | ------------ |
|
142 | ------------ | |
145 |
|
143 | |||
146 | Use profiles to maintain different configurations (modules to load, function |
|
144 | Use profiles to maintain different configurations (modules to load, function | |
147 | definitions, option settings) for particular tasks. You can then have |
|
145 | definitions, option settings) for particular tasks. You can then have | |
148 | customized versions of IPython for specific purposes. :ref:`This section |
|
146 | customized versions of IPython for specific purposes. :ref:`This section | |
149 | <profiles>` has more details. |
|
147 | <profiles>` has more details. | |
150 |
|
148 | |||
151 |
|
149 | |||
152 | Embed IPython in your programs |
|
150 | Embed IPython in your programs | |
153 | ------------------------------ |
|
151 | ------------------------------ | |
154 |
|
152 | |||
155 | A few lines of code are enough to load a complete IPython inside your own |
|
153 | A few lines of code are enough to load a complete IPython inside your own | |
156 | programs, giving you the ability to work with your data interactively after |
|
154 | programs, giving you the ability to work with your data interactively after | |
157 | automatic processing has been completed. See :ref:`here <embedding>` for more. |
|
155 | automatic processing has been completed. See :ref:`here <embedding>` for more. | |
158 |
|
156 | |||
159 | Use the Python profiler |
|
157 | Use the Python profiler | |
160 | ----------------------- |
|
158 | ----------------------- | |
161 |
|
159 | |||
162 | When dealing with performance issues, the %run command with a -p option |
|
160 | When dealing with performance issues, the %run command with a -p option | |
163 | allows you to run complete programs under the control of the Python profiler. |
|
161 | allows you to run complete programs under the control of the Python profiler. | |
164 | The %prun command does a similar job for single Python expressions (like |
|
162 | The %prun command does a similar job for single Python expressions (like | |
165 | function calls). |
|
163 | function calls). | |
166 |
|
164 | |||
167 | Use IPython to present interactive demos |
|
165 | Use IPython to present interactive demos | |
168 | ---------------------------------------- |
|
166 | ---------------------------------------- | |
169 |
|
167 | |||
170 | Use the IPython.demo.Demo class to load any Python script as an interactive |
|
168 | Use the IPython.demo.Demo class to load any Python script as an interactive | |
171 | demo. With a minimal amount of simple markup, you can control the execution of |
|
169 | demo. With a minimal amount of simple markup, you can control the execution of | |
172 | the script, stopping as needed. See :ref:`here <interactive_demos>` for more. |
|
170 | the script, stopping as needed. See :ref:`here <interactive_demos>` for more. | |
173 |
|
171 | |||
174 | Run doctests |
|
172 | Run doctests | |
175 | ------------ |
|
173 | ------------ | |
176 |
|
174 | |||
177 | Run your doctests from within IPython for development and debugging. The |
|
175 | Run your doctests from within IPython for development and debugging. The | |
178 | special %doctest_mode command toggles a mode where the prompt, output and |
|
176 | special %doctest_mode command toggles a mode where the prompt, output and | |
179 | exceptions display matches as closely as possible that of the default Python |
|
177 | exceptions display matches as closely as possible that of the default Python | |
180 | interpreter. In addition, this mode allows you to directly paste in code that |
|
178 | interpreter. In addition, this mode allows you to directly paste in code that | |
181 | contains leading '>>>' prompts, even if they have extra leading whitespace |
|
179 | contains leading '>>>' prompts, even if they have extra leading whitespace | |
182 | (as is common in doctest files). This combined with the '%history -tn' call |
|
180 | (as is common in doctest files). This combined with the '%history -tn' call | |
183 | to see your translated history (with these extra prompts removed and no line |
|
181 | to see your translated history (with these extra prompts removed and no line | |
184 | numbers) allows for an easy doctest workflow, where you can go from doctest |
|
182 | numbers) allows for an easy doctest workflow, where you can go from doctest | |
185 | to interactive execution to pasting into valid Python code as needed. |
|
183 | to interactive execution to pasting into valid Python code as needed. | |
186 |
|
184 | |||
187 | Source code handling tips |
|
185 | Source code handling tips | |
188 | ========================= |
|
186 | ========================= | |
189 |
|
187 | |||
190 | IPython is a line-oriented program, without full control of the |
|
188 | IPython is a line-oriented program, without full control of the | |
191 | terminal. Therefore, it doesn't support true multiline editing. However, |
|
189 | terminal. Therefore, it doesn't support true multiline editing. However, | |
192 | it has a number of useful tools to help you in dealing effectively with |
|
190 | it has a number of useful tools to help you in dealing effectively with | |
193 | more complex editing. |
|
191 | more complex editing. | |
194 |
|
192 | |||
195 | The %edit command gives a reasonable approximation of multiline editing, |
|
193 | The %edit command gives a reasonable approximation of multiline editing, | |
196 | by invoking your favorite editor on the spot. IPython will execute the |
|
194 | by invoking your favorite editor on the spot. IPython will execute the | |
197 | code you type in there as if it were typed interactively. Type %edit? |
|
195 | code you type in there as if it were typed interactively. Type %edit? | |
198 | for the full details on the edit command. |
|
196 | for the full details on the edit command. | |
199 |
|
197 | |||
200 | If you have typed various commands during a session, which you'd like to |
|
198 | If you have typed various commands during a session, which you'd like to | |
201 | reuse, IPython provides you with a number of tools. Start by using %hist |
|
199 | reuse, IPython provides you with a number of tools. Start by using %hist | |
202 | to see your input history, so you can see the line numbers of all input. |
|
200 | to see your input history, so you can see the line numbers of all input. | |
203 | Let us say that you'd like to reuse lines 10 through 20, plus lines 24 |
|
201 | Let us say that you'd like to reuse lines 10 through 20, plus lines 24 | |
204 | and 28. All the commands below can operate on these with the syntax:: |
|
202 | and 28. All the commands below can operate on these with the syntax:: | |
205 |
|
203 | |||
206 | %command 10-20 24 28 |
|
204 | %command 10-20 24 28 | |
207 |
|
205 | |||
208 | where the command given can be: |
|
206 | where the command given can be: | |
209 |
|
207 | |||
210 | * %macro <macroname>: this stores the lines into a variable which, |
|
208 | * %macro <macroname>: this stores the lines into a variable which, | |
211 | when called at the prompt, re-executes the input. Macros can be |
|
209 | when called at the prompt, re-executes the input. Macros can be | |
212 | edited later using '%edit macroname', and they can be stored |
|
210 | edited later using '%edit macroname', and they can be stored | |
213 | persistently across sessions with '%store macroname' (the storage |
|
211 | persistently across sessions with '%store macroname' (the storage | |
214 | system is per-profile). The combination of quick macros, |
|
212 | system is per-profile). The combination of quick macros, | |
215 | persistent storage and editing, allows you to easily refine |
|
213 | persistent storage and editing, allows you to easily refine | |
216 | quick-and-dirty interactive input into permanent utilities, always |
|
214 | quick-and-dirty interactive input into permanent utilities, always | |
217 | available both in IPython and as files for general reuse. |
|
215 | available both in IPython and as files for general reuse. | |
218 | * %edit: this will open a text editor with those lines pre-loaded |
|
216 | * %edit: this will open a text editor with those lines pre-loaded | |
219 | for further modification. It will then execute the resulting |
|
217 | for further modification. It will then execute the resulting | |
220 | file's contents as if you had typed it at the prompt. |
|
218 | file's contents as if you had typed it at the prompt. | |
221 | * %save <filename>: this saves the lines directly to a named file on |
|
219 | * %save <filename>: this saves the lines directly to a named file on | |
222 | disk. |
|
220 | disk. | |
223 |
|
221 | |||
224 | While %macro saves input lines into memory for interactive re-execution, |
|
222 | While %macro saves input lines into memory for interactive re-execution, | |
225 | sometimes you'd like to save your input directly to a file. The %save |
|
223 | sometimes you'd like to save your input directly to a file. The %save | |
226 | magic does this: its input sytnax is the same as %macro, but it saves |
|
224 | magic does this: its input sytnax is the same as %macro, but it saves | |
227 | your input directly to a Python file. Note that the %logstart command |
|
225 | your input directly to a Python file. Note that the %logstart command | |
228 | also saves input, but it logs all input to disk (though you can |
|
226 | also saves input, but it logs all input to disk (though you can | |
229 | temporarily suspend it and reactivate it with %logoff/%logon); %save |
|
227 | temporarily suspend it and reactivate it with %logoff/%logon); %save | |
230 | allows you to select which lines of input you need to save. |
|
228 | allows you to select which lines of input you need to save. | |
231 |
|
229 | |||
232 |
|
230 | |||
233 | Lightweight 'version control' |
|
231 | Lightweight 'version control' | |
234 | ============================= |
|
232 | ============================= | |
235 |
|
233 | |||
236 | When you call %edit with no arguments, IPython opens an empty editor |
|
234 | When you call %edit with no arguments, IPython opens an empty editor | |
237 | with a temporary file, and it returns the contents of your editing |
|
235 | with a temporary file, and it returns the contents of your editing | |
238 | session as a string variable. Thanks to IPython's output caching |
|
236 | session as a string variable. Thanks to IPython's output caching | |
239 | mechanism, this is automatically stored:: |
|
237 | mechanism, this is automatically stored:: | |
240 |
|
238 | |||
241 | In [1]: %edit |
|
239 | In [1]: %edit | |
242 |
|
240 | |||
243 | IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py |
|
241 | IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py | |
244 |
|
242 | |||
245 | Editing... done. Executing edited code... |
|
243 | Editing... done. Executing edited code... | |
246 |
|
244 | |||
247 | hello - this is a temporary file |
|
245 | hello - this is a temporary file | |
248 |
|
246 | |||
249 | Out[1]: "print 'hello - this is a temporary file'\n" |
|
247 | Out[1]: "print 'hello - this is a temporary file'\n" | |
250 |
|
248 | |||
251 | Now, if you call '%edit -p', IPython tries to open an editor with the |
|
249 | Now, if you call '%edit -p', IPython tries to open an editor with the | |
252 | same data as the last time you used %edit. So if you haven't used %edit |
|
250 | same data as the last time you used %edit. So if you haven't used %edit | |
253 | in the meantime, this same contents will reopen; however, it will be |
|
251 | in the meantime, this same contents will reopen; however, it will be | |
254 | done in a new file. This means that if you make changes and you later |
|
252 | done in a new file. This means that if you make changes and you later | |
255 | want to find an old version, you can always retrieve it by using its |
|
253 | want to find an old version, you can always retrieve it by using its | |
256 | output number, via '%edit _NN', where NN is the number of the output |
|
254 | output number, via '%edit _NN', where NN is the number of the output | |
257 | prompt. |
|
255 | prompt. | |
258 |
|
256 | |||
259 | Continuing with the example above, this should illustrate this idea:: |
|
257 | Continuing with the example above, this should illustrate this idea:: | |
260 |
|
258 | |||
261 | In [2]: edit -p |
|
259 | In [2]: edit -p | |
262 |
|
260 | |||
263 | IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py |
|
261 | IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py | |
264 |
|
262 | |||
265 | Editing... done. Executing edited code... |
|
263 | Editing... done. Executing edited code... | |
266 |
|
264 | |||
267 | hello - now I made some changes |
|
265 | hello - now I made some changes | |
268 |
|
266 | |||
269 | Out[2]: "print 'hello - now I made some changes'\n" |
|
267 | Out[2]: "print 'hello - now I made some changes'\n" | |
270 |
|
268 | |||
271 | In [3]: edit _1 |
|
269 | In [3]: edit _1 | |
272 |
|
270 | |||
273 | IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py |
|
271 | IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py | |
274 |
|
272 | |||
275 | Editing... done. Executing edited code... |
|
273 | Editing... done. Executing edited code... | |
276 |
|
274 | |||
277 | hello - this is a temporary file |
|
275 | hello - this is a temporary file | |
278 |
|
276 | |||
279 | IPython version control at work :) |
|
277 | IPython version control at work :) | |
280 |
|
278 | |||
281 | Out[3]: "print 'hello - this is a temporary file'\nprint 'IPython version control at work :)'\n" |
|
279 | Out[3]: "print 'hello - this is a temporary file'\nprint 'IPython version control at work :)'\n" | |
282 |
|
280 | |||
283 |
|
281 | |||
284 | This section was written after a contribution by Alexander Belchenko on |
|
282 | This section was written after a contribution by Alexander Belchenko on | |
285 | the IPython user list. |
|
283 | the IPython user list. | |
286 |
|
284 | |||
287 |
|
285 | |||
288 | Effective logging |
|
286 | Effective logging | |
289 | ================= |
|
287 | ================= | |
290 |
|
288 | |||
291 | A very useful suggestion sent in by Robert Kern follows: |
|
289 | A very useful suggestion sent in by Robert Kern follows: | |
292 |
|
290 | |||
293 | I recently happened on a nifty way to keep tidy per-project log files. I |
|
291 | I recently happened on a nifty way to keep tidy per-project log files. I | |
294 | made a profile for my project (which is called "parkfield"):: |
|
292 | made a profile for my project (which is called "parkfield"):: | |
295 |
|
293 | |||
296 | include ipythonrc |
|
294 | include ipythonrc | |
297 |
|
295 | |||
298 | # cancel earlier logfile invocation: |
|
296 | # cancel earlier logfile invocation: | |
299 |
|
297 | |||
300 | logfile '' |
|
298 | logfile '' | |
301 |
|
299 | |||
302 | execute import time |
|
300 | execute import time | |
303 |
|
301 | |||
304 | execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate' |
|
302 | execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate' | |
305 |
|
303 | |||
306 | execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d')) |
|
304 | execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d')) | |
307 |
|
305 | |||
308 | I also added a shell alias for convenience:: |
|
306 | I also added a shell alias for convenience:: | |
309 |
|
307 | |||
310 | alias parkfield="ipython -pylab -profile parkfield" |
|
308 | alias parkfield="ipython -pylab -profile parkfield" | |
311 |
|
309 | |||
312 | Now I have a nice little directory with everything I ever type in, |
|
310 | Now I have a nice little directory with everything I ever type in, | |
313 | organized by project and date. |
|
311 | organized by project and date. | |
314 |
|
312 | |||
315 | Contribute your own: If you have your own favorite tip on using IPython |
|
313 | Contribute your own: If you have your own favorite tip on using IPython | |
316 | efficiently for a certain task (especially things which can't be done in |
|
314 | efficiently for a certain task (especially things which can't be done in | |
317 | the normal Python interpreter), don't hesitate to send it! |
|
315 | the normal Python interpreter), don't hesitate to send it! |
@@ -1,87 +1,91 b'' | |||||
1 | .. _license: |
|
1 | .. _license: | |
2 |
|
2 | |||
3 | ===================== |
|
3 | ===================== | |
4 | License and Copyright |
|
4 | License and Copyright | |
5 | ===================== |
|
5 | ===================== | |
6 |
|
6 | |||
7 | License |
|
7 | License | |
8 | ======= |
|
8 | ======= | |
9 |
|
9 | |||
10 | IPython is licensed under the terms of the new or revised BSD license, as follows:: |
|
10 | IPython is licensed under the terms of the new or revised BSD license, as follows:: | |
11 |
|
11 | |||
12 | Copyright (c) 2008, IPython Development Team |
|
12 | Copyright (c) 2008, IPython Development Team | |
13 |
|
13 | |||
14 | All rights reserved. |
|
14 | All rights reserved. | |
15 |
|
15 | |||
16 |
Redistribution and use in source and binary forms, with or without |
|
16 | Redistribution and use in source and binary forms, with or without | |
17 |
are permitted provided that the following conditions are |
|
17 | modification, are permitted provided that the following conditions are | |
18 |
|
18 | met: | ||
19 | Redistributions of source code must retain the above copyright notice, this list of |
|
19 | ||
20 | conditions and the following disclaimer. |
|
20 | Redistributions of source code must retain the above copyright notice, | |
21 |
|
21 | this list of conditions and the following disclaimer. | ||
22 | Redistributions in binary form must reproduce the above copyright notice, this list |
|
22 | ||
23 | of conditions and the following disclaimer in the documentation and/or other |
|
23 | Redistributions in binary form must reproduce the above copyright notice, | |
24 | materials provided with the distribution. |
|
24 | this list of conditions and the following disclaimer in the documentation | |
25 |
|
25 | and/or other materials provided with the distribution. | ||
26 | Neither the name of the IPython Development Team nor the names of its contributors |
|
26 | ||
27 | may be used to endorse or promote products derived from this software without |
|
27 | Neither the name of the IPython Development Team nor the names of its | |
28 | specific prior written permission. |
|
28 | contributors may be used to endorse or promote products derived from this | |
29 |
|
29 | software without specific prior written permission. | ||
30 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY |
|
30 | ||
31 | EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED |
|
31 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS | |
32 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. |
|
32 | IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, | |
33 | IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, |
|
33 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | |
34 | INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT |
|
34 | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR | |
35 | NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR |
|
35 | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, | |
36 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, |
|
36 | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, | |
37 | WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
|
37 | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR | |
38 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
|
38 | PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF | |
39 | POSSIBILITY OF SUCH DAMAGE. |
|
39 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING | |
|
40 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |||
|
41 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |||
40 |
|
42 | |||
41 | About the IPython Development Team |
|
43 | About the IPython Development Team | |
42 | ================================== |
|
44 | ================================== | |
43 |
|
45 | |||
44 |
Fernando Perez began IPython in 2001 based on code from Janko Hauser |
|
46 | Fernando Perez began IPython in 2001 based on code from Janko Hauser | |
45 |
and Nathaniel Gray <n8gray@caltech.edu>. |
|
47 | <jhauser@zscout.de> and Nathaniel Gray <n8gray@caltech.edu>. Fernando is still | |
|
48 | the project lead. | |||
46 |
|
49 | |||
47 |
The IPython Development Team is the set of all contributors to the IPython |
|
50 | The IPython Development Team is the set of all contributors to the IPython | |
48 |
This includes all of the IPython subprojects. Here is a list of the |
|
51 | project. This includes all of the IPython subprojects. Here is a list of the | |
|
52 | currently active contributors: | |||
49 |
|
53 | |||
50 | * Matthieu Brucher |
|
54 | * Matthieu Brucher | |
51 | * Ondrej Certik |
|
55 | * Ondrej Certik | |
52 | * Laurent Dufrechou |
|
56 | * Laurent Dufrechou | |
53 | * Robert Kern |
|
57 | * Robert Kern | |
54 | * Brian E. Granger |
|
58 | * Brian E. Granger | |
55 | * Fernando Perez (project leader) |
|
59 | * Fernando Perez (project leader) | |
56 | * Benjamin Ragan-Kelley |
|
60 | * Benjamin Ragan-Kelley | |
57 | * Ville M. Vainio |
|
61 | * Ville M. Vainio | |
58 | * Gael Varoququx |
|
62 | * Gael Varoququx | |
59 | * Stefan van der Walt |
|
63 | * Stefan van der Walt | |
60 | * Tech-X Corporation |
|
64 | * Tech-X Corporation | |
61 | * Barry Wark |
|
65 | * Barry Wark | |
62 |
|
66 | |||
63 | If your name is missing, please add it. |
|
67 | If your name is missing, please add it. | |
64 |
|
68 | |||
65 | Our Copyright Policy |
|
69 | Our Copyright Policy | |
66 | ==================== |
|
70 | ==================== | |
67 |
|
71 | |||
68 |
IPython uses a shared copyright model. Each contributor maintains copyright |
|
72 | IPython uses a shared copyright model. Each contributor maintains copyright | |
69 | their contributions to IPython. But, it is important to note that these |
|
73 | over their contributions to IPython. But, it is important to note that these | |
70 |
contributions are typically only changes to the repositories. Thus, the |
|
74 | contributions are typically only changes to the repositories. Thus, the | |
71 |
source code, in its entirety is not the copyright of any single person |
|
75 | IPython source code, in its entirety is not the copyright of any single person | |
72 | institution. Instead, it is the collective copyright of the entire IPython |
|
76 | or institution. Instead, it is the collective copyright of the entire IPython | |
73 | Development Team. If individual contributors want to maintain a record of what |
|
77 | Development Team. If individual contributors want to maintain a record of what | |
74 |
changes/contributions they have specific copyright on, they should indicate |
|
78 | changes/contributions they have specific copyright on, they should indicate | |
75 |
copyright in the commit message of the change, when they commit the |
|
79 | their copyright in the commit message of the change, when they commit the | |
76 | one of the IPython repositories. |
|
80 | change to one of the IPython repositories. | |
77 |
|
81 | |||
78 | Miscellaneous |
|
82 | Miscellaneous | |
79 | ============= |
|
83 | ============= | |
80 |
|
84 | |||
81 | Some files (DPyGetOpt.py, for example) may be licensed under different |
|
85 | Some files (DPyGetOpt.py, for example) may be licensed under different | |
82 | conditions. Ultimately each file indicates clearly the conditions under |
|
86 | conditions. Ultimately each file indicates clearly the conditions under which | |
83 |
|
|
87 | its author/authors have decided to publish the code. | |
84 |
|
88 | |||
85 | Versions of IPython up to and including 0.6.3 were released under the |
|
89 | Versions of IPython up to and including 0.6.3 were released under the GNU | |
86 |
|
|
90 | Lesser General Public License (LGPL), available at | |
87 | http://www.gnu.org/copyleft/lesser.html. No newline at end of file |
|
91 | http://www.gnu.org/copyleft/lesser.html. |
@@ -1,14 +1,16 b'' | |||||
1 | .. _parallel_index: |
|
1 | .. _parallel_index: | |
2 |
|
2 | |||
3 | ==================================== |
|
3 | ==================================== | |
4 | Using IPython for parallel computing |
|
4 | Using IPython for parallel computing | |
5 | ==================================== |
|
5 | ==================================== | |
6 |
|
6 | |||
7 | .. toctree:: |
|
7 | .. toctree:: | |
8 | :maxdepth: 2 |
|
8 | :maxdepth: 2 | |
9 |
|
9 | |||
10 | parallel_intro.txt |
|
10 | parallel_intro.txt | |
|
11 | parallel_process.txt | |||
11 | parallel_multiengine.txt |
|
12 | parallel_multiengine.txt | |
12 | parallel_task.txt |
|
13 | parallel_task.txt | |
13 | parallel_mpi.txt |
|
14 | parallel_mpi.txt | |
|
15 | parallel_security.txt | |||
14 |
|
16 |
@@ -1,327 +1,205 b'' | |||||
1 | .. _ip1par: |
|
1 | .. _ip1par: | |
2 |
|
2 | |||
3 | ============================ |
|
3 | ============================ | |
4 | Overview and getting started |
|
4 | Overview and getting started | |
5 | ============================ |
|
5 | ============================ | |
6 |
|
6 | |||
7 | .. contents:: |
|
|||
8 |
|
||||
9 | Introduction |
|
7 | Introduction | |
10 | ============ |
|
8 | ============ | |
11 |
|
9 | |||
12 |
This |
|
10 | This section gives an overview of IPython's sophisticated and powerful | |
13 |
|
|
11 | architecture for parallel and distributed computing. This architecture | |
14 |
|
|
12 | abstracts out parallelism in a very general way, which enables IPython to | |
15 |
|
|
13 | support many different styles of parallelism including: | |
16 | including: |
|
|||
17 |
|
14 | |||
18 | * Single program, multiple data (SPMD) parallelism. |
|
15 | * Single program, multiple data (SPMD) parallelism. | |
19 | * Multiple program, multiple data (MPMD) parallelism. |
|
16 | * Multiple program, multiple data (MPMD) parallelism. | |
20 |
* Message passing using |
|
17 | * Message passing using MPI. | |
21 | * Task farming. |
|
18 | * Task farming. | |
22 | * Data parallel. |
|
19 | * Data parallel. | |
23 | * Combinations of these approaches. |
|
20 | * Combinations of these approaches. | |
24 | * Custom user defined approaches. |
|
21 | * Custom user defined approaches. | |
25 |
|
22 | |||
26 | Most importantly, IPython enables all types of parallel applications to |
|
23 | Most importantly, IPython enables all types of parallel applications to | |
27 | be developed, executed, debugged and monitored *interactively*. Hence, |
|
24 | be developed, executed, debugged and monitored *interactively*. Hence, | |
28 | the ``I`` in IPython. The following are some example usage cases for IPython: |
|
25 | the ``I`` in IPython. The following are some example usage cases for IPython: | |
29 |
|
26 | |||
30 | * Quickly parallelize algorithms that are embarrassingly parallel |
|
27 | * Quickly parallelize algorithms that are embarrassingly parallel | |
31 | using a number of simple approaches. Many simple things can be |
|
28 | using a number of simple approaches. Many simple things can be | |
32 | parallelized interactively in one or two lines of code. |
|
29 | parallelized interactively in one or two lines of code. | |
33 |
|
30 | |||
34 | * Steer traditional MPI applications on a supercomputer from an |
|
31 | * Steer traditional MPI applications on a supercomputer from an | |
35 | IPython session on your laptop. |
|
32 | IPython session on your laptop. | |
36 |
|
33 | |||
37 | * Analyze and visualize large datasets (that could be remote and/or |
|
34 | * Analyze and visualize large datasets (that could be remote and/or | |
38 | distributed) interactively using IPython and tools like |
|
35 | distributed) interactively using IPython and tools like | |
39 | matplotlib/TVTK. |
|
36 | matplotlib/TVTK. | |
40 |
|
37 | |||
41 | * Develop, test and debug new parallel algorithms |
|
38 | * Develop, test and debug new parallel algorithms | |
42 | (that may use MPI) interactively. |
|
39 | (that may use MPI) interactively. | |
43 |
|
40 | |||
44 | * Tie together multiple MPI jobs running on different systems into |
|
41 | * Tie together multiple MPI jobs running on different systems into | |
45 | one giant distributed and parallel system. |
|
42 | one giant distributed and parallel system. | |
46 |
|
43 | |||
47 | * Start a parallel job on your cluster and then have a remote |
|
44 | * Start a parallel job on your cluster and then have a remote | |
48 | collaborator connect to it and pull back data into their |
|
45 | collaborator connect to it and pull back data into their | |
49 | local IPython session for plotting and analysis. |
|
46 | local IPython session for plotting and analysis. | |
50 |
|
47 | |||
51 | * Run a set of tasks on a set of CPUs using dynamic load balancing. |
|
48 | * Run a set of tasks on a set of CPUs using dynamic load balancing. | |
52 |
|
49 | |||
53 | Architecture overview |
|
50 | Architecture overview | |
54 | ===================== |
|
51 | ===================== | |
55 |
|
52 | |||
56 | The IPython architecture consists of three components: |
|
53 | The IPython architecture consists of three components: | |
57 |
|
54 | |||
58 | * The IPython engine. |
|
55 | * The IPython engine. | |
59 | * The IPython controller. |
|
56 | * The IPython controller. | |
60 | * Various controller clients. |
|
57 | * Various controller clients. | |
61 |
|
58 | |||
62 | These components live in the :mod:`IPython.kernel` package and are |
|
59 | These components live in the :mod:`IPython.kernel` package and are | |
63 | installed with IPython. They do, however, have additional dependencies |
|
60 | installed with IPython. They do, however, have additional dependencies | |
64 | that must be installed. For more information, see our |
|
61 | that must be installed. For more information, see our | |
65 | :ref:`installation documentation <install_index>`. |
|
62 | :ref:`installation documentation <install_index>`. | |
66 |
|
63 | |||
67 | IPython engine |
|
64 | IPython engine | |
68 | --------------- |
|
65 | --------------- | |
69 |
|
66 | |||
70 | The IPython engine is a Python instance that takes Python commands over a |
|
67 | The IPython engine is a Python instance that takes Python commands over a | |
71 | network connection. Eventually, the IPython engine will be a full IPython |
|
68 | network connection. Eventually, the IPython engine will be a full IPython | |
72 | interpreter, but for now, it is a regular Python interpreter. The engine |
|
69 | interpreter, but for now, it is a regular Python interpreter. The engine | |
73 | can also handle incoming and outgoing Python objects sent over a network |
|
70 | can also handle incoming and outgoing Python objects sent over a network | |
74 | connection. When multiple engines are started, parallel and distributed |
|
71 | connection. When multiple engines are started, parallel and distributed | |
75 | computing becomes possible. An important feature of an IPython engine is |
|
72 | computing becomes possible. An important feature of an IPython engine is | |
76 | that it blocks while user code is being executed. Read on for how the |
|
73 | that it blocks while user code is being executed. Read on for how the | |
77 | IPython controller solves this problem to expose a clean asynchronous API |
|
74 | IPython controller solves this problem to expose a clean asynchronous API | |
78 | to the user. |
|
75 | to the user. | |
79 |
|
76 | |||
80 | IPython controller |
|
77 | IPython controller | |
81 | ------------------ |
|
78 | ------------------ | |
82 |
|
79 | |||
83 | The IPython controller provides an interface for working with a set of |
|
80 | The IPython controller provides an interface for working with a set of | |
84 | engines. At an general level, the controller is a process to which |
|
81 | engines. At an general level, the controller is a process to which | |
85 | IPython engines can connect. For each connected engine, the controller |
|
82 | IPython engines can connect. For each connected engine, the controller | |
86 | manages a queue. All actions that can be performed on the engine go |
|
83 | manages a queue. All actions that can be performed on the engine go | |
87 | through this queue. While the engines themselves block when user code is |
|
84 | through this queue. While the engines themselves block when user code is | |
88 | run, the controller hides that from the user to provide a fully |
|
85 | run, the controller hides that from the user to provide a fully | |
89 | asynchronous interface to a set of engines. |
|
86 | asynchronous interface to a set of engines. | |
90 |
|
87 | |||
91 | .. note:: |
|
88 | .. note:: | |
92 |
|
89 | |||
93 | Because the controller listens on a network port for engines to |
|
90 | Because the controller listens on a network port for engines to | |
94 | connect to it, it must be started *before* any engines are started. |
|
91 | connect to it, it must be started *before* any engines are started. | |
95 |
|
92 | |||
96 | The controller also provides a single point of contact for users who wish |
|
93 | The controller also provides a single point of contact for users who wish | |
97 | to utilize the engines connected to the controller. There are different |
|
94 | to utilize the engines connected to the controller. There are different | |
98 | ways of working with a controller. In IPython these ways correspond to different interfaces that the controller is adapted to. Currently we have two default interfaces to the controller: |
|
95 | ways of working with a controller. In IPython these ways correspond to different interfaces that the controller is adapted to. Currently we have two default interfaces to the controller: | |
99 |
|
96 | |||
100 |
* The MultiEngine interface, which provides the simplest possible way of |
|
97 | * The MultiEngine interface, which provides the simplest possible way of | |
101 | with engines interactively. |
|
98 | working with engines interactively. | |
102 | * The Task interface, which provides presents the engines as a load balanced |
|
99 | * The Task interface, which provides presents the engines as a load balanced | |
103 | task farming system. |
|
100 | task farming system. | |
104 |
|
101 | |||
105 | Advanced users can easily add new custom interfaces to enable other |
|
102 | Advanced users can easily add new custom interfaces to enable other | |
106 | styles of parallelism. |
|
103 | styles of parallelism. | |
107 |
|
104 | |||
108 | .. note:: |
|
105 | .. note:: | |
109 |
|
106 | |||
110 | A single controller and set of engines can be accessed |
|
107 | A single controller and set of engines can be accessed | |
111 | through multiple interfaces simultaneously. This opens the |
|
108 | through multiple interfaces simultaneously. This opens the | |
112 | door for lots of interesting things. |
|
109 | door for lots of interesting things. | |
113 |
|
110 | |||
114 | Controller clients |
|
111 | Controller clients | |
115 | ------------------ |
|
112 | ------------------ | |
116 |
|
113 | |||
117 | For each controller interface, there is a corresponding client. These |
|
114 | For each controller interface, there is a corresponding client. These | |
118 | clients allow users to interact with a set of engines through the |
|
115 | clients allow users to interact with a set of engines through the | |
119 | interface. Here are the two default clients: |
|
116 | interface. Here are the two default clients: | |
120 |
|
117 | |||
121 | * The :class:`MultiEngineClient` class. |
|
118 | * The :class:`MultiEngineClient` class. | |
122 | * The :class:`TaskClient` class. |
|
119 | * The :class:`TaskClient` class. | |
123 |
|
120 | |||
124 | Security |
|
121 | Security | |
125 | -------- |
|
122 | -------- | |
126 |
|
123 | |||
127 |
By default (as long as `pyOpenSSL` is installed) all network connections between the controller and engines and the controller and clients are secure. What does this mean? First of all, all of the connections will be encrypted using SSL. Second, the connections are authenticated. We handle authentication in a |
|
124 | By default (as long as `pyOpenSSL` is installed) all network connections between the controller and engines and the controller and clients are secure. What does this mean? First of all, all of the connections will be encrypted using SSL. Second, the connections are authenticated. We handle authentication in a capability based security model [Capability]_. In this model, a "capability (known in some systems as a key) is a communicable, unforgeable token of authority". Put simply, a capability is like a key to your house. If you have the key to your house, you can get in. If not, you can't. | |
128 |
|
||||
129 | .. __: http://en.wikipedia.org/wiki/Capability-based_security |
|
|||
130 |
|
125 | |||
131 | In our architecture, the controller is the only process that listens on network ports, and is thus responsible to creating these keys. In IPython, these keys are known as Foolscap URLs, or FURLs, because of the underlying network protocol we are using. As a user, you don't need to know anything about the details of these FURLs, other than that when the controller starts, it saves a set of FURLs to files named :file:`something.furl`. The default location of these files is the :file:`~./ipython/security` directory. |
|
126 | In our architecture, the controller is the only process that listens on network ports, and is thus responsible to creating these keys. In IPython, these keys are known as Foolscap URLs, or FURLs, because of the underlying network protocol we are using. As a user, you don't need to know anything about the details of these FURLs, other than that when the controller starts, it saves a set of FURLs to files named :file:`something.furl`. The default location of these files is the :file:`~./ipython/security` directory. | |
132 |
|
127 | |||
133 |
To connect and authenticate to the controller an engine or client simply needs to present an appropriate |
|
128 | To connect and authenticate to the controller an engine or client simply needs to present an appropriate FURL (that was originally created by the controller) to the controller. Thus, the FURL files need to be copied to a location where the clients and engines can find them. Typically, this is the :file:`~./ipython/security` directory on the host where the client/engine is running (which could be a different host than the controller). Once the FURL files are copied over, everything should work fine. | |
134 |
|
129 | |||
135 |
Currently, there are three |
|
130 | Currently, there are three FURL files that the controller creates: | |
136 |
|
131 | |||
137 | ipcontroller-engine.furl |
|
132 | ipcontroller-engine.furl | |
138 |
This |
|
133 | This FURL file is the key that gives an engine the ability to connect | |
139 | to a controller. |
|
134 | to a controller. | |
140 |
|
135 | |||
141 | ipcontroller-tc.furl |
|
136 | ipcontroller-tc.furl | |
142 |
This |
|
137 | This FURL file is the key that a :class:`TaskClient` must use to | |
143 | connect to the task interface of a controller. |
|
138 | connect to the task interface of a controller. | |
144 |
|
139 | |||
145 | ipcontroller-mec.furl |
|
140 | ipcontroller-mec.furl | |
146 |
This |
|
141 | This FURL file is the key that a :class:`MultiEngineClient` must use | |
147 | connect to the multiengine interface of a controller. |
|
142 | to connect to the multiengine interface of a controller. | |
148 |
|
143 | |||
149 |
More details of how these |
|
144 | More details of how these FURL files are used are given below. | |
|
145 | ||||
|
146 | A detailed description of the security model and its implementation in IPython | |||
|
147 | can be found :ref:`here <parallelsecurity>`. | |||
150 |
|
148 | |||
151 | Getting Started |
|
149 | Getting Started | |
152 | =============== |
|
150 | =============== | |
153 |
|
151 | |||
154 | To use IPython for parallel computing, you need to start one instance of |
|
152 | To use IPython for parallel computing, you need to start one instance of | |
155 | the controller and one or more instances of the engine. The controller |
|
153 | the controller and one or more instances of the engine. Initially, it is best to simply start a controller and engines on a single host using the :command:`ipcluster` command. To start a controller and 4 engines on you localhost, just do:: | |
156 | and each engine can run on different machines or on the same machine. |
|
|||
157 | Because of this, there are many different possibilities for setting up |
|
|||
158 | the IP addresses and ports used by the various processes. |
|
|||
159 |
|
||||
160 | Starting the controller and engine on your local machine |
|
|||
161 | -------------------------------------------------------- |
|
|||
162 |
|
||||
163 | This is the simplest configuration that can be used and is useful for |
|
|||
164 | testing the system and on machines that have multiple cores and/or |
|
|||
165 | multple CPUs. The easiest way of getting started is to use the :command:`ipcluster` |
|
|||
166 | command:: |
|
|||
167 |
|
||||
168 | $ ipcluster -n 4 |
|
|||
169 |
|
||||
170 | This will start an IPython controller and then 4 engines that connect to |
|
|||
171 | the controller. Lastly, the script will print out the Python commands |
|
|||
172 | that you can use to connect to the controller. It is that easy. |
|
|||
173 |
|
||||
174 | .. warning:: |
|
|||
175 |
|
||||
176 | The :command:`ipcluster` does not currently work on Windows. We are |
|
|||
177 | working on it though. |
|
|||
178 |
|
||||
179 | Underneath the hood, the controller creates ``.furl`` files in the |
|
|||
180 | :file:`~./ipython/security` directory. Because the engines are on the |
|
|||
181 | same host, they automatically find the needed :file:`ipcontroller-engine.furl` |
|
|||
182 | there and use it to connect to the controller. |
|
|||
183 |
|
||||
184 | The :command:`ipcluster` script uses two other top-level |
|
|||
185 | scripts that you can also use yourself. These scripts are |
|
|||
186 | :command:`ipcontroller`, which starts the controller and :command:`ipengine` which |
|
|||
187 | starts one engine. To use these scripts to start things on your local |
|
|||
188 | machine, do the following. |
|
|||
189 |
|
||||
190 | First start the controller:: |
|
|||
191 |
|
||||
192 | $ ipcontroller |
|
|||
193 |
|
||||
194 | Next, start however many instances of the engine you want using (repeatedly) the command:: |
|
|||
195 |
|
||||
196 | $ ipengine |
|
|||
197 |
|
||||
198 | The engines should start and automatically connect to the controller using the ``.furl`` files in :file:`~./ipython/security`. You are now ready to use the controller and engines from IPython. |
|
|||
199 |
|
||||
200 | .. warning:: |
|
|||
201 |
|
||||
202 | The order of the above operations is very important. You *must* |
|
|||
203 | start the controller before the engines, since the engines connect |
|
|||
204 | to the controller as they get started. |
|
|||
205 |
|
||||
206 | .. note:: |
|
|||
207 |
|
||||
208 | On some platforms (OS X), to put the controller and engine into the background |
|
|||
209 | you may need to give these commands in the form ``(ipcontroller &)`` |
|
|||
210 | and ``(ipengine &)`` (with the parentheses) for them to work properly. |
|
|||
211 |
|
||||
212 |
|
||||
213 | Starting the controller and engines on different hosts |
|
|||
214 | ------------------------------------------------------ |
|
|||
215 |
|
||||
216 | When the controller and engines are running on different hosts, things are |
|
|||
217 | slightly more complicated, but the underlying ideas are the same: |
|
|||
218 |
|
||||
219 | 1. Start the controller on a host using :command:`ipcontroler`. |
|
|||
220 | 2. Copy :file:`ipcontroller-engine.furl` from :file:`~./ipython/security` on the controller's host to the host where the engines will run. |
|
|||
221 | 3. Use :command:`ipengine` on the engine's hosts to start the engines. |
|
|||
222 |
|
154 | |||
223 | The only thing you have to be careful of is to tell :command:`ipengine` where the :file:`ipcontroller-engine.furl` file is located. There are two ways you can do this: |
|
155 | $ ipcluster local -n 4 | |
224 |
|
156 | |||
225 | * Put :file:`ipcontroller-engine.furl` in the :file:`~./ipython/security` directory |
|
157 | More details about starting the IPython controller and engines can be found :ref:`here <parallel_process>` | |
226 | on the engine's host, where it will be found automatically. |
|
|||
227 | * Call :command:`ipengine` with the ``--furl-file=full_path_to_the_file`` flag. |
|
|||
228 |
|
||||
229 | The ``--furl-file`` flag works like this:: |
|
|||
230 |
|
||||
231 | $ ipengine --furl-file=/path/to/my/ipcontroller-engine.furl |
|
|||
232 |
|
||||
233 | .. note:: |
|
|||
234 |
|
||||
235 | If the controller's and engine's hosts all have a shared file system |
|
|||
236 | (:file:`~./ipython/security` is the same on all of them), then things |
|
|||
237 | will just work! |
|
|||
238 |
|
||||
239 | Make .furl files persistent |
|
|||
240 | --------------------------- |
|
|||
241 |
|
||||
242 | At fist glance it may seem that that managing the ``.furl`` files is a bit annoying. Going back to the house and key analogy, copying the ``.furl`` around each time you start the controller is like having to make a new key everytime you want to unlock the door and enter your house. As with your house, you want to be able to create the key (or ``.furl`` file) once, and then simply use it at any point in the future. |
|
|||
243 |
|
||||
244 | This is possible. The only thing you have to do is decide what ports the controller will listen on for the engines and clients. This is done as follows:: |
|
|||
245 |
|
||||
246 | $ ipcontroller --client-port=10101 --engine-port=10102 |
|
|||
247 |
|
||||
248 | Then, just copy the furl files over the first time and you are set. You can start and stop the controller and engines any many times as you want in the future, just make sure to tell the controller to use the *same* ports. |
|
|||
249 |
|
||||
250 | .. note:: |
|
|||
251 |
|
||||
252 | You may ask the question: what ports does the controller listen on if you |
|
|||
253 | don't tell is to use specific ones? The default is to use high random port |
|
|||
254 | numbers. We do this for two reasons: i) to increase security through obcurity |
|
|||
255 | and ii) to multiple controllers on a given host to start and automatically |
|
|||
256 | use different ports. |
|
|||
257 |
|
||||
258 | Starting engines using ``mpirun`` |
|
|||
259 | --------------------------------- |
|
|||
260 |
|
||||
261 | The IPython engines can be started using ``mpirun``/``mpiexec``, even if |
|
|||
262 | the engines don't call ``MPI_Init()`` or use the MPI API in any way. This is |
|
|||
263 | supported on modern MPI implementations like `Open MPI`_.. This provides |
|
|||
264 | an really nice way of starting a bunch of engine. On a system with MPI |
|
|||
265 | installed you can do:: |
|
|||
266 |
|
||||
267 | mpirun -n 4 ipengine |
|
|||
268 |
|
||||
269 | to start 4 engine on a cluster. This works even if you don't have any |
|
|||
270 | Python-MPI bindings installed. |
|
|||
271 |
|
||||
272 | .. _Open MPI: http://www.open-mpi.org/ |
|
|||
273 |
|
||||
274 | More details on using MPI with IPython can be found :ref:`here <parallelmpi>`. |
|
|||
275 |
|
||||
276 | Log files |
|
|||
277 | --------- |
|
|||
278 |
|
||||
279 | All of the components of IPython have log files associated with them. |
|
|||
280 | These log files can be extremely useful in debugging problems with |
|
|||
281 | IPython and can be found in the directory ``~/.ipython/log``. Sending |
|
|||
282 | the log files to us will often help us to debug any problems. |
|
|||
283 |
|
||||
284 | Next Steps |
|
|||
285 | ========== |
|
|||
286 |
|
158 | |||
287 | Once you have started the IPython controller and one or more engines, you |
|
159 | Once you have started the IPython controller and one or more engines, you | |
288 | are ready to use the engines to do something useful. To make sure |
|
160 | are ready to use the engines to do something useful. To make sure | |
289 |
everything is working correctly, try the following commands: |
|
161 | everything is working correctly, try the following commands: | |
|
162 | ||||
|
163 | .. sourcecode:: ipython | |||
290 |
|
164 | |||
291 | In [1]: from IPython.kernel import client |
|
165 | In [1]: from IPython.kernel import client | |
292 |
|
166 | |||
293 | In [2]: mec = client.MultiEngineClient() |
|
167 | In [2]: mec = client.MultiEngineClient() | |
294 |
|
168 | |||
295 | In [4]: mec.get_ids() |
|
169 | In [4]: mec.get_ids() | |
296 | Out[4]: [0, 1, 2, 3] |
|
170 | Out[4]: [0, 1, 2, 3] | |
297 |
|
171 | |||
298 | In [5]: mec.execute('print "Hello World"') |
|
172 | In [5]: mec.execute('print "Hello World"') | |
299 | Out[5]: |
|
173 | Out[5]: | |
300 | <Results List> |
|
174 | <Results List> | |
301 | [0] In [1]: print "Hello World" |
|
175 | [0] In [1]: print "Hello World" | |
302 | [0] Out[1]: Hello World |
|
176 | [0] Out[1]: Hello World | |
303 |
|
177 | |||
304 | [1] In [1]: print "Hello World" |
|
178 | [1] In [1]: print "Hello World" | |
305 | [1] Out[1]: Hello World |
|
179 | [1] Out[1]: Hello World | |
306 |
|
180 | |||
307 | [2] In [1]: print "Hello World" |
|
181 | [2] In [1]: print "Hello World" | |
308 | [2] Out[1]: Hello World |
|
182 | [2] Out[1]: Hello World | |
309 |
|
183 | |||
310 | [3] In [1]: print "Hello World" |
|
184 | [3] In [1]: print "Hello World" | |
311 | [3] Out[1]: Hello World |
|
185 | [3] Out[1]: Hello World | |
312 |
|
186 | |||
313 |
Remember, a client also needs to present a |
|
187 | Remember, a client also needs to present a FURL file to the controller. How does this happen? When a multiengine client is created with no arguments, the client tries to find the corresponding FURL file in the local :file:`~./ipython/security` directory. If it finds it, you are set. If you have put the FURL file in a different location or it has a different name, create the client like this:: | |
314 |
|
188 | |||
315 | mec = client.MultiEngineClient('/path/to/my/ipcontroller-mec.furl') |
|
189 | mec = client.MultiEngineClient('/path/to/my/ipcontroller-mec.furl') | |
316 |
|
190 | |||
317 | Same thing hold true of creating a task client:: |
|
191 | Same thing hold true of creating a task client:: | |
318 |
|
192 | |||
319 | tc = client.TaskClient('/path/to/my/ipcontroller-tc.furl') |
|
193 | tc = client.TaskClient('/path/to/my/ipcontroller-tc.furl') | |
320 |
|
194 | |||
321 | You are now ready to learn more about the :ref:`MultiEngine <parallelmultiengine>` and :ref:`Task <paralleltask>` interfaces to the controller. |
|
195 | You are now ready to learn more about the :ref:`MultiEngine <parallelmultiengine>` and :ref:`Task <paralleltask>` interfaces to the controller. | |
322 |
|
196 | |||
323 | .. note:: |
|
197 | .. note:: | |
324 |
|
198 | |||
325 | Don't forget that the engine, multiengine client and task client all have |
|
199 | Don't forget that the engine, multiengine client and task client all have | |
326 |
*different* furl files. |
|
200 | *different* furl files. You must move *each* of these around to an | |
327 |
location so that the engines and clients can use them to |
|
201 | appropriate location so that the engines and clients can use them to | |
|
202 | connect to the controller. | |||
|
203 | ||||
|
204 | .. [Capability] Capability-based security, http://en.wikipedia.org/wiki/Capability-based_security | |||
|
205 |
@@ -1,22 +1,157 b'' | |||||
1 | .. _parallelmpi: |
|
1 | .. _parallelmpi: | |
2 |
|
2 | |||
3 | ======================= |
|
3 | ======================= | |
4 | Using MPI with IPython |
|
4 | Using MPI with IPython | |
5 | ======================= |
|
5 | ======================= | |
6 |
|
6 | |||
7 | The simplest way of getting started with MPI is to install an MPI implementation |
|
7 | Often, a parallel algorithm will require moving data between the engines. One way of accomplishing this is by doing a pull and then a push using the multiengine client. However, this will be slow as all the data has to go through the controller to the client and then back through the controller, to its final destination. | |
8 | (we recommend `Open MPI`_) and `mpi4py`_ and then start the engines using the |
|
8 | ||
9 | ``mpirun`` command:: |
|
9 | A much better way of moving data between engines is to use a message passing library, such as the Message Passing Interface (MPI) [MPI]_. IPython's parallel computing architecture has been designed from the ground up to integrate with MPI. This document describes how to use MPI with IPython. | |
10 |
|
10 | |||
11 | mpirun -n 4 ipengine --mpi=mpi4py |
|
11 | Additional installation requirements | |
12 |
|
12 | ==================================== | ||
13 | This will automatically import `mpi4py`_ and make sure that `MPI_Init` is called |
|
13 | ||
14 | at the right time. We also have built in support for `PyTrilinos`_, which can be |
|
14 | If you want to use MPI with IPython, you will need to install: | |
15 | used (assuming `PyTrilinos`_ is installed) by starting the engines with:: |
|
15 | ||
16 |
|
16 | * A standard MPI implementation such as OpenMPI [OpenMPI]_ or MPICH. | ||
17 | mpirun -n 4 ipengine --mpi=pytrilinos |
|
17 | * The mpi4py [mpi4py]_ package. | |
18 |
|
18 | |||
19 | .. _MPI: http://www-unix.mcs.anl.gov/mpi/ |
|
19 | .. note:: | |
20 | .. _mpi4py: http://mpi4py.scipy.org/ |
|
20 | ||
21 | .. _Open MPI: http://www.open-mpi.org/ |
|
21 | The mpi4py package is not a strict requirement. However, you need to | |
22 | .. _PyTrilinos: http://trilinos.sandia.gov/packages/pytrilinos/ No newline at end of file |
|
22 | have *some* way of calling MPI from Python. You also need some way of | |
|
23 | making sure that :func:`MPI_Init` is called when the IPython engines start | |||
|
24 | up. There are a number of ways of doing this and a good number of | |||
|
25 | associated subtleties. We highly recommend just using mpi4py as it | |||
|
26 | takes care of most of these problems. If you want to do something | |||
|
27 | different, let us know and we can help you get started. | |||
|
28 | ||||
|
29 | Starting the engines with MPI enabled | |||
|
30 | ===================================== | |||
|
31 | ||||
|
32 | To use code that calls MPI, there are typically two things that MPI requires. | |||
|
33 | ||||
|
34 | 1. The process that wants to call MPI must be started using | |||
|
35 | :command:`mpirun` or a batch system (like PBS) that has MPI support. | |||
|
36 | 2. Once the process starts, it must call :func:`MPI_Init`. | |||
|
37 | ||||
|
38 | There are a couple of ways that you can start the IPython engines and get these things to happen. | |||
|
39 | ||||
|
40 | Automatic starting using :command:`mpirun` and :command:`ipcluster` | |||
|
41 | ------------------------------------------------------------------- | |||
|
42 | ||||
|
43 | The easiest approach is to use the `mpirun` mode of :command:`ipcluster`, which will first start a controller and then a set of engines using :command:`mpirun`:: | |||
|
44 | ||||
|
45 | $ ipcluster mpirun -n 4 | |||
|
46 | ||||
|
47 | This approach is best as interrupting :command:`ipcluster` will automatically | |||
|
48 | stop and clean up the controller and engines. | |||
|
49 | ||||
|
50 | Manual starting using :command:`mpirun` | |||
|
51 | --------------------------------------- | |||
|
52 | ||||
|
53 | If you want to start the IPython engines using the :command:`mpirun`, just do:: | |||
|
54 | ||||
|
55 | $ mpirun -n 4 ipengine --mpi=mpi4py | |||
|
56 | ||||
|
57 | This requires that you already have a controller running and that the FURL | |||
|
58 | files for the engines are in place. We also have built in support for | |||
|
59 | PyTrilinos [PyTrilinos]_, which can be used (assuming is installed) by | |||
|
60 | starting the engines with:: | |||
|
61 | ||||
|
62 | mpirun -n 4 ipengine --mpi=pytrilinos | |||
|
63 | ||||
|
64 | Automatic starting using PBS and :command:`ipcluster` | |||
|
65 | ----------------------------------------------------- | |||
|
66 | ||||
|
67 | The :command:`ipcluster` command also has built-in integration with PBS. For more information on this approach, see our documentation on :ref:`ipcluster <parallel_process>`. | |||
|
68 | ||||
|
69 | Actually using MPI | |||
|
70 | ================== | |||
|
71 | ||||
|
72 | Once the engines are running with MPI enabled, you are ready to go. You can now call any code that uses MPI in the IPython engines. And, all of this can be done interactively. Here we show a simple example that uses mpi4py [mpi4py]_. | |||
|
73 | ||||
|
74 | First, lets define a simply function that uses MPI to calculate the sum of a distributed array. Save the following text in a file called :file:`psum.py`: | |||
|
75 | ||||
|
76 | .. sourcecode:: python | |||
|
77 | ||||
|
78 | from mpi4py import MPI | |||
|
79 | import numpy as np | |||
|
80 | ||||
|
81 | def psum(a): | |||
|
82 | s = np.sum(a) | |||
|
83 | return MPI.COMM_WORLD.Allreduce(s,MPI.SUM) | |||
|
84 | ||||
|
85 | Now, start an IPython cluster in the same directory as :file:`psum.py`:: | |||
|
86 | ||||
|
87 | $ ipcluster mpirun -n 4 | |||
|
88 | ||||
|
89 | Finally, connect to the cluster and use this function interactively. In this case, we create a random array on each engine and sum up all the random arrays using our :func:`psum` function: | |||
|
90 | ||||
|
91 | .. sourcecode:: ipython | |||
|
92 | ||||
|
93 | In [1]: from IPython.kernel import client | |||
|
94 | ||||
|
95 | In [2]: mec = client.MultiEngineClient() | |||
|
96 | ||||
|
97 | In [3]: mec.activate() | |||
|
98 | ||||
|
99 | In [4]: px import numpy as np | |||
|
100 | Parallel execution on engines: all | |||
|
101 | Out[4]: | |||
|
102 | <Results List> | |||
|
103 | [0] In [13]: import numpy as np | |||
|
104 | [1] In [13]: import numpy as np | |||
|
105 | [2] In [13]: import numpy as np | |||
|
106 | [3] In [13]: import numpy as np | |||
|
107 | ||||
|
108 | In [6]: px a = np.random.rand(100) | |||
|
109 | Parallel execution on engines: all | |||
|
110 | Out[6]: | |||
|
111 | <Results List> | |||
|
112 | [0] In [15]: a = np.random.rand(100) | |||
|
113 | [1] In [15]: a = np.random.rand(100) | |||
|
114 | [2] In [15]: a = np.random.rand(100) | |||
|
115 | [3] In [15]: a = np.random.rand(100) | |||
|
116 | ||||
|
117 | In [7]: px from psum import psum | |||
|
118 | Parallel execution on engines: all | |||
|
119 | Out[7]: | |||
|
120 | <Results List> | |||
|
121 | [0] In [16]: from psum import psum | |||
|
122 | [1] In [16]: from psum import psum | |||
|
123 | [2] In [16]: from psum import psum | |||
|
124 | [3] In [16]: from psum import psum | |||
|
125 | ||||
|
126 | In [8]: px s = psum(a) | |||
|
127 | Parallel execution on engines: all | |||
|
128 | Out[8]: | |||
|
129 | <Results List> | |||
|
130 | [0] In [17]: s = psum(a) | |||
|
131 | [1] In [17]: s = psum(a) | |||
|
132 | [2] In [17]: s = psum(a) | |||
|
133 | [3] In [17]: s = psum(a) | |||
|
134 | ||||
|
135 | In [9]: px print s | |||
|
136 | Parallel execution on engines: all | |||
|
137 | Out[9]: | |||
|
138 | <Results List> | |||
|
139 | [0] In [18]: print s | |||
|
140 | [0] Out[18]: 187.451545803 | |||
|
141 | ||||
|
142 | [1] In [18]: print s | |||
|
143 | [1] Out[18]: 187.451545803 | |||
|
144 | ||||
|
145 | [2] In [18]: print s | |||
|
146 | [2] Out[18]: 187.451545803 | |||
|
147 | ||||
|
148 | [3] In [18]: print s | |||
|
149 | [3] Out[18]: 187.451545803 | |||
|
150 | ||||
|
151 | Any Python code that makes calls to MPI can be used in this manner, including | |||
|
152 | compiled C, C++ and Fortran libraries that have been exposed to Python. | |||
|
153 | ||||
|
154 | .. [MPI] Message Passing Interface. http://www-unix.mcs.anl.gov/mpi/ | |||
|
155 | .. [mpi4py] MPI for Python. mpi4py: http://mpi4py.scipy.org/ | |||
|
156 | .. [OpenMPI] Open MPI. http://www.open-mpi.org/ | |||
|
157 | .. [PyTrilinos] PyTrilinos. http://trilinos.sandia.gov/packages/pytrilinos/ No newline at end of file |
@@ -1,783 +1,828 b'' | |||||
1 | .. _parallelmultiengine: |
|
1 | .. _parallelmultiengine: | |
2 |
|
2 | |||
3 | =============================== |
|
3 | =============================== | |
4 | IPython's multiengine interface |
|
4 | IPython's multiengine interface | |
5 | =============================== |
|
5 | =============================== | |
6 |
|
6 | |||
7 | .. contents:: |
|
|||
8 |
|
||||
9 | The multiengine interface represents one possible way of working with a set of |
|
7 | The multiengine interface represents one possible way of working with a set of | |
10 | IPython engines. The basic idea behind the multiengine interface is that the |
|
8 | IPython engines. The basic idea behind the multiengine interface is that the | |
11 | capabilities of each engine are directly and explicitly exposed to the user. |
|
9 | capabilities of each engine are directly and explicitly exposed to the user. | |
12 | Thus, in the multiengine interface, each engine is given an id that is used to |
|
10 | Thus, in the multiengine interface, each engine is given an id that is used to | |
13 | identify the engine and give it work to do. This interface is very intuitive |
|
11 | identify the engine and give it work to do. This interface is very intuitive | |
14 | and is designed with interactive usage in mind, and is thus the best place for |
|
12 | and is designed with interactive usage in mind, and is thus the best place for | |
15 | new users of IPython to begin. |
|
13 | new users of IPython to begin. | |
16 |
|
14 | |||
17 | Starting the IPython controller and engines |
|
15 | Starting the IPython controller and engines | |
18 | =========================================== |
|
16 | =========================================== | |
19 |
|
17 | |||
20 | To follow along with this tutorial, you will need to start the IPython |
|
18 | To follow along with this tutorial, you will need to start the IPython | |
21 | controller and four IPython engines. The simplest way of doing this is to use |
|
19 | controller and four IPython engines. The simplest way of doing this is to use | |
22 | the :command:`ipcluster` command:: |
|
20 | the :command:`ipcluster` command:: | |
23 |
|
21 | |||
24 | $ ipcluster -n 4 |
|
22 | $ ipcluster local -n 4 | |
25 |
|
23 | |||
26 | For more detailed information about starting the controller and engines, see |
|
24 | For more detailed information about starting the controller and engines, see | |
27 | our :ref:`introduction <ip1par>` to using IPython for parallel computing. |
|
25 | our :ref:`introduction <ip1par>` to using IPython for parallel computing. | |
28 |
|
26 | |||
29 | Creating a ``MultiEngineClient`` instance |
|
27 | Creating a ``MultiEngineClient`` instance | |
30 | ========================================= |
|
28 | ========================================= | |
31 |
|
29 | |||
32 | The first step is to import the IPython :mod:`IPython.kernel.client` module |
|
30 | The first step is to import the IPython :mod:`IPython.kernel.client` module | |
33 |
and then create a :class:`MultiEngineClient` instance: |
|
31 | and then create a :class:`MultiEngineClient` instance: | |
|
32 | ||||
|
33 | .. sourcecode:: ipython | |||
34 |
|
34 | |||
35 | In [1]: from IPython.kernel import client |
|
35 | In [1]: from IPython.kernel import client | |
36 |
|
36 | |||
37 | In [2]: mec = client.MultiEngineClient() |
|
37 | In [2]: mec = client.MultiEngineClient() | |
38 |
|
38 | |||
39 | This form assumes that the :file:`ipcontroller-mec.furl` is in the |
|
39 | This form assumes that the :file:`ipcontroller-mec.furl` is in the | |
40 | :file:`~./ipython/security` directory on the client's host. If not, the |
|
40 | :file:`~./ipython/security` directory on the client's host. If not, the | |
41 |
location of the |
|
41 | location of the FURL file must be given as an argument to the | |
42 |
constructor: |
|
42 | constructor: | |
|
43 | ||||
|
44 | .. sourcecode:: ipython | |||
43 |
|
45 | |||
44 | In[2]: mec = client.MultiEngineClient('/path/to/my/ipcontroller-mec.furl') |
|
46 | In [2]: mec = client.MultiEngineClient('/path/to/my/ipcontroller-mec.furl') | |
45 |
|
47 | |||
46 | To make sure there are engines connected to the controller, use can get a list |
|
48 | To make sure there are engines connected to the controller, use can get a list | |
47 |
of engine ids: |
|
49 | of engine ids: | |
|
50 | ||||
|
51 | .. sourcecode:: ipython | |||
48 |
|
52 | |||
49 | In [3]: mec.get_ids() |
|
53 | In [3]: mec.get_ids() | |
50 | Out[3]: [0, 1, 2, 3] |
|
54 | Out[3]: [0, 1, 2, 3] | |
51 |
|
55 | |||
52 | Here we see that there are four engines ready to do work for us. |
|
56 | Here we see that there are four engines ready to do work for us. | |
53 |
|
57 | |||
54 | Quick and easy parallelism |
|
58 | Quick and easy parallelism | |
55 | ========================== |
|
59 | ========================== | |
56 |
|
60 | |||
57 | In many cases, you simply want to apply a Python function to a sequence of objects, but *in parallel*. The multiengine interface provides two simple ways of accomplishing this: a parallel version of :func:`map` and ``@parallel`` function decorator. |
|
61 | In many cases, you simply want to apply a Python function to a sequence of objects, but *in parallel*. The multiengine interface provides two simple ways of accomplishing this: a parallel version of :func:`map` and ``@parallel`` function decorator. | |
58 |
|
62 | |||
59 | Parallel map |
|
63 | Parallel map | |
60 | ------------ |
|
64 | ------------ | |
61 |
|
65 | |||
62 | Python's builtin :func:`map` functions allows a function to be applied to a |
|
66 | Python's builtin :func:`map` functions allows a function to be applied to a | |
63 | sequence element-by-element. This type of code is typically trivial to |
|
67 | sequence element-by-element. This type of code is typically trivial to | |
64 | parallelize. In fact, the multiengine interface in IPython already has a |
|
68 | parallelize. In fact, the multiengine interface in IPython already has a | |
65 |
parallel version of :meth:`map` that works just like its serial counterpart: |
|
69 | parallel version of :meth:`map` that works just like its serial counterpart: | |
|
70 | ||||
|
71 | .. sourcecode:: ipython | |||
66 |
|
72 | |||
67 | In [63]: serial_result = map(lambda x:x**10, range(32)) |
|
73 | In [63]: serial_result = map(lambda x:x**10, range(32)) | |
68 |
|
74 | |||
69 | In [64]: parallel_result = mec.map(lambda x:x**10, range(32)) |
|
75 | In [64]: parallel_result = mec.map(lambda x:x**10, range(32)) | |
70 |
|
76 | |||
71 | In [65]: serial_result==parallel_result |
|
77 | In [65]: serial_result==parallel_result | |
72 | Out[65]: True |
|
78 | Out[65]: True | |
73 |
|
79 | |||
74 | .. note:: |
|
80 | .. note:: | |
75 |
|
81 | |||
76 | The multiengine interface version of :meth:`map` does not do any load |
|
82 | The multiengine interface version of :meth:`map` does not do any load | |
77 | balancing. For a load balanced version, see the task interface. |
|
83 | balancing. For a load balanced version, see the task interface. | |
78 |
|
84 | |||
79 | .. seealso:: |
|
85 | .. seealso:: | |
80 |
|
86 | |||
81 | The :meth:`map` method has a number of options that can be controlled by |
|
87 | The :meth:`map` method has a number of options that can be controlled by | |
82 | the :meth:`mapper` method. See its docstring for more information. |
|
88 | the :meth:`mapper` method. See its docstring for more information. | |
83 |
|
89 | |||
84 | Parallel function decorator |
|
90 | Parallel function decorator | |
85 | --------------------------- |
|
91 | --------------------------- | |
86 |
|
92 | |||
87 |
Parallel functions are just like normal function, but they can be called on sequences and *in parallel*. The multiengine interface provides a decorator that turns any Python function into a parallel function: |
|
93 | Parallel functions are just like normal function, but they can be called on sequences and *in parallel*. The multiengine interface provides a decorator that turns any Python function into a parallel function: | |
|
94 | ||||
|
95 | .. sourcecode:: ipython | |||
88 |
|
96 | |||
89 | In [10]: @mec.parallel() |
|
97 | In [10]: @mec.parallel() | |
90 | ....: def f(x): |
|
98 | ....: def f(x): | |
91 | ....: return 10.0*x**4 |
|
99 | ....: return 10.0*x**4 | |
92 | ....: |
|
100 | ....: | |
93 |
|
101 | |||
94 | In [11]: f(range(32)) # this is done in parallel |
|
102 | In [11]: f(range(32)) # this is done in parallel | |
95 | Out[11]: |
|
103 | Out[11]: | |
96 | [0.0,10.0,160.0,...] |
|
104 | [0.0,10.0,160.0,...] | |
97 |
|
105 | |||
98 | See the docstring for the :meth:`parallel` decorator for options. |
|
106 | See the docstring for the :meth:`parallel` decorator for options. | |
99 |
|
107 | |||
100 | Running Python commands |
|
108 | Running Python commands | |
101 | ======================= |
|
109 | ======================= | |
102 |
|
110 | |||
103 | The most basic type of operation that can be performed on the engines is to |
|
111 | The most basic type of operation that can be performed on the engines is to | |
104 | execute Python code. Executing Python code can be done in blocking or |
|
112 | execute Python code. Executing Python code can be done in blocking or | |
105 | non-blocking mode (blocking is default) using the :meth:`execute` method. |
|
113 | non-blocking mode (blocking is default) using the :meth:`execute` method. | |
106 |
|
114 | |||
107 | Blocking execution |
|
115 | Blocking execution | |
108 | ------------------ |
|
116 | ------------------ | |
109 |
|
117 | |||
110 | In blocking mode, the :class:`MultiEngineClient` object (called ``mec`` in |
|
118 | In blocking mode, the :class:`MultiEngineClient` object (called ``mec`` in | |
111 | these examples) submits the command to the controller, which places the |
|
119 | these examples) submits the command to the controller, which places the | |
112 | command in the engines' queues for execution. The :meth:`execute` call then |
|
120 | command in the engines' queues for execution. The :meth:`execute` call then | |
113 |
blocks until the engines are done executing the command: |
|
121 | blocks until the engines are done executing the command: | |
|
122 | ||||
|
123 | .. sourcecode:: ipython | |||
114 |
|
124 | |||
115 | # The default is to run on all engines |
|
125 | # The default is to run on all engines | |
116 | In [4]: mec.execute('a=5') |
|
126 | In [4]: mec.execute('a=5') | |
117 | Out[4]: |
|
127 | Out[4]: | |
118 | <Results List> |
|
128 | <Results List> | |
119 | [0] In [1]: a=5 |
|
129 | [0] In [1]: a=5 | |
120 | [1] In [1]: a=5 |
|
130 | [1] In [1]: a=5 | |
121 | [2] In [1]: a=5 |
|
131 | [2] In [1]: a=5 | |
122 | [3] In [1]: a=5 |
|
132 | [3] In [1]: a=5 | |
123 |
|
133 | |||
124 | In [5]: mec.execute('b=10') |
|
134 | In [5]: mec.execute('b=10') | |
125 | Out[5]: |
|
135 | Out[5]: | |
126 | <Results List> |
|
136 | <Results List> | |
127 | [0] In [2]: b=10 |
|
137 | [0] In [2]: b=10 | |
128 | [1] In [2]: b=10 |
|
138 | [1] In [2]: b=10 | |
129 | [2] In [2]: b=10 |
|
139 | [2] In [2]: b=10 | |
130 | [3] In [2]: b=10 |
|
140 | [3] In [2]: b=10 | |
131 |
|
141 | |||
132 | Python commands can be executed on specific engines by calling execute using |
|
142 | Python commands can be executed on specific engines by calling execute using | |
133 |
the ``targets`` keyword argument: |
|
143 | the ``targets`` keyword argument: | |
|
144 | ||||
|
145 | .. sourcecode:: ipython | |||
134 |
|
146 | |||
135 | In [6]: mec.execute('c=a+b',targets=[0,2]) |
|
147 | In [6]: mec.execute('c=a+b',targets=[0,2]) | |
136 | Out[6]: |
|
148 | Out[6]: | |
137 | <Results List> |
|
149 | <Results List> | |
138 | [0] In [3]: c=a+b |
|
150 | [0] In [3]: c=a+b | |
139 | [2] In [3]: c=a+b |
|
151 | [2] In [3]: c=a+b | |
140 |
|
152 | |||
141 |
|
153 | |||
142 | In [7]: mec.execute('c=a-b',targets=[1,3]) |
|
154 | In [7]: mec.execute('c=a-b',targets=[1,3]) | |
143 | Out[7]: |
|
155 | Out[7]: | |
144 | <Results List> |
|
156 | <Results List> | |
145 | [1] In [3]: c=a-b |
|
157 | [1] In [3]: c=a-b | |
146 | [3] In [3]: c=a-b |
|
158 | [3] In [3]: c=a-b | |
147 |
|
159 | |||
148 |
|
160 | |||
149 | In [8]: mec.execute('print c') |
|
161 | In [8]: mec.execute('print c') | |
150 | Out[8]: |
|
162 | Out[8]: | |
151 | <Results List> |
|
163 | <Results List> | |
152 | [0] In [4]: print c |
|
164 | [0] In [4]: print c | |
153 | [0] Out[4]: 15 |
|
165 | [0] Out[4]: 15 | |
154 |
|
166 | |||
155 | [1] In [4]: print c |
|
167 | [1] In [4]: print c | |
156 | [1] Out[4]: -5 |
|
168 | [1] Out[4]: -5 | |
157 |
|
169 | |||
158 | [2] In [4]: print c |
|
170 | [2] In [4]: print c | |
159 | [2] Out[4]: 15 |
|
171 | [2] Out[4]: 15 | |
160 |
|
172 | |||
161 | [3] In [4]: print c |
|
173 | [3] In [4]: print c | |
162 | [3] Out[4]: -5 |
|
174 | [3] Out[4]: -5 | |
163 |
|
175 | |||
164 | This example also shows one of the most important things about the IPython |
|
176 | This example also shows one of the most important things about the IPython | |
165 | engines: they have a persistent user namespaces. The :meth:`execute` method |
|
177 | engines: they have a persistent user namespaces. The :meth:`execute` method | |
166 |
returns a Python ``dict`` that contains useful information: |
|
178 | returns a Python ``dict`` that contains useful information: | |
|
179 | ||||
|
180 | .. sourcecode:: ipython | |||
167 |
|
181 | |||
168 | In [9]: result_dict = mec.execute('d=10; print d') |
|
182 | In [9]: result_dict = mec.execute('d=10; print d') | |
169 |
|
183 | |||
170 | In [10]: for r in result_dict: |
|
184 | In [10]: for r in result_dict: | |
171 | ....: print r |
|
185 | ....: print r | |
172 | ....: |
|
186 | ....: | |
173 | ....: |
|
187 | ....: | |
174 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 0, 'stdout': '10\n'} |
|
188 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 0, 'stdout': '10\n'} | |
175 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 1, 'stdout': '10\n'} |
|
189 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 1, 'stdout': '10\n'} | |
176 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 2, 'stdout': '10\n'} |
|
190 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 2, 'stdout': '10\n'} | |
177 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 3, 'stdout': '10\n'} |
|
191 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 3, 'stdout': '10\n'} | |
178 |
|
192 | |||
179 | Non-blocking execution |
|
193 | Non-blocking execution | |
180 | ---------------------- |
|
194 | ---------------------- | |
181 |
|
195 | |||
182 | In non-blocking mode, :meth:`execute` submits the command to be executed and |
|
196 | In non-blocking mode, :meth:`execute` submits the command to be executed and | |
183 | then returns a :class:`PendingResult` object immediately. The |
|
197 | then returns a :class:`PendingResult` object immediately. The | |
184 | :class:`PendingResult` object gives you a way of getting a result at a later |
|
198 | :class:`PendingResult` object gives you a way of getting a result at a later | |
185 | time through its :meth:`get_result` method or :attr:`r` attribute. This allows |
|
199 | time through its :meth:`get_result` method or :attr:`r` attribute. This allows | |
186 | you to quickly submit long running commands without blocking your local |
|
200 | you to quickly submit long running commands without blocking your local | |
187 |
Python/IPython session: |
|
201 | Python/IPython session: | |
|
202 | ||||
|
203 | .. sourcecode:: ipython | |||
188 |
|
204 | |||
189 | # In blocking mode |
|
205 | # In blocking mode | |
190 | In [6]: mec.execute('import time') |
|
206 | In [6]: mec.execute('import time') | |
191 | Out[6]: |
|
207 | Out[6]: | |
192 | <Results List> |
|
208 | <Results List> | |
193 | [0] In [1]: import time |
|
209 | [0] In [1]: import time | |
194 | [1] In [1]: import time |
|
210 | [1] In [1]: import time | |
195 | [2] In [1]: import time |
|
211 | [2] In [1]: import time | |
196 | [3] In [1]: import time |
|
212 | [3] In [1]: import time | |
197 |
|
213 | |||
198 | # In non-blocking mode |
|
214 | # In non-blocking mode | |
199 | In [7]: pr = mec.execute('time.sleep(10)',block=False) |
|
215 | In [7]: pr = mec.execute('time.sleep(10)',block=False) | |
200 |
|
216 | |||
201 | # Now block for the result |
|
217 | # Now block for the result | |
202 | In [8]: pr.get_result() |
|
218 | In [8]: pr.get_result() | |
203 | Out[8]: |
|
219 | Out[8]: | |
204 | <Results List> |
|
220 | <Results List> | |
205 | [0] In [2]: time.sleep(10) |
|
221 | [0] In [2]: time.sleep(10) | |
206 | [1] In [2]: time.sleep(10) |
|
222 | [1] In [2]: time.sleep(10) | |
207 | [2] In [2]: time.sleep(10) |
|
223 | [2] In [2]: time.sleep(10) | |
208 | [3] In [2]: time.sleep(10) |
|
224 | [3] In [2]: time.sleep(10) | |
209 |
|
225 | |||
210 | # Again in non-blocking mode |
|
226 | # Again in non-blocking mode | |
211 | In [9]: pr = mec.execute('time.sleep(10)',block=False) |
|
227 | In [9]: pr = mec.execute('time.sleep(10)',block=False) | |
212 |
|
228 | |||
213 | # Poll to see if the result is ready |
|
229 | # Poll to see if the result is ready | |
214 | In [10]: pr.get_result(block=False) |
|
230 | In [10]: pr.get_result(block=False) | |
215 |
|
231 | |||
216 | # A shorthand for get_result(block=True) |
|
232 | # A shorthand for get_result(block=True) | |
217 | In [11]: pr.r |
|
233 | In [11]: pr.r | |
218 | Out[11]: |
|
234 | Out[11]: | |
219 | <Results List> |
|
235 | <Results List> | |
220 | [0] In [3]: time.sleep(10) |
|
236 | [0] In [3]: time.sleep(10) | |
221 | [1] In [3]: time.sleep(10) |
|
237 | [1] In [3]: time.sleep(10) | |
222 | [2] In [3]: time.sleep(10) |
|
238 | [2] In [3]: time.sleep(10) | |
223 | [3] In [3]: time.sleep(10) |
|
239 | [3] In [3]: time.sleep(10) | |
224 |
|
240 | |||
225 | Often, it is desirable to wait until a set of :class:`PendingResult` objects |
|
241 | Often, it is desirable to wait until a set of :class:`PendingResult` objects | |
226 | are done. For this, there is a the method :meth:`barrier`. This method takes a |
|
242 | are done. For this, there is a the method :meth:`barrier`. This method takes a | |
227 | tuple of :class:`PendingResult` objects and blocks until all of the associated |
|
243 | tuple of :class:`PendingResult` objects and blocks until all of the associated | |
228 |
results are ready: |
|
244 | results are ready: | |
|
245 | ||||
|
246 | .. sourcecode:: ipython | |||
229 |
|
247 | |||
230 | In [72]: mec.block=False |
|
248 | In [72]: mec.block=False | |
231 |
|
249 | |||
232 | # A trivial list of PendingResults objects |
|
250 | # A trivial list of PendingResults objects | |
233 | In [73]: pr_list = [mec.execute('time.sleep(3)') for i in range(10)] |
|
251 | In [73]: pr_list = [mec.execute('time.sleep(3)') for i in range(10)] | |
234 |
|
252 | |||
235 | # Wait until all of them are done |
|
253 | # Wait until all of them are done | |
236 | In [74]: mec.barrier(pr_list) |
|
254 | In [74]: mec.barrier(pr_list) | |
237 |
|
255 | |||
238 | # Then, their results are ready using get_result or the r attribute |
|
256 | # Then, their results are ready using get_result or the r attribute | |
239 | In [75]: pr_list[0].r |
|
257 | In [75]: pr_list[0].r | |
240 | Out[75]: |
|
258 | Out[75]: | |
241 | <Results List> |
|
259 | <Results List> | |
242 | [0] In [20]: time.sleep(3) |
|
260 | [0] In [20]: time.sleep(3) | |
243 | [1] In [19]: time.sleep(3) |
|
261 | [1] In [19]: time.sleep(3) | |
244 | [2] In [20]: time.sleep(3) |
|
262 | [2] In [20]: time.sleep(3) | |
245 | [3] In [19]: time.sleep(3) |
|
263 | [3] In [19]: time.sleep(3) | |
246 |
|
264 | |||
247 |
|
265 | |||
248 | The ``block`` and ``targets`` keyword arguments and attributes |
|
266 | The ``block`` and ``targets`` keyword arguments and attributes | |
249 | -------------------------------------------------------------- |
|
267 | -------------------------------------------------------------- | |
250 |
|
268 | |||
251 | Most methods in the multiengine interface (like :meth:`execute`) accept |
|
269 | Most methods in the multiengine interface (like :meth:`execute`) accept | |
252 | ``block`` and ``targets`` as keyword arguments. As we have seen above, these |
|
270 | ``block`` and ``targets`` as keyword arguments. As we have seen above, these | |
253 | keyword arguments control the blocking mode and which engines the command is |
|
271 | keyword arguments control the blocking mode and which engines the command is | |
254 | applied to. The :class:`MultiEngineClient` class also has :attr:`block` and |
|
272 | applied to. The :class:`MultiEngineClient` class also has :attr:`block` and | |
255 | :attr:`targets` attributes that control the default behavior when the keyword |
|
273 | :attr:`targets` attributes that control the default behavior when the keyword | |
256 | arguments are not provided. Thus the following logic is used for :attr:`block` |
|
274 | arguments are not provided. Thus the following logic is used for :attr:`block` | |
257 | and :attr:`targets`: |
|
275 | and :attr:`targets`: | |
258 |
|
276 | |||
259 | * If no keyword argument is provided, the instance attributes are used. |
|
277 | * If no keyword argument is provided, the instance attributes are used. | |
260 | * Keyword argument, if provided override the instance attributes. |
|
278 | * Keyword argument, if provided override the instance attributes. | |
261 |
|
279 | |||
262 |
The following examples demonstrate how to use the instance attributes: |
|
280 | The following examples demonstrate how to use the instance attributes: | |
|
281 | ||||
|
282 | .. sourcecode:: ipython | |||
263 |
|
283 | |||
264 | In [16]: mec.targets = [0,2] |
|
284 | In [16]: mec.targets = [0,2] | |
265 |
|
285 | |||
266 | In [17]: mec.block = False |
|
286 | In [17]: mec.block = False | |
267 |
|
287 | |||
268 | In [18]: pr = mec.execute('a=5') |
|
288 | In [18]: pr = mec.execute('a=5') | |
269 |
|
289 | |||
270 | In [19]: pr.r |
|
290 | In [19]: pr.r | |
271 | Out[19]: |
|
291 | Out[19]: | |
272 | <Results List> |
|
292 | <Results List> | |
273 | [0] In [6]: a=5 |
|
293 | [0] In [6]: a=5 | |
274 | [2] In [6]: a=5 |
|
294 | [2] In [6]: a=5 | |
275 |
|
295 | |||
276 | # Note targets='all' means all engines |
|
296 | # Note targets='all' means all engines | |
277 | In [20]: mec.targets = 'all' |
|
297 | In [20]: mec.targets = 'all' | |
278 |
|
298 | |||
279 | In [21]: mec.block = True |
|
299 | In [21]: mec.block = True | |
280 |
|
300 | |||
281 | In [22]: mec.execute('b=10; print b') |
|
301 | In [22]: mec.execute('b=10; print b') | |
282 | Out[22]: |
|
302 | Out[22]: | |
283 | <Results List> |
|
303 | <Results List> | |
284 | [0] In [7]: b=10; print b |
|
304 | [0] In [7]: b=10; print b | |
285 | [0] Out[7]: 10 |
|
305 | [0] Out[7]: 10 | |
286 |
|
306 | |||
287 | [1] In [6]: b=10; print b |
|
307 | [1] In [6]: b=10; print b | |
288 | [1] Out[6]: 10 |
|
308 | [1] Out[6]: 10 | |
289 |
|
309 | |||
290 | [2] In [7]: b=10; print b |
|
310 | [2] In [7]: b=10; print b | |
291 | [2] Out[7]: 10 |
|
311 | [2] Out[7]: 10 | |
292 |
|
312 | |||
293 | [3] In [6]: b=10; print b |
|
313 | [3] In [6]: b=10; print b | |
294 | [3] Out[6]: 10 |
|
314 | [3] Out[6]: 10 | |
295 |
|
315 | |||
296 | The :attr:`block` and :attr:`targets` instance attributes also determine the |
|
316 | The :attr:`block` and :attr:`targets` instance attributes also determine the | |
297 | behavior of the parallel magic commands. |
|
317 | behavior of the parallel magic commands. | |
298 |
|
318 | |||
299 |
|
319 | |||
300 | Parallel magic commands |
|
320 | Parallel magic commands | |
301 | ----------------------- |
|
321 | ----------------------- | |
302 |
|
322 | |||
303 | We provide a few IPython magic commands (``%px``, ``%autopx`` and ``%result``) |
|
323 | We provide a few IPython magic commands (``%px``, ``%autopx`` and ``%result``) | |
304 | that make it more pleasant to execute Python commands on the engines |
|
324 | that make it more pleasant to execute Python commands on the engines | |
305 | interactively. These are simply shortcuts to :meth:`execute` and |
|
325 | interactively. These are simply shortcuts to :meth:`execute` and | |
306 | :meth:`get_result`. The ``%px`` magic executes a single Python command on the |
|
326 | :meth:`get_result`. The ``%px`` magic executes a single Python command on the | |
307 | engines specified by the :attr:`targets` attribute of the |
|
327 | engines specified by the :attr:`targets` attribute of the | |
308 |
:class:`MultiEngineClient` instance (by default this is ``'all'``): |
|
328 | :class:`MultiEngineClient` instance (by default this is ``'all'``): | |
|
329 | ||||
|
330 | .. sourcecode:: ipython | |||
309 |
|
331 | |||
310 | # Make this MultiEngineClient active for parallel magic commands |
|
332 | # Make this MultiEngineClient active for parallel magic commands | |
311 | In [23]: mec.activate() |
|
333 | In [23]: mec.activate() | |
312 |
|
334 | |||
313 | In [24]: mec.block=True |
|
335 | In [24]: mec.block=True | |
314 |
|
336 | |||
315 | In [25]: import numpy |
|
337 | In [25]: import numpy | |
316 |
|
338 | |||
317 | In [26]: %px import numpy |
|
339 | In [26]: %px import numpy | |
318 | Executing command on Controller |
|
340 | Executing command on Controller | |
319 | Out[26]: |
|
341 | Out[26]: | |
320 | <Results List> |
|
342 | <Results List> | |
321 | [0] In [8]: import numpy |
|
343 | [0] In [8]: import numpy | |
322 | [1] In [7]: import numpy |
|
344 | [1] In [7]: import numpy | |
323 | [2] In [8]: import numpy |
|
345 | [2] In [8]: import numpy | |
324 | [3] In [7]: import numpy |
|
346 | [3] In [7]: import numpy | |
325 |
|
347 | |||
326 |
|
348 | |||
327 | In [27]: %px a = numpy.random.rand(2,2) |
|
349 | In [27]: %px a = numpy.random.rand(2,2) | |
328 | Executing command on Controller |
|
350 | Executing command on Controller | |
329 | Out[27]: |
|
351 | Out[27]: | |
330 | <Results List> |
|
352 | <Results List> | |
331 | [0] In [9]: a = numpy.random.rand(2,2) |
|
353 | [0] In [9]: a = numpy.random.rand(2,2) | |
332 | [1] In [8]: a = numpy.random.rand(2,2) |
|
354 | [1] In [8]: a = numpy.random.rand(2,2) | |
333 | [2] In [9]: a = numpy.random.rand(2,2) |
|
355 | [2] In [9]: a = numpy.random.rand(2,2) | |
334 | [3] In [8]: a = numpy.random.rand(2,2) |
|
356 | [3] In [8]: a = numpy.random.rand(2,2) | |
335 |
|
357 | |||
336 |
|
358 | |||
337 | In [28]: %px print numpy.linalg.eigvals(a) |
|
359 | In [28]: %px print numpy.linalg.eigvals(a) | |
338 | Executing command on Controller |
|
360 | Executing command on Controller | |
339 | Out[28]: |
|
361 | Out[28]: | |
340 | <Results List> |
|
362 | <Results List> | |
341 | [0] In [10]: print numpy.linalg.eigvals(a) |
|
363 | [0] In [10]: print numpy.linalg.eigvals(a) | |
342 | [0] Out[10]: [ 1.28167017 0.14197338] |
|
364 | [0] Out[10]: [ 1.28167017 0.14197338] | |
343 |
|
365 | |||
344 | [1] In [9]: print numpy.linalg.eigvals(a) |
|
366 | [1] In [9]: print numpy.linalg.eigvals(a) | |
345 | [1] Out[9]: [-0.14093616 1.27877273] |
|
367 | [1] Out[9]: [-0.14093616 1.27877273] | |
346 |
|
368 | |||
347 | [2] In [10]: print numpy.linalg.eigvals(a) |
|
369 | [2] In [10]: print numpy.linalg.eigvals(a) | |
348 | [2] Out[10]: [-0.37023573 1.06779409] |
|
370 | [2] Out[10]: [-0.37023573 1.06779409] | |
349 |
|
371 | |||
350 | [3] In [9]: print numpy.linalg.eigvals(a) |
|
372 | [3] In [9]: print numpy.linalg.eigvals(a) | |
351 | [3] Out[9]: [ 0.83664764 -0.25602658] |
|
373 | [3] Out[9]: [ 0.83664764 -0.25602658] | |
352 |
|
374 | |||
353 | The ``%result`` magic gets and prints the stdin/stdout/stderr of the last |
|
375 | The ``%result`` magic gets and prints the stdin/stdout/stderr of the last | |
354 | command executed on each engine. It is simply a shortcut to the |
|
376 | command executed on each engine. It is simply a shortcut to the | |
355 |
:meth:`get_result` method: |
|
377 | :meth:`get_result` method: | |
|
378 | ||||
|
379 | .. sourcecode:: ipython | |||
356 |
|
380 | |||
357 | In [29]: %result |
|
381 | In [29]: %result | |
358 | Out[29]: |
|
382 | Out[29]: | |
359 | <Results List> |
|
383 | <Results List> | |
360 | [0] In [10]: print numpy.linalg.eigvals(a) |
|
384 | [0] In [10]: print numpy.linalg.eigvals(a) | |
361 | [0] Out[10]: [ 1.28167017 0.14197338] |
|
385 | [0] Out[10]: [ 1.28167017 0.14197338] | |
362 |
|
386 | |||
363 | [1] In [9]: print numpy.linalg.eigvals(a) |
|
387 | [1] In [9]: print numpy.linalg.eigvals(a) | |
364 | [1] Out[9]: [-0.14093616 1.27877273] |
|
388 | [1] Out[9]: [-0.14093616 1.27877273] | |
365 |
|
389 | |||
366 | [2] In [10]: print numpy.linalg.eigvals(a) |
|
390 | [2] In [10]: print numpy.linalg.eigvals(a) | |
367 | [2] Out[10]: [-0.37023573 1.06779409] |
|
391 | [2] Out[10]: [-0.37023573 1.06779409] | |
368 |
|
392 | |||
369 | [3] In [9]: print numpy.linalg.eigvals(a) |
|
393 | [3] In [9]: print numpy.linalg.eigvals(a) | |
370 | [3] Out[9]: [ 0.83664764 -0.25602658] |
|
394 | [3] Out[9]: [ 0.83664764 -0.25602658] | |
371 |
|
395 | |||
372 | The ``%autopx`` magic switches to a mode where everything you type is executed |
|
396 | The ``%autopx`` magic switches to a mode where everything you type is executed | |
373 |
on the engines given by the :attr:`targets` attribute: |
|
397 | on the engines given by the :attr:`targets` attribute: | |
|
398 | ||||
|
399 | .. sourcecode:: ipython | |||
374 |
|
400 | |||
375 | In [30]: mec.block=False |
|
401 | In [30]: mec.block=False | |
376 |
|
402 | |||
377 | In [31]: %autopx |
|
403 | In [31]: %autopx | |
378 | Auto Parallel Enabled |
|
404 | Auto Parallel Enabled | |
379 | Type %autopx to disable |
|
405 | Type %autopx to disable | |
380 |
|
406 | |||
381 | In [32]: max_evals = [] |
|
407 | In [32]: max_evals = [] | |
382 | <IPython.kernel.multiengineclient.PendingResult object at 0x17b8a70> |
|
408 | <IPython.kernel.multiengineclient.PendingResult object at 0x17b8a70> | |
383 |
|
409 | |||
384 | In [33]: for i in range(100): |
|
410 | In [33]: for i in range(100): | |
385 | ....: a = numpy.random.rand(10,10) |
|
411 | ....: a = numpy.random.rand(10,10) | |
386 | ....: a = a+a.transpose() |
|
412 | ....: a = a+a.transpose() | |
387 | ....: evals = numpy.linalg.eigvals(a) |
|
413 | ....: evals = numpy.linalg.eigvals(a) | |
388 | ....: max_evals.append(evals[0].real) |
|
414 | ....: max_evals.append(evals[0].real) | |
389 | ....: |
|
415 | ....: | |
390 | ....: |
|
416 | ....: | |
391 | <IPython.kernel.multiengineclient.PendingResult object at 0x17af8f0> |
|
417 | <IPython.kernel.multiengineclient.PendingResult object at 0x17af8f0> | |
392 |
|
418 | |||
393 | In [34]: %autopx |
|
419 | In [34]: %autopx | |
394 | Auto Parallel Disabled |
|
420 | Auto Parallel Disabled | |
395 |
|
421 | |||
396 | In [35]: mec.block=True |
|
422 | In [35]: mec.block=True | |
397 |
|
423 | |||
398 | In [36]: px print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
424 | In [36]: px print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) | |
399 | Executing command on Controller |
|
425 | Executing command on Controller | |
400 | Out[36]: |
|
426 | Out[36]: | |
401 | <Results List> |
|
427 | <Results List> | |
402 | [0] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
428 | [0] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) | |
403 | [0] Out[13]: Average max eigenvalue is: 10.1387247332 |
|
429 | [0] Out[13]: Average max eigenvalue is: 10.1387247332 | |
404 |
|
430 | |||
405 | [1] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
431 | [1] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) | |
406 | [1] Out[12]: Average max eigenvalue is: 10.2076902286 |
|
432 | [1] Out[12]: Average max eigenvalue is: 10.2076902286 | |
407 |
|
433 | |||
408 | [2] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
434 | [2] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) | |
409 | [2] Out[13]: Average max eigenvalue is: 10.1891484655 |
|
435 | [2] Out[13]: Average max eigenvalue is: 10.1891484655 | |
410 |
|
436 | |||
411 | [3] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
437 | [3] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) | |
412 | [3] Out[12]: Average max eigenvalue is: 10.1158837784 |
|
438 | [3] Out[12]: Average max eigenvalue is: 10.1158837784 | |
413 |
|
439 | |||
414 |
|
440 | |||
415 | Moving Python objects around |
|
441 | Moving Python objects around | |
416 | ============================ |
|
442 | ============================ | |
417 |
|
443 | |||
418 | In addition to executing code on engines, you can transfer Python objects to |
|
444 | In addition to executing code on engines, you can transfer Python objects to | |
419 | and from your IPython session and the engines. In IPython, these operations |
|
445 | and from your IPython session and the engines. In IPython, these operations | |
420 | are called :meth:`push` (sending an object to the engines) and :meth:`pull` |
|
446 | are called :meth:`push` (sending an object to the engines) and :meth:`pull` | |
421 | (getting an object from the engines). |
|
447 | (getting an object from the engines). | |
422 |
|
448 | |||
423 | Basic push and pull |
|
449 | Basic push and pull | |
424 | ------------------- |
|
450 | ------------------- | |
425 |
|
451 | |||
426 |
Here are some examples of how you use :meth:`push` and :meth:`pull`: |
|
452 | Here are some examples of how you use :meth:`push` and :meth:`pull`: | |
|
453 | ||||
|
454 | .. sourcecode:: ipython | |||
427 |
|
455 | |||
428 | In [38]: mec.push(dict(a=1.03234,b=3453)) |
|
456 | In [38]: mec.push(dict(a=1.03234,b=3453)) | |
429 | Out[38]: [None, None, None, None] |
|
457 | Out[38]: [None, None, None, None] | |
430 |
|
458 | |||
431 | In [39]: mec.pull('a') |
|
459 | In [39]: mec.pull('a') | |
432 | Out[39]: [1.03234, 1.03234, 1.03234, 1.03234] |
|
460 | Out[39]: [1.03234, 1.03234, 1.03234, 1.03234] | |
433 |
|
461 | |||
434 | In [40]: mec.pull('b',targets=0) |
|
462 | In [40]: mec.pull('b',targets=0) | |
435 | Out[40]: [3453] |
|
463 | Out[40]: [3453] | |
436 |
|
464 | |||
437 | In [41]: mec.pull(('a','b')) |
|
465 | In [41]: mec.pull(('a','b')) | |
438 | Out[41]: [[1.03234, 3453], [1.03234, 3453], [1.03234, 3453], [1.03234, 3453]] |
|
466 | Out[41]: [[1.03234, 3453], [1.03234, 3453], [1.03234, 3453], [1.03234, 3453]] | |
439 |
|
467 | |||
440 | In [42]: mec.zip_pull(('a','b')) |
|
468 | In [42]: mec.zip_pull(('a','b')) | |
441 | Out[42]: [(1.03234, 1.03234, 1.03234, 1.03234), (3453, 3453, 3453, 3453)] |
|
469 | Out[42]: [(1.03234, 1.03234, 1.03234, 1.03234), (3453, 3453, 3453, 3453)] | |
442 |
|
470 | |||
443 | In [43]: mec.push(dict(c='speed')) |
|
471 | In [43]: mec.push(dict(c='speed')) | |
444 | Out[43]: [None, None, None, None] |
|
472 | Out[43]: [None, None, None, None] | |
445 |
|
473 | |||
446 | In [44]: %px print c |
|
474 | In [44]: %px print c | |
447 | Executing command on Controller |
|
475 | Executing command on Controller | |
448 | Out[44]: |
|
476 | Out[44]: | |
449 | <Results List> |
|
477 | <Results List> | |
450 | [0] In [14]: print c |
|
478 | [0] In [14]: print c | |
451 | [0] Out[14]: speed |
|
479 | [0] Out[14]: speed | |
452 |
|
480 | |||
453 | [1] In [13]: print c |
|
481 | [1] In [13]: print c | |
454 | [1] Out[13]: speed |
|
482 | [1] Out[13]: speed | |
455 |
|
483 | |||
456 | [2] In [14]: print c |
|
484 | [2] In [14]: print c | |
457 | [2] Out[14]: speed |
|
485 | [2] Out[14]: speed | |
458 |
|
486 | |||
459 | [3] In [13]: print c |
|
487 | [3] In [13]: print c | |
460 | [3] Out[13]: speed |
|
488 | [3] Out[13]: speed | |
461 |
|
489 | |||
462 | In non-blocking mode :meth:`push` and :meth:`pull` also return |
|
490 | In non-blocking mode :meth:`push` and :meth:`pull` also return | |
463 |
:class:`PendingResult` objects: |
|
491 | :class:`PendingResult` objects: | |
|
492 | ||||
|
493 | .. sourcecode:: ipython | |||
464 |
|
494 | |||
465 | In [47]: mec.block=False |
|
495 | In [47]: mec.block=False | |
466 |
|
496 | |||
467 | In [48]: pr = mec.pull('a') |
|
497 | In [48]: pr = mec.pull('a') | |
468 |
|
498 | |||
469 | In [49]: pr.r |
|
499 | In [49]: pr.r | |
470 | Out[49]: [1.03234, 1.03234, 1.03234, 1.03234] |
|
500 | Out[49]: [1.03234, 1.03234, 1.03234, 1.03234] | |
471 |
|
501 | |||
472 |
|
502 | |||
473 | Push and pull for functions |
|
503 | Push and pull for functions | |
474 | --------------------------- |
|
504 | --------------------------- | |
475 |
|
505 | |||
476 | Functions can also be pushed and pulled using :meth:`push_function` and |
|
506 | Functions can also be pushed and pulled using :meth:`push_function` and | |
477 |
:meth:`pull_function`: |
|
507 | :meth:`pull_function`: | |
478 |
|
508 | |||
|
509 | .. sourcecode:: ipython | |||
479 |
|
510 | |||
480 | In [52]: mec.block=True |
|
511 | In [52]: mec.block=True | |
481 |
|
512 | |||
482 | In [53]: def f(x): |
|
513 | In [53]: def f(x): | |
483 | ....: return 2.0*x**4 |
|
514 | ....: return 2.0*x**4 | |
484 | ....: |
|
515 | ....: | |
485 |
|
516 | |||
486 | In [54]: mec.push_function(dict(f=f)) |
|
517 | In [54]: mec.push_function(dict(f=f)) | |
487 | Out[54]: [None, None, None, None] |
|
518 | Out[54]: [None, None, None, None] | |
488 |
|
519 | |||
489 | In [55]: mec.execute('y = f(4.0)') |
|
520 | In [55]: mec.execute('y = f(4.0)') | |
490 | Out[55]: |
|
521 | Out[55]: | |
491 | <Results List> |
|
522 | <Results List> | |
492 | [0] In [15]: y = f(4.0) |
|
523 | [0] In [15]: y = f(4.0) | |
493 | [1] In [14]: y = f(4.0) |
|
524 | [1] In [14]: y = f(4.0) | |
494 | [2] In [15]: y = f(4.0) |
|
525 | [2] In [15]: y = f(4.0) | |
495 | [3] In [14]: y = f(4.0) |
|
526 | [3] In [14]: y = f(4.0) | |
496 |
|
527 | |||
497 |
|
528 | |||
498 | In [56]: px print y |
|
529 | In [56]: px print y | |
499 | Executing command on Controller |
|
530 | Executing command on Controller | |
500 | Out[56]: |
|
531 | Out[56]: | |
501 | <Results List> |
|
532 | <Results List> | |
502 | [0] In [16]: print y |
|
533 | [0] In [16]: print y | |
503 | [0] Out[16]: 512.0 |
|
534 | [0] Out[16]: 512.0 | |
504 |
|
535 | |||
505 | [1] In [15]: print y |
|
536 | [1] In [15]: print y | |
506 | [1] Out[15]: 512.0 |
|
537 | [1] Out[15]: 512.0 | |
507 |
|
538 | |||
508 | [2] In [16]: print y |
|
539 | [2] In [16]: print y | |
509 | [2] Out[16]: 512.0 |
|
540 | [2] Out[16]: 512.0 | |
510 |
|
541 | |||
511 | [3] In [15]: print y |
|
542 | [3] In [15]: print y | |
512 | [3] Out[15]: 512.0 |
|
543 | [3] Out[15]: 512.0 | |
513 |
|
544 | |||
514 |
|
545 | |||
515 | Dictionary interface |
|
546 | Dictionary interface | |
516 | -------------------- |
|
547 | -------------------- | |
517 |
|
548 | |||
518 | As a shorthand to :meth:`push` and :meth:`pull`, the |
|
549 | As a shorthand to :meth:`push` and :meth:`pull`, the | |
519 | :class:`MultiEngineClient` class implements some of the Python dictionary |
|
550 | :class:`MultiEngineClient` class implements some of the Python dictionary | |
520 | interface. This make the remote namespaces of the engines appear as a local |
|
551 | interface. This make the remote namespaces of the engines appear as a local | |
521 |
dictionary. Underneath, this uses :meth:`push` and :meth:`pull`: |
|
552 | dictionary. Underneath, this uses :meth:`push` and :meth:`pull`: | |
|
553 | ||||
|
554 | .. sourcecode:: ipython | |||
522 |
|
555 | |||
523 | In [50]: mec.block=True |
|
556 | In [50]: mec.block=True | |
524 |
|
557 | |||
525 | In [51]: mec['a']=['foo','bar'] |
|
558 | In [51]: mec['a']=['foo','bar'] | |
526 |
|
559 | |||
527 | In [52]: mec['a'] |
|
560 | In [52]: mec['a'] | |
528 | Out[52]: [['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar']] |
|
561 | Out[52]: [['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar']] | |
529 |
|
562 | |||
530 | Scatter and gather |
|
563 | Scatter and gather | |
531 | ------------------ |
|
564 | ------------------ | |
532 |
|
565 | |||
533 | Sometimes it is useful to partition a sequence and push the partitions to |
|
566 | Sometimes it is useful to partition a sequence and push the partitions to | |
534 | different engines. In MPI language, this is know as scatter/gather and we |
|
567 | different engines. In MPI language, this is know as scatter/gather and we | |
535 | follow that terminology. However, it is important to remember that in |
|
568 | follow that terminology. However, it is important to remember that in | |
536 | IPython's :class:`MultiEngineClient` class, :meth:`scatter` is from the |
|
569 | IPython's :class:`MultiEngineClient` class, :meth:`scatter` is from the | |
537 | interactive IPython session to the engines and :meth:`gather` is from the |
|
570 | interactive IPython session to the engines and :meth:`gather` is from the | |
538 | engines back to the interactive IPython session. For scatter/gather operations |
|
571 | engines back to the interactive IPython session. For scatter/gather operations | |
539 |
between engines, MPI should be used: |
|
572 | between engines, MPI should be used: | |
|
573 | ||||
|
574 | .. sourcecode:: ipython | |||
540 |
|
575 | |||
541 | In [58]: mec.scatter('a',range(16)) |
|
576 | In [58]: mec.scatter('a',range(16)) | |
542 | Out[58]: [None, None, None, None] |
|
577 | Out[58]: [None, None, None, None] | |
543 |
|
578 | |||
544 | In [59]: px print a |
|
579 | In [59]: px print a | |
545 | Executing command on Controller |
|
580 | Executing command on Controller | |
546 | Out[59]: |
|
581 | Out[59]: | |
547 | <Results List> |
|
582 | <Results List> | |
548 | [0] In [17]: print a |
|
583 | [0] In [17]: print a | |
549 | [0] Out[17]: [0, 1, 2, 3] |
|
584 | [0] Out[17]: [0, 1, 2, 3] | |
550 |
|
585 | |||
551 | [1] In [16]: print a |
|
586 | [1] In [16]: print a | |
552 | [1] Out[16]: [4, 5, 6, 7] |
|
587 | [1] Out[16]: [4, 5, 6, 7] | |
553 |
|
588 | |||
554 | [2] In [17]: print a |
|
589 | [2] In [17]: print a | |
555 | [2] Out[17]: [8, 9, 10, 11] |
|
590 | [2] Out[17]: [8, 9, 10, 11] | |
556 |
|
591 | |||
557 | [3] In [16]: print a |
|
592 | [3] In [16]: print a | |
558 | [3] Out[16]: [12, 13, 14, 15] |
|
593 | [3] Out[16]: [12, 13, 14, 15] | |
559 |
|
594 | |||
560 |
|
595 | |||
561 | In [60]: mec.gather('a') |
|
596 | In [60]: mec.gather('a') | |
562 | Out[60]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] |
|
597 | Out[60]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] | |
563 |
|
598 | |||
564 | Other things to look at |
|
599 | Other things to look at | |
565 | ======================= |
|
600 | ======================= | |
566 |
|
601 | |||
567 | How to do parallel list comprehensions |
|
602 | How to do parallel list comprehensions | |
568 | -------------------------------------- |
|
603 | -------------------------------------- | |
569 |
|
604 | |||
570 | In many cases list comprehensions are nicer than using the map function. While |
|
605 | In many cases list comprehensions are nicer than using the map function. While | |
571 | we don't have fully parallel list comprehensions, it is simple to get the |
|
606 | we don't have fully parallel list comprehensions, it is simple to get the | |
572 |
basic effect using :meth:`scatter` and :meth:`gather`: |
|
607 | basic effect using :meth:`scatter` and :meth:`gather`: | |
|
608 | ||||
|
609 | .. sourcecode:: ipython | |||
573 |
|
610 | |||
574 | In [66]: mec.scatter('x',range(64)) |
|
611 | In [66]: mec.scatter('x',range(64)) | |
575 | Out[66]: [None, None, None, None] |
|
612 | Out[66]: [None, None, None, None] | |
576 |
|
613 | |||
577 | In [67]: px y = [i**10 for i in x] |
|
614 | In [67]: px y = [i**10 for i in x] | |
578 | Executing command on Controller |
|
615 | Executing command on Controller | |
579 | Out[67]: |
|
616 | Out[67]: | |
580 | <Results List> |
|
617 | <Results List> | |
581 | [0] In [19]: y = [i**10 for i in x] |
|
618 | [0] In [19]: y = [i**10 for i in x] | |
582 | [1] In [18]: y = [i**10 for i in x] |
|
619 | [1] In [18]: y = [i**10 for i in x] | |
583 | [2] In [19]: y = [i**10 for i in x] |
|
620 | [2] In [19]: y = [i**10 for i in x] | |
584 | [3] In [18]: y = [i**10 for i in x] |
|
621 | [3] In [18]: y = [i**10 for i in x] | |
585 |
|
622 | |||
586 |
|
623 | |||
587 | In [68]: y = mec.gather('y') |
|
624 | In [68]: y = mec.gather('y') | |
588 |
|
625 | |||
589 | In [69]: print y |
|
626 | In [69]: print y | |
590 | [0, 1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824,...] |
|
627 | [0, 1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824,...] | |
591 |
|
628 | |||
592 | Parallel exceptions |
|
629 | Parallel exceptions | |
593 | ------------------- |
|
630 | ------------------- | |
594 |
|
631 | |||
595 | In the multiengine interface, parallel commands can raise Python exceptions, |
|
632 | In the multiengine interface, parallel commands can raise Python exceptions, | |
596 | just like serial commands. But, it is a little subtle, because a single |
|
633 | just like serial commands. But, it is a little subtle, because a single | |
597 | parallel command can actually raise multiple exceptions (one for each engine |
|
634 | parallel command can actually raise multiple exceptions (one for each engine | |
598 | the command was run on). To express this idea, the MultiEngine interface has a |
|
635 | the command was run on). To express this idea, the MultiEngine interface has a | |
599 | :exc:`CompositeError` exception class that will be raised in most cases. The |
|
636 | :exc:`CompositeError` exception class that will be raised in most cases. The | |
600 | :exc:`CompositeError` class is a special type of exception that wraps one or |
|
637 | :exc:`CompositeError` class is a special type of exception that wraps one or | |
601 |
more other types of exceptions. Here is how it works: |
|
638 | more other types of exceptions. Here is how it works: | |
|
639 | ||||
|
640 | .. sourcecode:: ipython | |||
602 |
|
641 | |||
603 | In [76]: mec.block=True |
|
642 | In [76]: mec.block=True | |
604 |
|
643 | |||
605 | In [77]: mec.execute('1/0') |
|
644 | In [77]: mec.execute('1/0') | |
606 | --------------------------------------------------------------------------- |
|
645 | --------------------------------------------------------------------------- | |
607 | CompositeError Traceback (most recent call last) |
|
646 | CompositeError Traceback (most recent call last) | |
608 |
|
647 | |||
609 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
648 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() | |
610 |
|
649 | |||
611 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) |
|
650 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) | |
612 | 432 targets, block = self._findTargetsAndBlock(targets, block) |
|
651 | 432 targets, block = self._findTargetsAndBlock(targets, block) | |
613 | 433 result = blockingCallFromThread(self.smultiengine.execute, lines, |
|
652 | 433 result = blockingCallFromThread(self.smultiengine.execute, lines, | |
614 | --> 434 targets=targets, block=block) |
|
653 | --> 434 targets=targets, block=block) | |
615 | 435 if block: |
|
654 | 435 if block: | |
616 | 436 result = ResultList(result) |
|
655 | 436 result = ResultList(result) | |
617 |
|
656 | |||
618 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) |
|
657 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) | |
619 | 72 result.raiseException() |
|
658 | 72 result.raiseException() | |
620 | 73 except Exception, e: |
|
659 | 73 except Exception, e: | |
621 | ---> 74 raise e |
|
660 | ---> 74 raise e | |
622 | 75 return result |
|
661 | 75 return result | |
623 | 76 |
|
662 | 76 | |
624 |
|
663 | |||
625 | CompositeError: one or more exceptions from call to method: execute |
|
664 | CompositeError: one or more exceptions from call to method: execute | |
626 | [0:execute]: ZeroDivisionError: integer division or modulo by zero |
|
665 | [0:execute]: ZeroDivisionError: integer division or modulo by zero | |
627 | [1:execute]: ZeroDivisionError: integer division or modulo by zero |
|
666 | [1:execute]: ZeroDivisionError: integer division or modulo by zero | |
628 | [2:execute]: ZeroDivisionError: integer division or modulo by zero |
|
667 | [2:execute]: ZeroDivisionError: integer division or modulo by zero | |
629 | [3:execute]: ZeroDivisionError: integer division or modulo by zero |
|
668 | [3:execute]: ZeroDivisionError: integer division or modulo by zero | |
630 |
|
669 | |||
631 |
Notice how the error message printed when :exc:`CompositeError` is raised has information about the individual exceptions that were raised on each engine. If you want, you can even raise one of these original exceptions: |
|
670 | Notice how the error message printed when :exc:`CompositeError` is raised has information about the individual exceptions that were raised on each engine. If you want, you can even raise one of these original exceptions: | |
|
671 | ||||
|
672 | .. sourcecode:: ipython | |||
632 |
|
673 | |||
633 | In [80]: try: |
|
674 | In [80]: try: | |
634 | ....: mec.execute('1/0') |
|
675 | ....: mec.execute('1/0') | |
635 | ....: except client.CompositeError, e: |
|
676 | ....: except client.CompositeError, e: | |
636 | ....: e.raise_exception() |
|
677 | ....: e.raise_exception() | |
637 | ....: |
|
678 | ....: | |
638 | ....: |
|
679 | ....: | |
639 | --------------------------------------------------------------------------- |
|
680 | --------------------------------------------------------------------------- | |
640 | ZeroDivisionError Traceback (most recent call last) |
|
681 | ZeroDivisionError Traceback (most recent call last) | |
641 |
|
682 | |||
642 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
683 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() | |
643 |
|
684 | |||
644 | /ipython1-client-r3021/ipython1/kernel/error.pyc in raise_exception(self, excid) |
|
685 | /ipython1-client-r3021/ipython1/kernel/error.pyc in raise_exception(self, excid) | |
645 | 156 raise IndexError("an exception with index %i does not exist"%excid) |
|
686 | 156 raise IndexError("an exception with index %i does not exist"%excid) | |
646 | 157 else: |
|
687 | 157 else: | |
647 | --> 158 raise et, ev, etb |
|
688 | --> 158 raise et, ev, etb | |
648 | 159 |
|
689 | 159 | |
649 | 160 def collect_exceptions(rlist, method): |
|
690 | 160 def collect_exceptions(rlist, method): | |
650 |
|
691 | |||
651 | ZeroDivisionError: integer division or modulo by zero |
|
692 | ZeroDivisionError: integer division or modulo by zero | |
652 |
|
693 | |||
653 | If you are working in IPython, you can simple type ``%debug`` after one of |
|
694 | If you are working in IPython, you can simple type ``%debug`` after one of | |
654 | these :exc:`CompositeError` exceptions is raised, and inspect the exception |
|
695 | these :exc:`CompositeError` exceptions is raised, and inspect the exception | |
655 |
instance: |
|
696 | instance: | |
|
697 | ||||
|
698 | .. sourcecode:: ipython | |||
656 |
|
699 | |||
657 | In [81]: mec.execute('1/0') |
|
700 | In [81]: mec.execute('1/0') | |
658 | --------------------------------------------------------------------------- |
|
701 | --------------------------------------------------------------------------- | |
659 | CompositeError Traceback (most recent call last) |
|
702 | CompositeError Traceback (most recent call last) | |
660 |
|
703 | |||
661 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
704 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() | |
662 |
|
705 | |||
663 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) |
|
706 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) | |
664 | 432 targets, block = self._findTargetsAndBlock(targets, block) |
|
707 | 432 targets, block = self._findTargetsAndBlock(targets, block) | |
665 | 433 result = blockingCallFromThread(self.smultiengine.execute, lines, |
|
708 | 433 result = blockingCallFromThread(self.smultiengine.execute, lines, | |
666 | --> 434 targets=targets, block=block) |
|
709 | --> 434 targets=targets, block=block) | |
667 | 435 if block: |
|
710 | 435 if block: | |
668 | 436 result = ResultList(result) |
|
711 | 436 result = ResultList(result) | |
669 |
|
712 | |||
670 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) |
|
713 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) | |
671 | 72 result.raiseException() |
|
714 | 72 result.raiseException() | |
672 | 73 except Exception, e: |
|
715 | 73 except Exception, e: | |
673 | ---> 74 raise e |
|
716 | ---> 74 raise e | |
674 | 75 return result |
|
717 | 75 return result | |
675 | 76 |
|
718 | 76 | |
676 |
|
719 | |||
677 | CompositeError: one or more exceptions from call to method: execute |
|
720 | CompositeError: one or more exceptions from call to method: execute | |
678 | [0:execute]: ZeroDivisionError: integer division or modulo by zero |
|
721 | [0:execute]: ZeroDivisionError: integer division or modulo by zero | |
679 | [1:execute]: ZeroDivisionError: integer division or modulo by zero |
|
722 | [1:execute]: ZeroDivisionError: integer division or modulo by zero | |
680 | [2:execute]: ZeroDivisionError: integer division or modulo by zero |
|
723 | [2:execute]: ZeroDivisionError: integer division or modulo by zero | |
681 | [3:execute]: ZeroDivisionError: integer division or modulo by zero |
|
724 | [3:execute]: ZeroDivisionError: integer division or modulo by zero | |
682 |
|
725 | |||
683 | In [82]: %debug |
|
726 | In [82]: %debug | |
684 | > |
|
727 | > | |
685 |
|
728 | |||
686 | /ipython1-client-r3021/ipython1/kernel/twistedutil.py(74)blockingCallFromThread() |
|
729 | /ipython1-client-r3021/ipython1/kernel/twistedutil.py(74)blockingCallFromThread() | |
687 | 73 except Exception, e: |
|
730 | 73 except Exception, e: | |
688 | ---> 74 raise e |
|
731 | ---> 74 raise e | |
689 | 75 return result |
|
732 | 75 return result | |
690 |
|
733 | |||
691 | # With the debugger running, e is the exceptions instance. We can tab complete |
|
734 | # With the debugger running, e is the exceptions instance. We can tab complete | |
692 | # on it and see the extra methods that are available. |
|
735 | # on it and see the extra methods that are available. | |
693 | ipdb> e. |
|
736 | ipdb> e. | |
694 | e.__class__ e.__getitem__ e.__new__ e.__setstate__ e.args |
|
737 | e.__class__ e.__getitem__ e.__new__ e.__setstate__ e.args | |
695 | e.__delattr__ e.__getslice__ e.__reduce__ e.__str__ e.elist |
|
738 | e.__delattr__ e.__getslice__ e.__reduce__ e.__str__ e.elist | |
696 | e.__dict__ e.__hash__ e.__reduce_ex__ e.__weakref__ e.message |
|
739 | e.__dict__ e.__hash__ e.__reduce_ex__ e.__weakref__ e.message | |
697 | e.__doc__ e.__init__ e.__repr__ e._get_engine_str e.print_tracebacks |
|
740 | e.__doc__ e.__init__ e.__repr__ e._get_engine_str e.print_tracebacks | |
698 | e.__getattribute__ e.__module__ e.__setattr__ e._get_traceback e.raise_exception |
|
741 | e.__getattribute__ e.__module__ e.__setattr__ e._get_traceback e.raise_exception | |
699 | ipdb> e.print_tracebacks() |
|
742 | ipdb> e.print_tracebacks() | |
700 | [0:execute]: |
|
743 | [0:execute]: | |
701 | --------------------------------------------------------------------------- |
|
744 | --------------------------------------------------------------------------- | |
702 | ZeroDivisionError Traceback (most recent call last) |
|
745 | ZeroDivisionError Traceback (most recent call last) | |
703 |
|
746 | |||
704 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
747 | /ipython1-client-r3021/docs/examples/<string> in <module>() | |
705 |
|
748 | |||
706 | ZeroDivisionError: integer division or modulo by zero |
|
749 | ZeroDivisionError: integer division or modulo by zero | |
707 |
|
750 | |||
708 | [1:execute]: |
|
751 | [1:execute]: | |
709 | --------------------------------------------------------------------------- |
|
752 | --------------------------------------------------------------------------- | |
710 | ZeroDivisionError Traceback (most recent call last) |
|
753 | ZeroDivisionError Traceback (most recent call last) | |
711 |
|
754 | |||
712 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
755 | /ipython1-client-r3021/docs/examples/<string> in <module>() | |
713 |
|
756 | |||
714 | ZeroDivisionError: integer division or modulo by zero |
|
757 | ZeroDivisionError: integer division or modulo by zero | |
715 |
|
758 | |||
716 | [2:execute]: |
|
759 | [2:execute]: | |
717 | --------------------------------------------------------------------------- |
|
760 | --------------------------------------------------------------------------- | |
718 | ZeroDivisionError Traceback (most recent call last) |
|
761 | ZeroDivisionError Traceback (most recent call last) | |
719 |
|
762 | |||
720 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
763 | /ipython1-client-r3021/docs/examples/<string> in <module>() | |
721 |
|
764 | |||
722 | ZeroDivisionError: integer division or modulo by zero |
|
765 | ZeroDivisionError: integer division or modulo by zero | |
723 |
|
766 | |||
724 | [3:execute]: |
|
767 | [3:execute]: | |
725 | --------------------------------------------------------------------------- |
|
768 | --------------------------------------------------------------------------- | |
726 | ZeroDivisionError Traceback (most recent call last) |
|
769 | ZeroDivisionError Traceback (most recent call last) | |
727 |
|
770 | |||
728 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
771 | /ipython1-client-r3021/docs/examples/<string> in <module>() | |
729 |
|
772 | |||
730 | ZeroDivisionError: integer division or modulo by zero |
|
773 | ZeroDivisionError: integer division or modulo by zero | |
731 |
|
774 | |||
732 | .. note:: |
|
775 | .. note:: | |
733 |
|
776 | |||
734 | The above example appears to be broken right now because of a change in |
|
777 | The above example appears to be broken right now because of a change in | |
735 | how we are using Twisted. |
|
778 | how we are using Twisted. | |
736 |
|
779 | |||
737 |
All of this same error handling magic even works in non-blocking mode: |
|
780 | All of this same error handling magic even works in non-blocking mode: | |
|
781 | ||||
|
782 | .. sourcecode:: ipython | |||
738 |
|
783 | |||
739 | In [83]: mec.block=False |
|
784 | In [83]: mec.block=False | |
740 |
|
785 | |||
741 | In [84]: pr = mec.execute('1/0') |
|
786 | In [84]: pr = mec.execute('1/0') | |
742 |
|
787 | |||
743 | In [85]: pr.r |
|
788 | In [85]: pr.r | |
744 | --------------------------------------------------------------------------- |
|
789 | --------------------------------------------------------------------------- | |
745 | CompositeError Traceback (most recent call last) |
|
790 | CompositeError Traceback (most recent call last) | |
746 |
|
791 | |||
747 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
792 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() | |
748 |
|
793 | |||
749 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in _get_r(self) |
|
794 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in _get_r(self) | |
750 | 170 |
|
795 | 170 | |
751 | 171 def _get_r(self): |
|
796 | 171 def _get_r(self): | |
752 | --> 172 return self.get_result(block=True) |
|
797 | --> 172 return self.get_result(block=True) | |
753 | 173 |
|
798 | 173 | |
754 | 174 r = property(_get_r) |
|
799 | 174 r = property(_get_r) | |
755 |
|
800 | |||
756 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_result(self, default, block) |
|
801 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_result(self, default, block) | |
757 | 131 return self.result |
|
802 | 131 return self.result | |
758 | 132 try: |
|
803 | 132 try: | |
759 | --> 133 result = self.client.get_pending_deferred(self.result_id, block) |
|
804 | --> 133 result = self.client.get_pending_deferred(self.result_id, block) | |
760 | 134 except error.ResultNotCompleted: |
|
805 | 134 except error.ResultNotCompleted: | |
761 | 135 return default |
|
806 | 135 return default | |
762 |
|
807 | |||
763 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_pending_deferred(self, deferredID, block) |
|
808 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_pending_deferred(self, deferredID, block) | |
764 | 385 |
|
809 | 385 | |
765 | 386 def get_pending_deferred(self, deferredID, block): |
|
810 | 386 def get_pending_deferred(self, deferredID, block): | |
766 | --> 387 return blockingCallFromThread(self.smultiengine.get_pending_deferred, deferredID, block) |
|
811 | --> 387 return blockingCallFromThread(self.smultiengine.get_pending_deferred, deferredID, block) | |
767 | 388 |
|
812 | 388 | |
768 | 389 def barrier(self, pendingResults): |
|
813 | 389 def barrier(self, pendingResults): | |
769 |
|
814 | |||
770 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) |
|
815 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) | |
771 | 72 result.raiseException() |
|
816 | 72 result.raiseException() | |
772 | 73 except Exception, e: |
|
817 | 73 except Exception, e: | |
773 | ---> 74 raise e |
|
818 | ---> 74 raise e | |
774 | 75 return result |
|
819 | 75 return result | |
775 | 76 |
|
820 | 76 | |
776 |
|
821 | |||
777 | CompositeError: one or more exceptions from call to method: execute |
|
822 | CompositeError: one or more exceptions from call to method: execute | |
778 | [0:execute]: ZeroDivisionError: integer division or modulo by zero |
|
823 | [0:execute]: ZeroDivisionError: integer division or modulo by zero | |
779 | [1:execute]: ZeroDivisionError: integer division or modulo by zero |
|
824 | [1:execute]: ZeroDivisionError: integer division or modulo by zero | |
780 | [2:execute]: ZeroDivisionError: integer division or modulo by zero |
|
825 | [2:execute]: ZeroDivisionError: integer division or modulo by zero | |
781 | [3:execute]: ZeroDivisionError: integer division or modulo by zero |
|
826 | [3:execute]: ZeroDivisionError: integer division or modulo by zero | |
782 |
|
827 | |||
783 |
|
828 |
@@ -1,93 +1,99 b'' | |||||
1 | .. _paralleltask: |
|
1 | .. _paralleltask: | |
2 |
|
2 | |||
3 | ========================== |
|
3 | ========================== | |
4 | The IPython task interface |
|
4 | The IPython task interface | |
5 | ========================== |
|
5 | ========================== | |
6 |
|
6 | |||
7 | .. contents:: |
|
|||
8 |
|
||||
9 | The task interface to the controller presents the engines as a fault tolerant, dynamic load-balanced system or workers. Unlike the multiengine interface, in the task interface, the user have no direct access to individual engines. In some ways, this interface is simpler, but in other ways it is more powerful. |
|
7 | The task interface to the controller presents the engines as a fault tolerant, dynamic load-balanced system or workers. Unlike the multiengine interface, in the task interface, the user have no direct access to individual engines. In some ways, this interface is simpler, but in other ways it is more powerful. | |
10 |
|
8 | |||
11 | Best of all the user can use both of these interfaces running at the same time to take advantage or both of their strengths. When the user can break up the user's work into segments that do not depend on previous execution, the task interface is ideal. But it also has more power and flexibility, allowing the user to guide the distribution of jobs, without having to assign tasks to engines explicitly. |
|
9 | Best of all the user can use both of these interfaces running at the same time to take advantage or both of their strengths. When the user can break up the user's work into segments that do not depend on previous execution, the task interface is ideal. But it also has more power and flexibility, allowing the user to guide the distribution of jobs, without having to assign tasks to engines explicitly. | |
12 |
|
10 | |||
13 | Starting the IPython controller and engines |
|
11 | Starting the IPython controller and engines | |
14 | =========================================== |
|
12 | =========================================== | |
15 |
|
13 | |||
16 | To follow along with this tutorial, you will need to start the IPython |
|
14 | To follow along with this tutorial, you will need to start the IPython | |
17 | controller and four IPython engines. The simplest way of doing this is to use |
|
15 | controller and four IPython engines. The simplest way of doing this is to use | |
18 | the :command:`ipcluster` command:: |
|
16 | the :command:`ipcluster` command:: | |
19 |
|
17 | |||
20 | $ ipcluster -n 4 |
|
18 | $ ipcluster local -n 4 | |
21 |
|
19 | |||
22 | For more detailed information about starting the controller and engines, see |
|
20 | For more detailed information about starting the controller and engines, see | |
23 | our :ref:`introduction <ip1par>` to using IPython for parallel computing. |
|
21 | our :ref:`introduction <ip1par>` to using IPython for parallel computing. | |
24 |
|
22 | |||
25 | Creating a ``TaskClient`` instance |
|
23 | Creating a ``TaskClient`` instance | |
26 | ========================================= |
|
24 | ========================================= | |
27 |
|
25 | |||
28 | The first step is to import the IPython :mod:`IPython.kernel.client` module |
|
26 | The first step is to import the IPython :mod:`IPython.kernel.client` module | |
29 |
and then create a :class:`TaskClient` instance: |
|
27 | and then create a :class:`TaskClient` instance: | |
|
28 | ||||
|
29 | .. sourcecode:: ipython | |||
30 |
|
30 | |||
31 | In [1]: from IPython.kernel import client |
|
31 | In [1]: from IPython.kernel import client | |
32 |
|
32 | |||
33 | In [2]: tc = client.TaskClient() |
|
33 | In [2]: tc = client.TaskClient() | |
34 |
|
34 | |||
35 | This form assumes that the :file:`ipcontroller-tc.furl` is in the |
|
35 | This form assumes that the :file:`ipcontroller-tc.furl` is in the | |
36 | :file:`~./ipython/security` directory on the client's host. If not, the |
|
36 | :file:`~./ipython/security` directory on the client's host. If not, the | |
37 |
location of the |
|
37 | location of the FURL file must be given as an argument to the | |
38 |
constructor: |
|
38 | constructor: | |
|
39 | ||||
|
40 | .. sourcecode:: ipython | |||
39 |
|
41 | |||
40 | In[2]: mec = client.TaskClient('/path/to/my/ipcontroller-tc.furl') |
|
42 | In [2]: mec = client.TaskClient('/path/to/my/ipcontroller-tc.furl') | |
41 |
|
43 | |||
42 | Quick and easy parallelism |
|
44 | Quick and easy parallelism | |
43 | ========================== |
|
45 | ========================== | |
44 |
|
46 | |||
45 | In many cases, you simply want to apply a Python function to a sequence of objects, but *in parallel*. Like the multiengine interface, the task interface provides two simple ways of accomplishing this: a parallel version of :func:`map` and ``@parallel`` function decorator. However, the verions in the task interface have one important difference: they are dynamically load balanced. Thus, if the execution time per item varies significantly, you should use the versions in the task interface. |
|
47 | In many cases, you simply want to apply a Python function to a sequence of objects, but *in parallel*. Like the multiengine interface, the task interface provides two simple ways of accomplishing this: a parallel version of :func:`map` and ``@parallel`` function decorator. However, the verions in the task interface have one important difference: they are dynamically load balanced. Thus, if the execution time per item varies significantly, you should use the versions in the task interface. | |
46 |
|
48 | |||
47 | Parallel map |
|
49 | Parallel map | |
48 | ------------ |
|
50 | ------------ | |
49 |
|
51 | |||
50 |
The parallel :meth:`map` in the task interface is similar to that in the multiengine interface: |
|
52 | The parallel :meth:`map` in the task interface is similar to that in the multiengine interface: | |
|
53 | ||||
|
54 | .. sourcecode:: ipython | |||
51 |
|
55 | |||
52 | In [63]: serial_result = map(lambda x:x**10, range(32)) |
|
56 | In [63]: serial_result = map(lambda x:x**10, range(32)) | |
53 |
|
57 | |||
54 | In [64]: parallel_result = tc.map(lambda x:x**10, range(32)) |
|
58 | In [64]: parallel_result = tc.map(lambda x:x**10, range(32)) | |
55 |
|
59 | |||
56 | In [65]: serial_result==parallel_result |
|
60 | In [65]: serial_result==parallel_result | |
57 | Out[65]: True |
|
61 | Out[65]: True | |
58 |
|
62 | |||
59 | Parallel function decorator |
|
63 | Parallel function decorator | |
60 | --------------------------- |
|
64 | --------------------------- | |
61 |
|
65 | |||
62 |
Parallel functions are just like normal function, but they can be called on sequences and *in parallel*. The multiengine interface provides a decorator that turns any Python function into a parallel function: |
|
66 | Parallel functions are just like normal function, but they can be called on sequences and *in parallel*. The multiengine interface provides a decorator that turns any Python function into a parallel function: | |
|
67 | ||||
|
68 | .. sourcecode:: ipython | |||
63 |
|
69 | |||
64 | In [10]: @tc.parallel() |
|
70 | In [10]: @tc.parallel() | |
65 | ....: def f(x): |
|
71 | ....: def f(x): | |
66 | ....: return 10.0*x**4 |
|
72 | ....: return 10.0*x**4 | |
67 | ....: |
|
73 | ....: | |
68 |
|
74 | |||
69 | In [11]: f(range(32)) # this is done in parallel |
|
75 | In [11]: f(range(32)) # this is done in parallel | |
70 | Out[11]: |
|
76 | Out[11]: | |
71 | [0.0,10.0,160.0,...] |
|
77 | [0.0,10.0,160.0,...] | |
72 |
|
78 | |||
73 | More details |
|
79 | More details | |
74 | ============ |
|
80 | ============ | |
75 |
|
81 | |||
76 | The :class:`TaskClient` has many more powerful features that allow quite a bit of flexibility in how tasks are defined and run. The next places to look are in the following classes: |
|
82 | The :class:`TaskClient` has many more powerful features that allow quite a bit of flexibility in how tasks are defined and run. The next places to look are in the following classes: | |
77 |
|
83 | |||
78 | * :class:`IPython.kernel.client.TaskClient` |
|
84 | * :class:`IPython.kernel.client.TaskClient` | |
79 | * :class:`IPython.kernel.client.StringTask` |
|
85 | * :class:`IPython.kernel.client.StringTask` | |
80 | * :class:`IPython.kernel.client.MapTask` |
|
86 | * :class:`IPython.kernel.client.MapTask` | |
81 |
|
87 | |||
82 | The following is an overview of how to use these classes together: |
|
88 | The following is an overview of how to use these classes together: | |
83 |
|
89 | |||
84 | 1. Create a :class:`TaskClient`. |
|
90 | 1. Create a :class:`TaskClient`. | |
85 | 2. Create one or more instances of :class:`StringTask` or :class:`MapTask` |
|
91 | 2. Create one or more instances of :class:`StringTask` or :class:`MapTask` | |
86 | to define your tasks. |
|
92 | to define your tasks. | |
87 | 3. Submit your tasks to using the :meth:`run` method of your |
|
93 | 3. Submit your tasks to using the :meth:`run` method of your | |
88 | :class:`TaskClient` instance. |
|
94 | :class:`TaskClient` instance. | |
89 | 4. Use :meth:`TaskClient.get_task_result` to get the results of the |
|
95 | 4. Use :meth:`TaskClient.get_task_result` to get the results of the | |
90 | tasks. |
|
96 | tasks. | |
91 |
|
97 | |||
92 | We are in the process of developing more detailed information about the task interface. For now, the docstrings of the :class:`TaskClient`, :class:`StringTask` and :class:`MapTask` classes should be consulted. |
|
98 | We are in the process of developing more detailed information about the task interface. For now, the docstrings of the :class:`TaskClient`, :class:`StringTask` and :class:`MapTask` classes should be consulted. | |
93 |
|
99 |
General Comments 0
You need to be logged in to leave comments.
Login now