Show More
@@ -1,453 +1,453 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | An application for IPython. |
|
4 | 4 | |
|
5 | 5 | All top-level applications should use the classes in this module for |
|
6 | 6 | handling configuration and creating componenets. |
|
7 | 7 | |
|
8 | 8 | The job of an :class:`Application` is to create the master configuration |
|
9 | 9 | object and then create the configurable objects, passing the config to them. |
|
10 | 10 | |
|
11 | 11 | Authors: |
|
12 | 12 | |
|
13 | 13 | * Brian Granger |
|
14 | 14 | * Fernando Perez |
|
15 | 15 | |
|
16 | 16 | Notes |
|
17 | 17 | ----- |
|
18 | 18 | """ |
|
19 | 19 | |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | # Copyright (C) 2008-2009 The IPython Development Team |
|
22 | 22 | # |
|
23 | 23 | # Distributed under the terms of the BSD License. The full license is in |
|
24 | 24 | # the file COPYING, distributed as part of this software. |
|
25 | 25 | #----------------------------------------------------------------------------- |
|
26 | 26 | |
|
27 | 27 | #----------------------------------------------------------------------------- |
|
28 | 28 | # Imports |
|
29 | 29 | #----------------------------------------------------------------------------- |
|
30 | 30 | |
|
31 | 31 | import logging |
|
32 | 32 | import os |
|
33 | 33 | import sys |
|
34 | 34 | |
|
35 | 35 | from IPython.core import release, crashhandler |
|
36 | 36 | from IPython.utils.path import get_ipython_dir, get_ipython_package_dir |
|
37 | 37 | from IPython.config.loader import ( |
|
38 | 38 | PyFileConfigLoader, |
|
39 | 39 | ArgParseConfigLoader, |
|
40 | 40 | Config, |
|
41 | 41 | ) |
|
42 | 42 | |
|
43 | 43 | #----------------------------------------------------------------------------- |
|
44 | 44 | # Classes and functions |
|
45 | 45 | #----------------------------------------------------------------------------- |
|
46 | 46 | |
|
47 | 47 | class ApplicationError(Exception): |
|
48 | 48 | pass |
|
49 | 49 | |
|
50 | 50 | |
|
51 | 51 | class BaseAppConfigLoader(ArgParseConfigLoader): |
|
52 | 52 | """Default command line options for IPython based applications.""" |
|
53 | 53 | |
|
54 | 54 | def _add_ipython_dir(self, parser): |
|
55 | 55 | """Add the --ipython-dir option to the parser.""" |
|
56 | 56 | paa = parser.add_argument |
|
57 | 57 | paa('--ipython-dir', |
|
58 | 58 | dest='Global.ipython_dir',type=unicode, |
|
59 | 59 | help= |
|
60 | 60 | """Set to override default location of the IPython directory |
|
61 | 61 | IPYTHON_DIR, stored as Global.ipython_dir. This can also be |
|
62 | 62 | specified through the environment variable IPYTHON_DIR.""", |
|
63 | 63 | metavar='Global.ipython_dir') |
|
64 | 64 | |
|
65 | 65 | def _add_log_level(self, parser): |
|
66 | 66 | """Add the --log-level option to the parser.""" |
|
67 | 67 | paa = parser.add_argument |
|
68 | 68 | paa('--log-level', |
|
69 | 69 | dest="Global.log_level",type=int, |
|
70 | 70 | help='Set the log level (0,10,20,30,40,50). Default is 30.', |
|
71 | 71 | metavar='Global.log_level') |
|
72 | 72 | |
|
73 | 73 | def _add_arguments(self): |
|
74 | 74 | self._add_ipython_dir(self.parser) |
|
75 | 75 | self._add_log_level(self.parser) |
|
76 | 76 | |
|
77 | 77 | |
|
78 | 78 | class Application(object): |
|
79 | 79 | """Load a config, construct configurables and set them running. |
|
80 | 80 | |
|
81 | 81 | The configuration of an application can be done via three different Config |
|
82 | 82 | objects, which are loaded and ultimately merged into a single one used |
|
83 | 83 | from that point on by the app. These are: |
|
84 | 84 | |
|
85 | 85 | 1. default_config: internal defaults, implemented in code. |
|
86 | 86 | 2. file_config: read from the filesystem. |
|
87 | 87 | 3. command_line_config: read from the system's command line flags. |
|
88 | 88 | |
|
89 | 89 | During initialization, 3 is actually read before 2, since at the |
|
90 | 90 | command-line one may override the location of the file to be read. But the |
|
91 | 91 | above is the order in which the merge is made. |
|
92 | 92 | """ |
|
93 | 93 | |
|
94 | 94 | name = u'ipython' |
|
95 | 95 | description = 'IPython: an enhanced interactive Python shell.' |
|
96 | 96 | #: Usage message printed by argparse. If None, auto-generate |
|
97 | 97 | usage = None |
|
98 | 98 | #: The command line config loader. Subclass of ArgParseConfigLoader. |
|
99 | 99 | command_line_loader = BaseAppConfigLoader |
|
100 | 100 | #: The name of the config file to load, determined at runtime |
|
101 | 101 | config_file_name = None |
|
102 | 102 | #: The name of the default config file. Track separately from the actual |
|
103 | 103 | #: name because some logic happens only if we aren't using the default. |
|
104 | 104 | default_config_file_name = u'ipython_config.py' |
|
105 | 105 | default_log_level = logging.WARN |
|
106 | 106 | #: Set by --profile option |
|
107 | 107 | profile_name = None |
|
108 | #: User's ipython directory, typically ~/.ipython/ | |
|
108 | #: User's ipython directory, typically ~/.ipython or ~/.config/ipython/ | |
|
109 | 109 | ipython_dir = None |
|
110 | 110 | #: Internal defaults, implemented in code. |
|
111 | 111 | default_config = None |
|
112 | 112 | #: Read from the filesystem. |
|
113 | 113 | file_config = None |
|
114 | 114 | #: Read from the system's command line flags. |
|
115 | 115 | command_line_config = None |
|
116 | 116 | #: The final config that will be passed to the main object. |
|
117 | 117 | master_config = None |
|
118 | 118 | #: A reference to the argv to be used (typically ends up being sys.argv[1:]) |
|
119 | 119 | argv = None |
|
120 | 120 | #: extra arguments computed by the command-line loader |
|
121 | 121 | extra_args = None |
|
122 | 122 | #: The class to use as the crash handler. |
|
123 | 123 | crash_handler_class = crashhandler.CrashHandler |
|
124 | 124 | |
|
125 | 125 | # Private attributes |
|
126 | 126 | _exiting = False |
|
127 | 127 | _initialized = False |
|
128 | 128 | |
|
129 | 129 | def __init__(self, argv=None): |
|
130 | 130 | self.argv = sys.argv[1:] if argv is None else argv |
|
131 | 131 | self.init_logger() |
|
132 | 132 | |
|
133 | 133 | def init_logger(self): |
|
134 | 134 | self.log = logging.getLogger(self.__class__.__name__) |
|
135 | 135 | # This is used as the default until the command line arguments are read. |
|
136 | 136 | self.log.setLevel(self.default_log_level) |
|
137 | 137 | self._log_handler = logging.StreamHandler() |
|
138 | 138 | self._log_formatter = logging.Formatter("[%(name)s] %(message)s") |
|
139 | 139 | self._log_handler.setFormatter(self._log_formatter) |
|
140 | 140 | self.log.addHandler(self._log_handler) |
|
141 | 141 | |
|
142 | 142 | def _set_log_level(self, level): |
|
143 | 143 | self.log.setLevel(level) |
|
144 | 144 | |
|
145 | 145 | def _get_log_level(self): |
|
146 | 146 | return self.log.level |
|
147 | 147 | |
|
148 | 148 | log_level = property(_get_log_level, _set_log_level) |
|
149 | 149 | |
|
150 | 150 | def initialize(self): |
|
151 | 151 | """Initialize the application. |
|
152 | 152 | |
|
153 | 153 | Loads all configuration information and sets all application state, but |
|
154 | 154 | does not start any relevant processing (typically some kind of event |
|
155 | 155 | loop). |
|
156 | 156 | |
|
157 | 157 | Once this method has been called, the application is flagged as |
|
158 | 158 | initialized and the method becomes a no-op.""" |
|
159 | 159 | |
|
160 | 160 | if self._initialized: |
|
161 | 161 | return |
|
162 | 162 | |
|
163 | 163 | # The first part is protected with an 'attempt' wrapper, that will log |
|
164 | 164 | # failures with the basic system traceback machinery. Once our crash |
|
165 | 165 | # handler is in place, we can let any subsequent exception propagate, |
|
166 | 166 | # as our handler will log it with much better detail than the default. |
|
167 | 167 | self.attempt(self.create_crash_handler) |
|
168 | 168 | |
|
169 | 169 | # Configuration phase |
|
170 | 170 | # Default config (internally hardwired in application code) |
|
171 | 171 | self.create_default_config() |
|
172 | 172 | self.log_default_config() |
|
173 | 173 | self.set_default_config_log_level() |
|
174 | 174 | |
|
175 | 175 | # Command-line config |
|
176 | 176 | self.pre_load_command_line_config() |
|
177 | 177 | self.load_command_line_config() |
|
178 | 178 | self.set_command_line_config_log_level() |
|
179 | 179 | self.post_load_command_line_config() |
|
180 | 180 | self.log_command_line_config() |
|
181 | 181 | |
|
182 | 182 | # Find resources needed for filesystem access, using information from |
|
183 | 183 | # the above two |
|
184 | 184 | self.find_ipython_dir() |
|
185 | 185 | self.find_resources() |
|
186 | 186 | self.find_config_file_name() |
|
187 | 187 | self.find_config_file_paths() |
|
188 | 188 | |
|
189 | 189 | # File-based config |
|
190 | 190 | self.pre_load_file_config() |
|
191 | 191 | self.load_file_config() |
|
192 | 192 | self.set_file_config_log_level() |
|
193 | 193 | self.post_load_file_config() |
|
194 | 194 | self.log_file_config() |
|
195 | 195 | |
|
196 | 196 | # Merge all config objects into a single one the app can then use |
|
197 | 197 | self.merge_configs() |
|
198 | 198 | self.log_master_config() |
|
199 | 199 | |
|
200 | 200 | # Construction phase |
|
201 | 201 | self.pre_construct() |
|
202 | 202 | self.construct() |
|
203 | 203 | self.post_construct() |
|
204 | 204 | |
|
205 | 205 | # Done, flag as such and |
|
206 | 206 | self._initialized = True |
|
207 | 207 | |
|
208 | 208 | def start(self): |
|
209 | 209 | """Start the application.""" |
|
210 | 210 | self.initialize() |
|
211 | 211 | self.start_app() |
|
212 | 212 | |
|
213 | 213 | #------------------------------------------------------------------------- |
|
214 | 214 | # Various stages of Application creation |
|
215 | 215 | #------------------------------------------------------------------------- |
|
216 | 216 | |
|
217 | 217 | def create_crash_handler(self): |
|
218 | 218 | """Create a crash handler, typically setting sys.excepthook to it.""" |
|
219 | 219 | self.crash_handler = self.crash_handler_class(self) |
|
220 | 220 | sys.excepthook = self.crash_handler |
|
221 | 221 | |
|
222 | 222 | def create_default_config(self): |
|
223 | 223 | """Create defaults that can't be set elsewhere. |
|
224 | 224 | |
|
225 | 225 | For the most part, we try to set default in the class attributes |
|
226 | 226 | of Configurables. But, defaults the top-level Application (which is |
|
227 | 227 | not a HasTraits or Configurables) are not set in this way. Instead |
|
228 | 228 | we set them here. The Global section is for variables like this that |
|
229 | 229 | don't belong to a particular configurable. |
|
230 | 230 | """ |
|
231 | 231 | c = Config() |
|
232 | 232 | c.Global.ipython_dir = get_ipython_dir() |
|
233 | 233 | c.Global.log_level = self.log_level |
|
234 | 234 | self.default_config = c |
|
235 | 235 | |
|
236 | 236 | def log_default_config(self): |
|
237 | 237 | self.log.debug('Default config loaded:') |
|
238 | 238 | self.log.debug(repr(self.default_config)) |
|
239 | 239 | |
|
240 | 240 | def set_default_config_log_level(self): |
|
241 | 241 | try: |
|
242 | 242 | self.log_level = self.default_config.Global.log_level |
|
243 | 243 | except AttributeError: |
|
244 | 244 | # Fallback to the default_log_level class attribute |
|
245 | 245 | pass |
|
246 | 246 | |
|
247 | 247 | def create_command_line_config(self): |
|
248 | 248 | """Create and return a command line config loader.""" |
|
249 | 249 | return self.command_line_loader( |
|
250 | 250 | self.argv, |
|
251 | 251 | description=self.description, |
|
252 | 252 | version=release.version, |
|
253 | 253 | usage=self.usage |
|
254 | 254 | ) |
|
255 | 255 | |
|
256 | 256 | def pre_load_command_line_config(self): |
|
257 | 257 | """Do actions just before loading the command line config.""" |
|
258 | 258 | pass |
|
259 | 259 | |
|
260 | 260 | def load_command_line_config(self): |
|
261 | 261 | """Load the command line config.""" |
|
262 | 262 | loader = self.create_command_line_config() |
|
263 | 263 | self.command_line_config = loader.load_config() |
|
264 | 264 | self.extra_args = loader.get_extra_args() |
|
265 | 265 | |
|
266 | 266 | def set_command_line_config_log_level(self): |
|
267 | 267 | try: |
|
268 | 268 | self.log_level = self.command_line_config.Global.log_level |
|
269 | 269 | except AttributeError: |
|
270 | 270 | pass |
|
271 | 271 | |
|
272 | 272 | def post_load_command_line_config(self): |
|
273 | 273 | """Do actions just after loading the command line config.""" |
|
274 | 274 | pass |
|
275 | 275 | |
|
276 | 276 | def log_command_line_config(self): |
|
277 | 277 | self.log.debug("Command line config loaded:") |
|
278 | 278 | self.log.debug(repr(self.command_line_config)) |
|
279 | 279 | |
|
280 | 280 | def find_ipython_dir(self): |
|
281 | 281 | """Set the IPython directory. |
|
282 | 282 | |
|
283 | 283 | This sets ``self.ipython_dir``, but the actual value that is passed to |
|
284 | 284 | the application is kept in either ``self.default_config`` or |
|
285 | 285 | ``self.command_line_config``. This also adds ``self.ipython_dir`` to |
|
286 | 286 | ``sys.path`` so config files there can be referenced by other config |
|
287 | 287 | files. |
|
288 | 288 | """ |
|
289 | 289 | |
|
290 | 290 | try: |
|
291 | 291 | self.ipython_dir = self.command_line_config.Global.ipython_dir |
|
292 | 292 | except AttributeError: |
|
293 | 293 | self.ipython_dir = self.default_config.Global.ipython_dir |
|
294 | 294 | sys.path.append(os.path.abspath(self.ipython_dir)) |
|
295 | 295 | if not os.path.isdir(self.ipython_dir): |
|
296 | 296 | os.makedirs(self.ipython_dir, mode=0777) |
|
297 | 297 | self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir) |
|
298 | 298 | |
|
299 | 299 | def find_resources(self): |
|
300 | 300 | """Find other resources that need to be in place. |
|
301 | 301 | |
|
302 | 302 | Things like cluster directories need to be in place to find the |
|
303 | 303 | config file. These happen right after the IPython directory has |
|
304 | 304 | been set. |
|
305 | 305 | """ |
|
306 | 306 | pass |
|
307 | 307 | |
|
308 | 308 | def find_config_file_name(self): |
|
309 | 309 | """Find the config file name for this application. |
|
310 | 310 | |
|
311 | 311 | This must set ``self.config_file_name`` to the filename of the |
|
312 | 312 | config file to use (just the filename). The search paths for the |
|
313 | 313 | config file are set in :meth:`find_config_file_paths` and then passed |
|
314 | 314 | to the config file loader where they are resolved to an absolute path. |
|
315 | 315 | |
|
316 | 316 | If a profile has been set at the command line, this will resolve it. |
|
317 | 317 | """ |
|
318 | 318 | try: |
|
319 | 319 | self.config_file_name = self.command_line_config.Global.config_file |
|
320 | 320 | except AttributeError: |
|
321 | 321 | pass |
|
322 | 322 | else: |
|
323 | 323 | return |
|
324 | 324 | |
|
325 | 325 | try: |
|
326 | 326 | self.profile_name = self.command_line_config.Global.profile |
|
327 | 327 | except AttributeError: |
|
328 | 328 | # Just use the default as there is no profile |
|
329 | 329 | self.config_file_name = self.default_config_file_name |
|
330 | 330 | else: |
|
331 | 331 | # Use the default config file name and profile name if set |
|
332 | 332 | # to determine the used config file name. |
|
333 | 333 | name_parts = self.default_config_file_name.split('.') |
|
334 | 334 | name_parts.insert(1, u'_' + self.profile_name + u'.') |
|
335 | 335 | self.config_file_name = ''.join(name_parts) |
|
336 | 336 | |
|
337 | 337 | def find_config_file_paths(self): |
|
338 | 338 | """Set the search paths for resolving the config file. |
|
339 | 339 | |
|
340 | 340 | This must set ``self.config_file_paths`` to a sequence of search |
|
341 | 341 | paths to pass to the config file loader. |
|
342 | 342 | """ |
|
343 | 343 | # Include our own profiles directory last, so that users can still find |
|
344 | 344 | # our shipped copies of builtin profiles even if they don't have them |
|
345 | 345 | # in their local ipython directory. |
|
346 | 346 | prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile') |
|
347 | 347 | self.config_file_paths = (os.getcwd(), self.ipython_dir, prof_dir) |
|
348 | 348 | |
|
349 | 349 | def pre_load_file_config(self): |
|
350 | 350 | """Do actions before the config file is loaded.""" |
|
351 | 351 | pass |
|
352 | 352 | |
|
353 | 353 | def load_file_config(self): |
|
354 | 354 | """Load the config file. |
|
355 | 355 | |
|
356 | 356 | This tries to load the config file from disk. If successful, the |
|
357 | 357 | ``CONFIG_FILE`` config variable is set to the resolved config file |
|
358 | 358 | location. If not successful, an empty config is used. |
|
359 | 359 | """ |
|
360 | 360 | self.log.debug("Attempting to load config file: %s" % |
|
361 | 361 | self.config_file_name) |
|
362 | 362 | loader = PyFileConfigLoader(self.config_file_name, |
|
363 | 363 | path=self.config_file_paths) |
|
364 | 364 | try: |
|
365 | 365 | self.file_config = loader.load_config() |
|
366 | 366 | self.file_config.Global.config_file = loader.full_filename |
|
367 | 367 | except IOError: |
|
368 | 368 | # Only warn if the default config file was NOT being used. |
|
369 | 369 | if not self.config_file_name==self.default_config_file_name: |
|
370 | 370 | self.log.warn("Config file not found, skipping: %s" % |
|
371 | 371 | self.config_file_name, exc_info=True) |
|
372 | 372 | self.file_config = Config() |
|
373 | 373 | except: |
|
374 | 374 | self.log.warn("Error loading config file: %s" % |
|
375 | 375 | self.config_file_name, exc_info=True) |
|
376 | 376 | self.file_config = Config() |
|
377 | 377 | |
|
378 | 378 | def set_file_config_log_level(self): |
|
379 | 379 | # We need to keeep self.log_level updated. But we only use the value |
|
380 | 380 | # of the file_config if a value was not specified at the command |
|
381 | 381 | # line, because the command line overrides everything. |
|
382 | 382 | if not hasattr(self.command_line_config.Global, 'log_level'): |
|
383 | 383 | try: |
|
384 | 384 | self.log_level = self.file_config.Global.log_level |
|
385 | 385 | except AttributeError: |
|
386 | 386 | pass # Use existing value |
|
387 | 387 | |
|
388 | 388 | def post_load_file_config(self): |
|
389 | 389 | """Do actions after the config file is loaded.""" |
|
390 | 390 | pass |
|
391 | 391 | |
|
392 | 392 | def log_file_config(self): |
|
393 | 393 | if hasattr(self.file_config.Global, 'config_file'): |
|
394 | 394 | self.log.debug("Config file loaded: %s" % |
|
395 | 395 | self.file_config.Global.config_file) |
|
396 | 396 | self.log.debug(repr(self.file_config)) |
|
397 | 397 | |
|
398 | 398 | def merge_configs(self): |
|
399 | 399 | """Merge the default, command line and file config objects.""" |
|
400 | 400 | config = Config() |
|
401 | 401 | config._merge(self.default_config) |
|
402 | 402 | config._merge(self.file_config) |
|
403 | 403 | config._merge(self.command_line_config) |
|
404 | 404 | |
|
405 | 405 | # XXX fperez - propose to Brian we rename master_config to simply |
|
406 | 406 | # config, I think this is going to be heavily used in examples and |
|
407 | 407 | # application code and the name is shorter/easier to find/remember. |
|
408 | 408 | # For now, just alias it... |
|
409 | 409 | self.master_config = config |
|
410 | 410 | self.config = config |
|
411 | 411 | |
|
412 | 412 | def log_master_config(self): |
|
413 | 413 | self.log.debug("Master config created:") |
|
414 | 414 | self.log.debug(repr(self.master_config)) |
|
415 | 415 | |
|
416 | 416 | def pre_construct(self): |
|
417 | 417 | """Do actions after the config has been built, but before construct.""" |
|
418 | 418 | pass |
|
419 | 419 | |
|
420 | 420 | def construct(self): |
|
421 | 421 | """Construct the main objects that make up this app.""" |
|
422 | 422 | self.log.debug("Constructing main objects for application") |
|
423 | 423 | |
|
424 | 424 | def post_construct(self): |
|
425 | 425 | """Do actions after construct, but before starting the app.""" |
|
426 | 426 | pass |
|
427 | 427 | |
|
428 | 428 | def start_app(self): |
|
429 | 429 | """Actually start the app.""" |
|
430 | 430 | self.log.debug("Starting application") |
|
431 | 431 | |
|
432 | 432 | #------------------------------------------------------------------------- |
|
433 | 433 | # Utility methods |
|
434 | 434 | #------------------------------------------------------------------------- |
|
435 | 435 | |
|
436 | 436 | def exit(self, exit_status=0): |
|
437 | 437 | if self._exiting: |
|
438 | 438 | pass |
|
439 | 439 | else: |
|
440 | 440 | self.log.debug("Exiting application: %s" % self.name) |
|
441 | 441 | self._exiting = True |
|
442 | 442 | sys.exit(exit_status) |
|
443 | 443 | |
|
444 | 444 | def attempt(self, func): |
|
445 | 445 | try: |
|
446 | 446 | func() |
|
447 | 447 | except SystemExit: |
|
448 | 448 | raise |
|
449 | 449 | except: |
|
450 | 450 | self.log.critical("Aborting application: %s" % self.name, |
|
451 | 451 | exc_info=True) |
|
452 | 452 | self.exit(0) |
|
453 | 453 |
@@ -1,3510 +1,3510 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | 7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
8 | 8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | 9 | |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | import __builtin__ |
|
19 | 19 | import __future__ |
|
20 | 20 | import bdb |
|
21 | 21 | import inspect |
|
22 | 22 | import os |
|
23 | 23 | import sys |
|
24 | 24 | import shutil |
|
25 | 25 | import re |
|
26 | 26 | import time |
|
27 | 27 | import textwrap |
|
28 | 28 | import types |
|
29 | 29 | from cStringIO import StringIO |
|
30 | 30 | from getopt import getopt,GetoptError |
|
31 | 31 | from pprint import pformat |
|
32 | 32 | |
|
33 | 33 | # cProfile was added in Python2.5 |
|
34 | 34 | try: |
|
35 | 35 | import cProfile as profile |
|
36 | 36 | import pstats |
|
37 | 37 | except ImportError: |
|
38 | 38 | # profile isn't bundled by default in Debian for license reasons |
|
39 | 39 | try: |
|
40 | 40 | import profile,pstats |
|
41 | 41 | except ImportError: |
|
42 | 42 | profile = pstats = None |
|
43 | 43 | |
|
44 | 44 | import IPython |
|
45 | 45 | from IPython.core import debugger, oinspect |
|
46 | 46 | from IPython.core.error import TryNext |
|
47 | 47 | from IPython.core.error import UsageError |
|
48 | 48 | from IPython.core.fakemodule import FakeModule |
|
49 | 49 | from IPython.core.macro import Macro |
|
50 | 50 | from IPython.core import page |
|
51 | 51 | from IPython.core.prefilter import ESC_MAGIC |
|
52 | 52 | from IPython.lib.pylabtools import mpl_runner |
|
53 | 53 | from IPython.external.Itpl import itpl, printpl |
|
54 | 54 | from IPython.testing import decorators as testdec |
|
55 | 55 | from IPython.utils.io import file_read, nlprint |
|
56 | 56 | import IPython.utils.io |
|
57 | 57 | from IPython.utils.path import get_py_filename |
|
58 | 58 | from IPython.utils.process import arg_split, abbrev_cwd |
|
59 | 59 | from IPython.utils.terminal import set_term_title |
|
60 | 60 | from IPython.utils.text import LSString, SList, StringTypes, format_screen |
|
61 | 61 | from IPython.utils.timing import clock, clock2 |
|
62 | 62 | from IPython.utils.warn import warn, error |
|
63 | 63 | from IPython.utils.ipstruct import Struct |
|
64 | 64 | import IPython.utils.generics |
|
65 | 65 | |
|
66 | 66 | #----------------------------------------------------------------------------- |
|
67 | 67 | # Utility functions |
|
68 | 68 | #----------------------------------------------------------------------------- |
|
69 | 69 | |
|
70 | 70 | def on_off(tag): |
|
71 | 71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
72 | 72 | return ['OFF','ON'][tag] |
|
73 | 73 | |
|
74 | 74 | class Bunch: pass |
|
75 | 75 | |
|
76 | 76 | def compress_dhist(dh): |
|
77 | 77 | head, tail = dh[:-10], dh[-10:] |
|
78 | 78 | |
|
79 | 79 | newhead = [] |
|
80 | 80 | done = set() |
|
81 | 81 | for h in head: |
|
82 | 82 | if h in done: |
|
83 | 83 | continue |
|
84 | 84 | newhead.append(h) |
|
85 | 85 | done.add(h) |
|
86 | 86 | |
|
87 | 87 | return newhead + tail |
|
88 | 88 | |
|
89 | 89 | |
|
90 | 90 | #*************************************************************************** |
|
91 | 91 | # Main class implementing Magic functionality |
|
92 | 92 | |
|
93 | 93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
94 | 94 | # on construction of the main InteractiveShell object. Something odd is going |
|
95 | 95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
96 | 96 | # eventually this needs to be clarified. |
|
97 | 97 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
98 | 98 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
99 | 99 | # make Magic a configurable that InteractiveShell does not subclass. |
|
100 | 100 | |
|
101 | 101 | class Magic: |
|
102 | 102 | """Magic functions for InteractiveShell. |
|
103 | 103 | |
|
104 | 104 | Shell functions which can be reached as %function_name. All magic |
|
105 | 105 | functions should accept a string, which they can parse for their own |
|
106 | 106 | needs. This can make some functions easier to type, eg `%cd ../` |
|
107 | 107 | vs. `%cd("../")` |
|
108 | 108 | |
|
109 | 109 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
110 | 110 | at the command line, but it is is needed in the definition. """ |
|
111 | 111 | |
|
112 | 112 | # class globals |
|
113 | 113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
114 | 114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
115 | 115 | |
|
116 | 116 | #...................................................................... |
|
117 | 117 | # some utility functions |
|
118 | 118 | |
|
119 | 119 | def __init__(self,shell): |
|
120 | 120 | |
|
121 | 121 | self.options_table = {} |
|
122 | 122 | if profile is None: |
|
123 | 123 | self.magic_prun = self.profile_missing_notice |
|
124 | 124 | self.shell = shell |
|
125 | 125 | |
|
126 | 126 | # namespace for holding state we may need |
|
127 | 127 | self._magic_state = Bunch() |
|
128 | 128 | |
|
129 | 129 | def profile_missing_notice(self, *args, **kwargs): |
|
130 | 130 | error("""\ |
|
131 | 131 | The profile module could not be found. It has been removed from the standard |
|
132 | 132 | python packages because of its non-free license. To use profiling, install the |
|
133 | 133 | python-profiler package from non-free.""") |
|
134 | 134 | |
|
135 | 135 | def default_option(self,fn,optstr): |
|
136 | 136 | """Make an entry in the options_table for fn, with value optstr""" |
|
137 | 137 | |
|
138 | 138 | if fn not in self.lsmagic(): |
|
139 | 139 | error("%s is not a magic function" % fn) |
|
140 | 140 | self.options_table[fn] = optstr |
|
141 | 141 | |
|
142 | 142 | def lsmagic(self): |
|
143 | 143 | """Return a list of currently available magic functions. |
|
144 | 144 | |
|
145 | 145 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
146 | 146 | ['magic_ls','magic_cd',...]""" |
|
147 | 147 | |
|
148 | 148 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
149 | 149 | |
|
150 | 150 | # magics in class definition |
|
151 | 151 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
152 | 152 | callable(Magic.__dict__[fn]) |
|
153 | 153 | # in instance namespace (run-time user additions) |
|
154 | 154 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
155 | 155 | callable(self.__dict__[fn]) |
|
156 | 156 | # and bound magics by user (so they can access self): |
|
157 | 157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
158 | 158 | callable(self.__class__.__dict__[fn]) |
|
159 | 159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
160 | 160 | filter(inst_magic,self.__dict__.keys()) + \ |
|
161 | 161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
162 | 162 | out = [] |
|
163 | 163 | for fn in set(magics): |
|
164 | 164 | out.append(fn.replace('magic_','',1)) |
|
165 | 165 | out.sort() |
|
166 | 166 | return out |
|
167 | 167 | |
|
168 | 168 | def extract_input_slices(self,slices,raw=False): |
|
169 | 169 | """Return as a string a set of input history slices. |
|
170 | 170 | |
|
171 | 171 | Inputs: |
|
172 | 172 | |
|
173 | 173 | - slices: the set of slices is given as a list of strings (like |
|
174 | 174 | ['1','4:8','9'], since this function is for use by magic functions |
|
175 | 175 | which get their arguments as strings. |
|
176 | 176 | |
|
177 | 177 | Optional inputs: |
|
178 | 178 | |
|
179 | 179 | - raw(False): by default, the processed input is used. If this is |
|
180 | 180 | true, the raw input history is used instead. |
|
181 | 181 | |
|
182 | 182 | Note that slices can be called with two notations: |
|
183 | 183 | |
|
184 | 184 | N:M -> standard python form, means including items N...(M-1). |
|
185 | 185 | |
|
186 | 186 | N-M -> include items N..M (closed endpoint).""" |
|
187 | 187 | |
|
188 | 188 | if raw: |
|
189 | 189 | hist = self.shell.history_manager.input_hist_raw |
|
190 | 190 | else: |
|
191 | 191 | hist = self.shell.history_manager.input_hist_parsed |
|
192 | 192 | |
|
193 | 193 | cmds = [] |
|
194 | 194 | for chunk in slices: |
|
195 | 195 | if ':' in chunk: |
|
196 | 196 | ini,fin = map(int,chunk.split(':')) |
|
197 | 197 | elif '-' in chunk: |
|
198 | 198 | ini,fin = map(int,chunk.split('-')) |
|
199 | 199 | fin += 1 |
|
200 | 200 | else: |
|
201 | 201 | ini = int(chunk) |
|
202 | 202 | fin = ini+1 |
|
203 | 203 | cmds.append(''.join(hist[ini:fin])) |
|
204 | 204 | return cmds |
|
205 | 205 | |
|
206 | 206 | def arg_err(self,func): |
|
207 | 207 | """Print docstring if incorrect arguments were passed""" |
|
208 | 208 | print 'Error in arguments:' |
|
209 | 209 | print oinspect.getdoc(func) |
|
210 | 210 | |
|
211 | 211 | def format_latex(self,strng): |
|
212 | 212 | """Format a string for latex inclusion.""" |
|
213 | 213 | |
|
214 | 214 | # Characters that need to be escaped for latex: |
|
215 | 215 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
216 | 216 | # Magic command names as headers: |
|
217 | 217 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
218 | 218 | re.MULTILINE) |
|
219 | 219 | # Magic commands |
|
220 | 220 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
221 | 221 | re.MULTILINE) |
|
222 | 222 | # Paragraph continue |
|
223 | 223 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
224 | 224 | |
|
225 | 225 | # The "\n" symbol |
|
226 | 226 | newline_re = re.compile(r'\\n') |
|
227 | 227 | |
|
228 | 228 | # Now build the string for output: |
|
229 | 229 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
230 | 230 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
231 | 231 | strng) |
|
232 | 232 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
233 | 233 | strng = par_re.sub(r'\\\\',strng) |
|
234 | 234 | strng = escape_re.sub(r'\\\1',strng) |
|
235 | 235 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
236 | 236 | return strng |
|
237 | 237 | |
|
238 | 238 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
239 | 239 | """Parse options passed to an argument string. |
|
240 | 240 | |
|
241 | 241 | The interface is similar to that of getopt(), but it returns back a |
|
242 | 242 | Struct with the options as keys and the stripped argument string still |
|
243 | 243 | as a string. |
|
244 | 244 | |
|
245 | 245 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
246 | 246 | This allows us to easily expand variables, glob files, quote |
|
247 | 247 | arguments, etc. |
|
248 | 248 | |
|
249 | 249 | Options: |
|
250 | 250 | -mode: default 'string'. If given as 'list', the argument string is |
|
251 | 251 | returned as a list (split on whitespace) instead of a string. |
|
252 | 252 | |
|
253 | 253 | -list_all: put all option values in lists. Normally only options |
|
254 | 254 | appearing more than once are put in a list. |
|
255 | 255 | |
|
256 | 256 | -posix (True): whether to split the input line in POSIX mode or not, |
|
257 | 257 | as per the conventions outlined in the shlex module from the |
|
258 | 258 | standard library.""" |
|
259 | 259 | |
|
260 | 260 | # inject default options at the beginning of the input line |
|
261 | 261 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
262 | 262 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
263 | 263 | |
|
264 | 264 | mode = kw.get('mode','string') |
|
265 | 265 | if mode not in ['string','list']: |
|
266 | 266 | raise ValueError,'incorrect mode given: %s' % mode |
|
267 | 267 | # Get options |
|
268 | 268 | list_all = kw.get('list_all',0) |
|
269 | 269 | posix = kw.get('posix', os.name == 'posix') |
|
270 | 270 | |
|
271 | 271 | # Check if we have more than one argument to warrant extra processing: |
|
272 | 272 | odict = {} # Dictionary with options |
|
273 | 273 | args = arg_str.split() |
|
274 | 274 | if len(args) >= 1: |
|
275 | 275 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
276 | 276 | # need to look for options |
|
277 | 277 | argv = arg_split(arg_str,posix) |
|
278 | 278 | # Do regular option processing |
|
279 | 279 | try: |
|
280 | 280 | opts,args = getopt(argv,opt_str,*long_opts) |
|
281 | 281 | except GetoptError,e: |
|
282 | 282 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
283 | 283 | " ".join(long_opts))) |
|
284 | 284 | for o,a in opts: |
|
285 | 285 | if o.startswith('--'): |
|
286 | 286 | o = o[2:] |
|
287 | 287 | else: |
|
288 | 288 | o = o[1:] |
|
289 | 289 | try: |
|
290 | 290 | odict[o].append(a) |
|
291 | 291 | except AttributeError: |
|
292 | 292 | odict[o] = [odict[o],a] |
|
293 | 293 | except KeyError: |
|
294 | 294 | if list_all: |
|
295 | 295 | odict[o] = [a] |
|
296 | 296 | else: |
|
297 | 297 | odict[o] = a |
|
298 | 298 | |
|
299 | 299 | # Prepare opts,args for return |
|
300 | 300 | opts = Struct(odict) |
|
301 | 301 | if mode == 'string': |
|
302 | 302 | args = ' '.join(args) |
|
303 | 303 | |
|
304 | 304 | return opts,args |
|
305 | 305 | |
|
306 | 306 | #...................................................................... |
|
307 | 307 | # And now the actual magic functions |
|
308 | 308 | |
|
309 | 309 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
310 | 310 | def magic_lsmagic(self, parameter_s = ''): |
|
311 | 311 | """List currently available magic functions.""" |
|
312 | 312 | mesc = ESC_MAGIC |
|
313 | 313 | print 'Available magic functions:\n'+mesc+\ |
|
314 | 314 | (' '+mesc).join(self.lsmagic()) |
|
315 | 315 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
316 | 316 | return None |
|
317 | 317 | |
|
318 | 318 | def magic_magic(self, parameter_s = ''): |
|
319 | 319 | """Print information about the magic function system. |
|
320 | 320 | |
|
321 | 321 | Supported formats: -latex, -brief, -rest |
|
322 | 322 | """ |
|
323 | 323 | |
|
324 | 324 | mode = '' |
|
325 | 325 | try: |
|
326 | 326 | if parameter_s.split()[0] == '-latex': |
|
327 | 327 | mode = 'latex' |
|
328 | 328 | if parameter_s.split()[0] == '-brief': |
|
329 | 329 | mode = 'brief' |
|
330 | 330 | if parameter_s.split()[0] == '-rest': |
|
331 | 331 | mode = 'rest' |
|
332 | 332 | rest_docs = [] |
|
333 | 333 | except: |
|
334 | 334 | pass |
|
335 | 335 | |
|
336 | 336 | magic_docs = [] |
|
337 | 337 | for fname in self.lsmagic(): |
|
338 | 338 | mname = 'magic_' + fname |
|
339 | 339 | for space in (Magic,self,self.__class__): |
|
340 | 340 | try: |
|
341 | 341 | fn = space.__dict__[mname] |
|
342 | 342 | except KeyError: |
|
343 | 343 | pass |
|
344 | 344 | else: |
|
345 | 345 | break |
|
346 | 346 | if mode == 'brief': |
|
347 | 347 | # only first line |
|
348 | 348 | if fn.__doc__: |
|
349 | 349 | fndoc = fn.__doc__.split('\n',1)[0] |
|
350 | 350 | else: |
|
351 | 351 | fndoc = 'No documentation' |
|
352 | 352 | else: |
|
353 | 353 | if fn.__doc__: |
|
354 | 354 | fndoc = fn.__doc__.rstrip() |
|
355 | 355 | else: |
|
356 | 356 | fndoc = 'No documentation' |
|
357 | 357 | |
|
358 | 358 | |
|
359 | 359 | if mode == 'rest': |
|
360 | 360 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
361 | 361 | fname,fndoc)) |
|
362 | 362 | |
|
363 | 363 | else: |
|
364 | 364 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
365 | 365 | fname,fndoc)) |
|
366 | 366 | |
|
367 | 367 | magic_docs = ''.join(magic_docs) |
|
368 | 368 | |
|
369 | 369 | if mode == 'rest': |
|
370 | 370 | return "".join(rest_docs) |
|
371 | 371 | |
|
372 | 372 | if mode == 'latex': |
|
373 | 373 | print self.format_latex(magic_docs) |
|
374 | 374 | return |
|
375 | 375 | else: |
|
376 | 376 | magic_docs = format_screen(magic_docs) |
|
377 | 377 | if mode == 'brief': |
|
378 | 378 | return magic_docs |
|
379 | 379 | |
|
380 | 380 | outmsg = """ |
|
381 | 381 | IPython's 'magic' functions |
|
382 | 382 | =========================== |
|
383 | 383 | |
|
384 | 384 | The magic function system provides a series of functions which allow you to |
|
385 | 385 | control the behavior of IPython itself, plus a lot of system-type |
|
386 | 386 | features. All these functions are prefixed with a % character, but parameters |
|
387 | 387 | are given without parentheses or quotes. |
|
388 | 388 | |
|
389 | 389 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
390 | 390 | %automagic function), you don't need to type in the % explicitly. By default, |
|
391 | 391 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
392 | 392 | |
|
393 | 393 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
394 | 394 | to 'mydir', if it exists. |
|
395 | 395 | |
|
396 | 396 | You can define your own magic functions to extend the system. See the supplied |
|
397 | 397 | ipythonrc and example-magic.py files for details (in your ipython |
|
398 | configuration directory, typically $HOME/.ipython/). | |
|
398 | configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere). | |
|
399 | 399 | |
|
400 | 400 | You can also define your own aliased names for magic functions. In your |
|
401 | 401 | ipythonrc file, placing a line like: |
|
402 | 402 | |
|
403 | 403 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
404 | 404 | |
|
405 | 405 | will define %pf as a new name for %profile. |
|
406 | 406 | |
|
407 | 407 | You can also call magics in code using the magic() function, which IPython |
|
408 | 408 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
409 | 409 | |
|
410 | 410 | For a list of the available magic functions, use %lsmagic. For a description |
|
411 | 411 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
412 | 412 | |
|
413 | 413 | Currently the magic system has the following functions:\n""" |
|
414 | 414 | |
|
415 | 415 | mesc = ESC_MAGIC |
|
416 | 416 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
417 | 417 | "\n\n%s%s\n\n%s" % (outmsg, |
|
418 | 418 | magic_docs,mesc,mesc, |
|
419 | 419 | (' '+mesc).join(self.lsmagic()), |
|
420 | 420 | Magic.auto_status[self.shell.automagic] ) ) |
|
421 | 421 | page.page(outmsg) |
|
422 | 422 | |
|
423 | 423 | def magic_automagic(self, parameter_s = ''): |
|
424 | 424 | """Make magic functions callable without having to type the initial %. |
|
425 | 425 | |
|
426 | 426 | Without argumentsl toggles on/off (when off, you must call it as |
|
427 | 427 | %automagic, of course). With arguments it sets the value, and you can |
|
428 | 428 | use any of (case insensitive): |
|
429 | 429 | |
|
430 | 430 | - on,1,True: to activate |
|
431 | 431 | |
|
432 | 432 | - off,0,False: to deactivate. |
|
433 | 433 | |
|
434 | 434 | Note that magic functions have lowest priority, so if there's a |
|
435 | 435 | variable whose name collides with that of a magic fn, automagic won't |
|
436 | 436 | work for that function (you get the variable instead). However, if you |
|
437 | 437 | delete the variable (del var), the previously shadowed magic function |
|
438 | 438 | becomes visible to automagic again.""" |
|
439 | 439 | |
|
440 | 440 | arg = parameter_s.lower() |
|
441 | 441 | if parameter_s in ('on','1','true'): |
|
442 | 442 | self.shell.automagic = True |
|
443 | 443 | elif parameter_s in ('off','0','false'): |
|
444 | 444 | self.shell.automagic = False |
|
445 | 445 | else: |
|
446 | 446 | self.shell.automagic = not self.shell.automagic |
|
447 | 447 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
448 | 448 | |
|
449 | 449 | @testdec.skip_doctest |
|
450 | 450 | def magic_autocall(self, parameter_s = ''): |
|
451 | 451 | """Make functions callable without having to type parentheses. |
|
452 | 452 | |
|
453 | 453 | Usage: |
|
454 | 454 | |
|
455 | 455 | %autocall [mode] |
|
456 | 456 | |
|
457 | 457 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
458 | 458 | value is toggled on and off (remembering the previous state). |
|
459 | 459 | |
|
460 | 460 | In more detail, these values mean: |
|
461 | 461 | |
|
462 | 462 | 0 -> fully disabled |
|
463 | 463 | |
|
464 | 464 | 1 -> active, but do not apply if there are no arguments on the line. |
|
465 | 465 | |
|
466 | 466 | In this mode, you get: |
|
467 | 467 | |
|
468 | 468 | In [1]: callable |
|
469 | 469 | Out[1]: <built-in function callable> |
|
470 | 470 | |
|
471 | 471 | In [2]: callable 'hello' |
|
472 | 472 | ------> callable('hello') |
|
473 | 473 | Out[2]: False |
|
474 | 474 | |
|
475 | 475 | 2 -> Active always. Even if no arguments are present, the callable |
|
476 | 476 | object is called: |
|
477 | 477 | |
|
478 | 478 | In [2]: float |
|
479 | 479 | ------> float() |
|
480 | 480 | Out[2]: 0.0 |
|
481 | 481 | |
|
482 | 482 | Note that even with autocall off, you can still use '/' at the start of |
|
483 | 483 | a line to treat the first argument on the command line as a function |
|
484 | 484 | and add parentheses to it: |
|
485 | 485 | |
|
486 | 486 | In [8]: /str 43 |
|
487 | 487 | ------> str(43) |
|
488 | 488 | Out[8]: '43' |
|
489 | 489 | |
|
490 | 490 | # all-random (note for auto-testing) |
|
491 | 491 | """ |
|
492 | 492 | |
|
493 | 493 | if parameter_s: |
|
494 | 494 | arg = int(parameter_s) |
|
495 | 495 | else: |
|
496 | 496 | arg = 'toggle' |
|
497 | 497 | |
|
498 | 498 | if not arg in (0,1,2,'toggle'): |
|
499 | 499 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
500 | 500 | return |
|
501 | 501 | |
|
502 | 502 | if arg in (0,1,2): |
|
503 | 503 | self.shell.autocall = arg |
|
504 | 504 | else: # toggle |
|
505 | 505 | if self.shell.autocall: |
|
506 | 506 | self._magic_state.autocall_save = self.shell.autocall |
|
507 | 507 | self.shell.autocall = 0 |
|
508 | 508 | else: |
|
509 | 509 | try: |
|
510 | 510 | self.shell.autocall = self._magic_state.autocall_save |
|
511 | 511 | except AttributeError: |
|
512 | 512 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
513 | 513 | |
|
514 | 514 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
515 | 515 | |
|
516 | 516 | |
|
517 | 517 | def magic_page(self, parameter_s=''): |
|
518 | 518 | """Pretty print the object and display it through a pager. |
|
519 | 519 | |
|
520 | 520 | %page [options] OBJECT |
|
521 | 521 | |
|
522 | 522 | If no object is given, use _ (last output). |
|
523 | 523 | |
|
524 | 524 | Options: |
|
525 | 525 | |
|
526 | 526 | -r: page str(object), don't pretty-print it.""" |
|
527 | 527 | |
|
528 | 528 | # After a function contributed by Olivier Aubert, slightly modified. |
|
529 | 529 | |
|
530 | 530 | # Process options/args |
|
531 | 531 | opts,args = self.parse_options(parameter_s,'r') |
|
532 | 532 | raw = 'r' in opts |
|
533 | 533 | |
|
534 | 534 | oname = args and args or '_' |
|
535 | 535 | info = self._ofind(oname) |
|
536 | 536 | if info['found']: |
|
537 | 537 | txt = (raw and str or pformat)( info['obj'] ) |
|
538 | 538 | page.page(txt) |
|
539 | 539 | else: |
|
540 | 540 | print 'Object `%s` not found' % oname |
|
541 | 541 | |
|
542 | 542 | def magic_profile(self, parameter_s=''): |
|
543 | 543 | """Print your currently active IPython profile.""" |
|
544 | 544 | if self.shell.profile: |
|
545 | 545 | printpl('Current IPython profile: $self.shell.profile.') |
|
546 | 546 | else: |
|
547 | 547 | print 'No profile active.' |
|
548 | 548 | |
|
549 | 549 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
550 | 550 | """Provide detailed information about an object. |
|
551 | 551 | |
|
552 | 552 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
553 | 553 | |
|
554 | 554 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
555 | 555 | |
|
556 | 556 | |
|
557 | 557 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
558 | 558 | detail_level = 0 |
|
559 | 559 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
560 | 560 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
561 | 561 | pinfo,qmark1,oname,qmark2 = \ |
|
562 | 562 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
563 | 563 | if pinfo or qmark1 or qmark2: |
|
564 | 564 | detail_level = 1 |
|
565 | 565 | if "*" in oname: |
|
566 | 566 | self.magic_psearch(oname) |
|
567 | 567 | else: |
|
568 | 568 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
569 | 569 | namespaces=namespaces) |
|
570 | 570 | |
|
571 | 571 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
572 | 572 | """Provide extra detailed information about an object. |
|
573 | 573 | |
|
574 | 574 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
575 | 575 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
576 | 576 | namespaces=namespaces) |
|
577 | 577 | |
|
578 | 578 | @testdec.skip_doctest |
|
579 | 579 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
580 | 580 | """Print the definition header for any callable object. |
|
581 | 581 | |
|
582 | 582 | If the object is a class, print the constructor information. |
|
583 | 583 | |
|
584 | 584 | Examples |
|
585 | 585 | -------- |
|
586 | 586 | :: |
|
587 | 587 | |
|
588 | 588 | In [3]: %pdef urllib.urlopen |
|
589 | 589 | urllib.urlopen(url, data=None, proxies=None) |
|
590 | 590 | """ |
|
591 | 591 | self._inspect('pdef',parameter_s, namespaces) |
|
592 | 592 | |
|
593 | 593 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
594 | 594 | """Print the docstring for an object. |
|
595 | 595 | |
|
596 | 596 | If the given object is a class, it will print both the class and the |
|
597 | 597 | constructor docstrings.""" |
|
598 | 598 | self._inspect('pdoc',parameter_s, namespaces) |
|
599 | 599 | |
|
600 | 600 | def magic_psource(self, parameter_s='', namespaces=None): |
|
601 | 601 | """Print (or run through pager) the source code for an object.""" |
|
602 | 602 | self._inspect('psource',parameter_s, namespaces) |
|
603 | 603 | |
|
604 | 604 | def magic_pfile(self, parameter_s=''): |
|
605 | 605 | """Print (or run through pager) the file where an object is defined. |
|
606 | 606 | |
|
607 | 607 | The file opens at the line where the object definition begins. IPython |
|
608 | 608 | will honor the environment variable PAGER if set, and otherwise will |
|
609 | 609 | do its best to print the file in a convenient form. |
|
610 | 610 | |
|
611 | 611 | If the given argument is not an object currently defined, IPython will |
|
612 | 612 | try to interpret it as a filename (automatically adding a .py extension |
|
613 | 613 | if needed). You can thus use %pfile as a syntax highlighting code |
|
614 | 614 | viewer.""" |
|
615 | 615 | |
|
616 | 616 | # first interpret argument as an object name |
|
617 | 617 | out = self._inspect('pfile',parameter_s) |
|
618 | 618 | # if not, try the input as a filename |
|
619 | 619 | if out == 'not found': |
|
620 | 620 | try: |
|
621 | 621 | filename = get_py_filename(parameter_s) |
|
622 | 622 | except IOError,msg: |
|
623 | 623 | print msg |
|
624 | 624 | return |
|
625 | 625 | page.page(self.shell.inspector.format(file(filename).read())) |
|
626 | 626 | |
|
627 | 627 | def magic_psearch(self, parameter_s=''): |
|
628 | 628 | """Search for object in namespaces by wildcard. |
|
629 | 629 | |
|
630 | 630 | %psearch [options] PATTERN [OBJECT TYPE] |
|
631 | 631 | |
|
632 | 632 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
633 | 633 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
634 | 634 | rest of the command line must be unchanged (options come first), so |
|
635 | 635 | for example the following forms are equivalent |
|
636 | 636 | |
|
637 | 637 | %psearch -i a* function |
|
638 | 638 | -i a* function? |
|
639 | 639 | ?-i a* function |
|
640 | 640 | |
|
641 | 641 | Arguments: |
|
642 | 642 | |
|
643 | 643 | PATTERN |
|
644 | 644 | |
|
645 | 645 | where PATTERN is a string containing * as a wildcard similar to its |
|
646 | 646 | use in a shell. The pattern is matched in all namespaces on the |
|
647 | 647 | search path. By default objects starting with a single _ are not |
|
648 | 648 | matched, many IPython generated objects have a single |
|
649 | 649 | underscore. The default is case insensitive matching. Matching is |
|
650 | 650 | also done on the attributes of objects and not only on the objects |
|
651 | 651 | in a module. |
|
652 | 652 | |
|
653 | 653 | [OBJECT TYPE] |
|
654 | 654 | |
|
655 | 655 | Is the name of a python type from the types module. The name is |
|
656 | 656 | given in lowercase without the ending type, ex. StringType is |
|
657 | 657 | written string. By adding a type here only objects matching the |
|
658 | 658 | given type are matched. Using all here makes the pattern match all |
|
659 | 659 | types (this is the default). |
|
660 | 660 | |
|
661 | 661 | Options: |
|
662 | 662 | |
|
663 | 663 | -a: makes the pattern match even objects whose names start with a |
|
664 | 664 | single underscore. These names are normally ommitted from the |
|
665 | 665 | search. |
|
666 | 666 | |
|
667 | 667 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
668 | 668 | these options is given, the default is read from your ipythonrc |
|
669 | 669 | file. The option name which sets this value is |
|
670 | 670 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
671 | 671 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
672 | 672 | search. |
|
673 | 673 | |
|
674 | 674 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
675 | 675 | specifiy can be searched in any of the following namespaces: |
|
676 | 676 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
677 | 677 | 'builtin' and 'user' are the search defaults. Note that you should |
|
678 | 678 | not use quotes when specifying namespaces. |
|
679 | 679 | |
|
680 | 680 | 'Builtin' contains the python module builtin, 'user' contains all |
|
681 | 681 | user data, 'alias' only contain the shell aliases and no python |
|
682 | 682 | objects, 'internal' contains objects used by IPython. The |
|
683 | 683 | 'user_global' namespace is only used by embedded IPython instances, |
|
684 | 684 | and it contains module-level globals. You can add namespaces to the |
|
685 | 685 | search with -s or exclude them with -e (these options can be given |
|
686 | 686 | more than once). |
|
687 | 687 | |
|
688 | 688 | Examples: |
|
689 | 689 | |
|
690 | 690 | %psearch a* -> objects beginning with an a |
|
691 | 691 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
692 | 692 | %psearch a* function -> all functions beginning with an a |
|
693 | 693 | %psearch re.e* -> objects beginning with an e in module re |
|
694 | 694 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
695 | 695 | %psearch r*.* string -> all strings in modules beginning with r |
|
696 | 696 | |
|
697 | 697 | Case sensitve search: |
|
698 | 698 | |
|
699 | 699 | %psearch -c a* list all object beginning with lower case a |
|
700 | 700 | |
|
701 | 701 | Show objects beginning with a single _: |
|
702 | 702 | |
|
703 | 703 | %psearch -a _* list objects beginning with a single underscore""" |
|
704 | 704 | try: |
|
705 | 705 | parameter_s = parameter_s.encode('ascii') |
|
706 | 706 | except UnicodeEncodeError: |
|
707 | 707 | print 'Python identifiers can only contain ascii characters.' |
|
708 | 708 | return |
|
709 | 709 | |
|
710 | 710 | # default namespaces to be searched |
|
711 | 711 | def_search = ['user','builtin'] |
|
712 | 712 | |
|
713 | 713 | # Process options/args |
|
714 | 714 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
715 | 715 | opt = opts.get |
|
716 | 716 | shell = self.shell |
|
717 | 717 | psearch = shell.inspector.psearch |
|
718 | 718 | |
|
719 | 719 | # select case options |
|
720 | 720 | if opts.has_key('i'): |
|
721 | 721 | ignore_case = True |
|
722 | 722 | elif opts.has_key('c'): |
|
723 | 723 | ignore_case = False |
|
724 | 724 | else: |
|
725 | 725 | ignore_case = not shell.wildcards_case_sensitive |
|
726 | 726 | |
|
727 | 727 | # Build list of namespaces to search from user options |
|
728 | 728 | def_search.extend(opt('s',[])) |
|
729 | 729 | ns_exclude = ns_exclude=opt('e',[]) |
|
730 | 730 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
731 | 731 | |
|
732 | 732 | # Call the actual search |
|
733 | 733 | try: |
|
734 | 734 | psearch(args,shell.ns_table,ns_search, |
|
735 | 735 | show_all=opt('a'),ignore_case=ignore_case) |
|
736 | 736 | except: |
|
737 | 737 | shell.showtraceback() |
|
738 | 738 | |
|
739 | 739 | @testdec.skip_doctest |
|
740 | 740 | def magic_who_ls(self, parameter_s=''): |
|
741 | 741 | """Return a sorted list of all interactive variables. |
|
742 | 742 | |
|
743 | 743 | If arguments are given, only variables of types matching these |
|
744 | 744 | arguments are returned. |
|
745 | 745 | |
|
746 | 746 | Examples |
|
747 | 747 | -------- |
|
748 | 748 | |
|
749 | 749 | Define two variables and list them with who_ls:: |
|
750 | 750 | |
|
751 | 751 | In [1]: alpha = 123 |
|
752 | 752 | |
|
753 | 753 | In [2]: beta = 'test' |
|
754 | 754 | |
|
755 | 755 | In [3]: %who_ls |
|
756 | 756 | Out[3]: ['alpha', 'beta'] |
|
757 | 757 | |
|
758 | 758 | In [4]: %who_ls int |
|
759 | 759 | Out[4]: ['alpha'] |
|
760 | 760 | |
|
761 | 761 | In [5]: %who_ls str |
|
762 | 762 | Out[5]: ['beta'] |
|
763 | 763 | """ |
|
764 | 764 | |
|
765 | 765 | user_ns = self.shell.user_ns |
|
766 | 766 | internal_ns = self.shell.internal_ns |
|
767 | 767 | user_ns_hidden = self.shell.user_ns_hidden |
|
768 | 768 | out = [ i for i in user_ns |
|
769 | 769 | if not i.startswith('_') \ |
|
770 | 770 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
771 | 771 | |
|
772 | 772 | typelist = parameter_s.split() |
|
773 | 773 | if typelist: |
|
774 | 774 | typeset = set(typelist) |
|
775 | 775 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
776 | 776 | |
|
777 | 777 | out.sort() |
|
778 | 778 | return out |
|
779 | 779 | |
|
780 | 780 | @testdec.skip_doctest |
|
781 | 781 | def magic_who(self, parameter_s=''): |
|
782 | 782 | """Print all interactive variables, with some minimal formatting. |
|
783 | 783 | |
|
784 | 784 | If any arguments are given, only variables whose type matches one of |
|
785 | 785 | these are printed. For example: |
|
786 | 786 | |
|
787 | 787 | %who function str |
|
788 | 788 | |
|
789 | 789 | will only list functions and strings, excluding all other types of |
|
790 | 790 | variables. To find the proper type names, simply use type(var) at a |
|
791 | 791 | command line to see how python prints type names. For example: |
|
792 | 792 | |
|
793 | 793 | In [1]: type('hello')\\ |
|
794 | 794 | Out[1]: <type 'str'> |
|
795 | 795 | |
|
796 | 796 | indicates that the type name for strings is 'str'. |
|
797 | 797 | |
|
798 | 798 | %who always excludes executed names loaded through your configuration |
|
799 | 799 | file and things which are internal to IPython. |
|
800 | 800 | |
|
801 | 801 | This is deliberate, as typically you may load many modules and the |
|
802 | 802 | purpose of %who is to show you only what you've manually defined. |
|
803 | 803 | |
|
804 | 804 | Examples |
|
805 | 805 | -------- |
|
806 | 806 | |
|
807 | 807 | Define two variables and list them with who:: |
|
808 | 808 | |
|
809 | 809 | In [1]: alpha = 123 |
|
810 | 810 | |
|
811 | 811 | In [2]: beta = 'test' |
|
812 | 812 | |
|
813 | 813 | In [3]: %who |
|
814 | 814 | alpha beta |
|
815 | 815 | |
|
816 | 816 | In [4]: %who int |
|
817 | 817 | alpha |
|
818 | 818 | |
|
819 | 819 | In [5]: %who str |
|
820 | 820 | beta |
|
821 | 821 | """ |
|
822 | 822 | |
|
823 | 823 | varlist = self.magic_who_ls(parameter_s) |
|
824 | 824 | if not varlist: |
|
825 | 825 | if parameter_s: |
|
826 | 826 | print 'No variables match your requested type.' |
|
827 | 827 | else: |
|
828 | 828 | print 'Interactive namespace is empty.' |
|
829 | 829 | return |
|
830 | 830 | |
|
831 | 831 | # if we have variables, move on... |
|
832 | 832 | count = 0 |
|
833 | 833 | for i in varlist: |
|
834 | 834 | print i+'\t', |
|
835 | 835 | count += 1 |
|
836 | 836 | if count > 8: |
|
837 | 837 | count = 0 |
|
838 | 838 | |
|
839 | 839 | |
|
840 | 840 | |
|
841 | 841 | @testdec.skip_doctest |
|
842 | 842 | def magic_whos(self, parameter_s=''): |
|
843 | 843 | """Like %who, but gives some extra information about each variable. |
|
844 | 844 | |
|
845 | 845 | The same type filtering of %who can be applied here. |
|
846 | 846 | |
|
847 | 847 | For all variables, the type is printed. Additionally it prints: |
|
848 | 848 | |
|
849 | 849 | - For {},[],(): their length. |
|
850 | 850 | |
|
851 | 851 | - For numpy and Numeric arrays, a summary with shape, number of |
|
852 | 852 | elements, typecode and size in memory. |
|
853 | 853 | |
|
854 | 854 | - Everything else: a string representation, snipping their middle if |
|
855 | 855 | too long. |
|
856 | 856 | |
|
857 | 857 | Examples |
|
858 | 858 | -------- |
|
859 | 859 | |
|
860 | 860 | Define two variables and list them with whos:: |
|
861 | 861 | |
|
862 | 862 | In [1]: alpha = 123 |
|
863 | 863 | |
|
864 | 864 | In [2]: beta = 'test' |
|
865 | 865 | |
|
866 | 866 | In [3]: %whos |
|
867 | 867 | Variable Type Data/Info |
|
868 | 868 | -------------------------------- |
|
869 | 869 | alpha int 123 |
|
870 | 870 | beta str test |
|
871 | 871 | """ |
|
872 | 872 | |
|
873 | 873 | varnames = self.magic_who_ls(parameter_s) |
|
874 | 874 | if not varnames: |
|
875 | 875 | if parameter_s: |
|
876 | 876 | print 'No variables match your requested type.' |
|
877 | 877 | else: |
|
878 | 878 | print 'Interactive namespace is empty.' |
|
879 | 879 | return |
|
880 | 880 | |
|
881 | 881 | # if we have variables, move on... |
|
882 | 882 | |
|
883 | 883 | # for these types, show len() instead of data: |
|
884 | 884 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
885 | 885 | |
|
886 | 886 | # for numpy/Numeric arrays, display summary info |
|
887 | 887 | try: |
|
888 | 888 | import numpy |
|
889 | 889 | except ImportError: |
|
890 | 890 | ndarray_type = None |
|
891 | 891 | else: |
|
892 | 892 | ndarray_type = numpy.ndarray.__name__ |
|
893 | 893 | try: |
|
894 | 894 | import Numeric |
|
895 | 895 | except ImportError: |
|
896 | 896 | array_type = None |
|
897 | 897 | else: |
|
898 | 898 | array_type = Numeric.ArrayType.__name__ |
|
899 | 899 | |
|
900 | 900 | # Find all variable names and types so we can figure out column sizes |
|
901 | 901 | def get_vars(i): |
|
902 | 902 | return self.shell.user_ns[i] |
|
903 | 903 | |
|
904 | 904 | # some types are well known and can be shorter |
|
905 | 905 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
906 | 906 | def type_name(v): |
|
907 | 907 | tn = type(v).__name__ |
|
908 | 908 | return abbrevs.get(tn,tn) |
|
909 | 909 | |
|
910 | 910 | varlist = map(get_vars,varnames) |
|
911 | 911 | |
|
912 | 912 | typelist = [] |
|
913 | 913 | for vv in varlist: |
|
914 | 914 | tt = type_name(vv) |
|
915 | 915 | |
|
916 | 916 | if tt=='instance': |
|
917 | 917 | typelist.append( abbrevs.get(str(vv.__class__), |
|
918 | 918 | str(vv.__class__))) |
|
919 | 919 | else: |
|
920 | 920 | typelist.append(tt) |
|
921 | 921 | |
|
922 | 922 | # column labels and # of spaces as separator |
|
923 | 923 | varlabel = 'Variable' |
|
924 | 924 | typelabel = 'Type' |
|
925 | 925 | datalabel = 'Data/Info' |
|
926 | 926 | colsep = 3 |
|
927 | 927 | # variable format strings |
|
928 | 928 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
929 | 929 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
930 | 930 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
931 | 931 | # find the size of the columns to format the output nicely |
|
932 | 932 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
933 | 933 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
934 | 934 | # table header |
|
935 | 935 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
936 | 936 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
937 | 937 | # and the table itself |
|
938 | 938 | kb = 1024 |
|
939 | 939 | Mb = 1048576 # kb**2 |
|
940 | 940 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
941 | 941 | print itpl(vformat), |
|
942 | 942 | if vtype in seq_types: |
|
943 | 943 | print len(var) |
|
944 | 944 | elif vtype in [array_type,ndarray_type]: |
|
945 | 945 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
946 | 946 | if vtype==ndarray_type: |
|
947 | 947 | # numpy |
|
948 | 948 | vsize = var.size |
|
949 | 949 | vbytes = vsize*var.itemsize |
|
950 | 950 | vdtype = var.dtype |
|
951 | 951 | else: |
|
952 | 952 | # Numeric |
|
953 | 953 | vsize = Numeric.size(var) |
|
954 | 954 | vbytes = vsize*var.itemsize() |
|
955 | 955 | vdtype = var.typecode() |
|
956 | 956 | |
|
957 | 957 | if vbytes < 100000: |
|
958 | 958 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
959 | 959 | else: |
|
960 | 960 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
961 | 961 | if vbytes < Mb: |
|
962 | 962 | print '(%s kb)' % (vbytes/kb,) |
|
963 | 963 | else: |
|
964 | 964 | print '(%s Mb)' % (vbytes/Mb,) |
|
965 | 965 | else: |
|
966 | 966 | try: |
|
967 | 967 | vstr = str(var) |
|
968 | 968 | except UnicodeEncodeError: |
|
969 | 969 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
970 | 970 | 'backslashreplace') |
|
971 | 971 | vstr = vstr.replace('\n','\\n') |
|
972 | 972 | if len(vstr) < 50: |
|
973 | 973 | print vstr |
|
974 | 974 | else: |
|
975 | 975 | printpl(vfmt_short) |
|
976 | 976 | |
|
977 | 977 | def magic_reset(self, parameter_s=''): |
|
978 | 978 | """Resets the namespace by removing all names defined by the user. |
|
979 | 979 | |
|
980 | 980 | Input/Output history are left around in case you need them. |
|
981 | 981 | |
|
982 | 982 | Parameters |
|
983 | 983 | ---------- |
|
984 | 984 | -y : force reset without asking for confirmation. |
|
985 | 985 | |
|
986 | 986 | Examples |
|
987 | 987 | -------- |
|
988 | 988 | In [6]: a = 1 |
|
989 | 989 | |
|
990 | 990 | In [7]: a |
|
991 | 991 | Out[7]: 1 |
|
992 | 992 | |
|
993 | 993 | In [8]: 'a' in _ip.user_ns |
|
994 | 994 | Out[8]: True |
|
995 | 995 | |
|
996 | 996 | In [9]: %reset -f |
|
997 | 997 | |
|
998 | 998 | In [10]: 'a' in _ip.user_ns |
|
999 | 999 | Out[10]: False |
|
1000 | 1000 | """ |
|
1001 | 1001 | |
|
1002 | 1002 | if parameter_s == '-f': |
|
1003 | 1003 | ans = True |
|
1004 | 1004 | else: |
|
1005 | 1005 | ans = self.shell.ask_yes_no( |
|
1006 | 1006 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1007 | 1007 | if not ans: |
|
1008 | 1008 | print 'Nothing done.' |
|
1009 | 1009 | return |
|
1010 | 1010 | user_ns = self.shell.user_ns |
|
1011 | 1011 | for i in self.magic_who_ls(): |
|
1012 | 1012 | del(user_ns[i]) |
|
1013 | 1013 | |
|
1014 | 1014 | # Also flush the private list of module references kept for script |
|
1015 | 1015 | # execution protection |
|
1016 | 1016 | self.shell.clear_main_mod_cache() |
|
1017 | 1017 | |
|
1018 | 1018 | def magic_reset_selective(self, parameter_s=''): |
|
1019 | 1019 | """Resets the namespace by removing names defined by the user. |
|
1020 | 1020 | |
|
1021 | 1021 | Input/Output history are left around in case you need them. |
|
1022 | 1022 | |
|
1023 | 1023 | %reset_selective [-f] regex |
|
1024 | 1024 | |
|
1025 | 1025 | No action is taken if regex is not included |
|
1026 | 1026 | |
|
1027 | 1027 | Options |
|
1028 | 1028 | -f : force reset without asking for confirmation. |
|
1029 | 1029 | |
|
1030 | 1030 | Examples |
|
1031 | 1031 | -------- |
|
1032 | 1032 | |
|
1033 | 1033 | We first fully reset the namespace so your output looks identical to |
|
1034 | 1034 | this example for pedagogical reasons; in practice you do not need a |
|
1035 | 1035 | full reset. |
|
1036 | 1036 | |
|
1037 | 1037 | In [1]: %reset -f |
|
1038 | 1038 | |
|
1039 | 1039 | Now, with a clean namespace we can make a few variables and use |
|
1040 | 1040 | %reset_selective to only delete names that match our regexp: |
|
1041 | 1041 | |
|
1042 | 1042 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1043 | 1043 | |
|
1044 | 1044 | In [3]: who_ls |
|
1045 | 1045 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1046 | 1046 | |
|
1047 | 1047 | In [4]: %reset_selective -f b[2-3]m |
|
1048 | 1048 | |
|
1049 | 1049 | In [5]: who_ls |
|
1050 | 1050 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1051 | 1051 | |
|
1052 | 1052 | In [6]: %reset_selective -f d |
|
1053 | 1053 | |
|
1054 | 1054 | In [7]: who_ls |
|
1055 | 1055 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1056 | 1056 | |
|
1057 | 1057 | In [8]: %reset_selective -f c |
|
1058 | 1058 | |
|
1059 | 1059 | In [9]: who_ls |
|
1060 | 1060 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1061 | 1061 | |
|
1062 | 1062 | In [10]: %reset_selective -f b |
|
1063 | 1063 | |
|
1064 | 1064 | In [11]: who_ls |
|
1065 | 1065 | Out[11]: ['a'] |
|
1066 | 1066 | """ |
|
1067 | 1067 | |
|
1068 | 1068 | opts, regex = self.parse_options(parameter_s,'f') |
|
1069 | 1069 | |
|
1070 | 1070 | if opts.has_key('f'): |
|
1071 | 1071 | ans = True |
|
1072 | 1072 | else: |
|
1073 | 1073 | ans = self.shell.ask_yes_no( |
|
1074 | 1074 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1075 | 1075 | if not ans: |
|
1076 | 1076 | print 'Nothing done.' |
|
1077 | 1077 | return |
|
1078 | 1078 | user_ns = self.shell.user_ns |
|
1079 | 1079 | if not regex: |
|
1080 | 1080 | print 'No regex pattern specified. Nothing done.' |
|
1081 | 1081 | return |
|
1082 | 1082 | else: |
|
1083 | 1083 | try: |
|
1084 | 1084 | m = re.compile(regex) |
|
1085 | 1085 | except TypeError: |
|
1086 | 1086 | raise TypeError('regex must be a string or compiled pattern') |
|
1087 | 1087 | for i in self.magic_who_ls(): |
|
1088 | 1088 | if m.search(i): |
|
1089 | 1089 | del(user_ns[i]) |
|
1090 | 1090 | |
|
1091 | 1091 | def magic_logstart(self,parameter_s=''): |
|
1092 | 1092 | """Start logging anywhere in a session. |
|
1093 | 1093 | |
|
1094 | 1094 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1095 | 1095 | |
|
1096 | 1096 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1097 | 1097 | current directory, in 'rotate' mode (see below). |
|
1098 | 1098 | |
|
1099 | 1099 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1100 | 1100 | history up to that point and then continues logging. |
|
1101 | 1101 | |
|
1102 | 1102 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1103 | 1103 | of (note that the modes are given unquoted):\\ |
|
1104 | 1104 | append: well, that says it.\\ |
|
1105 | 1105 | backup: rename (if exists) to name~ and start name.\\ |
|
1106 | 1106 | global: single logfile in your home dir, appended to.\\ |
|
1107 | 1107 | over : overwrite existing log.\\ |
|
1108 | 1108 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1109 | 1109 | |
|
1110 | 1110 | Options: |
|
1111 | 1111 | |
|
1112 | 1112 | -o: log also IPython's output. In this mode, all commands which |
|
1113 | 1113 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1114 | 1114 | their corresponding input line. The output lines are always |
|
1115 | 1115 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1116 | 1116 | Python code. |
|
1117 | 1117 | |
|
1118 | 1118 | Since this marker is always the same, filtering only the output from |
|
1119 | 1119 | a log is very easy, using for example a simple awk call: |
|
1120 | 1120 | |
|
1121 | 1121 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1122 | 1122 | |
|
1123 | 1123 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1124 | 1124 | input, so that user lines are logged in their final form, converted |
|
1125 | 1125 | into valid Python. For example, %Exit is logged as |
|
1126 | 1126 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1127 | 1127 | exactly as typed, with no transformations applied. |
|
1128 | 1128 | |
|
1129 | 1129 | -t: put timestamps before each input line logged (these are put in |
|
1130 | 1130 | comments).""" |
|
1131 | 1131 | |
|
1132 | 1132 | opts,par = self.parse_options(parameter_s,'ort') |
|
1133 | 1133 | log_output = 'o' in opts |
|
1134 | 1134 | log_raw_input = 'r' in opts |
|
1135 | 1135 | timestamp = 't' in opts |
|
1136 | 1136 | |
|
1137 | 1137 | logger = self.shell.logger |
|
1138 | 1138 | |
|
1139 | 1139 | # if no args are given, the defaults set in the logger constructor by |
|
1140 | 1140 | # ipytohn remain valid |
|
1141 | 1141 | if par: |
|
1142 | 1142 | try: |
|
1143 | 1143 | logfname,logmode = par.split() |
|
1144 | 1144 | except: |
|
1145 | 1145 | logfname = par |
|
1146 | 1146 | logmode = 'backup' |
|
1147 | 1147 | else: |
|
1148 | 1148 | logfname = logger.logfname |
|
1149 | 1149 | logmode = logger.logmode |
|
1150 | 1150 | # put logfname into rc struct as if it had been called on the command |
|
1151 | 1151 | # line, so it ends up saved in the log header Save it in case we need |
|
1152 | 1152 | # to restore it... |
|
1153 | 1153 | old_logfile = self.shell.logfile |
|
1154 | 1154 | if logfname: |
|
1155 | 1155 | logfname = os.path.expanduser(logfname) |
|
1156 | 1156 | self.shell.logfile = logfname |
|
1157 | 1157 | |
|
1158 | 1158 | loghead = '# IPython log file\n\n' |
|
1159 | 1159 | try: |
|
1160 | 1160 | started = logger.logstart(logfname,loghead,logmode, |
|
1161 | 1161 | log_output,timestamp,log_raw_input) |
|
1162 | 1162 | except: |
|
1163 | 1163 | self.shell.logfile = old_logfile |
|
1164 | 1164 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1165 | 1165 | else: |
|
1166 | 1166 | # log input history up to this point, optionally interleaving |
|
1167 | 1167 | # output if requested |
|
1168 | 1168 | |
|
1169 | 1169 | if timestamp: |
|
1170 | 1170 | # disable timestamping for the previous history, since we've |
|
1171 | 1171 | # lost those already (no time machine here). |
|
1172 | 1172 | logger.timestamp = False |
|
1173 | 1173 | |
|
1174 | 1174 | if log_raw_input: |
|
1175 | 1175 | input_hist = self.shell.history_manager.input_hist_raw |
|
1176 | 1176 | else: |
|
1177 | 1177 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1178 | 1178 | |
|
1179 | 1179 | if log_output: |
|
1180 | 1180 | log_write = logger.log_write |
|
1181 | 1181 | output_hist = self.shell.history_manager.output_hist |
|
1182 | 1182 | for n in range(1,len(input_hist)-1): |
|
1183 | 1183 | log_write(input_hist[n].rstrip()) |
|
1184 | 1184 | if n in output_hist: |
|
1185 | 1185 | log_write(repr(output_hist[n]),'output') |
|
1186 | 1186 | else: |
|
1187 | 1187 | logger.log_write(''.join(input_hist[1:])) |
|
1188 | 1188 | if timestamp: |
|
1189 | 1189 | # re-enable timestamping |
|
1190 | 1190 | logger.timestamp = True |
|
1191 | 1191 | |
|
1192 | 1192 | print ('Activating auto-logging. ' |
|
1193 | 1193 | 'Current session state plus future input saved.') |
|
1194 | 1194 | logger.logstate() |
|
1195 | 1195 | |
|
1196 | 1196 | def magic_logstop(self,parameter_s=''): |
|
1197 | 1197 | """Fully stop logging and close log file. |
|
1198 | 1198 | |
|
1199 | 1199 | In order to start logging again, a new %logstart call needs to be made, |
|
1200 | 1200 | possibly (though not necessarily) with a new filename, mode and other |
|
1201 | 1201 | options.""" |
|
1202 | 1202 | self.logger.logstop() |
|
1203 | 1203 | |
|
1204 | 1204 | def magic_logoff(self,parameter_s=''): |
|
1205 | 1205 | """Temporarily stop logging. |
|
1206 | 1206 | |
|
1207 | 1207 | You must have previously started logging.""" |
|
1208 | 1208 | self.shell.logger.switch_log(0) |
|
1209 | 1209 | |
|
1210 | 1210 | def magic_logon(self,parameter_s=''): |
|
1211 | 1211 | """Restart logging. |
|
1212 | 1212 | |
|
1213 | 1213 | This function is for restarting logging which you've temporarily |
|
1214 | 1214 | stopped with %logoff. For starting logging for the first time, you |
|
1215 | 1215 | must use the %logstart function, which allows you to specify an |
|
1216 | 1216 | optional log filename.""" |
|
1217 | 1217 | |
|
1218 | 1218 | self.shell.logger.switch_log(1) |
|
1219 | 1219 | |
|
1220 | 1220 | def magic_logstate(self,parameter_s=''): |
|
1221 | 1221 | """Print the status of the logging system.""" |
|
1222 | 1222 | |
|
1223 | 1223 | self.shell.logger.logstate() |
|
1224 | 1224 | |
|
1225 | 1225 | def magic_pdb(self, parameter_s=''): |
|
1226 | 1226 | """Control the automatic calling of the pdb interactive debugger. |
|
1227 | 1227 | |
|
1228 | 1228 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1229 | 1229 | argument it works as a toggle. |
|
1230 | 1230 | |
|
1231 | 1231 | When an exception is triggered, IPython can optionally call the |
|
1232 | 1232 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1233 | 1233 | this feature on and off. |
|
1234 | 1234 | |
|
1235 | 1235 | The initial state of this feature is set in your ipythonrc |
|
1236 | 1236 | configuration file (the variable is called 'pdb'). |
|
1237 | 1237 | |
|
1238 | 1238 | If you want to just activate the debugger AFTER an exception has fired, |
|
1239 | 1239 | without having to type '%pdb on' and rerunning your code, you can use |
|
1240 | 1240 | the %debug magic.""" |
|
1241 | 1241 | |
|
1242 | 1242 | par = parameter_s.strip().lower() |
|
1243 | 1243 | |
|
1244 | 1244 | if par: |
|
1245 | 1245 | try: |
|
1246 | 1246 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1247 | 1247 | except KeyError: |
|
1248 | 1248 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1249 | 1249 | 'or nothing for a toggle.') |
|
1250 | 1250 | return |
|
1251 | 1251 | else: |
|
1252 | 1252 | # toggle |
|
1253 | 1253 | new_pdb = not self.shell.call_pdb |
|
1254 | 1254 | |
|
1255 | 1255 | # set on the shell |
|
1256 | 1256 | self.shell.call_pdb = new_pdb |
|
1257 | 1257 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1258 | 1258 | |
|
1259 | 1259 | def magic_debug(self, parameter_s=''): |
|
1260 | 1260 | """Activate the interactive debugger in post-mortem mode. |
|
1261 | 1261 | |
|
1262 | 1262 | If an exception has just occurred, this lets you inspect its stack |
|
1263 | 1263 | frames interactively. Note that this will always work only on the last |
|
1264 | 1264 | traceback that occurred, so you must call this quickly after an |
|
1265 | 1265 | exception that you wish to inspect has fired, because if another one |
|
1266 | 1266 | occurs, it clobbers the previous one. |
|
1267 | 1267 | |
|
1268 | 1268 | If you want IPython to automatically do this on every exception, see |
|
1269 | 1269 | the %pdb magic for more details. |
|
1270 | 1270 | """ |
|
1271 | 1271 | self.shell.debugger(force=True) |
|
1272 | 1272 | |
|
1273 | 1273 | @testdec.skip_doctest |
|
1274 | 1274 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1275 | 1275 | opts=None,arg_lst=None,prog_ns=None): |
|
1276 | 1276 | |
|
1277 | 1277 | """Run a statement through the python code profiler. |
|
1278 | 1278 | |
|
1279 | 1279 | Usage: |
|
1280 | 1280 | %prun [options] statement |
|
1281 | 1281 | |
|
1282 | 1282 | The given statement (which doesn't require quote marks) is run via the |
|
1283 | 1283 | python profiler in a manner similar to the profile.run() function. |
|
1284 | 1284 | Namespaces are internally managed to work correctly; profile.run |
|
1285 | 1285 | cannot be used in IPython because it makes certain assumptions about |
|
1286 | 1286 | namespaces which do not hold under IPython. |
|
1287 | 1287 | |
|
1288 | 1288 | Options: |
|
1289 | 1289 | |
|
1290 | 1290 | -l <limit>: you can place restrictions on what or how much of the |
|
1291 | 1291 | profile gets printed. The limit value can be: |
|
1292 | 1292 | |
|
1293 | 1293 | * A string: only information for function names containing this string |
|
1294 | 1294 | is printed. |
|
1295 | 1295 | |
|
1296 | 1296 | * An integer: only these many lines are printed. |
|
1297 | 1297 | |
|
1298 | 1298 | * A float (between 0 and 1): this fraction of the report is printed |
|
1299 | 1299 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1300 | 1300 | |
|
1301 | 1301 | You can combine several limits with repeated use of the option. For |
|
1302 | 1302 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1303 | 1303 | information about class constructors. |
|
1304 | 1304 | |
|
1305 | 1305 | -r: return the pstats.Stats object generated by the profiling. This |
|
1306 | 1306 | object has all the information about the profile in it, and you can |
|
1307 | 1307 | later use it for further analysis or in other functions. |
|
1308 | 1308 | |
|
1309 | 1309 | -s <key>: sort profile by given key. You can provide more than one key |
|
1310 | 1310 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1311 | 1311 | default sorting key is 'time'. |
|
1312 | 1312 | |
|
1313 | 1313 | The following is copied verbatim from the profile documentation |
|
1314 | 1314 | referenced below: |
|
1315 | 1315 | |
|
1316 | 1316 | When more than one key is provided, additional keys are used as |
|
1317 | 1317 | secondary criteria when the there is equality in all keys selected |
|
1318 | 1318 | before them. |
|
1319 | 1319 | |
|
1320 | 1320 | Abbreviations can be used for any key names, as long as the |
|
1321 | 1321 | abbreviation is unambiguous. The following are the keys currently |
|
1322 | 1322 | defined: |
|
1323 | 1323 | |
|
1324 | 1324 | Valid Arg Meaning |
|
1325 | 1325 | "calls" call count |
|
1326 | 1326 | "cumulative" cumulative time |
|
1327 | 1327 | "file" file name |
|
1328 | 1328 | "module" file name |
|
1329 | 1329 | "pcalls" primitive call count |
|
1330 | 1330 | "line" line number |
|
1331 | 1331 | "name" function name |
|
1332 | 1332 | "nfl" name/file/line |
|
1333 | 1333 | "stdname" standard name |
|
1334 | 1334 | "time" internal time |
|
1335 | 1335 | |
|
1336 | 1336 | Note that all sorts on statistics are in descending order (placing |
|
1337 | 1337 | most time consuming items first), where as name, file, and line number |
|
1338 | 1338 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1339 | 1339 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1340 | 1340 | sort of the name as printed, which means that the embedded line |
|
1341 | 1341 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1342 | 1342 | would (if the file names were the same) appear in the string order |
|
1343 | 1343 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1344 | 1344 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1345 | 1345 | sort_stats("name", "file", "line"). |
|
1346 | 1346 | |
|
1347 | 1347 | -T <filename>: save profile results as shown on screen to a text |
|
1348 | 1348 | file. The profile is still shown on screen. |
|
1349 | 1349 | |
|
1350 | 1350 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1351 | 1351 | filename. This data is in a format understod by the pstats module, and |
|
1352 | 1352 | is generated by a call to the dump_stats() method of profile |
|
1353 | 1353 | objects. The profile is still shown on screen. |
|
1354 | 1354 | |
|
1355 | 1355 | If you want to run complete programs under the profiler's control, use |
|
1356 | 1356 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1357 | 1357 | contains profiler specific options as described here. |
|
1358 | 1358 | |
|
1359 | 1359 | You can read the complete documentation for the profile module with:: |
|
1360 | 1360 | |
|
1361 | 1361 | In [1]: import profile; profile.help() |
|
1362 | 1362 | """ |
|
1363 | 1363 | |
|
1364 | 1364 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1365 | 1365 | # protect user quote marks |
|
1366 | 1366 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1367 | 1367 | |
|
1368 | 1368 | if user_mode: # regular user call |
|
1369 | 1369 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1370 | 1370 | list_all=1) |
|
1371 | 1371 | namespace = self.shell.user_ns |
|
1372 | 1372 | else: # called to run a program by %run -p |
|
1373 | 1373 | try: |
|
1374 | 1374 | filename = get_py_filename(arg_lst[0]) |
|
1375 | 1375 | except IOError,msg: |
|
1376 | 1376 | error(msg) |
|
1377 | 1377 | return |
|
1378 | 1378 | |
|
1379 | 1379 | arg_str = 'execfile(filename,prog_ns)' |
|
1380 | 1380 | namespace = locals() |
|
1381 | 1381 | |
|
1382 | 1382 | opts.merge(opts_def) |
|
1383 | 1383 | |
|
1384 | 1384 | prof = profile.Profile() |
|
1385 | 1385 | try: |
|
1386 | 1386 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1387 | 1387 | sys_exit = '' |
|
1388 | 1388 | except SystemExit: |
|
1389 | 1389 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1390 | 1390 | |
|
1391 | 1391 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1392 | 1392 | |
|
1393 | 1393 | lims = opts.l |
|
1394 | 1394 | if lims: |
|
1395 | 1395 | lims = [] # rebuild lims with ints/floats/strings |
|
1396 | 1396 | for lim in opts.l: |
|
1397 | 1397 | try: |
|
1398 | 1398 | lims.append(int(lim)) |
|
1399 | 1399 | except ValueError: |
|
1400 | 1400 | try: |
|
1401 | 1401 | lims.append(float(lim)) |
|
1402 | 1402 | except ValueError: |
|
1403 | 1403 | lims.append(lim) |
|
1404 | 1404 | |
|
1405 | 1405 | # Trap output. |
|
1406 | 1406 | stdout_trap = StringIO() |
|
1407 | 1407 | |
|
1408 | 1408 | if hasattr(stats,'stream'): |
|
1409 | 1409 | # In newer versions of python, the stats object has a 'stream' |
|
1410 | 1410 | # attribute to write into. |
|
1411 | 1411 | stats.stream = stdout_trap |
|
1412 | 1412 | stats.print_stats(*lims) |
|
1413 | 1413 | else: |
|
1414 | 1414 | # For older versions, we manually redirect stdout during printing |
|
1415 | 1415 | sys_stdout = sys.stdout |
|
1416 | 1416 | try: |
|
1417 | 1417 | sys.stdout = stdout_trap |
|
1418 | 1418 | stats.print_stats(*lims) |
|
1419 | 1419 | finally: |
|
1420 | 1420 | sys.stdout = sys_stdout |
|
1421 | 1421 | |
|
1422 | 1422 | output = stdout_trap.getvalue() |
|
1423 | 1423 | output = output.rstrip() |
|
1424 | 1424 | |
|
1425 | 1425 | page.page(output) |
|
1426 | 1426 | print sys_exit, |
|
1427 | 1427 | |
|
1428 | 1428 | dump_file = opts.D[0] |
|
1429 | 1429 | text_file = opts.T[0] |
|
1430 | 1430 | if dump_file: |
|
1431 | 1431 | prof.dump_stats(dump_file) |
|
1432 | 1432 | print '\n*** Profile stats marshalled to file',\ |
|
1433 | 1433 | `dump_file`+'.',sys_exit |
|
1434 | 1434 | if text_file: |
|
1435 | 1435 | pfile = file(text_file,'w') |
|
1436 | 1436 | pfile.write(output) |
|
1437 | 1437 | pfile.close() |
|
1438 | 1438 | print '\n*** Profile printout saved to text file',\ |
|
1439 | 1439 | `text_file`+'.',sys_exit |
|
1440 | 1440 | |
|
1441 | 1441 | if opts.has_key('r'): |
|
1442 | 1442 | return stats |
|
1443 | 1443 | else: |
|
1444 | 1444 | return None |
|
1445 | 1445 | |
|
1446 | 1446 | @testdec.skip_doctest |
|
1447 | 1447 | def magic_run(self, parameter_s ='',runner=None, |
|
1448 | 1448 | file_finder=get_py_filename): |
|
1449 | 1449 | """Run the named file inside IPython as a program. |
|
1450 | 1450 | |
|
1451 | 1451 | Usage:\\ |
|
1452 | 1452 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1453 | 1453 | |
|
1454 | 1454 | Parameters after the filename are passed as command-line arguments to |
|
1455 | 1455 | the program (put in sys.argv). Then, control returns to IPython's |
|
1456 | 1456 | prompt. |
|
1457 | 1457 | |
|
1458 | 1458 | This is similar to running at a system prompt:\\ |
|
1459 | 1459 | $ python file args\\ |
|
1460 | 1460 | but with the advantage of giving you IPython's tracebacks, and of |
|
1461 | 1461 | loading all variables into your interactive namespace for further use |
|
1462 | 1462 | (unless -p is used, see below). |
|
1463 | 1463 | |
|
1464 | 1464 | The file is executed in a namespace initially consisting only of |
|
1465 | 1465 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1466 | 1466 | sees its environment as if it were being run as a stand-alone program |
|
1467 | 1467 | (except for sharing global objects such as previously imported |
|
1468 | 1468 | modules). But after execution, the IPython interactive namespace gets |
|
1469 | 1469 | updated with all variables defined in the program (except for __name__ |
|
1470 | 1470 | and sys.argv). This allows for very convenient loading of code for |
|
1471 | 1471 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1472 | 1472 | |
|
1473 | 1473 | Options: |
|
1474 | 1474 | |
|
1475 | 1475 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1476 | 1476 | without extension (as python does under import). This allows running |
|
1477 | 1477 | scripts and reloading the definitions in them without calling code |
|
1478 | 1478 | protected by an ' if __name__ == "__main__" ' clause. |
|
1479 | 1479 | |
|
1480 | 1480 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1481 | 1481 | is useful if you are experimenting with code written in a text editor |
|
1482 | 1482 | which depends on variables defined interactively. |
|
1483 | 1483 | |
|
1484 | 1484 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1485 | 1485 | being run. This is particularly useful if IPython is being used to |
|
1486 | 1486 | run unittests, which always exit with a sys.exit() call. In such |
|
1487 | 1487 | cases you are interested in the output of the test results, not in |
|
1488 | 1488 | seeing a traceback of the unittest module. |
|
1489 | 1489 | |
|
1490 | 1490 | -t: print timing information at the end of the run. IPython will give |
|
1491 | 1491 | you an estimated CPU time consumption for your script, which under |
|
1492 | 1492 | Unix uses the resource module to avoid the wraparound problems of |
|
1493 | 1493 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1494 | 1494 | is also given (for Windows platforms this is reported as 0.0). |
|
1495 | 1495 | |
|
1496 | 1496 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1497 | 1497 | must be an integer indicating how many times you want the script to |
|
1498 | 1498 | run. The final timing report will include total and per run results. |
|
1499 | 1499 | |
|
1500 | 1500 | For example (testing the script uniq_stable.py): |
|
1501 | 1501 | |
|
1502 | 1502 | In [1]: run -t uniq_stable |
|
1503 | 1503 | |
|
1504 | 1504 | IPython CPU timings (estimated):\\ |
|
1505 | 1505 | User : 0.19597 s.\\ |
|
1506 | 1506 | System: 0.0 s.\\ |
|
1507 | 1507 | |
|
1508 | 1508 | In [2]: run -t -N5 uniq_stable |
|
1509 | 1509 | |
|
1510 | 1510 | IPython CPU timings (estimated):\\ |
|
1511 | 1511 | Total runs performed: 5\\ |
|
1512 | 1512 | Times : Total Per run\\ |
|
1513 | 1513 | User : 0.910862 s, 0.1821724 s.\\ |
|
1514 | 1514 | System: 0.0 s, 0.0 s. |
|
1515 | 1515 | |
|
1516 | 1516 | -d: run your program under the control of pdb, the Python debugger. |
|
1517 | 1517 | This allows you to execute your program step by step, watch variables, |
|
1518 | 1518 | etc. Internally, what IPython does is similar to calling: |
|
1519 | 1519 | |
|
1520 | 1520 | pdb.run('execfile("YOURFILENAME")') |
|
1521 | 1521 | |
|
1522 | 1522 | with a breakpoint set on line 1 of your file. You can change the line |
|
1523 | 1523 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1524 | 1524 | (where N must be an integer). For example: |
|
1525 | 1525 | |
|
1526 | 1526 | %run -d -b40 myscript |
|
1527 | 1527 | |
|
1528 | 1528 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1529 | 1529 | the first breakpoint must be set on a line which actually does |
|
1530 | 1530 | something (not a comment or docstring) for it to stop execution. |
|
1531 | 1531 | |
|
1532 | 1532 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1533 | 1533 | first enter 'c' (without qoutes) to start execution up to the first |
|
1534 | 1534 | breakpoint. |
|
1535 | 1535 | |
|
1536 | 1536 | Entering 'help' gives information about the use of the debugger. You |
|
1537 | 1537 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1538 | 1538 | at a prompt. |
|
1539 | 1539 | |
|
1540 | 1540 | -p: run program under the control of the Python profiler module (which |
|
1541 | 1541 | prints a detailed report of execution times, function calls, etc). |
|
1542 | 1542 | |
|
1543 | 1543 | You can pass other options after -p which affect the behavior of the |
|
1544 | 1544 | profiler itself. See the docs for %prun for details. |
|
1545 | 1545 | |
|
1546 | 1546 | In this mode, the program's variables do NOT propagate back to the |
|
1547 | 1547 | IPython interactive namespace (because they remain in the namespace |
|
1548 | 1548 | where the profiler executes them). |
|
1549 | 1549 | |
|
1550 | 1550 | Internally this triggers a call to %prun, see its documentation for |
|
1551 | 1551 | details on the options available specifically for profiling. |
|
1552 | 1552 | |
|
1553 | 1553 | There is one special usage for which the text above doesn't apply: |
|
1554 | 1554 | if the filename ends with .ipy, the file is run as ipython script, |
|
1555 | 1555 | just as if the commands were written on IPython prompt. |
|
1556 | 1556 | """ |
|
1557 | 1557 | |
|
1558 | 1558 | # get arguments and set sys.argv for program to be run. |
|
1559 | 1559 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1560 | 1560 | mode='list',list_all=1) |
|
1561 | 1561 | |
|
1562 | 1562 | try: |
|
1563 | 1563 | filename = file_finder(arg_lst[0]) |
|
1564 | 1564 | except IndexError: |
|
1565 | 1565 | warn('you must provide at least a filename.') |
|
1566 | 1566 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1567 | 1567 | return |
|
1568 | 1568 | except IOError,msg: |
|
1569 | 1569 | error(msg) |
|
1570 | 1570 | return |
|
1571 | 1571 | |
|
1572 | 1572 | if filename.lower().endswith('.ipy'): |
|
1573 | 1573 | self.shell.safe_execfile_ipy(filename) |
|
1574 | 1574 | return |
|
1575 | 1575 | |
|
1576 | 1576 | # Control the response to exit() calls made by the script being run |
|
1577 | 1577 | exit_ignore = opts.has_key('e') |
|
1578 | 1578 | |
|
1579 | 1579 | # Make sure that the running script gets a proper sys.argv as if it |
|
1580 | 1580 | # were run from a system shell. |
|
1581 | 1581 | save_argv = sys.argv # save it for later restoring |
|
1582 | 1582 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1583 | 1583 | |
|
1584 | 1584 | if opts.has_key('i'): |
|
1585 | 1585 | # Run in user's interactive namespace |
|
1586 | 1586 | prog_ns = self.shell.user_ns |
|
1587 | 1587 | __name__save = self.shell.user_ns['__name__'] |
|
1588 | 1588 | prog_ns['__name__'] = '__main__' |
|
1589 | 1589 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1590 | 1590 | else: |
|
1591 | 1591 | # Run in a fresh, empty namespace |
|
1592 | 1592 | if opts.has_key('n'): |
|
1593 | 1593 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1594 | 1594 | else: |
|
1595 | 1595 | name = '__main__' |
|
1596 | 1596 | |
|
1597 | 1597 | main_mod = self.shell.new_main_mod() |
|
1598 | 1598 | prog_ns = main_mod.__dict__ |
|
1599 | 1599 | prog_ns['__name__'] = name |
|
1600 | 1600 | |
|
1601 | 1601 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1602 | 1602 | # set the __file__ global in the script's namespace |
|
1603 | 1603 | prog_ns['__file__'] = filename |
|
1604 | 1604 | |
|
1605 | 1605 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1606 | 1606 | # that, if we overwrite __main__, we replace it at the end |
|
1607 | 1607 | main_mod_name = prog_ns['__name__'] |
|
1608 | 1608 | |
|
1609 | 1609 | if main_mod_name == '__main__': |
|
1610 | 1610 | restore_main = sys.modules['__main__'] |
|
1611 | 1611 | else: |
|
1612 | 1612 | restore_main = False |
|
1613 | 1613 | |
|
1614 | 1614 | # This needs to be undone at the end to prevent holding references to |
|
1615 | 1615 | # every single object ever created. |
|
1616 | 1616 | sys.modules[main_mod_name] = main_mod |
|
1617 | 1617 | |
|
1618 | 1618 | stats = None |
|
1619 | 1619 | try: |
|
1620 | 1620 | self.shell.save_history() |
|
1621 | 1621 | |
|
1622 | 1622 | if opts.has_key('p'): |
|
1623 | 1623 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1624 | 1624 | else: |
|
1625 | 1625 | if opts.has_key('d'): |
|
1626 | 1626 | deb = debugger.Pdb(self.shell.colors) |
|
1627 | 1627 | # reset Breakpoint state, which is moronically kept |
|
1628 | 1628 | # in a class |
|
1629 | 1629 | bdb.Breakpoint.next = 1 |
|
1630 | 1630 | bdb.Breakpoint.bplist = {} |
|
1631 | 1631 | bdb.Breakpoint.bpbynumber = [None] |
|
1632 | 1632 | # Set an initial breakpoint to stop execution |
|
1633 | 1633 | maxtries = 10 |
|
1634 | 1634 | bp = int(opts.get('b',[1])[0]) |
|
1635 | 1635 | checkline = deb.checkline(filename,bp) |
|
1636 | 1636 | if not checkline: |
|
1637 | 1637 | for bp in range(bp+1,bp+maxtries+1): |
|
1638 | 1638 | if deb.checkline(filename,bp): |
|
1639 | 1639 | break |
|
1640 | 1640 | else: |
|
1641 | 1641 | msg = ("\nI failed to find a valid line to set " |
|
1642 | 1642 | "a breakpoint\n" |
|
1643 | 1643 | "after trying up to line: %s.\n" |
|
1644 | 1644 | "Please set a valid breakpoint manually " |
|
1645 | 1645 | "with the -b option." % bp) |
|
1646 | 1646 | error(msg) |
|
1647 | 1647 | return |
|
1648 | 1648 | # if we find a good linenumber, set the breakpoint |
|
1649 | 1649 | deb.do_break('%s:%s' % (filename,bp)) |
|
1650 | 1650 | # Start file run |
|
1651 | 1651 | print "NOTE: Enter 'c' at the", |
|
1652 | 1652 | print "%s prompt to start your script." % deb.prompt |
|
1653 | 1653 | try: |
|
1654 | 1654 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1655 | 1655 | |
|
1656 | 1656 | except: |
|
1657 | 1657 | etype, value, tb = sys.exc_info() |
|
1658 | 1658 | # Skip three frames in the traceback: the %run one, |
|
1659 | 1659 | # one inside bdb.py, and the command-line typed by the |
|
1660 | 1660 | # user (run by exec in pdb itself). |
|
1661 | 1661 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1662 | 1662 | else: |
|
1663 | 1663 | if runner is None: |
|
1664 | 1664 | runner = self.shell.safe_execfile |
|
1665 | 1665 | if opts.has_key('t'): |
|
1666 | 1666 | # timed execution |
|
1667 | 1667 | try: |
|
1668 | 1668 | nruns = int(opts['N'][0]) |
|
1669 | 1669 | if nruns < 1: |
|
1670 | 1670 | error('Number of runs must be >=1') |
|
1671 | 1671 | return |
|
1672 | 1672 | except (KeyError): |
|
1673 | 1673 | nruns = 1 |
|
1674 | 1674 | if nruns == 1: |
|
1675 | 1675 | t0 = clock2() |
|
1676 | 1676 | runner(filename,prog_ns,prog_ns, |
|
1677 | 1677 | exit_ignore=exit_ignore) |
|
1678 | 1678 | t1 = clock2() |
|
1679 | 1679 | t_usr = t1[0]-t0[0] |
|
1680 | 1680 | t_sys = t1[1]-t0[1] |
|
1681 | 1681 | print "\nIPython CPU timings (estimated):" |
|
1682 | 1682 | print " User : %10s s." % t_usr |
|
1683 | 1683 | print " System: %10s s." % t_sys |
|
1684 | 1684 | else: |
|
1685 | 1685 | runs = range(nruns) |
|
1686 | 1686 | t0 = clock2() |
|
1687 | 1687 | for nr in runs: |
|
1688 | 1688 | runner(filename,prog_ns,prog_ns, |
|
1689 | 1689 | exit_ignore=exit_ignore) |
|
1690 | 1690 | t1 = clock2() |
|
1691 | 1691 | t_usr = t1[0]-t0[0] |
|
1692 | 1692 | t_sys = t1[1]-t0[1] |
|
1693 | 1693 | print "\nIPython CPU timings (estimated):" |
|
1694 | 1694 | print "Total runs performed:",nruns |
|
1695 | 1695 | print " Times : %10s %10s" % ('Total','Per run') |
|
1696 | 1696 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1697 | 1697 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1698 | 1698 | |
|
1699 | 1699 | else: |
|
1700 | 1700 | # regular execution |
|
1701 | 1701 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1702 | 1702 | |
|
1703 | 1703 | if opts.has_key('i'): |
|
1704 | 1704 | self.shell.user_ns['__name__'] = __name__save |
|
1705 | 1705 | else: |
|
1706 | 1706 | # The shell MUST hold a reference to prog_ns so after %run |
|
1707 | 1707 | # exits, the python deletion mechanism doesn't zero it out |
|
1708 | 1708 | # (leaving dangling references). |
|
1709 | 1709 | self.shell.cache_main_mod(prog_ns,filename) |
|
1710 | 1710 | # update IPython interactive namespace |
|
1711 | 1711 | |
|
1712 | 1712 | # Some forms of read errors on the file may mean the |
|
1713 | 1713 | # __name__ key was never set; using pop we don't have to |
|
1714 | 1714 | # worry about a possible KeyError. |
|
1715 | 1715 | prog_ns.pop('__name__', None) |
|
1716 | 1716 | |
|
1717 | 1717 | self.shell.user_ns.update(prog_ns) |
|
1718 | 1718 | finally: |
|
1719 | 1719 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1720 | 1720 | # being a module to becoming a dict missing some key data after |
|
1721 | 1721 | # %run. As best I can see, this is NOT something IPython is doing |
|
1722 | 1722 | # at all, and similar problems have been reported before: |
|
1723 | 1723 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1724 | 1724 | # Since this seems to be done by the interpreter itself, the best |
|
1725 | 1725 | # we can do is to at least restore __builtins__ for the user on |
|
1726 | 1726 | # exit. |
|
1727 | 1727 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1728 | 1728 | |
|
1729 | 1729 | # Ensure key global structures are restored |
|
1730 | 1730 | sys.argv = save_argv |
|
1731 | 1731 | if restore_main: |
|
1732 | 1732 | sys.modules['__main__'] = restore_main |
|
1733 | 1733 | else: |
|
1734 | 1734 | # Remove from sys.modules the reference to main_mod we'd |
|
1735 | 1735 | # added. Otherwise it will trap references to objects |
|
1736 | 1736 | # contained therein. |
|
1737 | 1737 | del sys.modules[main_mod_name] |
|
1738 | 1738 | |
|
1739 | 1739 | self.shell.reload_history() |
|
1740 | 1740 | |
|
1741 | 1741 | return stats |
|
1742 | 1742 | |
|
1743 | 1743 | @testdec.skip_doctest |
|
1744 | 1744 | def magic_timeit(self, parameter_s =''): |
|
1745 | 1745 | """Time execution of a Python statement or expression |
|
1746 | 1746 | |
|
1747 | 1747 | Usage:\\ |
|
1748 | 1748 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1749 | 1749 | |
|
1750 | 1750 | Time execution of a Python statement or expression using the timeit |
|
1751 | 1751 | module. |
|
1752 | 1752 | |
|
1753 | 1753 | Options: |
|
1754 | 1754 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1755 | 1755 | is not given, a fitting value is chosen. |
|
1756 | 1756 | |
|
1757 | 1757 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1758 | 1758 | Default: 3 |
|
1759 | 1759 | |
|
1760 | 1760 | -t: use time.time to measure the time, which is the default on Unix. |
|
1761 | 1761 | This function measures wall time. |
|
1762 | 1762 | |
|
1763 | 1763 | -c: use time.clock to measure the time, which is the default on |
|
1764 | 1764 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1765 | 1765 | instead and returns the CPU user time. |
|
1766 | 1766 | |
|
1767 | 1767 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1768 | 1768 | Default: 3 |
|
1769 | 1769 | |
|
1770 | 1770 | |
|
1771 | 1771 | Examples: |
|
1772 | 1772 | |
|
1773 | 1773 | In [1]: %timeit pass |
|
1774 | 1774 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1775 | 1775 | |
|
1776 | 1776 | In [2]: u = None |
|
1777 | 1777 | |
|
1778 | 1778 | In [3]: %timeit u is None |
|
1779 | 1779 | 10000000 loops, best of 3: 184 ns per loop |
|
1780 | 1780 | |
|
1781 | 1781 | In [4]: %timeit -r 4 u == None |
|
1782 | 1782 | 1000000 loops, best of 4: 242 ns per loop |
|
1783 | 1783 | |
|
1784 | 1784 | In [5]: import time |
|
1785 | 1785 | |
|
1786 | 1786 | In [6]: %timeit -n1 time.sleep(2) |
|
1787 | 1787 | 1 loops, best of 3: 2 s per loop |
|
1788 | 1788 | |
|
1789 | 1789 | |
|
1790 | 1790 | The times reported by %timeit will be slightly higher than those |
|
1791 | 1791 | reported by the timeit.py script when variables are accessed. This is |
|
1792 | 1792 | due to the fact that %timeit executes the statement in the namespace |
|
1793 | 1793 | of the shell, compared with timeit.py, which uses a single setup |
|
1794 | 1794 | statement to import function or create variables. Generally, the bias |
|
1795 | 1795 | does not matter as long as results from timeit.py are not mixed with |
|
1796 | 1796 | those from %timeit.""" |
|
1797 | 1797 | |
|
1798 | 1798 | import timeit |
|
1799 | 1799 | import math |
|
1800 | 1800 | |
|
1801 | 1801 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1802 | 1802 | # certain terminals. Until we figure out a robust way of |
|
1803 | 1803 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1804 | 1804 | # microseconds. I am really NOT happy about disabling the proper |
|
1805 | 1805 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1806 | 1806 | # right solution for this is, I'm all ears... |
|
1807 | 1807 | # |
|
1808 | 1808 | # Note: using |
|
1809 | 1809 | # |
|
1810 | 1810 | # s = u'\xb5' |
|
1811 | 1811 | # s.encode(sys.getdefaultencoding()) |
|
1812 | 1812 | # |
|
1813 | 1813 | # is not sufficient, as I've seen terminals where that fails but |
|
1814 | 1814 | # print s |
|
1815 | 1815 | # |
|
1816 | 1816 | # succeeds |
|
1817 | 1817 | # |
|
1818 | 1818 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1819 | 1819 | |
|
1820 | 1820 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1821 | 1821 | units = [u"s", u"ms",u'us',"ns"] |
|
1822 | 1822 | |
|
1823 | 1823 | scaling = [1, 1e3, 1e6, 1e9] |
|
1824 | 1824 | |
|
1825 | 1825 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1826 | 1826 | posix=False) |
|
1827 | 1827 | if stmt == "": |
|
1828 | 1828 | return |
|
1829 | 1829 | timefunc = timeit.default_timer |
|
1830 | 1830 | number = int(getattr(opts, "n", 0)) |
|
1831 | 1831 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1832 | 1832 | precision = int(getattr(opts, "p", 3)) |
|
1833 | 1833 | if hasattr(opts, "t"): |
|
1834 | 1834 | timefunc = time.time |
|
1835 | 1835 | if hasattr(opts, "c"): |
|
1836 | 1836 | timefunc = clock |
|
1837 | 1837 | |
|
1838 | 1838 | timer = timeit.Timer(timer=timefunc) |
|
1839 | 1839 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1840 | 1840 | # but is there a better way to achieve that the code stmt has access |
|
1841 | 1841 | # to the shell namespace? |
|
1842 | 1842 | |
|
1843 | 1843 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1844 | 1844 | 'setup': "pass"} |
|
1845 | 1845 | # Track compilation time so it can be reported if too long |
|
1846 | 1846 | # Minimum time above which compilation time will be reported |
|
1847 | 1847 | tc_min = 0.1 |
|
1848 | 1848 | |
|
1849 | 1849 | t0 = clock() |
|
1850 | 1850 | code = compile(src, "<magic-timeit>", "exec") |
|
1851 | 1851 | tc = clock()-t0 |
|
1852 | 1852 | |
|
1853 | 1853 | ns = {} |
|
1854 | 1854 | exec code in self.shell.user_ns, ns |
|
1855 | 1855 | timer.inner = ns["inner"] |
|
1856 | 1856 | |
|
1857 | 1857 | if number == 0: |
|
1858 | 1858 | # determine number so that 0.2 <= total time < 2.0 |
|
1859 | 1859 | number = 1 |
|
1860 | 1860 | for i in range(1, 10): |
|
1861 | 1861 | if timer.timeit(number) >= 0.2: |
|
1862 | 1862 | break |
|
1863 | 1863 | number *= 10 |
|
1864 | 1864 | |
|
1865 | 1865 | best = min(timer.repeat(repeat, number)) / number |
|
1866 | 1866 | |
|
1867 | 1867 | if best > 0.0 and best < 1000.0: |
|
1868 | 1868 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1869 | 1869 | elif best >= 1000.0: |
|
1870 | 1870 | order = 0 |
|
1871 | 1871 | else: |
|
1872 | 1872 | order = 3 |
|
1873 | 1873 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1874 | 1874 | precision, |
|
1875 | 1875 | best * scaling[order], |
|
1876 | 1876 | units[order]) |
|
1877 | 1877 | if tc > tc_min: |
|
1878 | 1878 | print "Compiler time: %.2f s" % tc |
|
1879 | 1879 | |
|
1880 | 1880 | @testdec.skip_doctest |
|
1881 | 1881 | def magic_time(self,parameter_s = ''): |
|
1882 | 1882 | """Time execution of a Python statement or expression. |
|
1883 | 1883 | |
|
1884 | 1884 | The CPU and wall clock times are printed, and the value of the |
|
1885 | 1885 | expression (if any) is returned. Note that under Win32, system time |
|
1886 | 1886 | is always reported as 0, since it can not be measured. |
|
1887 | 1887 | |
|
1888 | 1888 | This function provides very basic timing functionality. In Python |
|
1889 | 1889 | 2.3, the timeit module offers more control and sophistication, so this |
|
1890 | 1890 | could be rewritten to use it (patches welcome). |
|
1891 | 1891 | |
|
1892 | 1892 | Some examples: |
|
1893 | 1893 | |
|
1894 | 1894 | In [1]: time 2**128 |
|
1895 | 1895 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1896 | 1896 | Wall time: 0.00 |
|
1897 | 1897 | Out[1]: 340282366920938463463374607431768211456L |
|
1898 | 1898 | |
|
1899 | 1899 | In [2]: n = 1000000 |
|
1900 | 1900 | |
|
1901 | 1901 | In [3]: time sum(range(n)) |
|
1902 | 1902 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1903 | 1903 | Wall time: 1.37 |
|
1904 | 1904 | Out[3]: 499999500000L |
|
1905 | 1905 | |
|
1906 | 1906 | In [4]: time print 'hello world' |
|
1907 | 1907 | hello world |
|
1908 | 1908 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1909 | 1909 | Wall time: 0.00 |
|
1910 | 1910 | |
|
1911 | 1911 | Note that the time needed by Python to compile the given expression |
|
1912 | 1912 | will be reported if it is more than 0.1s. In this example, the |
|
1913 | 1913 | actual exponentiation is done by Python at compilation time, so while |
|
1914 | 1914 | the expression can take a noticeable amount of time to compute, that |
|
1915 | 1915 | time is purely due to the compilation: |
|
1916 | 1916 | |
|
1917 | 1917 | In [5]: time 3**9999; |
|
1918 | 1918 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1919 | 1919 | Wall time: 0.00 s |
|
1920 | 1920 | |
|
1921 | 1921 | In [6]: time 3**999999; |
|
1922 | 1922 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1923 | 1923 | Wall time: 0.00 s |
|
1924 | 1924 | Compiler : 0.78 s |
|
1925 | 1925 | """ |
|
1926 | 1926 | |
|
1927 | 1927 | # fail immediately if the given expression can't be compiled |
|
1928 | 1928 | |
|
1929 | 1929 | expr = self.shell.prefilter(parameter_s,False) |
|
1930 | 1930 | |
|
1931 | 1931 | # Minimum time above which compilation time will be reported |
|
1932 | 1932 | tc_min = 0.1 |
|
1933 | 1933 | |
|
1934 | 1934 | try: |
|
1935 | 1935 | mode = 'eval' |
|
1936 | 1936 | t0 = clock() |
|
1937 | 1937 | code = compile(expr,'<timed eval>',mode) |
|
1938 | 1938 | tc = clock()-t0 |
|
1939 | 1939 | except SyntaxError: |
|
1940 | 1940 | mode = 'exec' |
|
1941 | 1941 | t0 = clock() |
|
1942 | 1942 | code = compile(expr,'<timed exec>',mode) |
|
1943 | 1943 | tc = clock()-t0 |
|
1944 | 1944 | # skew measurement as little as possible |
|
1945 | 1945 | glob = self.shell.user_ns |
|
1946 | 1946 | clk = clock2 |
|
1947 | 1947 | wtime = time.time |
|
1948 | 1948 | # time execution |
|
1949 | 1949 | wall_st = wtime() |
|
1950 | 1950 | if mode=='eval': |
|
1951 | 1951 | st = clk() |
|
1952 | 1952 | out = eval(code,glob) |
|
1953 | 1953 | end = clk() |
|
1954 | 1954 | else: |
|
1955 | 1955 | st = clk() |
|
1956 | 1956 | exec code in glob |
|
1957 | 1957 | end = clk() |
|
1958 | 1958 | out = None |
|
1959 | 1959 | wall_end = wtime() |
|
1960 | 1960 | # Compute actual times and report |
|
1961 | 1961 | wall_time = wall_end-wall_st |
|
1962 | 1962 | cpu_user = end[0]-st[0] |
|
1963 | 1963 | cpu_sys = end[1]-st[1] |
|
1964 | 1964 | cpu_tot = cpu_user+cpu_sys |
|
1965 | 1965 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1966 | 1966 | (cpu_user,cpu_sys,cpu_tot) |
|
1967 | 1967 | print "Wall time: %.2f s" % wall_time |
|
1968 | 1968 | if tc > tc_min: |
|
1969 | 1969 | print "Compiler : %.2f s" % tc |
|
1970 | 1970 | return out |
|
1971 | 1971 | |
|
1972 | 1972 | @testdec.skip_doctest |
|
1973 | 1973 | def magic_macro(self,parameter_s = ''): |
|
1974 | 1974 | """Define a set of input lines as a macro for future re-execution. |
|
1975 | 1975 | |
|
1976 | 1976 | Usage:\\ |
|
1977 | 1977 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1978 | 1978 | |
|
1979 | 1979 | Options: |
|
1980 | 1980 | |
|
1981 | 1981 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1982 | 1982 | so that magics are loaded in their transformed version to valid |
|
1983 | 1983 | Python. If this option is given, the raw input as typed as the |
|
1984 | 1984 | command line is used instead. |
|
1985 | 1985 | |
|
1986 | 1986 | This will define a global variable called `name` which is a string |
|
1987 | 1987 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1988 | 1988 | above) from your input history into a single string. This variable |
|
1989 | 1989 | acts like an automatic function which re-executes those lines as if |
|
1990 | 1990 | you had typed them. You just type 'name' at the prompt and the code |
|
1991 | 1991 | executes. |
|
1992 | 1992 | |
|
1993 | 1993 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1994 | 1994 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1995 | 1995 | using the lines numbered 5,6 and 7. |
|
1996 | 1996 | |
|
1997 | 1997 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1998 | 1998 | notation, where N:M means numbers N through M-1. |
|
1999 | 1999 | |
|
2000 | 2000 | For example, if your history contains (%hist prints it): |
|
2001 | 2001 | |
|
2002 | 2002 | 44: x=1 |
|
2003 | 2003 | 45: y=3 |
|
2004 | 2004 | 46: z=x+y |
|
2005 | 2005 | 47: print x |
|
2006 | 2006 | 48: a=5 |
|
2007 | 2007 | 49: print 'x',x,'y',y |
|
2008 | 2008 | |
|
2009 | 2009 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2010 | 2010 | called my_macro with: |
|
2011 | 2011 | |
|
2012 | 2012 | In [55]: %macro my_macro 44-47 49 |
|
2013 | 2013 | |
|
2014 | 2014 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2015 | 2015 | in one pass. |
|
2016 | 2016 | |
|
2017 | 2017 | You don't need to give the line-numbers in order, and any given line |
|
2018 | 2018 | number can appear multiple times. You can assemble macros with any |
|
2019 | 2019 | lines from your input history in any order. |
|
2020 | 2020 | |
|
2021 | 2021 | The macro is a simple object which holds its value in an attribute, |
|
2022 | 2022 | but IPython's display system checks for macros and executes them as |
|
2023 | 2023 | code instead of printing them when you type their name. |
|
2024 | 2024 | |
|
2025 | 2025 | You can view a macro's contents by explicitly printing it with: |
|
2026 | 2026 | |
|
2027 | 2027 | 'print macro_name'. |
|
2028 | 2028 | |
|
2029 | 2029 | For one-off cases which DON'T contain magic function calls in them you |
|
2030 | 2030 | can obtain similar results by explicitly executing slices from your |
|
2031 | 2031 | input history with: |
|
2032 | 2032 | |
|
2033 | 2033 | In [60]: exec In[44:48]+In[49]""" |
|
2034 | 2034 | |
|
2035 | 2035 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2036 | 2036 | if not args: |
|
2037 | 2037 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
2038 | 2038 | macs.sort() |
|
2039 | 2039 | return macs |
|
2040 | 2040 | if len(args) == 1: |
|
2041 | 2041 | raise UsageError( |
|
2042 | 2042 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2043 | 2043 | name,ranges = args[0], args[1:] |
|
2044 | 2044 | |
|
2045 | 2045 | #print 'rng',ranges # dbg |
|
2046 | 2046 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
2047 | 2047 | macro = Macro(lines) |
|
2048 | 2048 | self.shell.define_macro(name, macro) |
|
2049 | 2049 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2050 | 2050 | print 'Macro contents:' |
|
2051 | 2051 | print macro, |
|
2052 | 2052 | |
|
2053 | 2053 | def magic_save(self,parameter_s = ''): |
|
2054 | 2054 | """Save a set of lines to a given filename. |
|
2055 | 2055 | |
|
2056 | 2056 | Usage:\\ |
|
2057 | 2057 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2058 | 2058 | |
|
2059 | 2059 | Options: |
|
2060 | 2060 | |
|
2061 | 2061 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2062 | 2062 | so that magics are loaded in their transformed version to valid |
|
2063 | 2063 | Python. If this option is given, the raw input as typed as the |
|
2064 | 2064 | command line is used instead. |
|
2065 | 2065 | |
|
2066 | 2066 | This function uses the same syntax as %macro for line extraction, but |
|
2067 | 2067 | instead of creating a macro it saves the resulting string to the |
|
2068 | 2068 | filename you specify. |
|
2069 | 2069 | |
|
2070 | 2070 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2071 | 2071 | it asks for confirmation before overwriting existing files.""" |
|
2072 | 2072 | |
|
2073 | 2073 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2074 | 2074 | fname,ranges = args[0], args[1:] |
|
2075 | 2075 | if not fname.endswith('.py'): |
|
2076 | 2076 | fname += '.py' |
|
2077 | 2077 | if os.path.isfile(fname): |
|
2078 | 2078 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2079 | 2079 | if ans.lower() not in ['y','yes']: |
|
2080 | 2080 | print 'Operation cancelled.' |
|
2081 | 2081 | return |
|
2082 | 2082 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2083 | 2083 | f = file(fname,'w') |
|
2084 | 2084 | f.write(cmds) |
|
2085 | 2085 | f.close() |
|
2086 | 2086 | print 'The following commands were written to file `%s`:' % fname |
|
2087 | 2087 | print cmds |
|
2088 | 2088 | |
|
2089 | 2089 | def _edit_macro(self,mname,macro): |
|
2090 | 2090 | """open an editor with the macro data in a file""" |
|
2091 | 2091 | filename = self.shell.mktempfile(macro.value) |
|
2092 | 2092 | self.shell.hooks.editor(filename) |
|
2093 | 2093 | |
|
2094 | 2094 | # and make a new macro object, to replace the old one |
|
2095 | 2095 | mfile = open(filename) |
|
2096 | 2096 | mvalue = mfile.read() |
|
2097 | 2097 | mfile.close() |
|
2098 | 2098 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2099 | 2099 | |
|
2100 | 2100 | def magic_ed(self,parameter_s=''): |
|
2101 | 2101 | """Alias to %edit.""" |
|
2102 | 2102 | return self.magic_edit(parameter_s) |
|
2103 | 2103 | |
|
2104 | 2104 | @testdec.skip_doctest |
|
2105 | 2105 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2106 | 2106 | """Bring up an editor and execute the resulting code. |
|
2107 | 2107 | |
|
2108 | 2108 | Usage: |
|
2109 | 2109 | %edit [options] [args] |
|
2110 | 2110 | |
|
2111 | 2111 | %edit runs IPython's editor hook. The default version of this hook is |
|
2112 | 2112 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2113 | 2113 | environment variable $EDITOR. If this isn't found, it will default to |
|
2114 | 2114 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2115 | 2115 | docstring for how to change the editor hook. |
|
2116 | 2116 | |
|
2117 | 2117 | You can also set the value of this editor via the command line option |
|
2118 | 2118 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2119 | 2119 | specifically for IPython an editor different from your typical default |
|
2120 | 2120 | (and for Windows users who typically don't set environment variables). |
|
2121 | 2121 | |
|
2122 | 2122 | This command allows you to conveniently edit multi-line code right in |
|
2123 | 2123 | your IPython session. |
|
2124 | 2124 | |
|
2125 | 2125 | If called without arguments, %edit opens up an empty editor with a |
|
2126 | 2126 | temporary file and will execute the contents of this file when you |
|
2127 | 2127 | close it (don't forget to save it!). |
|
2128 | 2128 | |
|
2129 | 2129 | |
|
2130 | 2130 | Options: |
|
2131 | 2131 | |
|
2132 | 2132 | -n <number>: open the editor at a specified line number. By default, |
|
2133 | 2133 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2134 | 2134 | you can configure this by providing your own modified hook if your |
|
2135 | 2135 | favorite editor supports line-number specifications with a different |
|
2136 | 2136 | syntax. |
|
2137 | 2137 | |
|
2138 | 2138 | -p: this will call the editor with the same data as the previous time |
|
2139 | 2139 | it was used, regardless of how long ago (in your current session) it |
|
2140 | 2140 | was. |
|
2141 | 2141 | |
|
2142 | 2142 | -r: use 'raw' input. This option only applies to input taken from the |
|
2143 | 2143 | user's history. By default, the 'processed' history is used, so that |
|
2144 | 2144 | magics are loaded in their transformed version to valid Python. If |
|
2145 | 2145 | this option is given, the raw input as typed as the command line is |
|
2146 | 2146 | used instead. When you exit the editor, it will be executed by |
|
2147 | 2147 | IPython's own processor. |
|
2148 | 2148 | |
|
2149 | 2149 | -x: do not execute the edited code immediately upon exit. This is |
|
2150 | 2150 | mainly useful if you are editing programs which need to be called with |
|
2151 | 2151 | command line arguments, which you can then do using %run. |
|
2152 | 2152 | |
|
2153 | 2153 | |
|
2154 | 2154 | Arguments: |
|
2155 | 2155 | |
|
2156 | 2156 | If arguments are given, the following possibilites exist: |
|
2157 | 2157 | |
|
2158 | 2158 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2159 | 2159 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2160 | 2160 | loaded into the editor. The syntax is the same of the %macro command. |
|
2161 | 2161 | |
|
2162 | 2162 | - If the argument doesn't start with a number, it is evaluated as a |
|
2163 | 2163 | variable and its contents loaded into the editor. You can thus edit |
|
2164 | 2164 | any string which contains python code (including the result of |
|
2165 | 2165 | previous edits). |
|
2166 | 2166 | |
|
2167 | 2167 | - If the argument is the name of an object (other than a string), |
|
2168 | 2168 | IPython will try to locate the file where it was defined and open the |
|
2169 | 2169 | editor at the point where it is defined. You can use `%edit function` |
|
2170 | 2170 | to load an editor exactly at the point where 'function' is defined, |
|
2171 | 2171 | edit it and have the file be executed automatically. |
|
2172 | 2172 | |
|
2173 | 2173 | If the object is a macro (see %macro for details), this opens up your |
|
2174 | 2174 | specified editor with a temporary file containing the macro's data. |
|
2175 | 2175 | Upon exit, the macro is reloaded with the contents of the file. |
|
2176 | 2176 | |
|
2177 | 2177 | Note: opening at an exact line is only supported under Unix, and some |
|
2178 | 2178 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2179 | 2179 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2180 | 2180 | (X)Emacs, vi, jed, pico and joe all do. |
|
2181 | 2181 | |
|
2182 | 2182 | - If the argument is not found as a variable, IPython will look for a |
|
2183 | 2183 | file with that name (adding .py if necessary) and load it into the |
|
2184 | 2184 | editor. It will execute its contents with execfile() when you exit, |
|
2185 | 2185 | loading any code in the file into your interactive namespace. |
|
2186 | 2186 | |
|
2187 | 2187 | After executing your code, %edit will return as output the code you |
|
2188 | 2188 | typed in the editor (except when it was an existing file). This way |
|
2189 | 2189 | you can reload the code in further invocations of %edit as a variable, |
|
2190 | 2190 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2191 | 2191 | the output. |
|
2192 | 2192 | |
|
2193 | 2193 | Note that %edit is also available through the alias %ed. |
|
2194 | 2194 | |
|
2195 | 2195 | This is an example of creating a simple function inside the editor and |
|
2196 | 2196 | then modifying it. First, start up the editor: |
|
2197 | 2197 | |
|
2198 | 2198 | In [1]: ed |
|
2199 | 2199 | Editing... done. Executing edited code... |
|
2200 | 2200 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2201 | 2201 | |
|
2202 | 2202 | We can then call the function foo(): |
|
2203 | 2203 | |
|
2204 | 2204 | In [2]: foo() |
|
2205 | 2205 | foo() was defined in an editing session |
|
2206 | 2206 | |
|
2207 | 2207 | Now we edit foo. IPython automatically loads the editor with the |
|
2208 | 2208 | (temporary) file where foo() was previously defined: |
|
2209 | 2209 | |
|
2210 | 2210 | In [3]: ed foo |
|
2211 | 2211 | Editing... done. Executing edited code... |
|
2212 | 2212 | |
|
2213 | 2213 | And if we call foo() again we get the modified version: |
|
2214 | 2214 | |
|
2215 | 2215 | In [4]: foo() |
|
2216 | 2216 | foo() has now been changed! |
|
2217 | 2217 | |
|
2218 | 2218 | Here is an example of how to edit a code snippet successive |
|
2219 | 2219 | times. First we call the editor: |
|
2220 | 2220 | |
|
2221 | 2221 | In [5]: ed |
|
2222 | 2222 | Editing... done. Executing edited code... |
|
2223 | 2223 | hello |
|
2224 | 2224 | Out[5]: "print 'hello'n" |
|
2225 | 2225 | |
|
2226 | 2226 | Now we call it again with the previous output (stored in _): |
|
2227 | 2227 | |
|
2228 | 2228 | In [6]: ed _ |
|
2229 | 2229 | Editing... done. Executing edited code... |
|
2230 | 2230 | hello world |
|
2231 | 2231 | Out[6]: "print 'hello world'n" |
|
2232 | 2232 | |
|
2233 | 2233 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2234 | 2234 | |
|
2235 | 2235 | In [7]: ed _8 |
|
2236 | 2236 | Editing... done. Executing edited code... |
|
2237 | 2237 | hello again |
|
2238 | 2238 | Out[7]: "print 'hello again'n" |
|
2239 | 2239 | |
|
2240 | 2240 | |
|
2241 | 2241 | Changing the default editor hook: |
|
2242 | 2242 | |
|
2243 | 2243 | If you wish to write your own editor hook, you can put it in a |
|
2244 | 2244 | configuration file which you load at startup time. The default hook |
|
2245 | 2245 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2246 | 2246 | starting example for further modifications. That file also has |
|
2247 | 2247 | general instructions on how to set a new hook for use once you've |
|
2248 | 2248 | defined it.""" |
|
2249 | 2249 | |
|
2250 | 2250 | # FIXME: This function has become a convoluted mess. It needs a |
|
2251 | 2251 | # ground-up rewrite with clean, simple logic. |
|
2252 | 2252 | |
|
2253 | 2253 | def make_filename(arg): |
|
2254 | 2254 | "Make a filename from the given args" |
|
2255 | 2255 | try: |
|
2256 | 2256 | filename = get_py_filename(arg) |
|
2257 | 2257 | except IOError: |
|
2258 | 2258 | if args.endswith('.py'): |
|
2259 | 2259 | filename = arg |
|
2260 | 2260 | else: |
|
2261 | 2261 | filename = None |
|
2262 | 2262 | return filename |
|
2263 | 2263 | |
|
2264 | 2264 | # custom exceptions |
|
2265 | 2265 | class DataIsObject(Exception): pass |
|
2266 | 2266 | |
|
2267 | 2267 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2268 | 2268 | # Set a few locals from the options for convenience: |
|
2269 | 2269 | opts_p = opts.has_key('p') |
|
2270 | 2270 | opts_r = opts.has_key('r') |
|
2271 | 2271 | |
|
2272 | 2272 | # Default line number value |
|
2273 | 2273 | lineno = opts.get('n',None) |
|
2274 | 2274 | |
|
2275 | 2275 | if opts_p: |
|
2276 | 2276 | args = '_%s' % last_call[0] |
|
2277 | 2277 | if not self.shell.user_ns.has_key(args): |
|
2278 | 2278 | args = last_call[1] |
|
2279 | 2279 | |
|
2280 | 2280 | # use last_call to remember the state of the previous call, but don't |
|
2281 | 2281 | # let it be clobbered by successive '-p' calls. |
|
2282 | 2282 | try: |
|
2283 | 2283 | last_call[0] = self.shell.displayhook.prompt_count |
|
2284 | 2284 | if not opts_p: |
|
2285 | 2285 | last_call[1] = parameter_s |
|
2286 | 2286 | except: |
|
2287 | 2287 | pass |
|
2288 | 2288 | |
|
2289 | 2289 | # by default this is done with temp files, except when the given |
|
2290 | 2290 | # arg is a filename |
|
2291 | 2291 | use_temp = 1 |
|
2292 | 2292 | |
|
2293 | 2293 | if re.match(r'\d',args): |
|
2294 | 2294 | # Mode where user specifies ranges of lines, like in %macro. |
|
2295 | 2295 | # This means that you can't edit files whose names begin with |
|
2296 | 2296 | # numbers this way. Tough. |
|
2297 | 2297 | ranges = args.split() |
|
2298 | 2298 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2299 | 2299 | elif args.endswith('.py'): |
|
2300 | 2300 | filename = make_filename(args) |
|
2301 | 2301 | data = '' |
|
2302 | 2302 | use_temp = 0 |
|
2303 | 2303 | elif args: |
|
2304 | 2304 | try: |
|
2305 | 2305 | # Load the parameter given as a variable. If not a string, |
|
2306 | 2306 | # process it as an object instead (below) |
|
2307 | 2307 | |
|
2308 | 2308 | #print '*** args',args,'type',type(args) # dbg |
|
2309 | 2309 | data = eval(args,self.shell.user_ns) |
|
2310 | 2310 | if not type(data) in StringTypes: |
|
2311 | 2311 | raise DataIsObject |
|
2312 | 2312 | |
|
2313 | 2313 | except (NameError,SyntaxError): |
|
2314 | 2314 | # given argument is not a variable, try as a filename |
|
2315 | 2315 | filename = make_filename(args) |
|
2316 | 2316 | if filename is None: |
|
2317 | 2317 | warn("Argument given (%s) can't be found as a variable " |
|
2318 | 2318 | "or as a filename." % args) |
|
2319 | 2319 | return |
|
2320 | 2320 | |
|
2321 | 2321 | data = '' |
|
2322 | 2322 | use_temp = 0 |
|
2323 | 2323 | except DataIsObject: |
|
2324 | 2324 | |
|
2325 | 2325 | # macros have a special edit function |
|
2326 | 2326 | if isinstance(data,Macro): |
|
2327 | 2327 | self._edit_macro(args,data) |
|
2328 | 2328 | return |
|
2329 | 2329 | |
|
2330 | 2330 | # For objects, try to edit the file where they are defined |
|
2331 | 2331 | try: |
|
2332 | 2332 | filename = inspect.getabsfile(data) |
|
2333 | 2333 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2334 | 2334 | # class created by %edit? Try to find source |
|
2335 | 2335 | # by looking for method definitions instead, the |
|
2336 | 2336 | # __module__ in those classes is FakeModule. |
|
2337 | 2337 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2338 | 2338 | for attr in attrs: |
|
2339 | 2339 | if not inspect.ismethod(attr): |
|
2340 | 2340 | continue |
|
2341 | 2341 | filename = inspect.getabsfile(attr) |
|
2342 | 2342 | if filename and 'fakemodule' not in filename.lower(): |
|
2343 | 2343 | # change the attribute to be the edit target instead |
|
2344 | 2344 | data = attr |
|
2345 | 2345 | break |
|
2346 | 2346 | |
|
2347 | 2347 | datafile = 1 |
|
2348 | 2348 | except TypeError: |
|
2349 | 2349 | filename = make_filename(args) |
|
2350 | 2350 | datafile = 1 |
|
2351 | 2351 | warn('Could not find file where `%s` is defined.\n' |
|
2352 | 2352 | 'Opening a file named `%s`' % (args,filename)) |
|
2353 | 2353 | # Now, make sure we can actually read the source (if it was in |
|
2354 | 2354 | # a temp file it's gone by now). |
|
2355 | 2355 | if datafile: |
|
2356 | 2356 | try: |
|
2357 | 2357 | if lineno is None: |
|
2358 | 2358 | lineno = inspect.getsourcelines(data)[1] |
|
2359 | 2359 | except IOError: |
|
2360 | 2360 | filename = make_filename(args) |
|
2361 | 2361 | if filename is None: |
|
2362 | 2362 | warn('The file `%s` where `%s` was defined cannot ' |
|
2363 | 2363 | 'be read.' % (filename,data)) |
|
2364 | 2364 | return |
|
2365 | 2365 | use_temp = 0 |
|
2366 | 2366 | else: |
|
2367 | 2367 | data = '' |
|
2368 | 2368 | |
|
2369 | 2369 | if use_temp: |
|
2370 | 2370 | filename = self.shell.mktempfile(data) |
|
2371 | 2371 | print 'IPython will make a temporary file named:',filename |
|
2372 | 2372 | |
|
2373 | 2373 | # do actual editing here |
|
2374 | 2374 | print 'Editing...', |
|
2375 | 2375 | sys.stdout.flush() |
|
2376 | 2376 | try: |
|
2377 | 2377 | # Quote filenames that may have spaces in them |
|
2378 | 2378 | if ' ' in filename: |
|
2379 | 2379 | filename = "%s" % filename |
|
2380 | 2380 | self.shell.hooks.editor(filename,lineno) |
|
2381 | 2381 | except TryNext: |
|
2382 | 2382 | warn('Could not open editor') |
|
2383 | 2383 | return |
|
2384 | 2384 | |
|
2385 | 2385 | # XXX TODO: should this be generalized for all string vars? |
|
2386 | 2386 | # For now, this is special-cased to blocks created by cpaste |
|
2387 | 2387 | if args.strip() == 'pasted_block': |
|
2388 | 2388 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2389 | 2389 | |
|
2390 | 2390 | if opts.has_key('x'): # -x prevents actual execution |
|
2391 | 2391 | |
|
2392 | 2392 | else: |
|
2393 | 2393 | print 'done. Executing edited code...' |
|
2394 | 2394 | if opts_r: |
|
2395 | 2395 | self.shell.run_cell(file_read(filename)) |
|
2396 | 2396 | else: |
|
2397 | 2397 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2398 | 2398 | self.shell.user_ns) |
|
2399 | 2399 | |
|
2400 | 2400 | |
|
2401 | 2401 | if use_temp: |
|
2402 | 2402 | try: |
|
2403 | 2403 | return open(filename).read() |
|
2404 | 2404 | except IOError,msg: |
|
2405 | 2405 | if msg.filename == filename: |
|
2406 | 2406 | warn('File not found. Did you forget to save?') |
|
2407 | 2407 | return |
|
2408 | 2408 | else: |
|
2409 | 2409 | self.shell.showtraceback() |
|
2410 | 2410 | |
|
2411 | 2411 | def magic_xmode(self,parameter_s = ''): |
|
2412 | 2412 | """Switch modes for the exception handlers. |
|
2413 | 2413 | |
|
2414 | 2414 | Valid modes: Plain, Context and Verbose. |
|
2415 | 2415 | |
|
2416 | 2416 | If called without arguments, acts as a toggle.""" |
|
2417 | 2417 | |
|
2418 | 2418 | def xmode_switch_err(name): |
|
2419 | 2419 | warn('Error changing %s exception modes.\n%s' % |
|
2420 | 2420 | (name,sys.exc_info()[1])) |
|
2421 | 2421 | |
|
2422 | 2422 | shell = self.shell |
|
2423 | 2423 | new_mode = parameter_s.strip().capitalize() |
|
2424 | 2424 | try: |
|
2425 | 2425 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2426 | 2426 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2427 | 2427 | except: |
|
2428 | 2428 | xmode_switch_err('user') |
|
2429 | 2429 | |
|
2430 | 2430 | def magic_colors(self,parameter_s = ''): |
|
2431 | 2431 | """Switch color scheme for prompts, info system and exception handlers. |
|
2432 | 2432 | |
|
2433 | 2433 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2434 | 2434 | |
|
2435 | 2435 | Color scheme names are not case-sensitive. |
|
2436 | 2436 | |
|
2437 | 2437 | Examples |
|
2438 | 2438 | -------- |
|
2439 | 2439 | To get a plain black and white terminal:: |
|
2440 | 2440 | |
|
2441 | 2441 | %colors nocolor |
|
2442 | 2442 | """ |
|
2443 | 2443 | |
|
2444 | 2444 | def color_switch_err(name): |
|
2445 | 2445 | warn('Error changing %s color schemes.\n%s' % |
|
2446 | 2446 | (name,sys.exc_info()[1])) |
|
2447 | 2447 | |
|
2448 | 2448 | |
|
2449 | 2449 | new_scheme = parameter_s.strip() |
|
2450 | 2450 | if not new_scheme: |
|
2451 | 2451 | raise UsageError( |
|
2452 | 2452 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2453 | 2453 | return |
|
2454 | 2454 | # local shortcut |
|
2455 | 2455 | shell = self.shell |
|
2456 | 2456 | |
|
2457 | 2457 | import IPython.utils.rlineimpl as readline |
|
2458 | 2458 | |
|
2459 | 2459 | if not readline.have_readline and sys.platform == "win32": |
|
2460 | 2460 | msg = """\ |
|
2461 | 2461 | Proper color support under MS Windows requires the pyreadline library. |
|
2462 | 2462 | You can find it at: |
|
2463 | 2463 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2464 | 2464 | Gary's readline needs the ctypes module, from: |
|
2465 | 2465 | http://starship.python.net/crew/theller/ctypes |
|
2466 | 2466 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2467 | 2467 | |
|
2468 | 2468 | Defaulting color scheme to 'NoColor'""" |
|
2469 | 2469 | new_scheme = 'NoColor' |
|
2470 | 2470 | warn(msg) |
|
2471 | 2471 | |
|
2472 | 2472 | # readline option is 0 |
|
2473 | 2473 | if not shell.has_readline: |
|
2474 | 2474 | new_scheme = 'NoColor' |
|
2475 | 2475 | |
|
2476 | 2476 | # Set prompt colors |
|
2477 | 2477 | try: |
|
2478 | 2478 | shell.displayhook.set_colors(new_scheme) |
|
2479 | 2479 | except: |
|
2480 | 2480 | color_switch_err('prompt') |
|
2481 | 2481 | else: |
|
2482 | 2482 | shell.colors = \ |
|
2483 | 2483 | shell.displayhook.color_table.active_scheme_name |
|
2484 | 2484 | # Set exception colors |
|
2485 | 2485 | try: |
|
2486 | 2486 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2487 | 2487 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2488 | 2488 | except: |
|
2489 | 2489 | color_switch_err('exception') |
|
2490 | 2490 | |
|
2491 | 2491 | # Set info (for 'object?') colors |
|
2492 | 2492 | if shell.color_info: |
|
2493 | 2493 | try: |
|
2494 | 2494 | shell.inspector.set_active_scheme(new_scheme) |
|
2495 | 2495 | except: |
|
2496 | 2496 | color_switch_err('object inspector') |
|
2497 | 2497 | else: |
|
2498 | 2498 | shell.inspector.set_active_scheme('NoColor') |
|
2499 | 2499 | |
|
2500 | 2500 | def magic_pprint(self, parameter_s=''): |
|
2501 | 2501 | """Toggle pretty printing on/off.""" |
|
2502 | 2502 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
2503 | 2503 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
2504 | 2504 | print 'Pretty printing has been turned', \ |
|
2505 | 2505 | ['OFF','ON'][ptformatter.pprint] |
|
2506 | 2506 | |
|
2507 | 2507 | def magic_Exit(self, parameter_s=''): |
|
2508 | 2508 | """Exit IPython.""" |
|
2509 | 2509 | |
|
2510 | 2510 | self.shell.ask_exit() |
|
2511 | 2511 | |
|
2512 | 2512 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
2513 | 2513 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
2514 | 2514 | |
|
2515 | 2515 | #...................................................................... |
|
2516 | 2516 | # Functions to implement unix shell-type things |
|
2517 | 2517 | |
|
2518 | 2518 | @testdec.skip_doctest |
|
2519 | 2519 | def magic_alias(self, parameter_s = ''): |
|
2520 | 2520 | """Define an alias for a system command. |
|
2521 | 2521 | |
|
2522 | 2522 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2523 | 2523 | |
|
2524 | 2524 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2525 | 2525 | params' (from your underlying operating system). |
|
2526 | 2526 | |
|
2527 | 2527 | Aliases have lower precedence than magic functions and Python normal |
|
2528 | 2528 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2529 | 2529 | alias can not be executed until 'del foo' removes the Python variable. |
|
2530 | 2530 | |
|
2531 | 2531 | You can use the %l specifier in an alias definition to represent the |
|
2532 | 2532 | whole line when the alias is called. For example: |
|
2533 | 2533 | |
|
2534 | 2534 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2535 | 2535 | In [3]: bracket hello world |
|
2536 | 2536 | Input in brackets: <hello world> |
|
2537 | 2537 | |
|
2538 | 2538 | You can also define aliases with parameters using %s specifiers (one |
|
2539 | 2539 | per parameter): |
|
2540 | 2540 | |
|
2541 | 2541 | In [1]: alias parts echo first %s second %s |
|
2542 | 2542 | In [2]: %parts A B |
|
2543 | 2543 | first A second B |
|
2544 | 2544 | In [3]: %parts A |
|
2545 | 2545 | Incorrect number of arguments: 2 expected. |
|
2546 | 2546 | parts is an alias to: 'echo first %s second %s' |
|
2547 | 2547 | |
|
2548 | 2548 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2549 | 2549 | the other in your aliases. |
|
2550 | 2550 | |
|
2551 | 2551 | Aliases expand Python variables just like system calls using ! or !! |
|
2552 | 2552 | do: all expressions prefixed with '$' get expanded. For details of |
|
2553 | 2553 | the semantic rules, see PEP-215: |
|
2554 | 2554 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2555 | 2555 | IPython for variable expansion. If you want to access a true shell |
|
2556 | 2556 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2557 | 2557 | |
|
2558 | 2558 | In [6]: alias show echo |
|
2559 | 2559 | In [7]: PATH='A Python string' |
|
2560 | 2560 | In [8]: show $PATH |
|
2561 | 2561 | A Python string |
|
2562 | 2562 | In [9]: show $$PATH |
|
2563 | 2563 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2564 | 2564 | |
|
2565 | 2565 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2566 | 2566 | and %rehashx functions, which automatically create aliases for the |
|
2567 | 2567 | contents of your $PATH. |
|
2568 | 2568 | |
|
2569 | 2569 | If called with no parameters, %alias prints the current alias table.""" |
|
2570 | 2570 | |
|
2571 | 2571 | par = parameter_s.strip() |
|
2572 | 2572 | if not par: |
|
2573 | 2573 | stored = self.db.get('stored_aliases', {} ) |
|
2574 | 2574 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2575 | 2575 | # for k, v in stored: |
|
2576 | 2576 | # atab.append(k, v[0]) |
|
2577 | 2577 | |
|
2578 | 2578 | print "Total number of aliases:", len(aliases) |
|
2579 | 2579 | sys.stdout.flush() |
|
2580 | 2580 | return aliases |
|
2581 | 2581 | |
|
2582 | 2582 | # Now try to define a new one |
|
2583 | 2583 | try: |
|
2584 | 2584 | alias,cmd = par.split(None, 1) |
|
2585 | 2585 | except: |
|
2586 | 2586 | print oinspect.getdoc(self.magic_alias) |
|
2587 | 2587 | else: |
|
2588 | 2588 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2589 | 2589 | # end magic_alias |
|
2590 | 2590 | |
|
2591 | 2591 | def magic_unalias(self, parameter_s = ''): |
|
2592 | 2592 | """Remove an alias""" |
|
2593 | 2593 | |
|
2594 | 2594 | aname = parameter_s.strip() |
|
2595 | 2595 | self.shell.alias_manager.undefine_alias(aname) |
|
2596 | 2596 | stored = self.db.get('stored_aliases', {} ) |
|
2597 | 2597 | if aname in stored: |
|
2598 | 2598 | print "Removing %stored alias",aname |
|
2599 | 2599 | del stored[aname] |
|
2600 | 2600 | self.db['stored_aliases'] = stored |
|
2601 | 2601 | |
|
2602 | 2602 | def magic_rehashx(self, parameter_s = ''): |
|
2603 | 2603 | """Update the alias table with all executable files in $PATH. |
|
2604 | 2604 | |
|
2605 | 2605 | This version explicitly checks that every entry in $PATH is a file |
|
2606 | 2606 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2607 | 2607 | |
|
2608 | 2608 | Under Windows, it checks executability as a match agains a |
|
2609 | 2609 | '|'-separated string of extensions, stored in the IPython config |
|
2610 | 2610 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2611 | 2611 | |
|
2612 | 2612 | This function also resets the root module cache of module completer, |
|
2613 | 2613 | used on slow filesystems. |
|
2614 | 2614 | """ |
|
2615 | 2615 | from IPython.core.alias import InvalidAliasError |
|
2616 | 2616 | |
|
2617 | 2617 | # for the benefit of module completer in ipy_completers.py |
|
2618 | 2618 | del self.db['rootmodules'] |
|
2619 | 2619 | |
|
2620 | 2620 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2621 | 2621 | os.environ.get('PATH','').split(os.pathsep)] |
|
2622 | 2622 | path = filter(os.path.isdir,path) |
|
2623 | 2623 | |
|
2624 | 2624 | syscmdlist = [] |
|
2625 | 2625 | # Now define isexec in a cross platform manner. |
|
2626 | 2626 | if os.name == 'posix': |
|
2627 | 2627 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2628 | 2628 | os.access(fname,os.X_OK) |
|
2629 | 2629 | else: |
|
2630 | 2630 | try: |
|
2631 | 2631 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2632 | 2632 | except KeyError: |
|
2633 | 2633 | winext = 'exe|com|bat|py' |
|
2634 | 2634 | if 'py' not in winext: |
|
2635 | 2635 | winext += '|py' |
|
2636 | 2636 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2637 | 2637 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2638 | 2638 | savedir = os.getcwd() |
|
2639 | 2639 | |
|
2640 | 2640 | # Now walk the paths looking for executables to alias. |
|
2641 | 2641 | try: |
|
2642 | 2642 | # write the whole loop for posix/Windows so we don't have an if in |
|
2643 | 2643 | # the innermost part |
|
2644 | 2644 | if os.name == 'posix': |
|
2645 | 2645 | for pdir in path: |
|
2646 | 2646 | os.chdir(pdir) |
|
2647 | 2647 | for ff in os.listdir(pdir): |
|
2648 | 2648 | if isexec(ff): |
|
2649 | 2649 | try: |
|
2650 | 2650 | # Removes dots from the name since ipython |
|
2651 | 2651 | # will assume names with dots to be python. |
|
2652 | 2652 | self.shell.alias_manager.define_alias( |
|
2653 | 2653 | ff.replace('.',''), ff) |
|
2654 | 2654 | except InvalidAliasError: |
|
2655 | 2655 | pass |
|
2656 | 2656 | else: |
|
2657 | 2657 | syscmdlist.append(ff) |
|
2658 | 2658 | else: |
|
2659 | 2659 | no_alias = self.shell.alias_manager.no_alias |
|
2660 | 2660 | for pdir in path: |
|
2661 | 2661 | os.chdir(pdir) |
|
2662 | 2662 | for ff in os.listdir(pdir): |
|
2663 | 2663 | base, ext = os.path.splitext(ff) |
|
2664 | 2664 | if isexec(ff) and base.lower() not in no_alias: |
|
2665 | 2665 | if ext.lower() == '.exe': |
|
2666 | 2666 | ff = base |
|
2667 | 2667 | try: |
|
2668 | 2668 | # Removes dots from the name since ipython |
|
2669 | 2669 | # will assume names with dots to be python. |
|
2670 | 2670 | self.shell.alias_manager.define_alias( |
|
2671 | 2671 | base.lower().replace('.',''), ff) |
|
2672 | 2672 | except InvalidAliasError: |
|
2673 | 2673 | pass |
|
2674 | 2674 | syscmdlist.append(ff) |
|
2675 | 2675 | db = self.db |
|
2676 | 2676 | db['syscmdlist'] = syscmdlist |
|
2677 | 2677 | finally: |
|
2678 | 2678 | os.chdir(savedir) |
|
2679 | 2679 | |
|
2680 | 2680 | @testdec.skip_doctest |
|
2681 | 2681 | def magic_pwd(self, parameter_s = ''): |
|
2682 | 2682 | """Return the current working directory path. |
|
2683 | 2683 | |
|
2684 | 2684 | Examples |
|
2685 | 2685 | -------- |
|
2686 | 2686 | :: |
|
2687 | 2687 | |
|
2688 | 2688 | In [9]: pwd |
|
2689 | 2689 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2690 | 2690 | """ |
|
2691 | 2691 | return os.getcwd() |
|
2692 | 2692 | |
|
2693 | 2693 | @testdec.skip_doctest |
|
2694 | 2694 | def magic_cd(self, parameter_s=''): |
|
2695 | 2695 | """Change the current working directory. |
|
2696 | 2696 | |
|
2697 | 2697 | This command automatically maintains an internal list of directories |
|
2698 | 2698 | you visit during your IPython session, in the variable _dh. The |
|
2699 | 2699 | command %dhist shows this history nicely formatted. You can also |
|
2700 | 2700 | do 'cd -<tab>' to see directory history conveniently. |
|
2701 | 2701 | |
|
2702 | 2702 | Usage: |
|
2703 | 2703 | |
|
2704 | 2704 | cd 'dir': changes to directory 'dir'. |
|
2705 | 2705 | |
|
2706 | 2706 | cd -: changes to the last visited directory. |
|
2707 | 2707 | |
|
2708 | 2708 | cd -<n>: changes to the n-th directory in the directory history. |
|
2709 | 2709 | |
|
2710 | 2710 | cd --foo: change to directory that matches 'foo' in history |
|
2711 | 2711 | |
|
2712 | 2712 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2713 | 2713 | (note: cd <bookmark_name> is enough if there is no |
|
2714 | 2714 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2715 | 2715 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2716 | 2716 | |
|
2717 | 2717 | Options: |
|
2718 | 2718 | |
|
2719 | 2719 | -q: quiet. Do not print the working directory after the cd command is |
|
2720 | 2720 | executed. By default IPython's cd command does print this directory, |
|
2721 | 2721 | since the default prompts do not display path information. |
|
2722 | 2722 | |
|
2723 | 2723 | Note that !cd doesn't work for this purpose because the shell where |
|
2724 | 2724 | !command runs is immediately discarded after executing 'command'. |
|
2725 | 2725 | |
|
2726 | 2726 | Examples |
|
2727 | 2727 | -------- |
|
2728 | 2728 | :: |
|
2729 | 2729 | |
|
2730 | 2730 | In [10]: cd parent/child |
|
2731 | 2731 | /home/tsuser/parent/child |
|
2732 | 2732 | """ |
|
2733 | 2733 | |
|
2734 | 2734 | parameter_s = parameter_s.strip() |
|
2735 | 2735 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2736 | 2736 | |
|
2737 | 2737 | oldcwd = os.getcwd() |
|
2738 | 2738 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2739 | 2739 | # jump in directory history by number |
|
2740 | 2740 | if numcd: |
|
2741 | 2741 | nn = int(numcd.group(2)) |
|
2742 | 2742 | try: |
|
2743 | 2743 | ps = self.shell.user_ns['_dh'][nn] |
|
2744 | 2744 | except IndexError: |
|
2745 | 2745 | print 'The requested directory does not exist in history.' |
|
2746 | 2746 | return |
|
2747 | 2747 | else: |
|
2748 | 2748 | opts = {} |
|
2749 | 2749 | elif parameter_s.startswith('--'): |
|
2750 | 2750 | ps = None |
|
2751 | 2751 | fallback = None |
|
2752 | 2752 | pat = parameter_s[2:] |
|
2753 | 2753 | dh = self.shell.user_ns['_dh'] |
|
2754 | 2754 | # first search only by basename (last component) |
|
2755 | 2755 | for ent in reversed(dh): |
|
2756 | 2756 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2757 | 2757 | ps = ent |
|
2758 | 2758 | break |
|
2759 | 2759 | |
|
2760 | 2760 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2761 | 2761 | fallback = ent |
|
2762 | 2762 | |
|
2763 | 2763 | # if we have no last part match, pick the first full path match |
|
2764 | 2764 | if ps is None: |
|
2765 | 2765 | ps = fallback |
|
2766 | 2766 | |
|
2767 | 2767 | if ps is None: |
|
2768 | 2768 | print "No matching entry in directory history" |
|
2769 | 2769 | return |
|
2770 | 2770 | else: |
|
2771 | 2771 | opts = {} |
|
2772 | 2772 | |
|
2773 | 2773 | |
|
2774 | 2774 | else: |
|
2775 | 2775 | #turn all non-space-escaping backslashes to slashes, |
|
2776 | 2776 | # for c:\windows\directory\names\ |
|
2777 | 2777 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2778 | 2778 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2779 | 2779 | # jump to previous |
|
2780 | 2780 | if ps == '-': |
|
2781 | 2781 | try: |
|
2782 | 2782 | ps = self.shell.user_ns['_dh'][-2] |
|
2783 | 2783 | except IndexError: |
|
2784 | 2784 | raise UsageError('%cd -: No previous directory to change to.') |
|
2785 | 2785 | # jump to bookmark if needed |
|
2786 | 2786 | else: |
|
2787 | 2787 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2788 | 2788 | bkms = self.db.get('bookmarks', {}) |
|
2789 | 2789 | |
|
2790 | 2790 | if bkms.has_key(ps): |
|
2791 | 2791 | target = bkms[ps] |
|
2792 | 2792 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2793 | 2793 | ps = target |
|
2794 | 2794 | else: |
|
2795 | 2795 | if opts.has_key('b'): |
|
2796 | 2796 | raise UsageError("Bookmark '%s' not found. " |
|
2797 | 2797 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2798 | 2798 | |
|
2799 | 2799 | # at this point ps should point to the target dir |
|
2800 | 2800 | if ps: |
|
2801 | 2801 | try: |
|
2802 | 2802 | os.chdir(os.path.expanduser(ps)) |
|
2803 | 2803 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2804 | 2804 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2805 | 2805 | except OSError: |
|
2806 | 2806 | print sys.exc_info()[1] |
|
2807 | 2807 | else: |
|
2808 | 2808 | cwd = os.getcwd() |
|
2809 | 2809 | dhist = self.shell.user_ns['_dh'] |
|
2810 | 2810 | if oldcwd != cwd: |
|
2811 | 2811 | dhist.append(cwd) |
|
2812 | 2812 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2813 | 2813 | |
|
2814 | 2814 | else: |
|
2815 | 2815 | os.chdir(self.shell.home_dir) |
|
2816 | 2816 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2817 | 2817 | set_term_title('IPython: ' + '~') |
|
2818 | 2818 | cwd = os.getcwd() |
|
2819 | 2819 | dhist = self.shell.user_ns['_dh'] |
|
2820 | 2820 | |
|
2821 | 2821 | if oldcwd != cwd: |
|
2822 | 2822 | dhist.append(cwd) |
|
2823 | 2823 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2824 | 2824 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2825 | 2825 | print self.shell.user_ns['_dh'][-1] |
|
2826 | 2826 | |
|
2827 | 2827 | |
|
2828 | 2828 | def magic_env(self, parameter_s=''): |
|
2829 | 2829 | """List environment variables.""" |
|
2830 | 2830 | |
|
2831 | 2831 | return os.environ.data |
|
2832 | 2832 | |
|
2833 | 2833 | def magic_pushd(self, parameter_s=''): |
|
2834 | 2834 | """Place the current dir on stack and change directory. |
|
2835 | 2835 | |
|
2836 | 2836 | Usage:\\ |
|
2837 | 2837 | %pushd ['dirname'] |
|
2838 | 2838 | """ |
|
2839 | 2839 | |
|
2840 | 2840 | dir_s = self.shell.dir_stack |
|
2841 | 2841 | tgt = os.path.expanduser(parameter_s) |
|
2842 | 2842 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2843 | 2843 | if tgt: |
|
2844 | 2844 | self.magic_cd(parameter_s) |
|
2845 | 2845 | dir_s.insert(0,cwd) |
|
2846 | 2846 | return self.magic_dirs() |
|
2847 | 2847 | |
|
2848 | 2848 | def magic_popd(self, parameter_s=''): |
|
2849 | 2849 | """Change to directory popped off the top of the stack. |
|
2850 | 2850 | """ |
|
2851 | 2851 | if not self.shell.dir_stack: |
|
2852 | 2852 | raise UsageError("%popd on empty stack") |
|
2853 | 2853 | top = self.shell.dir_stack.pop(0) |
|
2854 | 2854 | self.magic_cd(top) |
|
2855 | 2855 | print "popd ->",top |
|
2856 | 2856 | |
|
2857 | 2857 | def magic_dirs(self, parameter_s=''): |
|
2858 | 2858 | """Return the current directory stack.""" |
|
2859 | 2859 | |
|
2860 | 2860 | return self.shell.dir_stack |
|
2861 | 2861 | |
|
2862 | 2862 | def magic_dhist(self, parameter_s=''): |
|
2863 | 2863 | """Print your history of visited directories. |
|
2864 | 2864 | |
|
2865 | 2865 | %dhist -> print full history\\ |
|
2866 | 2866 | %dhist n -> print last n entries only\\ |
|
2867 | 2867 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2868 | 2868 | |
|
2869 | 2869 | This history is automatically maintained by the %cd command, and |
|
2870 | 2870 | always available as the global list variable _dh. You can use %cd -<n> |
|
2871 | 2871 | to go to directory number <n>. |
|
2872 | 2872 | |
|
2873 | 2873 | Note that most of time, you should view directory history by entering |
|
2874 | 2874 | cd -<TAB>. |
|
2875 | 2875 | |
|
2876 | 2876 | """ |
|
2877 | 2877 | |
|
2878 | 2878 | dh = self.shell.user_ns['_dh'] |
|
2879 | 2879 | if parameter_s: |
|
2880 | 2880 | try: |
|
2881 | 2881 | args = map(int,parameter_s.split()) |
|
2882 | 2882 | except: |
|
2883 | 2883 | self.arg_err(Magic.magic_dhist) |
|
2884 | 2884 | return |
|
2885 | 2885 | if len(args) == 1: |
|
2886 | 2886 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2887 | 2887 | elif len(args) == 2: |
|
2888 | 2888 | ini,fin = args |
|
2889 | 2889 | else: |
|
2890 | 2890 | self.arg_err(Magic.magic_dhist) |
|
2891 | 2891 | return |
|
2892 | 2892 | else: |
|
2893 | 2893 | ini,fin = 0,len(dh) |
|
2894 | 2894 | nlprint(dh, |
|
2895 | 2895 | header = 'Directory history (kept in _dh)', |
|
2896 | 2896 | start=ini,stop=fin) |
|
2897 | 2897 | |
|
2898 | 2898 | @testdec.skip_doctest |
|
2899 | 2899 | def magic_sc(self, parameter_s=''): |
|
2900 | 2900 | """Shell capture - execute a shell command and capture its output. |
|
2901 | 2901 | |
|
2902 | 2902 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2903 | 2903 | |
|
2904 | 2904 | You should use the form 'var = !command' instead. Example: |
|
2905 | 2905 | |
|
2906 | 2906 | "%sc -l myfiles = ls ~" should now be written as |
|
2907 | 2907 | |
|
2908 | 2908 | "myfiles = !ls ~" |
|
2909 | 2909 | |
|
2910 | 2910 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2911 | 2911 | below. |
|
2912 | 2912 | |
|
2913 | 2913 | -- |
|
2914 | 2914 | %sc [options] varname=command |
|
2915 | 2915 | |
|
2916 | 2916 | IPython will run the given command using commands.getoutput(), and |
|
2917 | 2917 | will then update the user's interactive namespace with a variable |
|
2918 | 2918 | called varname, containing the value of the call. Your command can |
|
2919 | 2919 | contain shell wildcards, pipes, etc. |
|
2920 | 2920 | |
|
2921 | 2921 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2922 | 2922 | supply must follow Python's standard conventions for valid names. |
|
2923 | 2923 | |
|
2924 | 2924 | (A special format without variable name exists for internal use) |
|
2925 | 2925 | |
|
2926 | 2926 | Options: |
|
2927 | 2927 | |
|
2928 | 2928 | -l: list output. Split the output on newlines into a list before |
|
2929 | 2929 | assigning it to the given variable. By default the output is stored |
|
2930 | 2930 | as a single string. |
|
2931 | 2931 | |
|
2932 | 2932 | -v: verbose. Print the contents of the variable. |
|
2933 | 2933 | |
|
2934 | 2934 | In most cases you should not need to split as a list, because the |
|
2935 | 2935 | returned value is a special type of string which can automatically |
|
2936 | 2936 | provide its contents either as a list (split on newlines) or as a |
|
2937 | 2937 | space-separated string. These are convenient, respectively, either |
|
2938 | 2938 | for sequential processing or to be passed to a shell command. |
|
2939 | 2939 | |
|
2940 | 2940 | For example: |
|
2941 | 2941 | |
|
2942 | 2942 | # all-random |
|
2943 | 2943 | |
|
2944 | 2944 | # Capture into variable a |
|
2945 | 2945 | In [1]: sc a=ls *py |
|
2946 | 2946 | |
|
2947 | 2947 | # a is a string with embedded newlines |
|
2948 | 2948 | In [2]: a |
|
2949 | 2949 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2950 | 2950 | |
|
2951 | 2951 | # which can be seen as a list: |
|
2952 | 2952 | In [3]: a.l |
|
2953 | 2953 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2954 | 2954 | |
|
2955 | 2955 | # or as a whitespace-separated string: |
|
2956 | 2956 | In [4]: a.s |
|
2957 | 2957 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2958 | 2958 | |
|
2959 | 2959 | # a.s is useful to pass as a single command line: |
|
2960 | 2960 | In [5]: !wc -l $a.s |
|
2961 | 2961 | 146 setup.py |
|
2962 | 2962 | 130 win32_manual_post_install.py |
|
2963 | 2963 | 276 total |
|
2964 | 2964 | |
|
2965 | 2965 | # while the list form is useful to loop over: |
|
2966 | 2966 | In [6]: for f in a.l: |
|
2967 | 2967 | ...: !wc -l $f |
|
2968 | 2968 | ...: |
|
2969 | 2969 | 146 setup.py |
|
2970 | 2970 | 130 win32_manual_post_install.py |
|
2971 | 2971 | |
|
2972 | 2972 | Similiarly, the lists returned by the -l option are also special, in |
|
2973 | 2973 | the sense that you can equally invoke the .s attribute on them to |
|
2974 | 2974 | automatically get a whitespace-separated string from their contents: |
|
2975 | 2975 | |
|
2976 | 2976 | In [7]: sc -l b=ls *py |
|
2977 | 2977 | |
|
2978 | 2978 | In [8]: b |
|
2979 | 2979 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2980 | 2980 | |
|
2981 | 2981 | In [9]: b.s |
|
2982 | 2982 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2983 | 2983 | |
|
2984 | 2984 | In summary, both the lists and strings used for ouptut capture have |
|
2985 | 2985 | the following special attributes: |
|
2986 | 2986 | |
|
2987 | 2987 | .l (or .list) : value as list. |
|
2988 | 2988 | .n (or .nlstr): value as newline-separated string. |
|
2989 | 2989 | .s (or .spstr): value as space-separated string. |
|
2990 | 2990 | """ |
|
2991 | 2991 | |
|
2992 | 2992 | opts,args = self.parse_options(parameter_s,'lv') |
|
2993 | 2993 | # Try to get a variable name and command to run |
|
2994 | 2994 | try: |
|
2995 | 2995 | # the variable name must be obtained from the parse_options |
|
2996 | 2996 | # output, which uses shlex.split to strip options out. |
|
2997 | 2997 | var,_ = args.split('=',1) |
|
2998 | 2998 | var = var.strip() |
|
2999 | 2999 | # But the the command has to be extracted from the original input |
|
3000 | 3000 | # parameter_s, not on what parse_options returns, to avoid the |
|
3001 | 3001 | # quote stripping which shlex.split performs on it. |
|
3002 | 3002 | _,cmd = parameter_s.split('=',1) |
|
3003 | 3003 | except ValueError: |
|
3004 | 3004 | var,cmd = '','' |
|
3005 | 3005 | # If all looks ok, proceed |
|
3006 | 3006 | split = 'l' in opts |
|
3007 | 3007 | out = self.shell.getoutput(cmd, split=split) |
|
3008 | 3008 | if opts.has_key('v'): |
|
3009 | 3009 | print '%s ==\n%s' % (var,pformat(out)) |
|
3010 | 3010 | if var: |
|
3011 | 3011 | self.shell.user_ns.update({var:out}) |
|
3012 | 3012 | else: |
|
3013 | 3013 | return out |
|
3014 | 3014 | |
|
3015 | 3015 | def magic_sx(self, parameter_s=''): |
|
3016 | 3016 | """Shell execute - run a shell command and capture its output. |
|
3017 | 3017 | |
|
3018 | 3018 | %sx command |
|
3019 | 3019 | |
|
3020 | 3020 | IPython will run the given command using commands.getoutput(), and |
|
3021 | 3021 | return the result formatted as a list (split on '\\n'). Since the |
|
3022 | 3022 | output is _returned_, it will be stored in ipython's regular output |
|
3023 | 3023 | cache Out[N] and in the '_N' automatic variables. |
|
3024 | 3024 | |
|
3025 | 3025 | Notes: |
|
3026 | 3026 | |
|
3027 | 3027 | 1) If an input line begins with '!!', then %sx is automatically |
|
3028 | 3028 | invoked. That is, while: |
|
3029 | 3029 | !ls |
|
3030 | 3030 | causes ipython to simply issue system('ls'), typing |
|
3031 | 3031 | !!ls |
|
3032 | 3032 | is a shorthand equivalent to: |
|
3033 | 3033 | %sx ls |
|
3034 | 3034 | |
|
3035 | 3035 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3036 | 3036 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3037 | 3037 | to process line-oriented shell output via further python commands. |
|
3038 | 3038 | %sc is meant to provide much finer control, but requires more |
|
3039 | 3039 | typing. |
|
3040 | 3040 | |
|
3041 | 3041 | 3) Just like %sc -l, this is a list with special attributes: |
|
3042 | 3042 | |
|
3043 | 3043 | .l (or .list) : value as list. |
|
3044 | 3044 | .n (or .nlstr): value as newline-separated string. |
|
3045 | 3045 | .s (or .spstr): value as whitespace-separated string. |
|
3046 | 3046 | |
|
3047 | 3047 | This is very useful when trying to use such lists as arguments to |
|
3048 | 3048 | system commands.""" |
|
3049 | 3049 | |
|
3050 | 3050 | if parameter_s: |
|
3051 | 3051 | return self.shell.getoutput(parameter_s) |
|
3052 | 3052 | |
|
3053 | 3053 | def magic_r(self, parameter_s=''): |
|
3054 | 3054 | """Repeat previous input. |
|
3055 | 3055 | |
|
3056 | 3056 | Note: Consider using the more powerfull %rep instead! |
|
3057 | 3057 | |
|
3058 | 3058 | If given an argument, repeats the previous command which starts with |
|
3059 | 3059 | the same string, otherwise it just repeats the previous input. |
|
3060 | 3060 | |
|
3061 | 3061 | Shell escaped commands (with ! as first character) are not recognized |
|
3062 | 3062 | by this system, only pure python code and magic commands. |
|
3063 | 3063 | """ |
|
3064 | 3064 | |
|
3065 | 3065 | start = parameter_s.strip() |
|
3066 | 3066 | esc_magic = ESC_MAGIC |
|
3067 | 3067 | # Identify magic commands even if automagic is on (which means |
|
3068 | 3068 | # the in-memory version is different from that typed by the user). |
|
3069 | 3069 | if self.shell.automagic: |
|
3070 | 3070 | start_magic = esc_magic+start |
|
3071 | 3071 | else: |
|
3072 | 3072 | start_magic = start |
|
3073 | 3073 | # Look through the input history in reverse |
|
3074 | 3074 | for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1): |
|
3075 | 3075 | input = self.shell.history_manager.input_hist_parsed[n] |
|
3076 | 3076 | # skip plain 'r' lines so we don't recurse to infinity |
|
3077 | 3077 | if input != '_ip.magic("r")\n' and \ |
|
3078 | 3078 | (input.startswith(start) or input.startswith(start_magic)): |
|
3079 | 3079 | #print 'match',`input` # dbg |
|
3080 | 3080 | print 'Executing:',input, |
|
3081 | 3081 | self.shell.run_cell(input) |
|
3082 | 3082 | return |
|
3083 | 3083 | print 'No previous input matching `%s` found.' % start |
|
3084 | 3084 | |
|
3085 | 3085 | |
|
3086 | 3086 | def magic_bookmark(self, parameter_s=''): |
|
3087 | 3087 | """Manage IPython's bookmark system. |
|
3088 | 3088 | |
|
3089 | 3089 | %bookmark <name> - set bookmark to current dir |
|
3090 | 3090 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3091 | 3091 | %bookmark -l - list all bookmarks |
|
3092 | 3092 | %bookmark -d <name> - remove bookmark |
|
3093 | 3093 | %bookmark -r - remove all bookmarks |
|
3094 | 3094 | |
|
3095 | 3095 | You can later on access a bookmarked folder with: |
|
3096 | 3096 | %cd -b <name> |
|
3097 | 3097 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3098 | 3098 | there is such a bookmark defined. |
|
3099 | 3099 | |
|
3100 | 3100 | Your bookmarks persist through IPython sessions, but they are |
|
3101 | 3101 | associated with each profile.""" |
|
3102 | 3102 | |
|
3103 | 3103 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3104 | 3104 | if len(args) > 2: |
|
3105 | 3105 | raise UsageError("%bookmark: too many arguments") |
|
3106 | 3106 | |
|
3107 | 3107 | bkms = self.db.get('bookmarks',{}) |
|
3108 | 3108 | |
|
3109 | 3109 | if opts.has_key('d'): |
|
3110 | 3110 | try: |
|
3111 | 3111 | todel = args[0] |
|
3112 | 3112 | except IndexError: |
|
3113 | 3113 | raise UsageError( |
|
3114 | 3114 | "%bookmark -d: must provide a bookmark to delete") |
|
3115 | 3115 | else: |
|
3116 | 3116 | try: |
|
3117 | 3117 | del bkms[todel] |
|
3118 | 3118 | except KeyError: |
|
3119 | 3119 | raise UsageError( |
|
3120 | 3120 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3121 | 3121 | |
|
3122 | 3122 | elif opts.has_key('r'): |
|
3123 | 3123 | bkms = {} |
|
3124 | 3124 | elif opts.has_key('l'): |
|
3125 | 3125 | bks = bkms.keys() |
|
3126 | 3126 | bks.sort() |
|
3127 | 3127 | if bks: |
|
3128 | 3128 | size = max(map(len,bks)) |
|
3129 | 3129 | else: |
|
3130 | 3130 | size = 0 |
|
3131 | 3131 | fmt = '%-'+str(size)+'s -> %s' |
|
3132 | 3132 | print 'Current bookmarks:' |
|
3133 | 3133 | for bk in bks: |
|
3134 | 3134 | print fmt % (bk,bkms[bk]) |
|
3135 | 3135 | else: |
|
3136 | 3136 | if not args: |
|
3137 | 3137 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3138 | 3138 | elif len(args)==1: |
|
3139 | 3139 | bkms[args[0]] = os.getcwd() |
|
3140 | 3140 | elif len(args)==2: |
|
3141 | 3141 | bkms[args[0]] = args[1] |
|
3142 | 3142 | self.db['bookmarks'] = bkms |
|
3143 | 3143 | |
|
3144 | 3144 | def magic_pycat(self, parameter_s=''): |
|
3145 | 3145 | """Show a syntax-highlighted file through a pager. |
|
3146 | 3146 | |
|
3147 | 3147 | This magic is similar to the cat utility, but it will assume the file |
|
3148 | 3148 | to be Python source and will show it with syntax highlighting. """ |
|
3149 | 3149 | |
|
3150 | 3150 | try: |
|
3151 | 3151 | filename = get_py_filename(parameter_s) |
|
3152 | 3152 | cont = file_read(filename) |
|
3153 | 3153 | except IOError: |
|
3154 | 3154 | try: |
|
3155 | 3155 | cont = eval(parameter_s,self.user_ns) |
|
3156 | 3156 | except NameError: |
|
3157 | 3157 | cont = None |
|
3158 | 3158 | if cont is None: |
|
3159 | 3159 | print "Error: no such file or variable" |
|
3160 | 3160 | return |
|
3161 | 3161 | |
|
3162 | 3162 | page.page(self.shell.pycolorize(cont)) |
|
3163 | 3163 | |
|
3164 | 3164 | def _rerun_pasted(self): |
|
3165 | 3165 | """ Rerun a previously pasted command. |
|
3166 | 3166 | """ |
|
3167 | 3167 | b = self.user_ns.get('pasted_block', None) |
|
3168 | 3168 | if b is None: |
|
3169 | 3169 | raise UsageError('No previous pasted block available') |
|
3170 | 3170 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3171 | 3171 | exec b in self.user_ns |
|
3172 | 3172 | |
|
3173 | 3173 | def _get_pasted_lines(self, sentinel): |
|
3174 | 3174 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3175 | 3175 | """ |
|
3176 | 3176 | from IPython.core import interactiveshell |
|
3177 | 3177 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3178 | 3178 | while True: |
|
3179 | 3179 | l = interactiveshell.raw_input_original(':') |
|
3180 | 3180 | if l == sentinel: |
|
3181 | 3181 | return |
|
3182 | 3182 | else: |
|
3183 | 3183 | yield l |
|
3184 | 3184 | |
|
3185 | 3185 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3186 | 3186 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3187 | 3187 | code. |
|
3188 | 3188 | """ |
|
3189 | 3189 | # Regular expressions that declare text we strip from the input: |
|
3190 | 3190 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3191 | 3191 | r'^\s*(\s?>)+', # Python input prompt |
|
3192 | 3192 | r'^\s*\.{3,}', # Continuation prompts |
|
3193 | 3193 | r'^\++', |
|
3194 | 3194 | ] |
|
3195 | 3195 | |
|
3196 | 3196 | strip_from_start = map(re.compile,strip_re) |
|
3197 | 3197 | |
|
3198 | 3198 | lines = [] |
|
3199 | 3199 | for l in raw_lines: |
|
3200 | 3200 | for pat in strip_from_start: |
|
3201 | 3201 | l = pat.sub('',l) |
|
3202 | 3202 | lines.append(l) |
|
3203 | 3203 | |
|
3204 | 3204 | block = "\n".join(lines) + '\n' |
|
3205 | 3205 | #print "block:\n",block |
|
3206 | 3206 | return block |
|
3207 | 3207 | |
|
3208 | 3208 | def _execute_block(self, block, par): |
|
3209 | 3209 | """ Execute a block, or store it in a variable, per the user's request. |
|
3210 | 3210 | """ |
|
3211 | 3211 | if not par: |
|
3212 | 3212 | b = textwrap.dedent(block) |
|
3213 | 3213 | self.user_ns['pasted_block'] = b |
|
3214 | 3214 | exec b in self.user_ns |
|
3215 | 3215 | else: |
|
3216 | 3216 | self.user_ns[par] = SList(block.splitlines()) |
|
3217 | 3217 | print "Block assigned to '%s'" % par |
|
3218 | 3218 | |
|
3219 | 3219 | def magic_quickref(self,arg): |
|
3220 | 3220 | """ Show a quick reference sheet """ |
|
3221 | 3221 | import IPython.core.usage |
|
3222 | 3222 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3223 | 3223 | |
|
3224 | 3224 | page.page(qr) |
|
3225 | 3225 | |
|
3226 | 3226 | def magic_doctest_mode(self,parameter_s=''): |
|
3227 | 3227 | """Toggle doctest mode on and off. |
|
3228 | 3228 | |
|
3229 | 3229 | This mode is intended to make IPython behave as much as possible like a |
|
3230 | 3230 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3231 | 3231 | and output look. This makes it easy to copy and paste parts of a |
|
3232 | 3232 | session into doctests. It does so by: |
|
3233 | 3233 | |
|
3234 | 3234 | - Changing the prompts to the classic ``>>>`` ones. |
|
3235 | 3235 | - Changing the exception reporting mode to 'Plain'. |
|
3236 | 3236 | - Disabling pretty-printing of output. |
|
3237 | 3237 | |
|
3238 | 3238 | Note that IPython also supports the pasting of code snippets that have |
|
3239 | 3239 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3240 | 3240 | doctests from files or docstrings (even if they have leading |
|
3241 | 3241 | whitespace), and the code will execute correctly. You can then use |
|
3242 | 3242 | '%history -t' to see the translated history; this will give you the |
|
3243 | 3243 | input after removal of all the leading prompts and whitespace, which |
|
3244 | 3244 | can be pasted back into an editor. |
|
3245 | 3245 | |
|
3246 | 3246 | With these features, you can switch into this mode easily whenever you |
|
3247 | 3247 | need to do testing and changes to doctests, without having to leave |
|
3248 | 3248 | your existing IPython session. |
|
3249 | 3249 | """ |
|
3250 | 3250 | |
|
3251 | 3251 | from IPython.utils.ipstruct import Struct |
|
3252 | 3252 | |
|
3253 | 3253 | # Shorthands |
|
3254 | 3254 | shell = self.shell |
|
3255 | 3255 | oc = shell.displayhook |
|
3256 | 3256 | meta = shell.meta |
|
3257 | 3257 | disp_formatter = self.shell.display_formatter |
|
3258 | 3258 | ptformatter = disp_formatter.formatters['text/plain'] |
|
3259 | 3259 | # dstore is a data store kept in the instance metadata bag to track any |
|
3260 | 3260 | # changes we make, so we can undo them later. |
|
3261 | 3261 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3262 | 3262 | save_dstore = dstore.setdefault |
|
3263 | 3263 | |
|
3264 | 3264 | # save a few values we'll need to recover later |
|
3265 | 3265 | mode = save_dstore('mode',False) |
|
3266 | 3266 | save_dstore('rc_pprint',ptformatter.pprint) |
|
3267 | 3267 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3268 | 3268 | save_dstore('rc_separate_out',shell.separate_out) |
|
3269 | 3269 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3270 | 3270 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3271 | 3271 | save_dstore('rc_separate_in',shell.separate_in) |
|
3272 | 3272 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
3273 | 3273 | |
|
3274 | 3274 | if mode == False: |
|
3275 | 3275 | # turn on |
|
3276 | 3276 | oc.prompt1.p_template = '>>> ' |
|
3277 | 3277 | oc.prompt2.p_template = '... ' |
|
3278 | 3278 | oc.prompt_out.p_template = '' |
|
3279 | 3279 | |
|
3280 | 3280 | # Prompt separators like plain python |
|
3281 | 3281 | oc.input_sep = oc.prompt1.sep = '' |
|
3282 | 3282 | oc.output_sep = '' |
|
3283 | 3283 | oc.output_sep2 = '' |
|
3284 | 3284 | |
|
3285 | 3285 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3286 | 3286 | oc.prompt_out.pad_left = False |
|
3287 | 3287 | |
|
3288 | 3288 | ptformatter.pprint = False |
|
3289 | 3289 | disp_formatter.plain_text_only = True |
|
3290 | 3290 | |
|
3291 | 3291 | shell.magic_xmode('Plain') |
|
3292 | 3292 | else: |
|
3293 | 3293 | # turn off |
|
3294 | 3294 | oc.prompt1.p_template = shell.prompt_in1 |
|
3295 | 3295 | oc.prompt2.p_template = shell.prompt_in2 |
|
3296 | 3296 | oc.prompt_out.p_template = shell.prompt_out |
|
3297 | 3297 | |
|
3298 | 3298 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3299 | 3299 | |
|
3300 | 3300 | oc.output_sep = dstore.rc_separate_out |
|
3301 | 3301 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3302 | 3302 | |
|
3303 | 3303 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3304 | 3304 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3305 | 3305 | |
|
3306 | 3306 | ptformatter.pprint = dstore.rc_pprint |
|
3307 | 3307 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
3308 | 3308 | |
|
3309 | 3309 | shell.magic_xmode(dstore.xmode) |
|
3310 | 3310 | |
|
3311 | 3311 | # Store new mode and inform |
|
3312 | 3312 | dstore.mode = bool(1-int(mode)) |
|
3313 | 3313 | mode_label = ['OFF','ON'][dstore.mode] |
|
3314 | 3314 | print 'Doctest mode is:', mode_label |
|
3315 | 3315 | |
|
3316 | 3316 | def magic_gui(self, parameter_s=''): |
|
3317 | 3317 | """Enable or disable IPython GUI event loop integration. |
|
3318 | 3318 | |
|
3319 | 3319 | %gui [GUINAME] |
|
3320 | 3320 | |
|
3321 | 3321 | This magic replaces IPython's threaded shells that were activated |
|
3322 | 3322 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3323 | 3323 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3324 | 3324 | interrupts should work without any problems. The following toolkits |
|
3325 | 3325 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3326 | 3326 | |
|
3327 | 3327 | %gui wx # enable wxPython event loop integration |
|
3328 | 3328 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3329 | 3329 | %gui gtk # enable PyGTK event loop integration |
|
3330 | 3330 | %gui tk # enable Tk event loop integration |
|
3331 | 3331 | %gui # disable all event loop integration |
|
3332 | 3332 | |
|
3333 | 3333 | WARNING: after any of these has been called you can simply create |
|
3334 | 3334 | an application object, but DO NOT start the event loop yourself, as |
|
3335 | 3335 | we have already handled that. |
|
3336 | 3336 | """ |
|
3337 | 3337 | from IPython.lib.inputhook import enable_gui |
|
3338 | 3338 | opts, arg = self.parse_options(parameter_s, '') |
|
3339 | 3339 | if arg=='': arg = None |
|
3340 | 3340 | return enable_gui(arg) |
|
3341 | 3341 | |
|
3342 | 3342 | def magic_load_ext(self, module_str): |
|
3343 | 3343 | """Load an IPython extension by its module name.""" |
|
3344 | 3344 | return self.extension_manager.load_extension(module_str) |
|
3345 | 3345 | |
|
3346 | 3346 | def magic_unload_ext(self, module_str): |
|
3347 | 3347 | """Unload an IPython extension by its module name.""" |
|
3348 | 3348 | self.extension_manager.unload_extension(module_str) |
|
3349 | 3349 | |
|
3350 | 3350 | def magic_reload_ext(self, module_str): |
|
3351 | 3351 | """Reload an IPython extension by its module name.""" |
|
3352 | 3352 | self.extension_manager.reload_extension(module_str) |
|
3353 | 3353 | |
|
3354 | 3354 | @testdec.skip_doctest |
|
3355 | 3355 | def magic_install_profiles(self, s): |
|
3356 | 3356 | """Install the default IPython profiles into the .ipython dir. |
|
3357 | 3357 | |
|
3358 | 3358 | If the default profiles have already been installed, they will not |
|
3359 | 3359 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3360 | 3360 | option:: |
|
3361 | 3361 | |
|
3362 | 3362 | In [1]: %install_profiles -o |
|
3363 | 3363 | """ |
|
3364 | 3364 | if '-o' in s: |
|
3365 | 3365 | overwrite = True |
|
3366 | 3366 | else: |
|
3367 | 3367 | overwrite = False |
|
3368 | 3368 | from IPython.config import profile |
|
3369 | 3369 | profile_dir = os.path.split(profile.__file__)[0] |
|
3370 | 3370 | ipython_dir = self.ipython_dir |
|
3371 | 3371 | files = os.listdir(profile_dir) |
|
3372 | 3372 | |
|
3373 | 3373 | to_install = [] |
|
3374 | 3374 | for f in files: |
|
3375 | 3375 | if f.startswith('ipython_config'): |
|
3376 | 3376 | src = os.path.join(profile_dir, f) |
|
3377 | 3377 | dst = os.path.join(ipython_dir, f) |
|
3378 | 3378 | if (not os.path.isfile(dst)) or overwrite: |
|
3379 | 3379 | to_install.append((f, src, dst)) |
|
3380 | 3380 | if len(to_install)>0: |
|
3381 | 3381 | print "Installing profiles to: ", ipython_dir |
|
3382 | 3382 | for (f, src, dst) in to_install: |
|
3383 | 3383 | shutil.copy(src, dst) |
|
3384 | 3384 | print " %s" % f |
|
3385 | 3385 | |
|
3386 | 3386 | def magic_install_default_config(self, s): |
|
3387 | 3387 | """Install IPython's default config file into the .ipython dir. |
|
3388 | 3388 | |
|
3389 | 3389 | If the default config file (:file:`ipython_config.py`) is already |
|
3390 | 3390 | installed, it will not be overwritten. You can force overwriting |
|
3391 | 3391 | by using the ``-o`` option:: |
|
3392 | 3392 | |
|
3393 | 3393 | In [1]: %install_default_config |
|
3394 | 3394 | """ |
|
3395 | 3395 | if '-o' in s: |
|
3396 | 3396 | overwrite = True |
|
3397 | 3397 | else: |
|
3398 | 3398 | overwrite = False |
|
3399 | 3399 | from IPython.config import default |
|
3400 | 3400 | config_dir = os.path.split(default.__file__)[0] |
|
3401 | 3401 | ipython_dir = self.ipython_dir |
|
3402 | 3402 | default_config_file_name = 'ipython_config.py' |
|
3403 | 3403 | src = os.path.join(config_dir, default_config_file_name) |
|
3404 | 3404 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3405 | 3405 | if (not os.path.isfile(dst)) or overwrite: |
|
3406 | 3406 | shutil.copy(src, dst) |
|
3407 | 3407 | print "Installing default config file: %s" % dst |
|
3408 | 3408 | |
|
3409 | 3409 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3410 | 3410 | # handling and modify slightly %run |
|
3411 | 3411 | |
|
3412 | 3412 | @testdec.skip_doctest |
|
3413 | 3413 | def _pylab_magic_run(self, parameter_s=''): |
|
3414 | 3414 | Magic.magic_run(self, parameter_s, |
|
3415 | 3415 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3416 | 3416 | |
|
3417 | 3417 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3418 | 3418 | |
|
3419 | 3419 | @testdec.skip_doctest |
|
3420 | 3420 | def magic_pylab(self, s): |
|
3421 | 3421 | """Load numpy and matplotlib to work interactively. |
|
3422 | 3422 | |
|
3423 | 3423 | %pylab [GUINAME] |
|
3424 | 3424 | |
|
3425 | 3425 | This function lets you activate pylab (matplotlib, numpy and |
|
3426 | 3426 | interactive support) at any point during an IPython session. |
|
3427 | 3427 | |
|
3428 | 3428 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3429 | 3429 | pylab and mlab, as well as all names from numpy and pylab. |
|
3430 | 3430 | |
|
3431 | 3431 | Parameters |
|
3432 | 3432 | ---------- |
|
3433 | 3433 | guiname : optional |
|
3434 | 3434 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3435 | 3435 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3436 | 3436 | otherwise matplotlib's default (which you can override in your |
|
3437 | 3437 | matplotlib config file) is used. |
|
3438 | 3438 | |
|
3439 | 3439 | Examples |
|
3440 | 3440 | -------- |
|
3441 | 3441 | In this case, where the MPL default is TkAgg: |
|
3442 | 3442 | In [2]: %pylab |
|
3443 | 3443 | |
|
3444 | 3444 | Welcome to pylab, a matplotlib-based Python environment. |
|
3445 | 3445 | Backend in use: TkAgg |
|
3446 | 3446 | For more information, type 'help(pylab)'. |
|
3447 | 3447 | |
|
3448 | 3448 | But you can explicitly request a different backend: |
|
3449 | 3449 | In [3]: %pylab qt |
|
3450 | 3450 | |
|
3451 | 3451 | Welcome to pylab, a matplotlib-based Python environment. |
|
3452 | 3452 | Backend in use: Qt4Agg |
|
3453 | 3453 | For more information, type 'help(pylab)'. |
|
3454 | 3454 | """ |
|
3455 | 3455 | self.shell.enable_pylab(s) |
|
3456 | 3456 | |
|
3457 | 3457 | def magic_tb(self, s): |
|
3458 | 3458 | """Print the last traceback with the currently active exception mode. |
|
3459 | 3459 | |
|
3460 | 3460 | See %xmode for changing exception reporting modes.""" |
|
3461 | 3461 | self.shell.showtraceback() |
|
3462 | 3462 | |
|
3463 | 3463 | @testdec.skip_doctest |
|
3464 | 3464 | def magic_precision(self, s=''): |
|
3465 | 3465 | """Set floating point precision for pretty printing. |
|
3466 | 3466 | |
|
3467 | 3467 | Can set either integer precision or a format string. |
|
3468 | 3468 | |
|
3469 | 3469 | If numpy has been imported and precision is an int, |
|
3470 | 3470 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
3471 | 3471 | |
|
3472 | 3472 | If no argument is given, defaults will be restored. |
|
3473 | 3473 | |
|
3474 | 3474 | Examples |
|
3475 | 3475 | -------- |
|
3476 | 3476 | :: |
|
3477 | 3477 | |
|
3478 | 3478 | In [1]: from math import pi |
|
3479 | 3479 | |
|
3480 | 3480 | In [2]: %precision 3 |
|
3481 | 3481 | Out[2]: '%.3f' |
|
3482 | 3482 | |
|
3483 | 3483 | In [3]: pi |
|
3484 | 3484 | Out[3]: 3.142 |
|
3485 | 3485 | |
|
3486 | 3486 | In [4]: %precision %i |
|
3487 | 3487 | Out[4]: '%i' |
|
3488 | 3488 | |
|
3489 | 3489 | In [5]: pi |
|
3490 | 3490 | Out[5]: 3 |
|
3491 | 3491 | |
|
3492 | 3492 | In [6]: %precision %e |
|
3493 | 3493 | Out[6]: '%e' |
|
3494 | 3494 | |
|
3495 | 3495 | In [7]: pi**10 |
|
3496 | 3496 | Out[7]: 9.364805e+04 |
|
3497 | 3497 | |
|
3498 | 3498 | In [8]: %precision |
|
3499 | 3499 | Out[8]: '%r' |
|
3500 | 3500 | |
|
3501 | 3501 | In [9]: pi**10 |
|
3502 | 3502 | Out[9]: 93648.047476082982 |
|
3503 | 3503 | |
|
3504 | 3504 | """ |
|
3505 | 3505 | |
|
3506 | 3506 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
3507 | 3507 | ptformatter.float_precision = s |
|
3508 | 3508 | return ptformatter.float_format |
|
3509 | 3509 | |
|
3510 | 3510 | # end Magic |
@@ -1,507 +1,508 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Usage information for the main IPython applications. |
|
3 | 3 | """ |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (C) 2008-2010 The IPython Development Team |
|
6 | 6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
7 | 7 | # |
|
8 | 8 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | 9 | # the file COPYING, distributed as part of this software. |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | |
|
12 | 12 | import sys |
|
13 | 13 | from IPython.core import release |
|
14 | 14 | |
|
15 | 15 | cl_usage = """\ |
|
16 | 16 | ipython [options] [files] |
|
17 | 17 | |
|
18 | 18 | IPython: an enhanced interactive Python shell. |
|
19 | 19 | |
|
20 | 20 | A Python shell with automatic history (input and output), dynamic object |
|
21 | 21 | introspection, easier configuration, command completion, access to the |
|
22 | 22 | system shell and more. IPython can also be embedded in running programs. |
|
23 | 23 | |
|
24 | 24 | If invoked with no options, it executes all the files listed in sequence |
|
25 | 25 | and exits, use -i to enter interactive mode after running the files. Files |
|
26 | 26 | ending in .py will be treated as normal Python, but files ending in .ipy |
|
27 | 27 | can contain special IPython syntax (magic commands, shell expansions, etc.) |
|
28 | 28 | |
|
29 | 29 | Please note that some of the configuration options are not available at the |
|
30 | 30 | command line, simply because they are not practical here. Look into your |
|
31 | 31 | ipython_config.py configuration file for details on those. |
|
32 | 32 | |
|
33 |
This file typically installed in the |
|
|
34 | users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most | |
|
35 | instances. | |
|
33 | This file is typically installed in the IPYTHON_DIR directory. For Linux | |
|
34 | users, this will be $HOME/.config/ipython, and for other users it will be | |
|
35 | $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and | |
|
36 | Settings\\YourUserName in most instances. | |
|
36 | 37 | |
|
37 | 38 | In IPython's documentation, we will refer to this directory as IPYTHON_DIR, |
|
38 | 39 | you can change its default location by setting any path you want in this |
|
39 | 40 | environment variable. |
|
40 | 41 | |
|
41 | 42 | For more information, see the manual available in HTML and PDF in your |
|
42 | 43 | installation, or online at http://ipython.scipy.org. |
|
43 | 44 | """ |
|
44 | 45 | |
|
45 | 46 | interactive_usage = """ |
|
46 | 47 | IPython -- An enhanced Interactive Python |
|
47 | 48 | ========================================= |
|
48 | 49 | |
|
49 | 50 | IPython offers a combination of convenient shell features, special commands |
|
50 | 51 | and a history mechanism for both input (command history) and output (results |
|
51 | 52 | caching, similar to Mathematica). It is intended to be a fully compatible |
|
52 | 53 | replacement for the standard Python interpreter, while offering vastly |
|
53 | 54 | improved functionality and flexibility. |
|
54 | 55 | |
|
55 | 56 | At your system command line, type 'ipython -help' to see the command line |
|
56 | 57 | options available. This document only describes interactive features. |
|
57 | 58 | |
|
58 | 59 | Warning: IPython relies on the existence of a global variable called __IP which |
|
59 | 60 | controls the shell itself. If you redefine __IP to anything, bizarre behavior |
|
60 | 61 | will quickly occur. |
|
61 | 62 | |
|
62 | 63 | MAIN FEATURES |
|
63 | 64 | |
|
64 | 65 | * Access to the standard Python help. As of Python 2.1, a help system is |
|
65 | 66 | available with access to object docstrings and the Python manuals. Simply |
|
66 | 67 | type 'help' (no quotes) to access it. |
|
67 | 68 | |
|
68 | 69 | * Magic commands: type %magic for information on the magic subsystem. |
|
69 | 70 | |
|
70 | 71 | * System command aliases, via the %alias command or the ipythonrc config file. |
|
71 | 72 | |
|
72 | 73 | * Dynamic object information: |
|
73 | 74 | |
|
74 | 75 | Typing ?word or word? prints detailed information about an object. If |
|
75 | 76 | certain strings in the object are too long (docstrings, code, etc.) they get |
|
76 | 77 | snipped in the center for brevity. |
|
77 | 78 | |
|
78 | 79 | Typing ??word or word?? gives access to the full information without |
|
79 | 80 | snipping long strings. Long strings are sent to the screen through the less |
|
80 | 81 | pager if longer than the screen, printed otherwise. |
|
81 | 82 | |
|
82 | 83 | The ?/?? system gives access to the full source code for any object (if |
|
83 | 84 | available), shows function prototypes and other useful information. |
|
84 | 85 | |
|
85 | 86 | If you just want to see an object's docstring, type '%pdoc object' (without |
|
86 | 87 | quotes, and without % if you have automagic on). |
|
87 | 88 | |
|
88 | 89 | Both %pdoc and ?/?? give you access to documentation even on things which are |
|
89 | 90 | not explicitely defined. Try for example typing {}.get? or after import os, |
|
90 | 91 | type os.path.abspath??. The magic functions %pdef, %source and %file operate |
|
91 | 92 | similarly. |
|
92 | 93 | |
|
93 | 94 | * Completion in the local namespace, by typing TAB at the prompt. |
|
94 | 95 | |
|
95 | 96 | At any time, hitting tab will complete any available python commands or |
|
96 | 97 | variable names, and show you a list of the possible completions if there's |
|
97 | 98 | no unambiguous one. It will also complete filenames in the current directory. |
|
98 | 99 | |
|
99 | 100 | This feature requires the readline and rlcomplete modules, so it won't work |
|
100 | 101 | if your Python lacks readline support (such as under Windows). |
|
101 | 102 | |
|
102 | 103 | * Search previous command history in two ways (also requires readline): |
|
103 | 104 | |
|
104 | 105 | - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to |
|
105 | 106 | search through only the history items that match what you've typed so |
|
106 | 107 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like |
|
107 | 108 | normal arrow keys. |
|
108 | 109 | |
|
109 | 110 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches |
|
110 | 111 | your history for lines that match what you've typed so far, completing as |
|
111 | 112 | much as it can. |
|
112 | 113 | |
|
113 | 114 | * Persistent command history across sessions (readline required). |
|
114 | 115 | |
|
115 | 116 | * Logging of input with the ability to save and restore a working session. |
|
116 | 117 | |
|
117 | 118 | * System escape with !. Typing !ls will run 'ls' in the current directory. |
|
118 | 119 | |
|
119 | 120 | * The reload command does a 'deep' reload of a module: changes made to the |
|
120 | 121 | module since you imported will actually be available without having to exit. |
|
121 | 122 | |
|
122 | 123 | * Verbose and colored exception traceback printouts. See the magic xmode and |
|
123 | 124 | xcolor functions for details (just type %magic). |
|
124 | 125 | |
|
125 | 126 | * Input caching system: |
|
126 | 127 | |
|
127 | 128 | IPython offers numbered prompts (In/Out) with input and output caching. All |
|
128 | 129 | input is saved and can be retrieved as variables (besides the usual arrow |
|
129 | 130 | key recall). |
|
130 | 131 | |
|
131 | 132 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
132 | 133 | _i: stores previous input. |
|
133 | 134 | _ii: next previous. |
|
134 | 135 | _iii: next-next previous. |
|
135 | 136 | _ih : a list of all input _ih[n] is the input from line n. |
|
136 | 137 | |
|
137 | 138 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
138 | 139 | being the prompt counter), such that _i<n> == _ih[<n>] |
|
139 | 140 | |
|
140 | 141 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. |
|
141 | 142 | |
|
142 | 143 | You can create macros which contain multiple input lines from this history, |
|
143 | 144 | for later re-execution, with the %macro function. |
|
144 | 145 | |
|
145 | 146 | The history function %hist allows you to see any part of your input history |
|
146 | 147 | by printing a range of the _i variables. Note that inputs which contain |
|
147 | 148 | magic functions (%) appear in the history with a prepended comment. This is |
|
148 | 149 | because they aren't really valid Python code, so you can't exec them. |
|
149 | 150 | |
|
150 | 151 | * Output caching system: |
|
151 | 152 | |
|
152 | 153 | For output that is returned from actions, a system similar to the input |
|
153 | 154 | cache exists but using _ instead of _i. Only actions that produce a result |
|
154 | 155 | (NOT assignments, for example) are cached. If you are familiar with |
|
155 | 156 | Mathematica, IPython's _ variables behave exactly like Mathematica's % |
|
156 | 157 | variables. |
|
157 | 158 | |
|
158 | 159 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
159 | 160 | _ (one underscore): previous output. |
|
160 | 161 | __ (two underscores): next previous. |
|
161 | 162 | ___ (three underscores): next-next previous. |
|
162 | 163 | |
|
163 | 164 | Global variables named _<n> are dynamically created (<n> being the prompt |
|
164 | 165 | counter), such that the result of output <n> is always available as _<n>. |
|
165 | 166 | |
|
166 | 167 | Finally, a global dictionary named _oh exists with entries for all lines |
|
167 | 168 | which generated output. |
|
168 | 169 | |
|
169 | 170 | * Directory history: |
|
170 | 171 | |
|
171 | 172 | Your history of visited directories is kept in the global list _dh, and the |
|
172 | 173 | magic %cd command can be used to go to any entry in that list. |
|
173 | 174 | |
|
174 | 175 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) |
|
175 | 176 | |
|
176 | 177 | 1. Auto-parentheses |
|
177 | 178 | Callable objects (i.e. functions, methods, etc) can be invoked like |
|
178 | 179 | this (notice the commas between the arguments): |
|
179 | 180 | >>> callable_ob arg1, arg2, arg3 |
|
180 | 181 | and the input will be translated to this: |
|
181 | 182 | --> callable_ob(arg1, arg2, arg3) |
|
182 | 183 | You can force auto-parentheses by using '/' as the first character |
|
183 | 184 | of a line. For example: |
|
184 | 185 | >>> /globals # becomes 'globals()' |
|
185 | 186 | Note that the '/' MUST be the first character on the line! This |
|
186 | 187 | won't work: |
|
187 | 188 | >>> print /globals # syntax error |
|
188 | 189 | |
|
189 | 190 | In most cases the automatic algorithm should work, so you should |
|
190 | 191 | rarely need to explicitly invoke /. One notable exception is if you |
|
191 | 192 | are trying to call a function with a list of tuples as arguments (the |
|
192 | 193 | parenthesis will confuse IPython): |
|
193 | 194 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
194 | 195 | but this will work: |
|
195 | 196 | In [2]: /zip (1,2,3),(4,5,6) |
|
196 | 197 | ------> zip ((1,2,3),(4,5,6)) |
|
197 | 198 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
198 | 199 | |
|
199 | 200 | IPython tells you that it has altered your command line by |
|
200 | 201 | displaying the new command line preceded by -->. e.g.: |
|
201 | 202 | In [18]: callable list |
|
202 | 203 | -------> callable (list) |
|
203 | 204 | |
|
204 | 205 | 2. Auto-Quoting |
|
205 | 206 | You can force auto-quoting of a function's arguments by using ',' as |
|
206 | 207 | the first character of a line. For example: |
|
207 | 208 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
208 | 209 | |
|
209 | 210 | If you use ';' instead, the whole argument is quoted as a single |
|
210 | 211 | string (while ',' splits on whitespace): |
|
211 | 212 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
212 | 213 | >>> ;my_function a b c # becomes my_function("a b c") |
|
213 | 214 | |
|
214 | 215 | Note that the ',' MUST be the first character on the line! This |
|
215 | 216 | won't work: |
|
216 | 217 | >>> x = ,my_function /home/me # syntax error |
|
217 | 218 | """ |
|
218 | 219 | |
|
219 | 220 | interactive_usage_min = """\ |
|
220 | 221 | An enhanced console for Python. |
|
221 | 222 | Some of its features are: |
|
222 | 223 | - Readline support if the readline library is present. |
|
223 | 224 | - Tab completion in the local namespace. |
|
224 | 225 | - Logging of input, see command-line options. |
|
225 | 226 | - System shell escape via ! , eg !ls. |
|
226 | 227 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
227 | 228 | - Keeps track of locally defined variables via %who, %whos. |
|
228 | 229 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
229 | 230 | """ |
|
230 | 231 | |
|
231 | 232 | quick_reference = r""" |
|
232 | 233 | IPython -- An enhanced Interactive Python - Quick Reference Card |
|
233 | 234 | ================================================================ |
|
234 | 235 | |
|
235 | 236 | obj?, obj?? : Get help, or more help for object (also works as |
|
236 | 237 | ?obj, ??obj). |
|
237 | 238 | ?foo.*abc* : List names in 'foo' containing 'abc' in them. |
|
238 | 239 | %magic : Information about IPython's 'magic' % functions. |
|
239 | 240 | |
|
240 | 241 | Magic functions are prefixed by %, and typically take their arguments without |
|
241 | 242 | parentheses, quotes or even commas for convenience. |
|
242 | 243 | |
|
243 | 244 | Example magic function calls: |
|
244 | 245 | |
|
245 | 246 | %alias d ls -F : 'd' is now an alias for 'ls -F' |
|
246 | 247 | alias d ls -F : Works if 'alias' not a python name |
|
247 | 248 | alist = %alias : Get list of aliases to 'alist' |
|
248 | 249 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. |
|
249 | 250 | %cd?? : See help AND source for magic %cd |
|
250 | 251 | |
|
251 | 252 | System commands: |
|
252 | 253 | |
|
253 | 254 | !cp a.txt b/ : System command escape, calls os.system() |
|
254 | 255 | cp a.txt b/ : after %rehashx, most system commands work without ! |
|
255 | 256 | cp ${f}.txt $bar : Variable expansion in magics and system commands |
|
256 | 257 | files = !ls /usr : Capture sytem command output |
|
257 | 258 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' |
|
258 | 259 | |
|
259 | 260 | History: |
|
260 | 261 | |
|
261 | 262 | _i, _ii, _iii : Previous, next previous, next next previous input |
|
262 | 263 | _i4, _ih[2:5] : Input history line 4, lines 2-4 |
|
263 | 264 | exec _i81 : Execute input history line #81 again |
|
264 | 265 | %rep 81 : Edit input history line #81 |
|
265 | 266 | _, __, ___ : previous, next previous, next next previous output |
|
266 | 267 | _dh : Directory history |
|
267 | 268 | _oh : Output history |
|
268 | 269 | %hist : Command history. '%hist -g foo' search history for 'foo' |
|
269 | 270 | |
|
270 | 271 | Autocall: |
|
271 | 272 | |
|
272 | 273 | f 1,2 : f(1,2) |
|
273 | 274 | /f 1,2 : f(1,2) (forced autoparen) |
|
274 | 275 | ,f 1 2 : f("1","2") |
|
275 | 276 | ;f 1 2 : f("1 2") |
|
276 | 277 | |
|
277 | 278 | Remember: TAB completion works in many contexts, not just file names |
|
278 | 279 | or python names. |
|
279 | 280 | |
|
280 | 281 | The following magic functions are currently available: |
|
281 | 282 | |
|
282 | 283 | """ |
|
283 | 284 | |
|
284 | 285 | gui_reference = """\ |
|
285 | 286 | =============================== |
|
286 | 287 | The graphical IPython console |
|
287 | 288 | =============================== |
|
288 | 289 | |
|
289 | 290 | This console is designed to emulate the look, feel and workflow of a terminal |
|
290 | 291 | environment, while adding a number of enhancements that are simply not possible |
|
291 | 292 | in a real terminal, such as inline syntax highlighting, true multiline editing, |
|
292 | 293 | inline graphics and much more. |
|
293 | 294 | |
|
294 | 295 | This quick reference document contains the basic information you'll need to |
|
295 | 296 | know to make the most efficient use of it. For the various command line |
|
296 | 297 | options available at startup, type ``--help`` at the command line. |
|
297 | 298 | |
|
298 | 299 | |
|
299 | 300 | Multiline editing |
|
300 | 301 | ================= |
|
301 | 302 | |
|
302 | 303 | The graphical console is capable of true multiline editing, but it also tries |
|
303 | 304 | to behave intuitively like a terminal when possible. If you are used to |
|
304 | 305 | IPyhton's old terminal behavior, you should find the transition painless, and |
|
305 | 306 | once you learn a few basic keybindings it will be a much more efficient |
|
306 | 307 | environment. |
|
307 | 308 | |
|
308 | 309 | For single expressions or indented blocks, the console behaves almost like the |
|
309 | 310 | terminal IPython: single expressions are immediately evaluated, and indented |
|
310 | 311 | blocks are evaluated once a single blank line is entered:: |
|
311 | 312 | |
|
312 | 313 | In [1]: print "Hello IPython!" # Enter was pressed at the end of the line |
|
313 | 314 | Hello IPython! |
|
314 | 315 | |
|
315 | 316 | In [2]: for i in range(10): |
|
316 | 317 | ...: print i, |
|
317 | 318 | ...: |
|
318 | 319 | 0 1 2 3 4 5 6 7 8 9 |
|
319 | 320 | |
|
320 | 321 | If you want to enter more than one expression in a single input block |
|
321 | 322 | (something not possible in the terminal), you can use ``Control-Enter`` at the |
|
322 | 323 | end of your first line instead of ``Enter``. At that point the console goes |
|
323 | 324 | into 'cell mode' and even if your inputs are not indented, it will continue |
|
324 | 325 | accepting arbitrarily many lines until either you enter an extra blank line or |
|
325 | 326 | you hit ``Shift-Enter`` (the key binding that forces execution). When a |
|
326 | 327 | multiline cell is entered, IPython analyzes it and executes its code producing |
|
327 | 328 | an ``Out[n]`` prompt only for the last expression in it, while the rest of the |
|
328 | 329 | cell is executed as if it was a script. An example should clarify this:: |
|
329 | 330 | |
|
330 | 331 | In [3]: x=1 # Hit C-Enter here |
|
331 | 332 | ...: y=2 # from now on, regular Enter is sufficient |
|
332 | 333 | ...: z=3 |
|
333 | 334 | ...: x**2 # This does *not* produce an Out[] value |
|
334 | 335 | ...: x+y+z # Only the last expression does |
|
335 | 336 | ...: |
|
336 | 337 | Out[3]: 6 |
|
337 | 338 | |
|
338 | 339 | The behavior where an extra blank line forces execution is only active if you |
|
339 | 340 | are actually typing at the keyboard each line, and is meant to make it mimic |
|
340 | 341 | the IPython terminal behavior. If you paste a long chunk of input (for example |
|
341 | 342 | a long script copied form an editor or web browser), it can contain arbitrarily |
|
342 | 343 | many intermediate blank lines and they won't cause any problems. As always, |
|
343 | 344 | you can then make it execute by appending a blank line *at the end* or hitting |
|
344 | 345 | ``Shift-Enter`` anywhere within the cell. |
|
345 | 346 | |
|
346 | 347 | With the up arrow key, you can retrieve previous blocks of input that contain |
|
347 | 348 | multiple lines. You can move inside of a multiline cell like you would in any |
|
348 | 349 | text editor. When you want it executed, the simplest thing to do is to hit the |
|
349 | 350 | force execution key, ``Shift-Enter`` (though you can also navigate to the end |
|
350 | 351 | and append a blank line by using ``Enter`` twice). |
|
351 | 352 | |
|
352 | 353 | If you've edited a multiline cell and accidentally navigate out of it with the |
|
353 | 354 | up or down arrow keys, IPython will clear the cell and replace it with the |
|
354 | 355 | contents of the one above or below that you navigated to. If this was an |
|
355 | 356 | accident and you want to retrieve the cell you were editing, use the Undo |
|
356 | 357 | keybinding, ``Control-z``. |
|
357 | 358 | |
|
358 | 359 | |
|
359 | 360 | Key bindings |
|
360 | 361 | ============ |
|
361 | 362 | |
|
362 | 363 | The IPython console supports most of the basic Emacs line-oriented keybindings, |
|
363 | 364 | in addition to some of its own. |
|
364 | 365 | |
|
365 | 366 | The keybinding prefixes mean: |
|
366 | 367 | |
|
367 | 368 | - ``C``: Control |
|
368 | 369 | - ``S``: Shift |
|
369 | 370 | - ``M``: Meta (typically the Alt key) |
|
370 | 371 | |
|
371 | 372 | The keybindings themselves are: |
|
372 | 373 | |
|
373 | 374 | - ``Enter``: insert new line (may cause execution, see above). |
|
374 | 375 | - ``C-Enter``: force new line, *never* causes execution. |
|
375 | 376 | - ``S-Enter``: *force* execution regardless of where cursor is, no newline added. |
|
376 | 377 | - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped). |
|
377 | 378 | - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped). |
|
378 | 379 | - ``C-v``: paste text from clipboard. |
|
379 | 380 | - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows). |
|
380 | 381 | - ``C-S-z``: redo. |
|
381 | 382 | - ``C-o``: move to 'other' area, between pager and terminal. |
|
382 | 383 | - ``C-l``: clear terminal. |
|
383 | 384 | - ``C-a``: go to beginning of line. |
|
384 | 385 | - ``C-e``: go to end of line. |
|
385 | 386 | - ``C-k``: kill from cursor to the end of the line. |
|
386 | 387 | - ``C-y``: yank (paste) |
|
387 | 388 | - ``C-p``: previous line (like up arrow) |
|
388 | 389 | - ``C-n``: next line (like down arrow) |
|
389 | 390 | - ``C-f``: forward (like right arrow) |
|
390 | 391 | - ``C-b``: back (like left arrow) |
|
391 | 392 | - ``C-d``: delete next character. |
|
392 | 393 | - ``M-<``: move to the beginning of the input region. |
|
393 | 394 | - ``M->``: move to the end of the input region. |
|
394 | 395 | - ``M-d``: delete next word. |
|
395 | 396 | - ``M-Backspace``: delete previous word. |
|
396 | 397 | - ``C-.``: force a kernel restart (a confirmation dialog appears). |
|
397 | 398 | - ``C-+``: increase font size. |
|
398 | 399 | - ``C--``: decrease font size. |
|
399 | 400 | |
|
400 | 401 | The IPython pager |
|
401 | 402 | ================= |
|
402 | 403 | |
|
403 | 404 | IPython will show long blocks of text from many sources using a builtin pager. |
|
404 | 405 | You can control where this pager appears with the ``--paging`` command-line |
|
405 | 406 | flag: |
|
406 | 407 | |
|
407 | 408 | - default: it is overlaid on top of the main terminal. You must quit the pager |
|
408 | 409 | to get back to the terminal (similar to how a pager such as ``less`` or |
|
409 | 410 | ``more`` works). |
|
410 | 411 | |
|
411 | 412 | - vertical: the console is made double-tall, and the pager appears on the |
|
412 | 413 | bottom area when needed. You can view its contents while using the terminal. |
|
413 | 414 | |
|
414 | 415 | - horizontal: the console is made double-wide, and the pager appears on the |
|
415 | 416 | right area when needed. You can view its contents while using the terminal. |
|
416 | 417 | |
|
417 | 418 | If you use the vertical or horizontal paging modes, you can navigate between |
|
418 | 419 | terminal and pager as follows: |
|
419 | 420 | |
|
420 | 421 | - Tab key: goes from pager to terminal (but not the other way around). |
|
421 | 422 | - Control-o: goes from one to another always. |
|
422 | 423 | - Mouse: click on either. |
|
423 | 424 | |
|
424 | 425 | In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the |
|
425 | 426 | focus on the pager area). |
|
426 | 427 | |
|
427 | 428 | |
|
428 | 429 | Running subprocesses |
|
429 | 430 | ==================== |
|
430 | 431 | |
|
431 | 432 | The graphical IPython console uses the ``pexpect`` module to run subprocesses |
|
432 | 433 | when you type ``!command``. This has a number of advantages (true asynchronous |
|
433 | 434 | output from subprocesses as well as very robust termination of rogue |
|
434 | 435 | subprocesses with ``Control-C``), as well as some limitations. The main |
|
435 | 436 | limitation is that you can *not* interact back with the subprocess, so anything |
|
436 | 437 | that invokes a pager or expects you to type input into it will block and hang |
|
437 | 438 | (you can kill it with ``Control-C``). |
|
438 | 439 | |
|
439 | 440 | We have provided as magics ``%less`` to page files (aliased to ``%more``), |
|
440 | 441 | ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the |
|
441 | 442 | most common commands you'd want to call in your subshell and that would cause |
|
442 | 443 | problems if invoked via ``!cmd``, but you need to be aware of this limitation. |
|
443 | 444 | |
|
444 | 445 | Display |
|
445 | 446 | ======= |
|
446 | 447 | |
|
447 | 448 | The IPython console can now display objects in a variety of formats, including |
|
448 | 449 | HTML, PNG and SVG. This is accomplished using the display functions in |
|
449 | 450 | ``IPython.core.display``:: |
|
450 | 451 | |
|
451 | 452 | In [4]: from IPython.core.display import display, display_html |
|
452 | 453 | |
|
453 | 454 | In [5]: from IPython.core.display import display_png, display_svg |
|
454 | 455 | |
|
455 | 456 | Python objects can simply be passed to these functions and the appropriate |
|
456 | 457 | representations will be displayed in the console as long as the objects know |
|
457 | 458 | how to compute those representations. The easiest way of teaching objects how |
|
458 | 459 | to format themselves in various representations is to define special methods |
|
459 | 460 | such as: ``__html``, ``__svg__`` and ``__png__``. IPython's display formatters |
|
460 | 461 | can also be given custom formatter functions for various types:: |
|
461 | 462 | |
|
462 | 463 | In [6]: ip = get_ipython() |
|
463 | 464 | |
|
464 | 465 | In [7]: html_formatter = ip.display_formatter.formatters['text/html'] |
|
465 | 466 | |
|
466 | 467 | In [8]: html_formatter.for_type(Foo, foo_to_html) |
|
467 | 468 | |
|
468 | 469 | For further details, see ``IPython.core.formatters``. |
|
469 | 470 | |
|
470 | 471 | Inline matplotlib graphics |
|
471 | 472 | ========================== |
|
472 | 473 | |
|
473 | 474 | The IPython console is capable of displaying matplotlib figures inline, in SVG |
|
474 | 475 | format. If started with the ``--pylab inline`` flag, then all figures are |
|
475 | 476 | rendered inline automatically. If started with ``--pylab`` or ``--pylab <your |
|
476 | 477 | backend>``, then a GUI backend will be used, but IPython's ``display()`` and |
|
477 | 478 | ``getfigs()`` functions can be used to view plots inline:: |
|
478 | 479 | |
|
479 | 480 | In [9]: display(*getfigs()) # display all figures inline |
|
480 | 481 | |
|
481 | 482 | In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline |
|
482 | 483 | """ |
|
483 | 484 | |
|
484 | 485 | |
|
485 | 486 | quick_guide = """\ |
|
486 | 487 | ? -> Introduction and overview of IPython's features. |
|
487 | 488 | %quickref -> Quick reference. |
|
488 | 489 | help -> Python's own help system. |
|
489 | 490 | object? -> Details about 'object', use 'object??' for extra details. |
|
490 | 491 | """ |
|
491 | 492 | |
|
492 | 493 | gui_note = """\ |
|
493 | 494 | %guiref -> A brief reference about the graphical user interface. |
|
494 | 495 | """ |
|
495 | 496 | |
|
496 | 497 | default_banner_parts = [ |
|
497 | 498 | 'Python %s\n' % (sys.version.split('\n')[0],), |
|
498 | 499 | 'Type "copyright", "credits" or "license" for more information.\n\n', |
|
499 | 500 | 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,), |
|
500 | 501 | quick_guide |
|
501 | 502 | ] |
|
502 | 503 | |
|
503 | 504 | default_gui_banner_parts = default_banner_parts + [gui_note] |
|
504 | 505 | |
|
505 | 506 | default_banner = ''.join(default_banner_parts) |
|
506 | 507 | |
|
507 | 508 | default_gui_banner = ''.join(default_gui_banner_parts) |
@@ -1,374 +1,374 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | # -*- test-case-name: IPython.kernel.test.test_controllerservice -*- |
|
3 | 3 | |
|
4 | 4 | """A Twisted Service for the IPython Controller. |
|
5 | 5 | |
|
6 | 6 | The IPython Controller: |
|
7 | 7 | |
|
8 | 8 | * Listens for Engines to connect and then manages access to those engines. |
|
9 | 9 | * Listens for clients and passes commands from client to the Engines. |
|
10 | 10 | * Exposes an asynchronous interfaces to the Engines which themselves can block. |
|
11 | 11 | * Acts as a gateway to the Engines. |
|
12 | 12 | |
|
13 | 13 | The design of the controller is somewhat abstract to allow flexibility in how |
|
14 | 14 | the controller is presented to clients. This idea is that there is a basic |
|
15 | 15 | ControllerService class that allows engines to connect to it. But, this |
|
16 | 16 | basic class has no client interfaces. To expose client interfaces developers |
|
17 | 17 | provide an adapter that makes the ControllerService look like something. For |
|
18 | 18 | example, one client interface might support task farming and another might |
|
19 | 19 | support interactive usage. The important thing is that by using interfaces |
|
20 | 20 | and adapters, a single controller can be accessed from multiple interfaces. |
|
21 | 21 | Furthermore, by adapting various client interfaces to various network |
|
22 | 22 | protocols, each client interface can be exposed to multiple network protocols. |
|
23 | 23 | See multiengine.py for an example of how to adapt the ControllerService |
|
24 | 24 | to a client interface. |
|
25 | 25 | """ |
|
26 | 26 | |
|
27 | 27 | __docformat__ = "restructuredtext en" |
|
28 | 28 | |
|
29 | 29 | #------------------------------------------------------------------------------- |
|
30 | 30 | # Copyright (C) 2008 The IPython Development Team |
|
31 | 31 | # |
|
32 | 32 | # Distributed under the terms of the BSD License. The full license is in |
|
33 | 33 | # the file COPYING, distributed as part of this software. |
|
34 | 34 | #------------------------------------------------------------------------------- |
|
35 | 35 | |
|
36 | 36 | #------------------------------------------------------------------------------- |
|
37 | 37 | # Imports |
|
38 | 38 | #------------------------------------------------------------------------------- |
|
39 | 39 | |
|
40 | 40 | import os |
|
41 | 41 | |
|
42 | 42 | from twisted.application import service |
|
43 | 43 | from twisted.python import log |
|
44 | 44 | from zope.interface import Interface, implements, Attribute |
|
45 | 45 | |
|
46 | 46 | from IPython.kernel.engineservice import \ |
|
47 | 47 | IEngineCore, \ |
|
48 | 48 | IEngineSerialized, \ |
|
49 | 49 | IEngineQueued |
|
50 | 50 | |
|
51 | 51 | from IPython.utils.path import get_ipython_dir |
|
52 | 52 | from IPython.kernel import codeutil |
|
53 | 53 | |
|
54 | 54 | #------------------------------------------------------------------------------- |
|
55 | 55 | # Interfaces for the Controller |
|
56 | 56 | #------------------------------------------------------------------------------- |
|
57 | 57 | |
|
58 | 58 | class IControllerCore(Interface): |
|
59 | 59 | """Basic methods any controller must have. |
|
60 | 60 | |
|
61 | 61 | This is basically the aspect of the controller relevant to the |
|
62 | 62 | engines and does not assume anything about how the engines will |
|
63 | 63 | be presented to a client. |
|
64 | 64 | """ |
|
65 | 65 | |
|
66 | 66 | engines = Attribute("A dict of engine ids and engine instances.") |
|
67 | 67 | |
|
68 | 68 | def register_engine(remoteEngine, id=None, ip=None, port=None, |
|
69 | 69 | pid=None): |
|
70 | 70 | """Register new remote engine. |
|
71 | 71 | |
|
72 | 72 | The controller can use the ip, port, pid of the engine to do useful things |
|
73 | 73 | like kill the engines. |
|
74 | 74 | |
|
75 | 75 | :Parameters: |
|
76 | 76 | remoteEngine |
|
77 | 77 | An implementer of IEngineCore, IEngineSerialized and IEngineQueued. |
|
78 | 78 | id : int |
|
79 | 79 | Requested id. |
|
80 | 80 | ip : str |
|
81 | 81 | IP address the engine is running on. |
|
82 | 82 | port : int |
|
83 | 83 | Port the engine is on. |
|
84 | 84 | pid : int |
|
85 | 85 | pid of the running engine. |
|
86 | 86 | |
|
87 | 87 | :Returns: A dict of {'id':id} and possibly other key, value pairs. |
|
88 | 88 | """ |
|
89 | 89 | |
|
90 | 90 | def unregister_engine(id): |
|
91 | 91 | """Handle a disconnecting engine. |
|
92 | 92 | |
|
93 | 93 | :Parameters: |
|
94 | 94 | id |
|
95 | 95 | The integer engine id of the engine to unregister. |
|
96 | 96 | """ |
|
97 | 97 | |
|
98 | 98 | def on_register_engine_do(f, includeID, *args, **kwargs): |
|
99 | 99 | """Call ``f(*args, **kwargs)`` when an engine is registered. |
|
100 | 100 | |
|
101 | 101 | :Parameters: |
|
102 | 102 | includeID : int |
|
103 | 103 | If True the first argument to f will be the id of the engine. |
|
104 | 104 | """ |
|
105 | 105 | |
|
106 | 106 | def on_unregister_engine_do(f, includeID, *args, **kwargs): |
|
107 | 107 | """Call ``f(*args, **kwargs)`` when an engine is unregistered. |
|
108 | 108 | |
|
109 | 109 | :Parameters: |
|
110 | 110 | includeID : int |
|
111 | 111 | If True the first argument to f will be the id of the engine. |
|
112 | 112 | """ |
|
113 | 113 | |
|
114 | 114 | def on_register_engine_do_not(f): |
|
115 | 115 | """Stop calling f on engine registration""" |
|
116 | 116 | |
|
117 | 117 | def on_unregister_engine_do_not(f): |
|
118 | 118 | """Stop calling f on engine unregistration""" |
|
119 | 119 | |
|
120 | 120 | def on_n_engines_registered_do(n, f, *arg, **kwargs): |
|
121 | 121 | """Call f(*args, **kwargs) the first time the nth engine registers.""" |
|
122 | 122 | |
|
123 | 123 | class IControllerBase(IControllerCore): |
|
124 | 124 | """The basic controller interface.""" |
|
125 | 125 | pass |
|
126 | 126 | |
|
127 | 127 | |
|
128 | 128 | #------------------------------------------------------------------------------- |
|
129 | 129 | # Implementation of the ControllerService |
|
130 | 130 | #------------------------------------------------------------------------------- |
|
131 | 131 | |
|
132 | 132 | class ControllerService(object, service.Service): |
|
133 | 133 | """A basic Controller represented as a Twisted Service. |
|
134 | 134 | |
|
135 | 135 | This class doesn't implement any client notification mechanism. That |
|
136 | 136 | is up to adapted subclasses. |
|
137 | 137 | """ |
|
138 | 138 | |
|
139 | 139 | # I also pick up the IService interface by inheritance from service.Service |
|
140 | 140 | implements(IControllerBase) |
|
141 | 141 | name = 'ControllerService' |
|
142 | 142 | |
|
143 | 143 | def __init__(self, maxEngines=511, saveIDs=False): |
|
144 | 144 | self.saveIDs = saveIDs |
|
145 | 145 | self.engines = {} |
|
146 | 146 | self.availableIDs = range(maxEngines,-1,-1) # [511,...,0] |
|
147 | 147 | self._onRegister = [] |
|
148 | 148 | self._onUnregister = [] |
|
149 | 149 | self._onNRegistered = [] |
|
150 | 150 | |
|
151 | 151 | #--------------------------------------------------------------------------- |
|
152 | 152 | # Methods used to save the engine info to a log file |
|
153 | 153 | #--------------------------------------------------------------------------- |
|
154 | 154 | |
|
155 | 155 | def _buildEngineInfoString(self, id, ip, port, pid): |
|
156 | 156 | if id is None: |
|
157 | 157 | id = -99 |
|
158 | 158 | if ip is None: |
|
159 | 159 | ip = "-99" |
|
160 | 160 | if port is None: |
|
161 | 161 | port = -99 |
|
162 | 162 | if pid is None: |
|
163 | 163 | pid = -99 |
|
164 | 164 | return "Engine Info: %d %s %d %d" % (id, ip , port, pid) |
|
165 | 165 | |
|
166 | 166 | def _logEngineInfo(self, id, ip, port, pid): |
|
167 | 167 | log.msg(self._buildEngineInfoString(id,ip,port,pid)) |
|
168 | 168 | |
|
169 | 169 | def _getEngineInfoLogFile(self): |
|
170 | 170 | # Store all logs inside the ipython directory |
|
171 | 171 | ipdir = get_ipython_dir() |
|
172 | 172 | pjoin = os.path.join |
|
173 | 173 | logdir_base = pjoin(ipdir,'log') |
|
174 | 174 | if not os.path.isdir(logdir_base): |
|
175 | 175 | os.makedirs(logdir_base) |
|
176 | 176 | logfile = os.path.join(logdir_base,'ipcontroller-%s-engine-info.log' % os.getpid()) |
|
177 | 177 | return logfile |
|
178 | 178 | |
|
179 | 179 | def _logEngineInfoToFile(self, id, ip, port, pid): |
|
180 | 180 | """Log info about an engine to a log file. |
|
181 | 181 | |
|
182 | 182 | When an engine registers with a ControllerService, the ControllerService |
|
183 | 183 | saves information about the engine to a log file. That information |
|
184 | 184 | can be useful for various purposes, such as killing hung engines, etc. |
|
185 | 185 | |
|
186 | 186 | This method takes the assigned id, ip/port and pid of the engine |
|
187 | 187 | and saves it to a file of the form: |
|
188 | 188 | |
|
189 |
|
|
|
189 | IPYTHON_DIR/log/ipcontroller-###-engine-info.log | |
|
190 | 190 | |
|
191 | 191 | where ### is the pid of the controller. |
|
192 | 192 | |
|
193 | 193 | Each line of this file has the form: |
|
194 | 194 | |
|
195 | 195 | Engine Info: ip ip port pid |
|
196 | 196 | |
|
197 | 197 | If any of the entries are not known, they are replaced by -99. |
|
198 | 198 | """ |
|
199 | 199 | |
|
200 | 200 | fname = self._getEngineInfoLogFile() |
|
201 | 201 | f = open(fname, 'a') |
|
202 | 202 | s = self._buildEngineInfoString(id,ip,port,pid) |
|
203 | 203 | f.write(s + '\n') |
|
204 | 204 | f.close() |
|
205 | 205 | |
|
206 | 206 | #--------------------------------------------------------------------------- |
|
207 | 207 | # IControllerCore methods |
|
208 | 208 | #--------------------------------------------------------------------------- |
|
209 | 209 | |
|
210 | 210 | def register_engine(self, remoteEngine, id=None, |
|
211 | 211 | ip=None, port=None, pid=None): |
|
212 | 212 | """Register new engine connection""" |
|
213 | 213 | |
|
214 | 214 | # What happens if these assertions fail? |
|
215 | 215 | assert IEngineCore.providedBy(remoteEngine), \ |
|
216 | 216 | "engine passed to register_engine doesn't provide IEngineCore" |
|
217 | 217 | assert IEngineSerialized.providedBy(remoteEngine), \ |
|
218 | 218 | "engine passed to register_engine doesn't provide IEngineSerialized" |
|
219 | 219 | assert IEngineQueued.providedBy(remoteEngine), \ |
|
220 | 220 | "engine passed to register_engine doesn't provide IEngineQueued" |
|
221 | 221 | assert isinstance(id, int) or id is None, \ |
|
222 | 222 | "id to register_engine must be an integer or None" |
|
223 | 223 | assert isinstance(ip, str) or ip is None, \ |
|
224 | 224 | "ip to register_engine must be a string or None" |
|
225 | 225 | assert isinstance(port, int) or port is None, \ |
|
226 | 226 | "port to register_engine must be an integer or None" |
|
227 | 227 | assert isinstance(pid, int) or pid is None, \ |
|
228 | 228 | "pid to register_engine must be an integer or None" |
|
229 | 229 | |
|
230 | 230 | desiredID = id |
|
231 | 231 | if desiredID in self.engines.keys(): |
|
232 | 232 | desiredID = None |
|
233 | 233 | |
|
234 | 234 | if desiredID in self.availableIDs: |
|
235 | 235 | getID = desiredID |
|
236 | 236 | self.availableIDs.remove(desiredID) |
|
237 | 237 | else: |
|
238 | 238 | getID = self.availableIDs.pop() |
|
239 | 239 | remoteEngine.id = getID |
|
240 | 240 | remoteEngine.service = self |
|
241 | 241 | self.engines[getID] = remoteEngine |
|
242 | 242 | |
|
243 | 243 | # Log the Engine Information for monitoring purposes |
|
244 | 244 | self._logEngineInfoToFile(getID, ip, port, pid) |
|
245 | 245 | |
|
246 | 246 | msg = "registered engine with id: %i" %getID |
|
247 | 247 | log.msg(msg) |
|
248 | 248 | |
|
249 | 249 | for i in range(len(self._onRegister)): |
|
250 | 250 | (f,args,kwargs,ifid) = self._onRegister[i] |
|
251 | 251 | try: |
|
252 | 252 | if ifid: |
|
253 | 253 | f(getID, *args, **kwargs) |
|
254 | 254 | else: |
|
255 | 255 | f(*args, **kwargs) |
|
256 | 256 | except: |
|
257 | 257 | self._onRegister.pop(i) |
|
258 | 258 | |
|
259 | 259 | # Call functions when the nth engine is registered and them remove them |
|
260 | 260 | for i, (n, f, args, kwargs) in enumerate(self._onNRegistered): |
|
261 | 261 | if len(self.engines.keys()) == n: |
|
262 | 262 | try: |
|
263 | 263 | try: |
|
264 | 264 | f(*args, **kwargs) |
|
265 | 265 | except: |
|
266 | 266 | log.msg("Function %r failed when the %ith engine registered" % (f, n)) |
|
267 | 267 | finally: |
|
268 | 268 | self._onNRegistered.pop(i) |
|
269 | 269 | |
|
270 | 270 | return {'id':getID} |
|
271 | 271 | |
|
272 | 272 | def unregister_engine(self, id): |
|
273 | 273 | """Unregister engine by id.""" |
|
274 | 274 | |
|
275 | 275 | assert isinstance(id, int) or id is None, \ |
|
276 | 276 | "id to unregister_engine must be an integer or None" |
|
277 | 277 | |
|
278 | 278 | msg = "unregistered engine with id: %i" %id |
|
279 | 279 | log.msg(msg) |
|
280 | 280 | try: |
|
281 | 281 | del self.engines[id] |
|
282 | 282 | except KeyError: |
|
283 | 283 | log.msg("engine with id %i was not registered" % id) |
|
284 | 284 | else: |
|
285 | 285 | if not self.saveIDs: |
|
286 | 286 | self.availableIDs.append(id) |
|
287 | 287 | # Sort to assign lower ids first |
|
288 | 288 | self.availableIDs.sort(reverse=True) |
|
289 | 289 | else: |
|
290 | 290 | log.msg("preserving id %i" %id) |
|
291 | 291 | |
|
292 | 292 | for i in range(len(self._onUnregister)): |
|
293 | 293 | (f,args,kwargs,ifid) = self._onUnregister[i] |
|
294 | 294 | try: |
|
295 | 295 | if ifid: |
|
296 | 296 | f(id, *args, **kwargs) |
|
297 | 297 | else: |
|
298 | 298 | f(*args, **kwargs) |
|
299 | 299 | except: |
|
300 | 300 | self._onUnregister.pop(i) |
|
301 | 301 | |
|
302 | 302 | def on_register_engine_do(self, f, includeID, *args, **kwargs): |
|
303 | 303 | assert callable(f), "f must be callable" |
|
304 | 304 | self._onRegister.append((f,args,kwargs,includeID)) |
|
305 | 305 | |
|
306 | 306 | def on_unregister_engine_do(self, f, includeID, *args, **kwargs): |
|
307 | 307 | assert callable(f), "f must be callable" |
|
308 | 308 | self._onUnregister.append((f,args,kwargs,includeID)) |
|
309 | 309 | |
|
310 | 310 | def on_register_engine_do_not(self, f): |
|
311 | 311 | for i in range(len(self._onRegister)): |
|
312 | 312 | g = self._onRegister[i][0] |
|
313 | 313 | if f == g: |
|
314 | 314 | self._onRegister.pop(i) |
|
315 | 315 | return |
|
316 | 316 | |
|
317 | 317 | def on_unregister_engine_do_not(self, f): |
|
318 | 318 | for i in range(len(self._onUnregister)): |
|
319 | 319 | g = self._onUnregister[i][0] |
|
320 | 320 | if f == g: |
|
321 | 321 | self._onUnregister.pop(i) |
|
322 | 322 | return |
|
323 | 323 | |
|
324 | 324 | def on_n_engines_registered_do(self, n, f, *args, **kwargs): |
|
325 | 325 | if len(self.engines.keys()) >= n: |
|
326 | 326 | f(*args, **kwargs) |
|
327 | 327 | else: |
|
328 | 328 | self._onNRegistered.append((n,f,args,kwargs)) |
|
329 | 329 | |
|
330 | 330 | |
|
331 | 331 | #------------------------------------------------------------------------------- |
|
332 | 332 | # Base class for adapting controller to different client APIs |
|
333 | 333 | #------------------------------------------------------------------------------- |
|
334 | 334 | |
|
335 | 335 | class ControllerAdapterBase(object): |
|
336 | 336 | """All Controller adapters should inherit from this class. |
|
337 | 337 | |
|
338 | 338 | This class provides a wrapped version of the IControllerBase interface that |
|
339 | 339 | can be used to easily create new custom controllers. Subclasses of this |
|
340 | 340 | will provide a full implementation of IControllerBase. |
|
341 | 341 | |
|
342 | 342 | This class doesn't implement any client notification mechanism. That |
|
343 | 343 | is up to subclasses. |
|
344 | 344 | """ |
|
345 | 345 | |
|
346 | 346 | implements(IControllerBase) |
|
347 | 347 | |
|
348 | 348 | def __init__(self, controller): |
|
349 | 349 | self.controller = controller |
|
350 | 350 | # Needed for IControllerCore |
|
351 | 351 | self.engines = self.controller.engines |
|
352 | 352 | |
|
353 | 353 | def register_engine(self, remoteEngine, id=None, |
|
354 | 354 | ip=None, port=None, pid=None): |
|
355 | 355 | return self.controller.register_engine(remoteEngine, |
|
356 | 356 | id, ip, port, pid) |
|
357 | 357 | |
|
358 | 358 | def unregister_engine(self, id): |
|
359 | 359 | return self.controller.unregister_engine(id) |
|
360 | 360 | |
|
361 | 361 | def on_register_engine_do(self, f, includeID, *args, **kwargs): |
|
362 | 362 | return self.controller.on_register_engine_do(f, includeID, *args, **kwargs) |
|
363 | 363 | |
|
364 | 364 | def on_unregister_engine_do(self, f, includeID, *args, **kwargs): |
|
365 | 365 | return self.controller.on_unregister_engine_do(f, includeID, *args, **kwargs) |
|
366 | 366 | |
|
367 | 367 | def on_register_engine_do_not(self, f): |
|
368 | 368 | return self.controller.on_register_engine_do_not(f) |
|
369 | 369 | |
|
370 | 370 | def on_unregister_engine_do_not(self, f): |
|
371 | 371 | return self.controller.on_unregister_engine_do_not(f) |
|
372 | 372 | |
|
373 | 373 | def on_n_engines_registered_do(self, n, f, *args, **kwargs): |
|
374 | 374 | return self.controller.on_n_engines_registered_do(n, f, *args, **kwargs) |
@@ -1,271 +1,271 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | The IPython controller application. |
|
5 | 5 | """ |
|
6 | 6 | |
|
7 | 7 | #----------------------------------------------------------------------------- |
|
8 | 8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | from __future__ import with_statement |
|
19 | 19 | |
|
20 | 20 | import copy |
|
21 | 21 | import sys |
|
22 | 22 | |
|
23 | 23 | from twisted.application import service |
|
24 | 24 | from twisted.internet import reactor |
|
25 | 25 | from twisted.python import log |
|
26 | 26 | |
|
27 | 27 | from IPython.config.loader import Config |
|
28 | 28 | from IPython.kernel import controllerservice |
|
29 | 29 | from IPython.kernel.clusterdir import ( |
|
30 | 30 | ApplicationWithClusterDir, |
|
31 | 31 | ClusterDirConfigLoader |
|
32 | 32 | ) |
|
33 | 33 | from IPython.kernel.fcutil import FCServiceFactory, FURLError |
|
34 | 34 | from IPython.utils.traitlets import Instance, Unicode |
|
35 | 35 | |
|
36 | 36 | |
|
37 | 37 | #----------------------------------------------------------------------------- |
|
38 | 38 | # Module level variables |
|
39 | 39 | #----------------------------------------------------------------------------- |
|
40 | 40 | |
|
41 | 41 | |
|
42 | 42 | #: The default config file name for this application |
|
43 | 43 | default_config_file_name = u'ipcontroller_config.py' |
|
44 | 44 | |
|
45 | 45 | |
|
46 | 46 | _description = """Start the IPython controller for parallel computing. |
|
47 | 47 | |
|
48 | 48 | The IPython controller provides a gateway between the IPython engines and |
|
49 | 49 | clients. The controller needs to be started before the engines and can be |
|
50 | 50 | configured using command line options or using a cluster directory. Cluster |
|
51 | 51 | directories contain config, log and security files and are usually located in |
|
52 |
your |
|
|
52 | your ipython directory and named as "cluster_<profile>". See the --profile | |
|
53 | 53 | and --cluster-dir options for details. |
|
54 | 54 | """ |
|
55 | 55 | |
|
56 | 56 | #----------------------------------------------------------------------------- |
|
57 | 57 | # Default interfaces |
|
58 | 58 | #----------------------------------------------------------------------------- |
|
59 | 59 | |
|
60 | 60 | # The default client interfaces for FCClientServiceFactory.interfaces |
|
61 | 61 | default_client_interfaces = Config() |
|
62 | 62 | default_client_interfaces.Task.interface_chain = [ |
|
63 | 63 | 'IPython.kernel.task.ITaskController', |
|
64 | 64 | 'IPython.kernel.taskfc.IFCTaskController' |
|
65 | 65 | ] |
|
66 | 66 | |
|
67 | 67 | default_client_interfaces.Task.furl_file = 'ipcontroller-tc.furl' |
|
68 | 68 | |
|
69 | 69 | default_client_interfaces.MultiEngine.interface_chain = [ |
|
70 | 70 | 'IPython.kernel.multiengine.IMultiEngine', |
|
71 | 71 | 'IPython.kernel.multienginefc.IFCSynchronousMultiEngine' |
|
72 | 72 | ] |
|
73 | 73 | |
|
74 | 74 | default_client_interfaces.MultiEngine.furl_file = u'ipcontroller-mec.furl' |
|
75 | 75 | |
|
76 | 76 | # Make this a dict we can pass to Config.__init__ for the default |
|
77 | 77 | default_client_interfaces = dict(copy.deepcopy(default_client_interfaces.items())) |
|
78 | 78 | |
|
79 | 79 | |
|
80 | 80 | |
|
81 | 81 | # The default engine interfaces for FCEngineServiceFactory.interfaces |
|
82 | 82 | default_engine_interfaces = Config() |
|
83 | 83 | default_engine_interfaces.Default.interface_chain = [ |
|
84 | 84 | 'IPython.kernel.enginefc.IFCControllerBase' |
|
85 | 85 | ] |
|
86 | 86 | |
|
87 | 87 | default_engine_interfaces.Default.furl_file = u'ipcontroller-engine.furl' |
|
88 | 88 | |
|
89 | 89 | # Make this a dict we can pass to Config.__init__ for the default |
|
90 | 90 | default_engine_interfaces = dict(copy.deepcopy(default_engine_interfaces.items())) |
|
91 | 91 | |
|
92 | 92 | |
|
93 | 93 | #----------------------------------------------------------------------------- |
|
94 | 94 | # Service factories |
|
95 | 95 | #----------------------------------------------------------------------------- |
|
96 | 96 | |
|
97 | 97 | |
|
98 | 98 | class FCClientServiceFactory(FCServiceFactory): |
|
99 | 99 | """A Foolscap implementation of the client services.""" |
|
100 | 100 | |
|
101 | 101 | cert_file = Unicode(u'ipcontroller-client.pem', config=True) |
|
102 | 102 | interfaces = Instance(klass=Config, kw=default_client_interfaces, |
|
103 | 103 | allow_none=False, config=True) |
|
104 | 104 | |
|
105 | 105 | |
|
106 | 106 | class FCEngineServiceFactory(FCServiceFactory): |
|
107 | 107 | """A Foolscap implementation of the engine services.""" |
|
108 | 108 | |
|
109 | 109 | cert_file = Unicode(u'ipcontroller-engine.pem', config=True) |
|
110 | 110 | interfaces = Instance(klass=dict, kw=default_engine_interfaces, |
|
111 | 111 | allow_none=False, config=True) |
|
112 | 112 | |
|
113 | 113 | |
|
114 | 114 | #----------------------------------------------------------------------------- |
|
115 | 115 | # Command line options |
|
116 | 116 | #----------------------------------------------------------------------------- |
|
117 | 117 | |
|
118 | 118 | |
|
119 | 119 | class IPControllerAppConfigLoader(ClusterDirConfigLoader): |
|
120 | 120 | |
|
121 | 121 | def _add_arguments(self): |
|
122 | 122 | super(IPControllerAppConfigLoader, self)._add_arguments() |
|
123 | 123 | paa = self.parser.add_argument |
|
124 | 124 | # Client config |
|
125 | 125 | paa('--client-ip', |
|
126 | 126 | type=str, dest='FCClientServiceFactory.ip', |
|
127 | 127 | help='The IP address or hostname the controller will listen on for ' |
|
128 | 128 | 'client connections.', |
|
129 | 129 | metavar='FCClientServiceFactory.ip') |
|
130 | 130 | paa('--client-port', |
|
131 | 131 | type=int, dest='FCClientServiceFactory.port', |
|
132 | 132 | help='The port the controller will listen on for client connections. ' |
|
133 | 133 | 'The default is to use 0, which will autoselect an open port.', |
|
134 | 134 | metavar='FCClientServiceFactory.port') |
|
135 | 135 | paa('--client-location',), dict( |
|
136 | 136 | type=str, dest='FCClientServiceFactory.location', |
|
137 | 137 | help='The hostname or IP that clients should connect to. This does ' |
|
138 | 138 | 'not control which interface the controller listens on. Instead, this ' |
|
139 | 139 | 'determines the hostname/IP that is listed in the FURL, which is how ' |
|
140 | 140 | 'clients know where to connect. Useful if the controller is listening ' |
|
141 | 141 | 'on multiple interfaces.', |
|
142 | 142 | metavar='FCClientServiceFactory.location') |
|
143 | 143 | # Engine config |
|
144 | 144 | paa('--engine-ip', |
|
145 | 145 | type=str, dest='FCEngineServiceFactory.ip', |
|
146 | 146 | help='The IP address or hostname the controller will listen on for ' |
|
147 | 147 | 'engine connections.', |
|
148 | 148 | metavar='FCEngineServiceFactory.ip') |
|
149 | 149 | paa('--engine-port', |
|
150 | 150 | type=int, dest='FCEngineServiceFactory.port', |
|
151 | 151 | help='The port the controller will listen on for engine connections. ' |
|
152 | 152 | 'The default is to use 0, which will autoselect an open port.', |
|
153 | 153 | metavar='FCEngineServiceFactory.port') |
|
154 | 154 | paa('--engine-location', |
|
155 | 155 | type=str, dest='FCEngineServiceFactory.location', |
|
156 | 156 | help='The hostname or IP that engines should connect to. This does ' |
|
157 | 157 | 'not control which interface the controller listens on. Instead, this ' |
|
158 | 158 | 'determines the hostname/IP that is listed in the FURL, which is how ' |
|
159 | 159 | 'engines know where to connect. Useful if the controller is listening ' |
|
160 | 160 | 'on multiple interfaces.', |
|
161 | 161 | metavar='FCEngineServiceFactory.location') |
|
162 | 162 | # Global config |
|
163 | 163 | paa('--log-to-file', |
|
164 | 164 | action='store_true', dest='Global.log_to_file', |
|
165 | 165 | help='Log to a file in the log directory (default is stdout)') |
|
166 | 166 | paa('-r','--reuse-furls', |
|
167 | 167 | action='store_true', dest='Global.reuse_furls', |
|
168 | 168 | help='Try to reuse all FURL files. If this is not set all FURL files ' |
|
169 | 169 | 'are deleted before the controller starts. This must be set if ' |
|
170 | 170 | 'specific ports are specified by --engine-port or --client-port.') |
|
171 | 171 | paa('--no-secure', |
|
172 | 172 | action='store_false', dest='Global.secure', |
|
173 | 173 | help='Turn off SSL encryption for all connections.') |
|
174 | 174 | paa('--secure', |
|
175 | 175 | action='store_true', dest='Global.secure', |
|
176 | 176 | help='Turn off SSL encryption for all connections.') |
|
177 | 177 | |
|
178 | 178 | |
|
179 | 179 | #----------------------------------------------------------------------------- |
|
180 | 180 | # The main application |
|
181 | 181 | #----------------------------------------------------------------------------- |
|
182 | 182 | |
|
183 | 183 | |
|
184 | 184 | class IPControllerApp(ApplicationWithClusterDir): |
|
185 | 185 | |
|
186 | 186 | name = u'ipcontroller' |
|
187 | 187 | description = _description |
|
188 | 188 | command_line_loader = IPControllerAppConfigLoader |
|
189 | 189 | default_config_file_name = default_config_file_name |
|
190 | 190 | auto_create_cluster_dir = True |
|
191 | 191 | |
|
192 | 192 | def create_default_config(self): |
|
193 | 193 | super(IPControllerApp, self).create_default_config() |
|
194 | 194 | # Don't set defaults for Global.secure or Global.reuse_furls |
|
195 | 195 | # as those are set in a component. |
|
196 | 196 | self.default_config.Global.import_statements = [] |
|
197 | 197 | self.default_config.Global.clean_logs = True |
|
198 | 198 | |
|
199 | 199 | def pre_construct(self): |
|
200 | 200 | super(IPControllerApp, self).pre_construct() |
|
201 | 201 | c = self.master_config |
|
202 | 202 | # The defaults for these are set in FCClientServiceFactory and |
|
203 | 203 | # FCEngineServiceFactory, so we only set them here if the global |
|
204 | 204 | # options have be set to override the class level defaults. |
|
205 | 205 | if hasattr(c.Global, 'reuse_furls'): |
|
206 | 206 | c.FCClientServiceFactory.reuse_furls = c.Global.reuse_furls |
|
207 | 207 | c.FCEngineServiceFactory.reuse_furls = c.Global.reuse_furls |
|
208 | 208 | del c.Global.reuse_furls |
|
209 | 209 | if hasattr(c.Global, 'secure'): |
|
210 | 210 | c.FCClientServiceFactory.secure = c.Global.secure |
|
211 | 211 | c.FCEngineServiceFactory.secure = c.Global.secure |
|
212 | 212 | del c.Global.secure |
|
213 | 213 | |
|
214 | 214 | def construct(self): |
|
215 | 215 | # This is the working dir by now. |
|
216 | 216 | sys.path.insert(0, '') |
|
217 | 217 | |
|
218 | 218 | self.start_logging() |
|
219 | 219 | self.import_statements() |
|
220 | 220 | |
|
221 | 221 | # Create the service hierarchy |
|
222 | 222 | self.main_service = service.MultiService() |
|
223 | 223 | # The controller service |
|
224 | 224 | controller_service = controllerservice.ControllerService() |
|
225 | 225 | controller_service.setServiceParent(self.main_service) |
|
226 | 226 | # The client tub and all its refereceables |
|
227 | 227 | try: |
|
228 | 228 | csfactory = FCClientServiceFactory(config=self.master_config, adaptee=controller_service) |
|
229 | 229 | except FURLError, e: |
|
230 | 230 | log.err(e) |
|
231 | 231 | self.exit(0) |
|
232 | 232 | client_service = csfactory.create() |
|
233 | 233 | client_service.setServiceParent(self.main_service) |
|
234 | 234 | # The engine tub |
|
235 | 235 | try: |
|
236 | 236 | esfactory = FCEngineServiceFactory(config=self.master_config, adaptee=controller_service) |
|
237 | 237 | except FURLError, e: |
|
238 | 238 | log.err(e) |
|
239 | 239 | self.exit(0) |
|
240 | 240 | engine_service = esfactory.create() |
|
241 | 241 | engine_service.setServiceParent(self.main_service) |
|
242 | 242 | |
|
243 | 243 | def import_statements(self): |
|
244 | 244 | statements = self.master_config.Global.import_statements |
|
245 | 245 | for s in statements: |
|
246 | 246 | try: |
|
247 | 247 | log.msg("Executing statement: '%s'" % s) |
|
248 | 248 | exec s in globals(), locals() |
|
249 | 249 | except: |
|
250 | 250 | log.msg("Error running statement: %s" % s) |
|
251 | 251 | |
|
252 | 252 | def start_app(self): |
|
253 | 253 | # Start the controller service. |
|
254 | 254 | self.main_service.startService() |
|
255 | 255 | # Write the .pid file overwriting old ones. This allow multiple |
|
256 | 256 | # controllers to clober each other. But Windows is not cleaning |
|
257 | 257 | # these up properly. |
|
258 | 258 | self.write_pid_file(overwrite=True) |
|
259 | 259 | # Add a trigger to delete the .pid file upon shutting down. |
|
260 | 260 | reactor.addSystemEventTrigger('during','shutdown', self.remove_pid_file) |
|
261 | 261 | reactor.run() |
|
262 | 262 | |
|
263 | 263 | |
|
264 | 264 | def launch_new_instance(): |
|
265 | 265 | """Create and run the IPython controller""" |
|
266 | 266 | app = IPControllerApp() |
|
267 | 267 | app.start() |
|
268 | 268 | |
|
269 | 269 | |
|
270 | 270 | if __name__ == '__main__': |
|
271 | 271 | launch_new_instance() |
@@ -1,242 +1,242 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | The IPython controller application |
|
5 | 5 | """ |
|
6 | 6 | |
|
7 | 7 | #----------------------------------------------------------------------------- |
|
8 | 8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | 9 | # |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | import os |
|
19 | 19 | import sys |
|
20 | 20 | |
|
21 | 21 | from twisted.application import service |
|
22 | 22 | from twisted.internet import reactor |
|
23 | 23 | from twisted.python import log |
|
24 | 24 | |
|
25 | 25 | from IPython.kernel.clusterdir import ( |
|
26 | 26 | ApplicationWithClusterDir, |
|
27 | 27 | ClusterDirConfigLoader |
|
28 | 28 | ) |
|
29 | 29 | from IPython.kernel.engineconnector import EngineConnector |
|
30 | 30 | from IPython.kernel.engineservice import EngineService |
|
31 | 31 | from IPython.kernel.fcutil import Tub |
|
32 | 32 | from IPython.utils.importstring import import_item |
|
33 | 33 | |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | # Module level variables |
|
36 | 36 | #----------------------------------------------------------------------------- |
|
37 | 37 | |
|
38 | 38 | #: The default config file name for this application |
|
39 | 39 | default_config_file_name = u'ipengine_config.py' |
|
40 | 40 | |
|
41 | 41 | |
|
42 | 42 | mpi4py_init = """from mpi4py import MPI as mpi |
|
43 | 43 | mpi.size = mpi.COMM_WORLD.Get_size() |
|
44 | 44 | mpi.rank = mpi.COMM_WORLD.Get_rank() |
|
45 | 45 | """ |
|
46 | 46 | |
|
47 | 47 | |
|
48 | 48 | pytrilinos_init = """from PyTrilinos import Epetra |
|
49 | 49 | class SimpleStruct: |
|
50 | 50 | pass |
|
51 | 51 | mpi = SimpleStruct() |
|
52 | 52 | mpi.rank = 0 |
|
53 | 53 | mpi.size = 0 |
|
54 | 54 | """ |
|
55 | 55 | |
|
56 | 56 | |
|
57 | 57 | _description = """Start an IPython engine for parallel computing.\n\n |
|
58 | 58 | |
|
59 | 59 | IPython engines run in parallel and perform computations on behalf of a client |
|
60 | 60 | and controller. A controller needs to be started before the engines. The |
|
61 | 61 | engine can be configured using command line options or using a cluster |
|
62 | 62 | directory. Cluster directories contain config, log and security files and are |
|
63 |
usually located in your |
|
|
63 | usually located in your ipython directory and named as "cluster_<profile>". | |
|
64 | 64 | See the --profile and --cluster-dir options for details. |
|
65 | 65 | """ |
|
66 | 66 | |
|
67 | 67 | #----------------------------------------------------------------------------- |
|
68 | 68 | # Command line options |
|
69 | 69 | #----------------------------------------------------------------------------- |
|
70 | 70 | |
|
71 | 71 | |
|
72 | 72 | class IPEngineAppConfigLoader(ClusterDirConfigLoader): |
|
73 | 73 | |
|
74 | 74 | def _add_arguments(self): |
|
75 | 75 | super(IPEngineAppConfigLoader, self)._add_arguments() |
|
76 | 76 | paa = self.parser.add_argument |
|
77 | 77 | # Controller config |
|
78 | 78 | paa('--furl-file', |
|
79 | 79 | type=unicode, dest='Global.furl_file', |
|
80 | 80 | help='The full location of the file containing the FURL of the ' |
|
81 | 81 | 'controller. If this is not given, the FURL file must be in the ' |
|
82 | 82 | 'security directory of the cluster directory. This location is ' |
|
83 | 83 | 'resolved using the --profile and --app-dir options.', |
|
84 | 84 | metavar='Global.furl_file') |
|
85 | 85 | # MPI |
|
86 | 86 | paa('--mpi', |
|
87 | 87 | type=str, dest='MPI.use', |
|
88 | 88 | help='How to enable MPI (mpi4py, pytrilinos, or empty string to disable).', |
|
89 | 89 | metavar='MPI.use') |
|
90 | 90 | # Global config |
|
91 | 91 | paa('--log-to-file', |
|
92 | 92 | action='store_true', dest='Global.log_to_file', |
|
93 | 93 | help='Log to a file in the log directory (default is stdout)') |
|
94 | 94 | |
|
95 | 95 | |
|
96 | 96 | #----------------------------------------------------------------------------- |
|
97 | 97 | # Main application |
|
98 | 98 | #----------------------------------------------------------------------------- |
|
99 | 99 | |
|
100 | 100 | |
|
101 | 101 | class IPEngineApp(ApplicationWithClusterDir): |
|
102 | 102 | |
|
103 | 103 | name = u'ipengine' |
|
104 | 104 | description = _description |
|
105 | 105 | command_line_loader = IPEngineAppConfigLoader |
|
106 | 106 | default_config_file_name = default_config_file_name |
|
107 | 107 | auto_create_cluster_dir = True |
|
108 | 108 | |
|
109 | 109 | def create_default_config(self): |
|
110 | 110 | super(IPEngineApp, self).create_default_config() |
|
111 | 111 | |
|
112 | 112 | # The engine should not clean logs as we don't want to remove the |
|
113 | 113 | # active log files of other running engines. |
|
114 | 114 | self.default_config.Global.clean_logs = False |
|
115 | 115 | |
|
116 | 116 | # Global config attributes |
|
117 | 117 | self.default_config.Global.exec_lines = [] |
|
118 | 118 | self.default_config.Global.shell_class = 'IPython.kernel.core.interpreter.Interpreter' |
|
119 | 119 | |
|
120 | 120 | # Configuration related to the controller |
|
121 | 121 | # This must match the filename (path not included) that the controller |
|
122 | 122 | # used for the FURL file. |
|
123 | 123 | self.default_config.Global.furl_file_name = u'ipcontroller-engine.furl' |
|
124 | 124 | # If given, this is the actual location of the controller's FURL file. |
|
125 | 125 | # If not, this is computed using the profile, app_dir and furl_file_name |
|
126 | 126 | self.default_config.Global.furl_file = u'' |
|
127 | 127 | |
|
128 | 128 | # The max number of connection attemps and the initial delay between |
|
129 | 129 | # those attemps. |
|
130 | 130 | self.default_config.Global.connect_delay = 0.1 |
|
131 | 131 | self.default_config.Global.connect_max_tries = 15 |
|
132 | 132 | |
|
133 | 133 | # MPI related config attributes |
|
134 | 134 | self.default_config.MPI.use = '' |
|
135 | 135 | self.default_config.MPI.mpi4py = mpi4py_init |
|
136 | 136 | self.default_config.MPI.pytrilinos = pytrilinos_init |
|
137 | 137 | |
|
138 | 138 | def post_load_command_line_config(self): |
|
139 | 139 | pass |
|
140 | 140 | |
|
141 | 141 | def pre_construct(self): |
|
142 | 142 | super(IPEngineApp, self).pre_construct() |
|
143 | 143 | self.find_cont_furl_file() |
|
144 | 144 | |
|
145 | 145 | def find_cont_furl_file(self): |
|
146 | 146 | """Set the furl file. |
|
147 | 147 | |
|
148 | 148 | Here we don't try to actually see if it exists for is valid as that |
|
149 | 149 | is hadled by the connection logic. |
|
150 | 150 | """ |
|
151 | 151 | config = self.master_config |
|
152 | 152 | # Find the actual controller FURL file |
|
153 | 153 | if not config.Global.furl_file: |
|
154 | 154 | try_this = os.path.join( |
|
155 | 155 | config.Global.cluster_dir, |
|
156 | 156 | config.Global.security_dir, |
|
157 | 157 | config.Global.furl_file_name |
|
158 | 158 | ) |
|
159 | 159 | config.Global.furl_file = try_this |
|
160 | 160 | |
|
161 | 161 | def construct(self): |
|
162 | 162 | # This is the working dir by now. |
|
163 | 163 | sys.path.insert(0, '') |
|
164 | 164 | |
|
165 | 165 | self.start_mpi() |
|
166 | 166 | self.start_logging() |
|
167 | 167 | |
|
168 | 168 | # Create the underlying shell class and EngineService |
|
169 | 169 | shell_class = import_item(self.master_config.Global.shell_class) |
|
170 | 170 | self.engine_service = EngineService(shell_class, mpi=mpi) |
|
171 | 171 | |
|
172 | 172 | self.exec_lines() |
|
173 | 173 | |
|
174 | 174 | # Create the service hierarchy |
|
175 | 175 | self.main_service = service.MultiService() |
|
176 | 176 | self.engine_service.setServiceParent(self.main_service) |
|
177 | 177 | self.tub_service = Tub() |
|
178 | 178 | self.tub_service.setServiceParent(self.main_service) |
|
179 | 179 | # This needs to be called before the connection is initiated |
|
180 | 180 | self.main_service.startService() |
|
181 | 181 | |
|
182 | 182 | # This initiates the connection to the controller and calls |
|
183 | 183 | # register_engine to tell the controller we are ready to do work |
|
184 | 184 | self.engine_connector = EngineConnector(self.tub_service) |
|
185 | 185 | |
|
186 | 186 | log.msg("Using furl file: %s" % self.master_config.Global.furl_file) |
|
187 | 187 | |
|
188 | 188 | reactor.callWhenRunning(self.call_connect) |
|
189 | 189 | |
|
190 | 190 | def call_connect(self): |
|
191 | 191 | d = self.engine_connector.connect_to_controller( |
|
192 | 192 | self.engine_service, |
|
193 | 193 | self.master_config.Global.furl_file, |
|
194 | 194 | self.master_config.Global.connect_delay, |
|
195 | 195 | self.master_config.Global.connect_max_tries |
|
196 | 196 | ) |
|
197 | 197 | |
|
198 | 198 | def handle_error(f): |
|
199 | 199 | log.msg('Error connecting to controller. This usually means that ' |
|
200 | 200 | 'i) the controller was not started, ii) a firewall was blocking ' |
|
201 | 201 | 'the engine from connecting to the controller or iii) the engine ' |
|
202 | 202 | ' was not pointed at the right FURL file:') |
|
203 | 203 | log.msg(f.getErrorMessage()) |
|
204 | 204 | reactor.callLater(0.1, reactor.stop) |
|
205 | 205 | |
|
206 | 206 | d.addErrback(handle_error) |
|
207 | 207 | |
|
208 | 208 | def start_mpi(self): |
|
209 | 209 | global mpi |
|
210 | 210 | mpikey = self.master_config.MPI.use |
|
211 | 211 | mpi_import_statement = self.master_config.MPI.get(mpikey, None) |
|
212 | 212 | if mpi_import_statement is not None: |
|
213 | 213 | try: |
|
214 | 214 | self.log.info("Initializing MPI:") |
|
215 | 215 | self.log.info(mpi_import_statement) |
|
216 | 216 | exec mpi_import_statement in globals() |
|
217 | 217 | except: |
|
218 | 218 | mpi = None |
|
219 | 219 | else: |
|
220 | 220 | mpi = None |
|
221 | 221 | |
|
222 | 222 | def exec_lines(self): |
|
223 | 223 | for line in self.master_config.Global.exec_lines: |
|
224 | 224 | try: |
|
225 | 225 | log.msg("Executing statement: '%s'" % line) |
|
226 | 226 | self.engine_service.execute(line) |
|
227 | 227 | except: |
|
228 | 228 | log.msg("Error executing statement: %s" % line) |
|
229 | 229 | |
|
230 | 230 | def start_app(self): |
|
231 | 231 | reactor.run() |
|
232 | 232 | |
|
233 | 233 | |
|
234 | 234 | def launch_new_instance(): |
|
235 | 235 | """Create and run the IPython controller""" |
|
236 | 236 | app = IPEngineApp() |
|
237 | 237 | app.start() |
|
238 | 238 | |
|
239 | 239 | |
|
240 | 240 | if __name__ == '__main__': |
|
241 | 241 | launch_new_instance() |
|
242 | 242 |
@@ -1,345 +1,383 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Utilities for path handling. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | import os |
|
18 | 18 | import sys |
|
19 | 19 | |
|
20 | 20 | import IPython |
|
21 | 21 | from IPython.utils.process import system |
|
22 | 22 | from IPython.utils.importstring import import_item |
|
23 | 23 | |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | # Code |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | |
|
28 | 28 | |
|
29 | 29 | def _get_long_path_name(path): |
|
30 | 30 | """Dummy no-op.""" |
|
31 | 31 | return path |
|
32 | 32 | |
|
33 | 33 | |
|
34 | 34 | if sys.platform == 'win32': |
|
35 | 35 | def _get_long_path_name(path): |
|
36 | 36 | """Get a long path name (expand ~) on Windows using ctypes. |
|
37 | 37 | |
|
38 | 38 | Examples |
|
39 | 39 | -------- |
|
40 | 40 | |
|
41 | 41 | >>> get_long_path_name('c:\\docume~1') |
|
42 | 42 | u'c:\\\\Documents and Settings' |
|
43 | 43 | |
|
44 | 44 | """ |
|
45 | 45 | try: |
|
46 | 46 | import ctypes |
|
47 | 47 | except ImportError: |
|
48 | 48 | raise ImportError('you need to have ctypes installed for this to work') |
|
49 | 49 | _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW |
|
50 | 50 | _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p, |
|
51 | 51 | ctypes.c_uint ] |
|
52 | 52 | |
|
53 | 53 | buf = ctypes.create_unicode_buffer(260) |
|
54 | 54 | rv = _GetLongPathName(path, buf, 260) |
|
55 | 55 | if rv == 0 or rv > 260: |
|
56 | 56 | return path |
|
57 | 57 | else: |
|
58 | 58 | return buf.value |
|
59 | 59 | |
|
60 | 60 | |
|
61 | 61 | def get_long_path_name(path): |
|
62 | 62 | """Expand a path into its long form. |
|
63 | 63 | |
|
64 | 64 | On Windows this expands any ~ in the paths. On other platforms, it is |
|
65 | 65 | a null operation. |
|
66 | 66 | """ |
|
67 | 67 | return _get_long_path_name(path) |
|
68 | 68 | |
|
69 | 69 | |
|
70 | 70 | def get_py_filename(name): |
|
71 | 71 | """Return a valid python filename in the current directory. |
|
72 | 72 | |
|
73 | 73 | If the given name is not a file, it adds '.py' and searches again. |
|
74 | 74 | Raises IOError with an informative message if the file isn't found.""" |
|
75 | 75 | |
|
76 | 76 | name = os.path.expanduser(name) |
|
77 | 77 | if not os.path.isfile(name) and not name.endswith('.py'): |
|
78 | 78 | name += '.py' |
|
79 | 79 | if os.path.isfile(name): |
|
80 | 80 | return name |
|
81 | 81 | else: |
|
82 | 82 | raise IOError,'File `%s` not found.' % name |
|
83 | 83 | |
|
84 | 84 | |
|
85 | 85 | def filefind(filename, path_dirs=None): |
|
86 | 86 | """Find a file by looking through a sequence of paths. |
|
87 | 87 | |
|
88 | 88 | This iterates through a sequence of paths looking for a file and returns |
|
89 | 89 | the full, absolute path of the first occurence of the file. If no set of |
|
90 | 90 | path dirs is given, the filename is tested as is, after running through |
|
91 | 91 | :func:`expandvars` and :func:`expanduser`. Thus a simple call:: |
|
92 | 92 | |
|
93 | 93 | filefind('myfile.txt') |
|
94 | 94 | |
|
95 | 95 | will find the file in the current working dir, but:: |
|
96 | 96 | |
|
97 | 97 | filefind('~/myfile.txt') |
|
98 | 98 | |
|
99 | 99 | Will find the file in the users home directory. This function does not |
|
100 | 100 | automatically try any paths, such as the cwd or the user's home directory. |
|
101 | 101 | |
|
102 | 102 | Parameters |
|
103 | 103 | ---------- |
|
104 | 104 | filename : str |
|
105 | 105 | The filename to look for. |
|
106 | 106 | path_dirs : str, None or sequence of str |
|
107 | 107 | The sequence of paths to look for the file in. If None, the filename |
|
108 | 108 | need to be absolute or be in the cwd. If a string, the string is |
|
109 | 109 | put into a sequence and the searched. If a sequence, walk through |
|
110 | 110 | each element and join with ``filename``, calling :func:`expandvars` |
|
111 | 111 | and :func:`expanduser` before testing for existence. |
|
112 | 112 | |
|
113 | 113 | Returns |
|
114 | 114 | ------- |
|
115 | 115 | Raises :exc:`IOError` or returns absolute path to file. |
|
116 | 116 | """ |
|
117 | 117 | |
|
118 | 118 | # If paths are quoted, abspath gets confused, strip them... |
|
119 | 119 | filename = filename.strip('"').strip("'") |
|
120 | 120 | # If the input is an absolute path, just check it exists |
|
121 | 121 | if os.path.isabs(filename) and os.path.isfile(filename): |
|
122 | 122 | return filename |
|
123 | 123 | |
|
124 | 124 | if path_dirs is None: |
|
125 | 125 | path_dirs = ("",) |
|
126 | 126 | elif isinstance(path_dirs, basestring): |
|
127 | 127 | path_dirs = (path_dirs,) |
|
128 | 128 | |
|
129 | 129 | for path in path_dirs: |
|
130 | 130 | if path == '.': path = os.getcwd() |
|
131 | 131 | testname = expand_path(os.path.join(path, filename)) |
|
132 | 132 | if os.path.isfile(testname): |
|
133 | 133 | return os.path.abspath(testname) |
|
134 | 134 | |
|
135 | 135 | raise IOError("File %r does not exist in any of the search paths: %r" % |
|
136 | 136 | (filename, path_dirs) ) |
|
137 | 137 | |
|
138 | 138 | |
|
139 | 139 | class HomeDirError(Exception): |
|
140 | 140 | pass |
|
141 | 141 | |
|
142 | 142 | |
|
143 | 143 | def get_home_dir(): |
|
144 | 144 | """Return the closest possible equivalent to a 'home' directory. |
|
145 | 145 | |
|
146 | 146 | * On POSIX, we try $HOME. |
|
147 | 147 | * On Windows we try: |
|
148 | 148 | - %HOMESHARE% |
|
149 | 149 | - %HOMEDRIVE\%HOMEPATH% |
|
150 | 150 | - %USERPROFILE% |
|
151 | 151 | - Registry hack for My Documents |
|
152 | 152 | - %HOME%: rare, but some people with unix-like setups may have defined it |
|
153 | 153 | * On Dos C:\ |
|
154 | 154 | |
|
155 | 155 | Currently only Posix and NT are implemented, a HomeDirError exception is |
|
156 | 156 | raised for all other OSes. |
|
157 | 157 | """ |
|
158 | 158 | |
|
159 | 159 | isdir = os.path.isdir |
|
160 | 160 | env = os.environ |
|
161 | 161 | |
|
162 | 162 | # first, check py2exe distribution root directory for _ipython. |
|
163 | 163 | # This overrides all. Normally does not exist. |
|
164 | 164 | |
|
165 | 165 | if hasattr(sys, "frozen"): #Is frozen by py2exe |
|
166 | 166 | if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file |
|
167 | 167 | root, rest = IPython.__file__.lower().split('library.zip') |
|
168 | 168 | else: |
|
169 | 169 | root=os.path.join(os.path.split(IPython.__file__)[0],"../../") |
|
170 | 170 | root=os.path.abspath(root).rstrip('\\') |
|
171 | 171 | if isdir(os.path.join(root, '_ipython')): |
|
172 | 172 | os.environ["IPYKITROOT"] = root |
|
173 | 173 | return root.decode(sys.getfilesystemencoding()) |
|
174 | 174 | |
|
175 | 175 | if os.name == 'posix': |
|
176 | 176 | # Linux, Unix, AIX, OS X |
|
177 | 177 | try: |
|
178 | 178 | homedir = env['HOME'] |
|
179 | 179 | except KeyError: |
|
180 | 180 | raise HomeDirError('Undefined $HOME, IPython cannot proceed.') |
|
181 | 181 | else: |
|
182 | 182 | return homedir.decode(sys.getfilesystemencoding()) |
|
183 | 183 | elif os.name == 'nt': |
|
184 | 184 | # Now for win9x, XP, Vista, 7? |
|
185 | 185 | # For some strange reason all of these return 'nt' for os.name. |
|
186 | 186 | # First look for a network home directory. This will return the UNC |
|
187 | 187 | # path (\\server\\Users\%username%) not the mapped path (Z:\). This |
|
188 | 188 | # is needed when running IPython on cluster where all paths have to |
|
189 | 189 | # be UNC. |
|
190 | 190 | try: |
|
191 | 191 | homedir = env['HOMESHARE'] |
|
192 | 192 | except KeyError: |
|
193 | 193 | pass |
|
194 | 194 | else: |
|
195 | 195 | if isdir(homedir): |
|
196 | 196 | return homedir.decode(sys.getfilesystemencoding()) |
|
197 | 197 | |
|
198 | 198 | # Now look for a local home directory |
|
199 | 199 | try: |
|
200 | 200 | homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH']) |
|
201 | 201 | except KeyError: |
|
202 | 202 | pass |
|
203 | 203 | else: |
|
204 | 204 | if isdir(homedir): |
|
205 | 205 | return homedir.decode(sys.getfilesystemencoding()) |
|
206 | 206 | |
|
207 | 207 | # Now the users profile directory |
|
208 | 208 | try: |
|
209 | 209 | homedir = os.path.join(env['USERPROFILE']) |
|
210 | 210 | except KeyError: |
|
211 | 211 | pass |
|
212 | 212 | else: |
|
213 | 213 | if isdir(homedir): |
|
214 | 214 | return homedir.decode(sys.getfilesystemencoding()) |
|
215 | 215 | |
|
216 | 216 | # Use the registry to get the 'My Documents' folder. |
|
217 | 217 | try: |
|
218 | 218 | import _winreg as wreg |
|
219 | 219 | key = wreg.OpenKey( |
|
220 | 220 | wreg.HKEY_CURRENT_USER, |
|
221 | 221 | "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" |
|
222 | 222 | ) |
|
223 | 223 | homedir = wreg.QueryValueEx(key,'Personal')[0] |
|
224 | 224 | key.Close() |
|
225 | 225 | except: |
|
226 | 226 | pass |
|
227 | 227 | else: |
|
228 | 228 | if isdir(homedir): |
|
229 | 229 | return homedir.decode(sys.getfilesystemencoding()) |
|
230 | 230 | |
|
231 | 231 | # A user with a lot of unix tools in win32 may have defined $HOME. |
|
232 | 232 | # Try this as a last ditch option. |
|
233 | 233 | try: |
|
234 | 234 | homedir = env['HOME'] |
|
235 | 235 | except KeyError: |
|
236 | 236 | pass |
|
237 | 237 | else: |
|
238 | 238 | if isdir(homedir): |
|
239 | 239 | return homedir.decode(sys.getfilesystemencoding()) |
|
240 | 240 | |
|
241 | 241 | # If all else fails, raise HomeDirError |
|
242 | 242 | raise HomeDirError('No valid home directory could be found') |
|
243 | 243 | elif os.name == 'dos': |
|
244 | 244 | # Desperate, may do absurd things in classic MacOS. May work under DOS. |
|
245 | 245 | return 'C:\\'.decode(sys.getfilesystemencoding()) |
|
246 | 246 | else: |
|
247 | 247 | raise HomeDirError('No valid home directory could be found for your OS') |
|
248 | 248 | |
|
249 | def get_xdg_dir(): | |
|
250 | """Return the XDG_CONFIG_HOME, if it is defined and exists, else None. | |
|
251 | ||
|
252 | This is only for posix (Linux,Unix,OS X, etc) systems. | |
|
253 | """ | |
|
254 | ||
|
255 | isdir = os.path.isdir | |
|
256 | env = os.environ | |
|
257 | ||
|
258 | if os.name == 'posix': | |
|
259 | # Linux, Unix, AIX, OS X | |
|
260 | # use ~/.config if not set OR empty | |
|
261 | xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config') | |
|
262 | if xdg and isdir(xdg): | |
|
263 | return xdg.decode(sys.getfilesystemencoding()) | |
|
264 | ||
|
265 | return None | |
|
266 | ||
|
249 | 267 | |
|
250 | 268 | def get_ipython_dir(): |
|
251 | 269 | """Get the IPython directory for this platform and user. |
|
252 | 270 | |
|
253 | 271 | This uses the logic in `get_home_dir` to find the home directory |
|
254 | 272 | and the adds .ipython to the end of the path. |
|
255 | 273 | """ |
|
274 | ||
|
275 | env = os.environ | |
|
276 | pjoin = os.path.join | |
|
277 | exists = os.path.exists | |
|
278 | ||
|
256 | 279 | ipdir_def = '.ipython' |
|
280 | xdg_def = 'ipython' | |
|
281 | ||
|
257 | 282 | home_dir = get_home_dir() |
|
283 | xdg_dir = get_xdg_dir() | |
|
258 | 284 | # import pdb; pdb.set_trace() # dbg |
|
259 | ipdir = os.environ.get( | |
|
260 | 'IPYTHON_DIR', os.environ.get( | |
|
261 | 'IPYTHONDIR', os.path.join(home_dir, ipdir_def) | |
|
262 | ) | |
|
263 | ) | |
|
285 | ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None)) | |
|
286 | if ipdir is None: | |
|
287 | # not set explicitly, use XDG_CONFIG_HOME or HOME | |
|
288 | home_ipdir = pjoin(home_dir, ipdir_def) | |
|
289 | if xdg_dir: | |
|
290 | # use XDG, as long as the user isn't already | |
|
291 | # using $HOME/.ipython and *not* XDG/ipython | |
|
292 | ||
|
293 | xdg_ipdir = pjoin(xdg_dir, xdg_def) | |
|
294 | ||
|
295 | if exists(xdg_ipdir) or not exists(home_ipdir): | |
|
296 | ipdir = xdg_ipdir | |
|
297 | ||
|
298 | if ipdir is None: | |
|
299 | # not using XDG | |
|
300 | ipdir = home_ipdir | |
|
301 | ||
|
264 | 302 | return ipdir.decode(sys.getfilesystemencoding()) |
|
265 | 303 | |
|
266 | 304 | |
|
267 | 305 | def get_ipython_package_dir(): |
|
268 | 306 | """Get the base directory where IPython itself is installed.""" |
|
269 | 307 | ipdir = os.path.dirname(IPython.__file__) |
|
270 | 308 | return ipdir.decode(sys.getfilesystemencoding()) |
|
271 | 309 | |
|
272 | 310 | |
|
273 | 311 | def get_ipython_module_path(module_str): |
|
274 | 312 | """Find the path to an IPython module in this version of IPython. |
|
275 | 313 | |
|
276 | 314 | This will always find the version of the module that is in this importable |
|
277 | 315 | IPython package. This will always return the path to the ``.py`` |
|
278 | 316 | version of the module. |
|
279 | 317 | """ |
|
280 | 318 | if module_str == 'IPython': |
|
281 | 319 | return os.path.join(get_ipython_package_dir(), '__init__.py') |
|
282 | 320 | mod = import_item(module_str) |
|
283 | 321 | the_path = mod.__file__.replace('.pyc', '.py') |
|
284 | 322 | the_path = the_path.replace('.pyo', '.py') |
|
285 | 323 | return the_path.decode(sys.getfilesystemencoding()) |
|
286 | 324 | |
|
287 | 325 | |
|
288 | 326 | def expand_path(s): |
|
289 | 327 | """Expand $VARS and ~names in a string, like a shell |
|
290 | 328 | |
|
291 | 329 | :Examples: |
|
292 | 330 | |
|
293 | 331 | In [2]: os.environ['FOO']='test' |
|
294 | 332 | |
|
295 | 333 | In [3]: expand_path('variable FOO is $FOO') |
|
296 | 334 | Out[3]: 'variable FOO is test' |
|
297 | 335 | """ |
|
298 | 336 | # This is a pretty subtle hack. When expand user is given a UNC path |
|
299 | 337 | # on Windows (\\server\share$\%username%), os.path.expandvars, removes |
|
300 | 338 | # the $ to get (\\server\share\%username%). I think it considered $ |
|
301 | 339 | # alone an empty var. But, we need the $ to remains there (it indicates |
|
302 | 340 | # a hidden share). |
|
303 | 341 | if os.name=='nt': |
|
304 | 342 | s = s.replace('$\\', 'IPYTHON_TEMP') |
|
305 | 343 | s = os.path.expandvars(os.path.expanduser(s)) |
|
306 | 344 | if os.name=='nt': |
|
307 | 345 | s = s.replace('IPYTHON_TEMP', '$\\') |
|
308 | 346 | return s |
|
309 | 347 | |
|
310 | 348 | |
|
311 | 349 | def target_outdated(target,deps): |
|
312 | 350 | """Determine whether a target is out of date. |
|
313 | 351 | |
|
314 | 352 | target_outdated(target,deps) -> 1/0 |
|
315 | 353 | |
|
316 | 354 | deps: list of filenames which MUST exist. |
|
317 | 355 | target: single filename which may or may not exist. |
|
318 | 356 | |
|
319 | 357 | If target doesn't exist or is older than any file listed in deps, return |
|
320 | 358 | true, otherwise return false. |
|
321 | 359 | """ |
|
322 | 360 | try: |
|
323 | 361 | target_time = os.path.getmtime(target) |
|
324 | 362 | except os.error: |
|
325 | 363 | return 1 |
|
326 | 364 | for dep in deps: |
|
327 | 365 | dep_time = os.path.getmtime(dep) |
|
328 | 366 | if dep_time > target_time: |
|
329 | 367 | #print "For target",target,"Dep failed:",dep # dbg |
|
330 | 368 | #print "times (dep,tar):",dep_time,target_time # dbg |
|
331 | 369 | return 1 |
|
332 | 370 | return 0 |
|
333 | 371 | |
|
334 | 372 | |
|
335 | 373 | def target_update(target,deps,cmd): |
|
336 | 374 | """Update a target with a given command given a list of dependencies. |
|
337 | 375 | |
|
338 | 376 | target_update(target,deps,cmd) -> runs cmd if target is outdated. |
|
339 | 377 | |
|
340 | 378 | This is just a wrapper around target_outdated() which calls the given |
|
341 | 379 | command if target is outdated.""" |
|
342 | 380 | |
|
343 | 381 | if target_outdated(target,deps): |
|
344 | 382 | system(cmd) |
|
345 | 383 |
@@ -1,272 +1,358 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Tests for IPython.utils.path.py""" |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (C) 2008 The IPython Development Team |
|
6 | 6 | # |
|
7 | 7 | # Distributed under the terms of the BSD License. The full license is in |
|
8 | 8 | # the file COPYING, distributed as part of this software. |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | # Imports |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | import os |
|
16 | 16 | import shutil |
|
17 | 17 | import sys |
|
18 | 18 | import tempfile |
|
19 | 19 | |
|
20 | 20 | from os.path import join, abspath, split |
|
21 | 21 | |
|
22 | 22 | import nose.tools as nt |
|
23 | 23 | |
|
24 | 24 | from nose import with_setup |
|
25 | 25 | |
|
26 | 26 | import IPython |
|
27 | 27 | from IPython.testing import decorators as dec |
|
28 | 28 | from IPython.testing.decorators import skip_if_not_win32, skip_win32 |
|
29 | 29 | from IPython.utils import path |
|
30 | 30 | |
|
31 | 31 | # Platform-dependent imports |
|
32 | 32 | try: |
|
33 | 33 | import _winreg as wreg |
|
34 | 34 | except ImportError: |
|
35 | 35 | #Fake _winreg module on none windows platforms |
|
36 | 36 | import new |
|
37 | 37 | sys.modules["_winreg"] = new.module("_winreg") |
|
38 | 38 | import _winreg as wreg |
|
39 | 39 | #Add entries that needs to be stubbed by the testing code |
|
40 | 40 | (wreg.OpenKey, wreg.QueryValueEx,) = (None, None) |
|
41 | 41 | |
|
42 | 42 | #----------------------------------------------------------------------------- |
|
43 | 43 | # Globals |
|
44 | 44 | #----------------------------------------------------------------------------- |
|
45 | 45 | env = os.environ |
|
46 | 46 | TEST_FILE_PATH = split(abspath(__file__))[0] |
|
47 | 47 | TMP_TEST_DIR = tempfile.mkdtemp() |
|
48 | 48 | HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir") |
|
49 | XDG_TEST_DIR = join(HOME_TEST_DIR, "xdg_test_dir") | |
|
49 | 50 | IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython') |
|
50 | 51 | # |
|
51 | 52 | # Setup/teardown functions/decorators |
|
52 | 53 | # |
|
53 | 54 | |
|
54 | 55 | def setup(): |
|
55 | 56 | """Setup testenvironment for the module: |
|
56 | 57 | |
|
57 | 58 | - Adds dummy home dir tree |
|
58 | 59 | """ |
|
59 | 60 | # Do not mask exceptions here. In particular, catching WindowsError is a |
|
60 | 61 | # problem because that exception is only defined on Windows... |
|
61 | 62 | os.makedirs(IP_TEST_DIR) |
|
63 | os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython')) | |
|
62 | 64 | |
|
63 | 65 | |
|
64 | 66 | def teardown(): |
|
65 | 67 | """Teardown testenvironment for the module: |
|
66 | 68 | |
|
67 | 69 | - Remove dummy home dir tree |
|
68 | 70 | """ |
|
69 | 71 | # Note: we remove the parent test dir, which is the root of all test |
|
70 | 72 | # subdirs we may have created. Use shutil instead of os.removedirs, so |
|
71 | 73 | # that non-empty directories are all recursively removed. |
|
72 | 74 | shutil.rmtree(TMP_TEST_DIR) |
|
73 | 75 | |
|
74 | 76 | |
|
75 | 77 | def setup_environment(): |
|
76 | 78 | """Setup testenvironment for some functions that are tested |
|
77 | 79 | in this module. In particular this functions stores attributes |
|
78 | 80 | and other things that we need to stub in some test functions. |
|
79 | 81 | This needs to be done on a function level and not module level because |
|
80 | 82 | each testfunction needs a pristine environment. |
|
81 | 83 | """ |
|
82 | 84 | global oldstuff, platformstuff |
|
83 | 85 | oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__) |
|
84 | 86 | |
|
85 | 87 | if os.name == 'nt': |
|
86 | 88 | platformstuff = (wreg.OpenKey, wreg.QueryValueEx,) |
|
87 | 89 | |
|
88 | 90 | |
|
89 | 91 | def teardown_environment(): |
|
90 | 92 | """Restore things that were remebered by the setup_environment function |
|
91 | 93 | """ |
|
92 | 94 | (oldenv, os.name, get_home_dir, IPython.__file__,) = oldstuff |
|
93 | 95 | |
|
94 | 96 | for key in env.keys(): |
|
95 | 97 | if key not in oldenv: |
|
96 | 98 | del env[key] |
|
97 | 99 | env.update(oldenv) |
|
98 | 100 | if hasattr(sys, 'frozen'): |
|
99 | 101 | del sys.frozen |
|
100 | 102 | if os.name == 'nt': |
|
101 | 103 | (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff |
|
102 | 104 | |
|
103 | 105 | # Build decorator that uses the setup_environment/setup_environment |
|
104 | 106 | with_environment = with_setup(setup_environment, teardown_environment) |
|
105 | 107 | |
|
106 | 108 | |
|
107 | 109 | @skip_if_not_win32 |
|
108 | 110 | @with_environment |
|
109 | 111 | def test_get_home_dir_1(): |
|
110 | 112 | """Testcase for py2exe logic, un-compressed lib |
|
111 | 113 | """ |
|
112 | 114 | sys.frozen = True |
|
113 | 115 | |
|
114 | 116 | #fake filename for IPython.__init__ |
|
115 | 117 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py")) |
|
116 | 118 | |
|
117 | 119 | home_dir = path.get_home_dir() |
|
118 | 120 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) |
|
119 | 121 | |
|
120 | 122 | |
|
121 | 123 | @skip_if_not_win32 |
|
122 | 124 | @with_environment |
|
123 | 125 | def test_get_home_dir_2(): |
|
124 | 126 | """Testcase for py2exe logic, compressed lib |
|
125 | 127 | """ |
|
126 | 128 | sys.frozen = True |
|
127 | 129 | #fake filename for IPython.__init__ |
|
128 | 130 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower() |
|
129 | 131 | |
|
130 | 132 | home_dir = path.get_home_dir() |
|
131 | 133 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower()) |
|
132 | 134 | |
|
133 | 135 | |
|
134 | 136 | @with_environment |
|
135 | 137 | @skip_win32 |
|
136 | 138 | def test_get_home_dir_3(): |
|
137 | 139 | """Testcase $HOME is set, then use its value as home directory.""" |
|
138 | 140 | env["HOME"] = HOME_TEST_DIR |
|
139 | 141 | home_dir = path.get_home_dir() |
|
140 | 142 | nt.assert_equal(home_dir, env["HOME"]) |
|
141 | 143 | |
|
142 | 144 | |
|
143 | 145 | @with_environment |
|
144 | 146 | def test_get_home_dir_4(): |
|
145 | 147 | """Testcase $HOME is not set, os=='posix'. |
|
146 | 148 | This should fail with HomeDirError""" |
|
147 | 149 | |
|
148 | 150 | os.name = 'posix' |
|
149 | 151 | if 'HOME' in env: del env['HOME'] |
|
150 | 152 | nt.assert_raises(path.HomeDirError, path.get_home_dir) |
|
151 | 153 | |
|
152 | 154 | |
|
153 | 155 | @skip_if_not_win32 |
|
154 | 156 | @with_environment |
|
155 | 157 | def test_get_home_dir_5(): |
|
156 | 158 | """Using HOMEDRIVE + HOMEPATH, os=='nt'. |
|
157 | 159 | |
|
158 | 160 | HOMESHARE is missing. |
|
159 | 161 | """ |
|
160 | 162 | |
|
161 | 163 | os.name = 'nt' |
|
162 | 164 | env.pop('HOMESHARE', None) |
|
163 | 165 | env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR) |
|
164 | 166 | home_dir = path.get_home_dir() |
|
165 | 167 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) |
|
166 | 168 | |
|
167 | 169 | |
|
168 | 170 | @skip_if_not_win32 |
|
169 | 171 | @with_environment |
|
170 | 172 | def test_get_home_dir_6(): |
|
171 | 173 | """Using USERPROFILE, os=='nt'. |
|
172 | 174 | |
|
173 | 175 | HOMESHARE, HOMEDRIVE, HOMEPATH are missing. |
|
174 | 176 | """ |
|
175 | 177 | |
|
176 | 178 | os.name = 'nt' |
|
177 | 179 | env.pop('HOMESHARE', None) |
|
178 | 180 | env.pop('HOMEDRIVE', None) |
|
179 | 181 | env.pop('HOMEPATH', None) |
|
180 | 182 | env["USERPROFILE"] = abspath(HOME_TEST_DIR) |
|
181 | 183 | home_dir = path.get_home_dir() |
|
182 | 184 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) |
|
183 | 185 | |
|
184 | 186 | |
|
185 | 187 | @skip_if_not_win32 |
|
186 | 188 | @with_environment |
|
187 | 189 | def test_get_home_dir_7(): |
|
188 | 190 | """Using HOMESHARE, os=='nt'.""" |
|
189 | 191 | |
|
190 | 192 | os.name = 'nt' |
|
191 | 193 | env["HOMESHARE"] = abspath(HOME_TEST_DIR) |
|
192 | 194 | home_dir = path.get_home_dir() |
|
193 | 195 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) |
|
194 | 196 | |
|
195 | 197 | # Should we stub wreg fully so we can run the test on all platforms? |
|
196 | 198 | @skip_if_not_win32 |
|
197 | 199 | @with_environment |
|
198 | 200 | def test_get_home_dir_8(): |
|
199 | 201 | """Using registry hack for 'My Documents', os=='nt' |
|
200 | 202 | |
|
201 | 203 | HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing. |
|
202 | 204 | """ |
|
203 | 205 | os.name = 'nt' |
|
204 | 206 | # Remove from stub environment all keys that may be set |
|
205 | 207 | for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']: |
|
206 | 208 | env.pop(key, None) |
|
207 | 209 | |
|
208 | 210 | #Stub windows registry functions |
|
209 | 211 | def OpenKey(x, y): |
|
210 | 212 | class key: |
|
211 | 213 | def Close(self): |
|
212 | 214 | pass |
|
213 | 215 | return key() |
|
214 | 216 | def QueryValueEx(x, y): |
|
215 | 217 | return [abspath(HOME_TEST_DIR)] |
|
216 | 218 | |
|
217 | 219 | wreg.OpenKey = OpenKey |
|
218 | 220 | wreg.QueryValueEx = QueryValueEx |
|
219 | 221 | |
|
220 | 222 | home_dir = path.get_home_dir() |
|
221 | 223 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) |
|
222 | 224 | |
|
223 | 225 | |
|
224 | 226 | @with_environment |
|
225 | 227 | def test_get_ipython_dir_1(): |
|
226 | 228 | """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions.""" |
|
227 | 229 | env['IPYTHON_DIR'] = "someplace/.ipython" |
|
228 | 230 | ipdir = path.get_ipython_dir() |
|
229 | 231 | nt.assert_equal(ipdir, "someplace/.ipython") |
|
230 | 232 | |
|
231 | 233 | |
|
232 | 234 | @with_environment |
|
233 | 235 | def test_get_ipython_dir_2(): |
|
234 | 236 | """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions.""" |
|
235 | 237 | path.get_home_dir = lambda : "someplace" |
|
236 | 238 | os.name = "posix" |
|
237 | 239 | env.pop('IPYTHON_DIR', None) |
|
238 | 240 | env.pop('IPYTHONDIR', None) |
|
241 | env.pop('XDG_CONFIG_HOME', None) | |
|
239 | 242 | ipdir = path.get_ipython_dir() |
|
240 | 243 | nt.assert_equal(ipdir, os.path.join("someplace", ".ipython")) |
|
241 | 244 | |
|
245 | @with_environment | |
|
246 | def test_get_ipython_dir_3(): | |
|
247 | """test_get_ipython_dir_3, use XDG if defined, and .ipython doesn't exist.""" | |
|
248 | path.get_home_dir = lambda : "someplace" | |
|
249 | os.name = "posix" | |
|
250 | env.pop('IPYTHON_DIR', None) | |
|
251 | env.pop('IPYTHONDIR', None) | |
|
252 | env['XDG_CONFIG_HOME'] = XDG_TEST_DIR | |
|
253 | ipdir = path.get_ipython_dir() | |
|
254 | nt.assert_equal(ipdir, os.path.join(XDG_TEST_DIR, "ipython")) | |
|
255 | ||
|
256 | @with_environment | |
|
257 | def test_get_ipython_dir_4(): | |
|
258 | """test_get_ipython_dir_4, use XDG if both exist.""" | |
|
259 | path.get_home_dir = lambda : HOME_TEST_DIR | |
|
260 | os.name = "posix" | |
|
261 | env.pop('IPYTHON_DIR', None) | |
|
262 | env.pop('IPYTHONDIR', None) | |
|
263 | env['XDG_CONFIG_HOME'] = XDG_TEST_DIR | |
|
264 | xdg_ipdir = os.path.join(XDG_TEST_DIR, "ipython") | |
|
265 | ipdir = path.get_ipython_dir() | |
|
266 | nt.assert_equal(ipdir, xdg_ipdir) | |
|
267 | ||
|
268 | @with_environment | |
|
269 | def test_get_ipython_dir_5(): | |
|
270 | """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist.""" | |
|
271 | os.name = "posix" | |
|
272 | env.pop('IPYTHON_DIR', None) | |
|
273 | env.pop('IPYTHONDIR', None) | |
|
274 | env['XDG_CONFIG_HOME'] = XDG_TEST_DIR | |
|
275 | os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython')) | |
|
276 | ipdir = path.get_ipython_dir() | |
|
277 | nt.assert_equal(ipdir, IP_TEST_DIR) | |
|
278 | ||
|
279 | @with_environment | |
|
280 | def test_get_ipython_dir_6(): | |
|
281 | """test_get_ipython_dir_6, use XDG if defined and neither exist.""" | |
|
282 | path.get_home_dir = lambda : 'somehome' | |
|
283 | path.get_xdg_dir = lambda : 'somexdg' | |
|
284 | os.name = "posix" | |
|
285 | env.pop('IPYTHON_DIR', None) | |
|
286 | env.pop('IPYTHONDIR', None) | |
|
287 | xdg_ipdir = os.path.join("somexdg", "ipython") | |
|
288 | ipdir = path.get_ipython_dir() | |
|
289 | nt.assert_equal(ipdir, xdg_ipdir) | |
|
290 | ||
|
291 | @with_environment | |
|
292 | def test_get_xdg_dir_1(): | |
|
293 | """test_get_xdg_dir_1, check xdg_dir""" | |
|
294 | reload(path) | |
|
295 | path.get_home_dir = lambda : 'somewhere' | |
|
296 | os.name = "posix" | |
|
297 | env.pop('IPYTHON_DIR', None) | |
|
298 | env.pop('IPYTHONDIR', None) | |
|
299 | env.pop('XDG_CONFIG_HOME', None) | |
|
300 | ||
|
301 | nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config')) | |
|
302 | ||
|
303 | ||
|
304 | @with_environment | |
|
305 | def test_get_xdg_dir_1(): | |
|
306 | """test_get_xdg_dir_1, check nonexistant xdg_dir""" | |
|
307 | reload(path) | |
|
308 | path.get_home_dir = lambda : HOME_TEST_DIR | |
|
309 | os.name = "posix" | |
|
310 | env.pop('IPYTHON_DIR', None) | |
|
311 | env.pop('IPYTHONDIR', None) | |
|
312 | env.pop('XDG_CONFIG_HOME', None) | |
|
313 | nt.assert_equal(path.get_xdg_dir(), None) | |
|
314 | ||
|
315 | @with_environment | |
|
316 | def test_get_xdg_dir_2(): | |
|
317 | """test_get_xdg_dir_2, check xdg_dir default to ~/.config""" | |
|
318 | reload(path) | |
|
319 | path.get_home_dir = lambda : HOME_TEST_DIR | |
|
320 | os.name = "posix" | |
|
321 | env.pop('IPYTHON_DIR', None) | |
|
322 | env.pop('IPYTHONDIR', None) | |
|
323 | env.pop('XDG_CONFIG_HOME', None) | |
|
324 | cfgdir=os.path.join(path.get_home_dir(), '.config') | |
|
325 | os.makedirs(cfgdir) | |
|
326 | ||
|
327 | nt.assert_equal(path.get_xdg_dir(), cfgdir) | |
|
242 | 328 | |
|
243 | 329 | def test_filefind(): |
|
244 | 330 | """Various tests for filefind""" |
|
245 | 331 | f = tempfile.NamedTemporaryFile() |
|
246 | 332 | # print 'fname:',f.name |
|
247 | 333 | alt_dirs = path.get_ipython_dir() |
|
248 | 334 | t = path.filefind(f.name, alt_dirs) |
|
249 | 335 | # print 'found:',t |
|
250 | 336 | |
|
251 | 337 | |
|
252 | 338 | def test_get_ipython_package_dir(): |
|
253 | 339 | ipdir = path.get_ipython_package_dir() |
|
254 | 340 | nt.assert_true(os.path.isdir(ipdir)) |
|
255 | 341 | |
|
256 | 342 | |
|
257 | 343 | def test_get_ipython_module_path(): |
|
258 | 344 | ipapp_path = path.get_ipython_module_path('IPython.frontend.terminal.ipapp') |
|
259 | 345 | nt.assert_true(os.path.isfile(ipapp_path)) |
|
260 | 346 | |
|
261 | 347 | |
|
262 | 348 | @dec.skip_if_not_win32 |
|
263 | 349 | def test_get_long_path_name_win32(): |
|
264 | 350 | p = path.get_long_path_name('c:\\docume~1') |
|
265 | 351 | nt.assert_equals(p,u'c:\\Documents and Settings') |
|
266 | 352 | |
|
267 | 353 | |
|
268 | 354 | @dec.skip_win32 |
|
269 | 355 | def test_get_long_path_name(): |
|
270 | 356 | p = path.get_long_path_name('/usr/local') |
|
271 | 357 | nt.assert_equals(p,'/usr/local') |
|
272 | 358 |
@@ -1,230 +1,231 b'' | |||
|
1 | 1 | .. _initial config: |
|
2 | 2 | |
|
3 | 3 | ============================================================= |
|
4 | 4 | Outdated configuration information that might still be useful |
|
5 | 5 | ============================================================= |
|
6 | 6 | |
|
7 | 7 | .. warning:: |
|
8 | 8 | |
|
9 | 9 | All of the information in this file is outdated. Until the new |
|
10 | 10 | configuration system is better documented, this material is being kept. |
|
11 | 11 | |
|
12 | 12 | This section will help you set various things in your environment for |
|
13 | 13 | your IPython sessions to be as efficient as possible. All of IPython's |
|
14 | 14 | configuration information, along with several example files, is stored |
|
15 |
in a directory named by default $HOME/.ipython |
|
|
15 | in a directory named by default $HOME/.config/ipython if $HOME/.config | |
|
16 | exists (Linux), or $HOME/.ipython as a secondary default. You can change this by | |
|
16 | 17 | defining the environment variable IPYTHONDIR, or at runtime with the |
|
17 | 18 | command line option -ipythondir. |
|
18 | 19 | |
|
19 | 20 | If all goes well, the first time you run IPython it should automatically create |
|
20 | 21 | a user copy of the config directory for you, based on its builtin defaults. You |
|
21 | 22 | can look at the files it creates to learn more about configuring the |
|
22 | 23 | system. The main file you will modify to configure IPython's behavior is called |
|
23 | 24 | ipythonrc (with a .ini extension under Windows), included for reference |
|
24 | 25 | :ref:`here <ipythonrc>`. This file is very commented and has many variables you |
|
25 | 26 | can change to suit your taste, you can find more details :ref:`here |
|
26 | 27 | <customization>`. Here we discuss the basic things you will want to make sure |
|
27 | 28 | things are working properly from the beginning. |
|
28 | 29 | |
|
29 | 30 | Color |
|
30 | 31 | ===== |
|
31 | 32 | |
|
32 | 33 | The default IPython configuration has most bells and whistles turned on |
|
33 | 34 | (they're pretty safe). But there's one that may cause problems on some |
|
34 | 35 | systems: the use of color on screen for displaying information. This is |
|
35 | 36 | very useful, since IPython can show prompts and exception tracebacks |
|
36 | 37 | with various colors, display syntax-highlighted source code, and in |
|
37 | 38 | general make it easier to visually parse information. |
|
38 | 39 | |
|
39 | 40 | The following terminals seem to handle the color sequences fine: |
|
40 | 41 | |
|
41 | 42 | * Linux main text console, KDE Konsole, Gnome Terminal, E-term, |
|
42 | 43 | rxvt, xterm. |
|
43 | 44 | * CDE terminal (tested under Solaris). This one boldfaces light colors. |
|
44 | 45 | * (X)Emacs buffers. See the emacs_ section for more details on |
|
45 | 46 | using IPython with (X)Emacs. |
|
46 | 47 | * A Windows (XP/2k) command prompt with pyreadline_. |
|
47 | 48 | * A Windows (XP/2k) CygWin shell. Although some users have reported |
|
48 | 49 | problems; it is not clear whether there is an issue for everyone |
|
49 | 50 | or only under specific configurations. If you have full color |
|
50 | 51 | support under cygwin, please post to the IPython mailing list so |
|
51 | 52 | this issue can be resolved for all users. |
|
52 | 53 | |
|
53 | 54 | .. _pyreadline: https://code.launchpad.net/pyreadline |
|
54 | 55 | |
|
55 | 56 | These have shown problems: |
|
56 | 57 | |
|
57 | 58 | * Windows command prompt in WinXP/2k logged into a Linux machine via |
|
58 | 59 | telnet or ssh. |
|
59 | 60 | * Windows native command prompt in WinXP/2k, without Gary Bishop's |
|
60 | 61 | extensions. Once Gary's readline library is installed, the normal |
|
61 | 62 | WinXP/2k command prompt works perfectly. |
|
62 | 63 | |
|
63 | 64 | Currently the following color schemes are available: |
|
64 | 65 | |
|
65 | 66 | * NoColor: uses no color escapes at all (all escapes are empty '' '' |
|
66 | 67 | strings). This 'scheme' is thus fully safe to use in any terminal. |
|
67 | 68 | * Linux: works well in Linux console type environments: dark |
|
68 | 69 | background with light fonts. It uses bright colors for |
|
69 | 70 | information, so it is difficult to read if you have a light |
|
70 | 71 | colored background. |
|
71 | 72 | * LightBG: the basic colors are similar to those in the Linux scheme |
|
72 | 73 | but darker. It is easy to read in terminals with light backgrounds. |
|
73 | 74 | |
|
74 | 75 | IPython uses colors for two main groups of things: prompts and |
|
75 | 76 | tracebacks which are directly printed to the terminal, and the object |
|
76 | 77 | introspection system which passes large sets of data through a pager. |
|
77 | 78 | |
|
78 | 79 | Input/Output prompts and exception tracebacks |
|
79 | 80 | ============================================= |
|
80 | 81 | |
|
81 | 82 | You can test whether the colored prompts and tracebacks work on your |
|
82 | 83 | system interactively by typing '%colors Linux' at the prompt (use |
|
83 | 84 | '%colors LightBG' if your terminal has a light background). If the input |
|
84 | 85 | prompt shows garbage like:: |
|
85 | 86 | |
|
86 | 87 | [0;32mIn [[1;32m1[0;32m]: [0;00m |
|
87 | 88 | |
|
88 | 89 | instead of (in color) something like:: |
|
89 | 90 | |
|
90 | 91 | In [1]: |
|
91 | 92 | |
|
92 | 93 | this means that your terminal doesn't properly handle color escape |
|
93 | 94 | sequences. You can go to a 'no color' mode by typing '%colors NoColor'. |
|
94 | 95 | |
|
95 | 96 | You can try using a different terminal emulator program (Emacs users, |
|
96 | 97 | see below). To permanently set your color preferences, edit the file |
|
97 |
$ |
|
|
98 | $IPYTHON_DIR/ipythonrc and set the colors option to the desired value. | |
|
98 | 99 | |
|
99 | 100 | |
|
100 | 101 | Object details (types, docstrings, source code, etc.) |
|
101 | 102 | ===================================================== |
|
102 | 103 | |
|
103 | 104 | IPython has a set of special functions for studying the objects you are working |
|
104 | 105 | with, discussed in detail :ref:`here <dynamic_object_info>`. But this system |
|
105 | 106 | relies on passing information which is longer than your screen through a data |
|
106 | 107 | pager, such as the common Unix less and more programs. In order to be able to |
|
107 | 108 | see this information in color, your pager needs to be properly configured. I |
|
108 | 109 | strongly recommend using less instead of more, as it seems that more simply can |
|
109 | 110 | not understand colored text correctly. |
|
110 | 111 | |
|
111 | 112 | In order to configure less as your default pager, do the following: |
|
112 | 113 | |
|
113 | 114 | 1. Set the environment PAGER variable to less. |
|
114 | 115 | 2. Set the environment LESS variable to -r (plus any other options |
|
115 | 116 | you always want to pass to less by default). This tells less to |
|
116 | 117 | properly interpret control sequences, which is how color |
|
117 | 118 | information is given to your terminal. |
|
118 | 119 | |
|
119 | 120 | For the bash shell, add to your ~/.bashrc file the lines:: |
|
120 | 121 | |
|
121 | 122 | export PAGER=less |
|
122 | 123 | export LESS=-r |
|
123 | 124 | |
|
124 | 125 | For the csh or tcsh shells, add to your ~/.cshrc file the lines:: |
|
125 | 126 | |
|
126 | 127 | setenv PAGER less |
|
127 | 128 | setenv LESS -r |
|
128 | 129 | |
|
129 | 130 | There is similar syntax for other Unix shells, look at your system |
|
130 | 131 | documentation for details. |
|
131 | 132 | |
|
132 | 133 | If you are on a system which lacks proper data pagers (such as Windows), |
|
133 | 134 | IPython will use a very limited builtin pager. |
|
134 | 135 | |
|
135 | 136 | .. _Prompts: |
|
136 | 137 | |
|
137 | 138 | Fine-tuning your prompt |
|
138 | 139 | ======================= |
|
139 | 140 | |
|
140 | 141 | IPython's prompts can be customized using a syntax similar to that of |
|
141 | 142 | the bash shell. Many of bash's escapes are supported, as well as a few |
|
142 | 143 | additional ones. We list them below:: |
|
143 | 144 | |
|
144 | 145 | \# |
|
145 | 146 | the prompt/history count number. This escape is automatically |
|
146 | 147 | wrapped in the coloring codes for the currently active color scheme. |
|
147 | 148 | \N |
|
148 | 149 | the 'naked' prompt/history count number: this is just the number |
|
149 | 150 | itself, without any coloring applied to it. This lets you produce |
|
150 | 151 | numbered prompts with your own colors. |
|
151 | 152 | \D |
|
152 | 153 | the prompt/history count, with the actual digits replaced by dots. |
|
153 | 154 | Used mainly in continuation prompts (prompt_in2) |
|
154 | 155 | \w |
|
155 | 156 | the current working directory |
|
156 | 157 | \W |
|
157 | 158 | the basename of current working directory |
|
158 | 159 | \Xn |
|
159 | 160 | where $n=0\ldots5.$ The current working directory, with $HOME |
|
160 | 161 | replaced by ~, and filtered out to contain only $n$ path elements |
|
161 | 162 | \Yn |
|
162 | 163 | Similar to \Xn, but with the $n+1$ element included if it is ~ (this |
|
163 | 164 | is similar to the behavior of the %cn escapes in tcsh) |
|
164 | 165 | \u |
|
165 | 166 | the username of the current user |
|
166 | 167 | \$ |
|
167 | 168 | if the effective UID is 0, a #, otherwise a $ |
|
168 | 169 | \h |
|
169 | 170 | the hostname up to the first '.' |
|
170 | 171 | \H |
|
171 | 172 | the hostname |
|
172 | 173 | \n |
|
173 | 174 | a newline |
|
174 | 175 | \r |
|
175 | 176 | a carriage return |
|
176 | 177 | \v |
|
177 | 178 | IPython version string |
|
178 | 179 | |
|
179 | 180 | In addition to these, ANSI color escapes can be insterted into the |
|
180 | 181 | prompts, as \C_ColorName. The list of valid color names is: Black, Blue, |
|
181 | 182 | Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray, |
|
182 | 183 | LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White, |
|
183 | 184 | Yellow. |
|
184 | 185 | |
|
185 | 186 | Finally, IPython supports the evaluation of arbitrary expressions in |
|
186 | 187 | your prompt string. The prompt strings are evaluated through the syntax |
|
187 | 188 | of PEP 215, but basically you can use $x.y to expand the value of x.y, |
|
188 | 189 | and for more complicated expressions you can use braces: ${foo()+x} will |
|
189 | 190 | call function foo and add to it the value of x, before putting the |
|
190 | 191 | result into your prompt. For example, using |
|
191 | 192 | prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: ' |
|
192 | 193 | will print the result of the uptime command on each prompt (assuming the |
|
193 | 194 | commands module has been imported in your ipythonrc file). |
|
194 | 195 | |
|
195 | 196 | |
|
196 | 197 | Prompt examples |
|
197 | 198 | |
|
198 | 199 | The following options in an ipythonrc file will give you IPython's |
|
199 | 200 | default prompts:: |
|
200 | 201 | |
|
201 | 202 | prompt_in1 'In [\#]:' |
|
202 | 203 | prompt_in2 ' .\D.:' |
|
203 | 204 | prompt_out 'Out[\#]:' |
|
204 | 205 | |
|
205 | 206 | which look like this:: |
|
206 | 207 | |
|
207 | 208 | In [1]: 1+2 |
|
208 | 209 | Out[1]: 3 |
|
209 | 210 | |
|
210 | 211 | In [2]: for i in (1,2,3): |
|
211 | 212 | ...: print i, |
|
212 | 213 | ...: |
|
213 | 214 | 1 2 3 |
|
214 | 215 | |
|
215 | 216 | These will give you a very colorful prompt with path information:: |
|
216 | 217 | |
|
217 | 218 | #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>' |
|
218 | 219 | prompt_in2 ' ..\D>' |
|
219 | 220 | prompt_out '<\#>' |
|
220 | 221 | |
|
221 | 222 | which look like this:: |
|
222 | 223 | |
|
223 | 224 | fperez[~/ipython]1> 1+2 |
|
224 | 225 | <1> 3 |
|
225 | 226 | fperez[~/ipython]2> for i in (1,2,3): |
|
226 | 227 | ...> print i, |
|
227 | 228 | ...> |
|
228 | 229 | 1 2 3 |
|
229 | 230 | |
|
230 | 231 |
@@ -1,329 +1,342 b'' | |||
|
1 | 1 | .. _config_overview: |
|
2 | 2 | |
|
3 | 3 | ============================================ |
|
4 | 4 | Overview of the IPython configuration system |
|
5 | 5 | ============================================ |
|
6 | 6 | |
|
7 | 7 | This section describes the IPython configuration system. Starting with version |
|
8 | 8 | 0.11, IPython has a completely new configuration system that is quite |
|
9 | 9 | different from the older :file:`ipythonrc` or :file:`ipy_user_conf.py` |
|
10 | 10 | approaches. The new configuration system was designed from scratch to address |
|
11 | 11 | the particular configuration needs of IPython. While there are many |
|
12 | 12 | other excellent configuration systems out there, we found that none of them |
|
13 | 13 | met our requirements. |
|
14 | 14 | |
|
15 | 15 | .. warning:: |
|
16 | 16 | |
|
17 | 17 | If you are upgrading to version 0.11 of IPython, you will need to migrate |
|
18 | 18 | your old :file:`ipythonrc` or :file:`ipy_user_conf.py` configuration files |
|
19 | 19 | to the new system. Read on for information on how to do this. |
|
20 | 20 | |
|
21 | 21 | The discussion that follows is focused on teaching user's how to configure |
|
22 | 22 | IPython to their liking. Developer's who want to know more about how they |
|
23 | 23 | can enable their objects to take advantage of the configuration system |
|
24 | 24 | should consult our :ref:`developer guide <developer_guide>` |
|
25 | 25 | |
|
26 | 26 | The main concepts |
|
27 | 27 | ================= |
|
28 | 28 | |
|
29 | 29 | There are a number of abstractions that the IPython configuration system uses. |
|
30 | 30 | Each of these abstractions is represented by a Python class. |
|
31 | 31 | |
|
32 | 32 | Configuration object: :class:`~IPython.config.loader.Config` |
|
33 | 33 | A configuration object is a simple dictionary-like class that holds |
|
34 | 34 | configuration attributes and sub-configuration objects. These classes |
|
35 | 35 | support dotted attribute style access (``Foo.bar``) in addition to the |
|
36 | 36 | regular dictionary style access (``Foo['bar']``). Configuration objects |
|
37 | 37 | are smart. They know how to merge themselves with other configuration |
|
38 | 38 | objects and they automatically create sub-configuration objects. |
|
39 | 39 | |
|
40 | 40 | Application: :class:`~IPython.core.application.Application` |
|
41 | 41 | An application is a process that does a specific job. The most obvious |
|
42 | 42 | application is the :command:`ipython` command line program. Each |
|
43 | 43 | application reads a *single* configuration file and command line options |
|
44 | 44 | and then produces a master configuration object for the application. This |
|
45 | 45 | configuration object is then passed to the configurable objects that the |
|
46 | 46 | application creates. These configurable objects implement the actual logic |
|
47 | 47 | of the application and know how to configure themselves given the |
|
48 | 48 | configuration object. |
|
49 | 49 | |
|
50 | 50 | Component: :class:`~IPython.config.configurable.Configurable` |
|
51 | 51 | A configurable is a regular Python class that serves as a base class for |
|
52 | 52 | all main classes in an application. The |
|
53 | 53 | :class:`~IPython.config.configurable.Configurable` base class is |
|
54 | 54 | lightweight and only does one things. |
|
55 | 55 | |
|
56 | 56 | This :class:`~IPython.config.configurable.Configurable` is a subclass |
|
57 | 57 | of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure |
|
58 | 58 | itself. Class level traits with the metadata ``config=True`` become |
|
59 | 59 | values that can be configured from the command line and configuration |
|
60 | 60 | files. |
|
61 | 61 | |
|
62 | 62 | Developers create :class:`~IPython.config.configurable.Configurable` |
|
63 | 63 | subclasses that implement all of the logic in the application. Each of |
|
64 | 64 | these subclasses has its own configuration information that controls how |
|
65 | 65 | instances are created. |
|
66 | 66 | |
|
67 | 67 | Having described these main concepts, we can now state the main idea in our |
|
68 | 68 | configuration system: *"configuration" allows the default values of class |
|
69 | 69 | attributes to be controlled on a class by class basis*. Thus all instances of |
|
70 | 70 | a given class are configured in the same way. Furthermore, if two instances |
|
71 | 71 | need to be configured differently, they need to be instances of two different |
|
72 | 72 | classes. While this model may seem a bit restrictive, we have found that it |
|
73 | 73 | expresses most things that need to be configured extremely well. However, it |
|
74 | 74 | is possible to create two instances of the same class that have different |
|
75 | 75 | trait values. This is done by overriding the configuration. |
|
76 | 76 | |
|
77 | 77 | Now, we show what our configuration objects and files look like. |
|
78 | 78 | |
|
79 | 79 | Configuration objects and files |
|
80 | 80 | =============================== |
|
81 | 81 | |
|
82 | 82 | A configuration file is simply a pure Python file that sets the attributes |
|
83 | 83 | of a global, pre-created configuration object. This configuration object is a |
|
84 | 84 | :class:`~IPython.config.loader.Config` instance. While in a configuration |
|
85 | 85 | file, to get a reference to this object, simply call the :func:`get_config` |
|
86 | 86 | function. We inject this function into the global namespace that the |
|
87 | 87 | configuration file is executed in. |
|
88 | 88 | |
|
89 | 89 | Here is an example of a super simple configuration file that does nothing:: |
|
90 | 90 | |
|
91 | 91 | c = get_config() |
|
92 | 92 | |
|
93 | 93 | Once you get a reference to the configuration object, you simply set |
|
94 | 94 | attributes on it. All you have to know is: |
|
95 | 95 | |
|
96 | 96 | * The name of each attribute. |
|
97 | 97 | * The type of each attribute. |
|
98 | 98 | |
|
99 | 99 | The answers to these two questions are provided by the various |
|
100 | 100 | :class:`~IPython.config.configurable.Configurable` subclasses that an |
|
101 | 101 | application uses. Let's look at how this would work for a simple component |
|
102 | 102 | subclass:: |
|
103 | 103 | |
|
104 | 104 | # Sample component that can be configured. |
|
105 | 105 | from IPython.config.configurable import Configurable |
|
106 | 106 | from IPython.utils.traitlets import Int, Float, Str, Bool |
|
107 | 107 | |
|
108 | 108 | class MyClass(Configurable): |
|
109 | 109 | name = Str('defaultname', config=True) |
|
110 | 110 | ranking = Int(0, config=True) |
|
111 | 111 | value = Float(99.0) |
|
112 | 112 | # The rest of the class implementation would go here.. |
|
113 | 113 | |
|
114 | 114 | In this example, we see that :class:`MyClass` has three attributes, two |
|
115 | 115 | of whom (``name``, ``ranking``) can be configured. All of the attributes |
|
116 | 116 | are given types and default values. If a :class:`MyClass` is instantiated, |
|
117 | 117 | but not configured, these default values will be used. But let's see how |
|
118 | 118 | to configure this class in a configuration file:: |
|
119 | 119 | |
|
120 | 120 | # Sample config file |
|
121 | 121 | c = get_config() |
|
122 | 122 | |
|
123 | 123 | c.MyClass.name = 'coolname' |
|
124 | 124 | c.MyClass.ranking = 10 |
|
125 | 125 | |
|
126 | 126 | After this configuration file is loaded, the values set in it will override |
|
127 | 127 | the class defaults anytime a :class:`MyClass` is created. Furthermore, |
|
128 | 128 | these attributes will be type checked and validated anytime they are set. |
|
129 | 129 | This type checking is handled by the :mod:`IPython.utils.traitlets` module, |
|
130 | 130 | which provides the :class:`Str`, :class:`Int` and :class:`Float` types. In |
|
131 | 131 | addition to these traitlets, the :mod:`IPython.utils.traitlets` provides |
|
132 | 132 | traitlets for a number of other types. |
|
133 | 133 | |
|
134 | 134 | .. note:: |
|
135 | 135 | |
|
136 | 136 | Underneath the hood, the :class:`Configurable` base class is a subclass of |
|
137 | 137 | :class:`IPython.utils.traitlets.HasTraits`. The |
|
138 | 138 | :mod:`IPython.utils.traitlets` module is a lightweight version of |
|
139 | 139 | :mod:`enthought.traits`. Our implementation is a pure Python subset |
|
140 | 140 | (mostly API compatible) of :mod:`enthought.traits` that does not have any |
|
141 | 141 | of the automatic GUI generation capabilities. Our plan is to achieve 100% |
|
142 | 142 | API compatibility to enable the actual :mod:`enthought.traits` to |
|
143 | 143 | eventually be used instead. Currently, we cannot use |
|
144 | 144 | :mod:`enthought.traits` as we are committed to the core of IPython being |
|
145 | 145 | pure Python. |
|
146 | 146 | |
|
147 | 147 | It should be very clear at this point what the naming convention is for |
|
148 | 148 | configuration attributes:: |
|
149 | 149 | |
|
150 | 150 | c.ClassName.attribute_name = attribute_value |
|
151 | 151 | |
|
152 | 152 | Here, ``ClassName`` is the name of the class whose configuration attribute you |
|
153 | 153 | want to set, ``attribute_name`` is the name of the attribute you want to set |
|
154 | 154 | and ``attribute_value`` the the value you want it to have. The ``ClassName`` |
|
155 | 155 | attribute of ``c`` is not the actual class, but instead is another |
|
156 | 156 | :class:`~IPython.config.loader.Config` instance. |
|
157 | 157 | |
|
158 | 158 | .. note:: |
|
159 | 159 | |
|
160 | 160 | The careful reader may wonder how the ``ClassName`` (``MyClass`` in |
|
161 | 161 | the above example) attribute of the configuration object ``c`` gets |
|
162 | 162 | created. These attributes are created on the fly by the |
|
163 | 163 | :class:`~IPython.config.loader.Config` instance, using a simple naming |
|
164 | 164 | convention. Any attribute of a :class:`~IPython.config.loader.Config` |
|
165 | 165 | instance whose name begins with an uppercase character is assumed to be a |
|
166 | 166 | sub-configuration and a new empty :class:`~IPython.config.loader.Config` |
|
167 | 167 | instance is dynamically created for that attribute. This allows deeply |
|
168 | 168 | hierarchical information created easily (``c.Foo.Bar.value``) on the fly. |
|
169 | 169 | |
|
170 | 170 | Configuration files inheritance |
|
171 | 171 | =============================== |
|
172 | 172 | |
|
173 | 173 | Let's say you want to have different configuration files for various purposes. |
|
174 | 174 | Our configuration system makes it easy for one configuration file to inherit |
|
175 | 175 | the information in another configuration file. The :func:`load_subconfig` |
|
176 | 176 | command can be used in a configuration file for this purpose. Here is a simple |
|
177 | 177 | example that loads all of the values from the file :file:`base_config.py`:: |
|
178 | 178 | |
|
179 | 179 | # base_config.py |
|
180 | 180 | c = get_config() |
|
181 | 181 | c.MyClass.name = 'coolname' |
|
182 | 182 | c.MyClass.ranking = 100 |
|
183 | 183 | |
|
184 | 184 | into the configuration file :file:`main_config.py`:: |
|
185 | 185 | |
|
186 | 186 | # main_config.py |
|
187 | 187 | c = get_config() |
|
188 | 188 | |
|
189 | 189 | # Load everything from base_config.py |
|
190 | 190 | load_subconfig('base_config.py') |
|
191 | 191 | |
|
192 | 192 | # Now override one of the values |
|
193 | 193 | c.MyClass.name = 'bettername' |
|
194 | 194 | |
|
195 | 195 | In a situation like this the :func:`load_subconfig` makes sure that the |
|
196 | 196 | search path for sub-configuration files is inherited from that of the parent. |
|
197 | 197 | Thus, you can typically put the two in the same directory and everything will |
|
198 | 198 | just work. |
|
199 | 199 | |
|
200 | 200 | Class based configuration inheritance |
|
201 | 201 | ===================================== |
|
202 | 202 | |
|
203 | 203 | There is another aspect of configuration where inheritance comes into play. |
|
204 | 204 | Sometimes, your classes will have an inheritance hierarchy that you want |
|
205 | 205 | to be reflected in the configuration system. Here is a simple example:: |
|
206 | 206 | |
|
207 | 207 | from IPython.config.configurable import Configurable |
|
208 | 208 | from IPython.utils.traitlets import Int, Float, Str, Bool |
|
209 | 209 | |
|
210 | 210 | class Foo(Configurable): |
|
211 | 211 | name = Str('fooname', config=True) |
|
212 | 212 | value = Float(100.0, config=True) |
|
213 | 213 | |
|
214 | 214 | class Bar(Foo): |
|
215 | 215 | name = Str('barname', config=True) |
|
216 | 216 | othervalue = Int(0, config=True) |
|
217 | 217 | |
|
218 | 218 | Now, we can create a configuration file to configure instances of :class:`Foo` |
|
219 | 219 | and :class:`Bar`:: |
|
220 | 220 | |
|
221 | 221 | # config file |
|
222 | 222 | c = get_config() |
|
223 | 223 | |
|
224 | 224 | c.Foo.name = 'bestname' |
|
225 | 225 | c.Bar.othervalue = 10 |
|
226 | 226 | |
|
227 | 227 | This class hierarchy and configuration file accomplishes the following: |
|
228 | 228 | |
|
229 | 229 | * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be |
|
230 | 230 | 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also |
|
231 | 231 | picks up the configuration information for :class:`Foo`. |
|
232 | 232 | * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be |
|
233 | 233 | ``100.0``, which is the value specified as the class default. |
|
234 | 234 | * The default value for :attr:`Bar.othervalue` will be 10 as set in the |
|
235 | 235 | configuration file. Because :class:`Foo` is the parent of :class:`Bar` |
|
236 | 236 | it doesn't know anything about the :attr:`othervalue` attribute. |
|
237 | 237 | |
|
238 | ||
|
239 | .. _ipython_dir: | |
|
240 | ||
|
238 | 241 | Configuration file location |
|
239 | 242 | =========================== |
|
240 | 243 | |
|
241 | 244 | So where should you put your configuration files? By default, all IPython |
|
242 | 245 | applications look in the so called "IPython directory". The location of |
|
243 | 246 | this directory is determined by the following algorithm: |
|
244 | 247 | |
|
245 | 248 | * If the ``--ipython-dir`` command line flag is given, its value is used. |
|
246 | 249 | |
|
247 | 250 | * If not, the value returned by :func:`IPython.utils.path.get_ipython_dir` |
|
248 | 251 | is used. This function will first look at the :envvar:`IPYTHON_DIR` |
|
249 |
environment variable and then default to |
|
|
250 | :file:`$HOME/.ipython`. | |
|
252 | environment variable and then default to a platform-specific default. | |
|
253 | ||
|
254 | On posix systems (Linux, Unix, etc.), IPython respects the ``$XDG_CONFIG_HOME`` | |
|
255 | part of the `XDG Base Directory`_ specification. If ``$XDG_CONFIG_HOME`` is | |
|
256 | defined and exists ( ``XDG_CONFIG_HOME`` has a default interpretation of | |
|
257 | :file:`$HOME/.config`), then IPython's config directory will be located in | |
|
258 | :file:`$XDG_CONFIG_HOME/ipython`. If users still have an IPython directory | |
|
259 | in :file:`$HOME/.ipython`, then that will be used. in preference to the | |
|
260 | system default. | |
|
251 | 261 | |
|
252 | 262 | For most users, the default value will simply be something like |
|
253 | :file:`$HOME/.ipython`. | |
|
263 | :file:`$HOME/.config/ipython` on Linux, or :file:`$HOME/.ipython` | |
|
264 | elsewhere. | |
|
254 | 265 | |
|
255 | 266 | Once the location of the IPython directory has been determined, you need to |
|
256 | 267 | know what filename to use for the configuration file. The basic idea is that |
|
257 | 268 | each application has its own default configuration filename. The default named |
|
258 | 269 | used by the :command:`ipython` command line program is |
|
259 | 270 | :file:`ipython_config.py`. This value can be overriden by the ``-config_file`` |
|
260 | 271 | command line flag. A sample :file:`ipython_config.py` file can be found |
|
261 | 272 | in :mod:`IPython.config.default.ipython_config.py`. Simple copy it to your |
|
262 | 273 | IPython directory to begin using it. |
|
263 | 274 | |
|
264 | 275 | .. _Profiles: |
|
265 | 276 | |
|
266 | 277 | Profiles |
|
267 | 278 | ======== |
|
268 | 279 | |
|
269 | 280 | A profile is simply a configuration file that follows a simple naming |
|
270 | 281 | convention and can be loaded using a simplified syntax. The idea is |
|
271 | 282 | that users often want to maintain a set of configuration files for different |
|
272 | 283 | purposes: one for doing numerical computing with NumPy and SciPy and |
|
273 | 284 | another for doing symbolic computing with SymPy. Profiles make it easy |
|
274 | 285 | to keep a separate configuration file for each of these purposes. |
|
275 | 286 | |
|
276 | 287 | Let's start by showing how a profile is used: |
|
277 | 288 | |
|
278 | 289 | .. code-block:: bash |
|
279 | 290 | |
|
280 | 291 | $ ipython -p sympy |
|
281 | 292 | |
|
282 | 293 | This tells the :command:`ipython` command line program to get its |
|
283 | 294 | configuration from the "sympy" profile. The search path for profiles is the |
|
284 | 295 | same as that of regular configuration files. The only difference is that |
|
285 | 296 | profiles are named in a special way. In the case above, the "sympy" profile |
|
286 | 297 | would need to have the name :file:`ipython_config_sympy.py`. |
|
287 | 298 | |
|
288 | 299 | The general pattern is this: simply add ``_profilename`` to the end of the |
|
289 | 300 | normal configuration file name. Then load the profile by adding ``-p |
|
290 | 301 | profilename`` to your command line options. |
|
291 | 302 | |
|
292 | 303 | IPython ships with some sample profiles in :mod:`IPython.config.profile`. |
|
293 | 304 | Simply copy these to your IPython directory to begin using them. |
|
294 | 305 | |
|
295 | 306 | Design requirements |
|
296 | 307 | =================== |
|
297 | 308 | |
|
298 | 309 | Here are the main requirements we wanted our configuration system to have: |
|
299 | 310 | |
|
300 | 311 | * Support for hierarchical configuration information. |
|
301 | 312 | |
|
302 | 313 | * Full integration with command line option parsers. Often, you want to read |
|
303 | 314 | a configuration file, but then override some of the values with command line |
|
304 | 315 | options. Our configuration system automates this process and allows each |
|
305 | 316 | command line option to be linked to a particular attribute in the |
|
306 | 317 | configuration hierarchy that it will override. |
|
307 | 318 | |
|
308 | 319 | * Configuration files that are themselves valid Python code. This accomplishes |
|
309 | 320 | many things. First, it becomes possible to put logic in your configuration |
|
310 | 321 | files that sets attributes based on your operating system, network setup, |
|
311 | 322 | Python version, etc. Second, Python has a super simple syntax for accessing |
|
312 | 323 | hierarchical data structures, namely regular attribute access |
|
313 | 324 | (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to |
|
314 | 325 | import configuration attributes from one configuration file to another. |
|
315 | 326 | Forth, even though Python is dynamically typed, it does have types that can |
|
316 | 327 | be checked at runtime. Thus, a ``1`` in a config file is the integer '1', |
|
317 | 328 | while a ``'1'`` is a string. |
|
318 | 329 | |
|
319 | 330 | * A fully automated method for getting the configuration information to the |
|
320 | 331 | classes that need it at runtime. Writing code that walks a configuration |
|
321 | 332 | hierarchy to extract a particular attribute is painful. When you have |
|
322 | 333 | complex configuration information with hundreds of attributes, this makes |
|
323 | 334 | you want to cry. |
|
324 | 335 | |
|
325 | 336 | * Type checking and validation that doesn't require the entire configuration |
|
326 | 337 | hierarchy to be specified statically before runtime. Python is a very |
|
327 | 338 | dynamic language and you don't always know everything that needs to be |
|
328 | 339 | configured when a program starts. |
|
329 | 340 | |
|
341 | ||
|
342 | .. _`XDG Base Directory`: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html |
@@ -1,167 +1,167 b'' | |||
|
1 | 1 | .. _documenting-ipython: |
|
2 | 2 | |
|
3 | 3 | ===================== |
|
4 | 4 | Documenting IPython |
|
5 | 5 | ===================== |
|
6 | 6 | |
|
7 | 7 | When contributing code to IPython, you should strive for clarity and |
|
8 | 8 | consistency, without falling prey to a style straitjacket. Basically, |
|
9 | 9 | 'document everything, try to be consistent, do what makes sense.' |
|
10 | 10 | |
|
11 | 11 | By and large we follow existing Python practices in major projects like Python |
|
12 | 12 | itself or NumPy, this document provides some additional detail for IPython. |
|
13 | 13 | |
|
14 | 14 | |
|
15 | 15 | Standalone documentation |
|
16 | 16 | ======================== |
|
17 | 17 | |
|
18 | 18 | All standalone documentation should be written in plain text (``.txt``) files |
|
19 | 19 | using reStructuredText [reStructuredText]_ for markup and formatting. All such |
|
20 | 20 | documentation should be placed in the directory :file:`docs/source` of the |
|
21 | 21 | IPython source tree. Or, when appropriate, a suitably named subdirectory |
|
22 | 22 | should be used. The documentation in this location will serve as the main |
|
23 | 23 | source for IPython documentation. |
|
24 | 24 | |
|
25 | 25 | The actual HTML and PDF docs are built using the Sphinx [Sphinx]_ |
|
26 | 26 | documentation generation tool. Once you have Sphinx installed, you can build |
|
27 | 27 | the html docs yourself by doing: |
|
28 | 28 | |
|
29 | 29 | .. code-block:: bash |
|
30 | 30 | |
|
31 | 31 | $ cd ipython-mybranch/docs |
|
32 | 32 | $ make html |
|
33 | 33 | |
|
34 | 34 | Our usage of Sphinx follows that of matplotlib [Matplotlib]_ closely. We are |
|
35 | 35 | using a number of Sphinx tools and extensions written by the matplotlib team |
|
36 | 36 | and will mostly follow their conventions, which are nicely spelled out in |
|
37 | 37 | their documentation guide [MatplotlibDocGuide]_. What follows is thus a |
|
38 | 38 | abridged version of the matplotlib documentation guide, taken with permission |
|
39 | 39 | from the matplotlib team. |
|
40 | 40 | |
|
41 | 41 | If you are reading this in a web browser, you can click on the "Show Source" |
|
42 | 42 | link to see the original reStricturedText for the following examples. |
|
43 | 43 | |
|
44 | 44 | A bit of Python code:: |
|
45 | 45 | |
|
46 | 46 | for i in range(10): |
|
47 | 47 | print i, |
|
48 | 48 | print "A big number:",2**34 |
|
49 | 49 | |
|
50 | 50 | An interactive Python session:: |
|
51 | 51 | |
|
52 | 52 | >>> from IPython.utils.path import get_ipython_dir |
|
53 | 53 | >>> get_ipython_dir() |
|
54 | '/home/fperez/.ipython' | |
|
54 | '/home/fperez/.config/ipython' | |
|
55 | 55 | |
|
56 | 56 | An IPython session: |
|
57 | 57 | |
|
58 | 58 | .. code-block:: ipython |
|
59 | 59 | |
|
60 | 60 | In [7]: import IPython |
|
61 | 61 | |
|
62 | 62 | In [8]: print "This IPython is version:",IPython.__version__ |
|
63 | 63 | This IPython is version: 0.9.1 |
|
64 | 64 | |
|
65 | 65 | In [9]: 2+4 |
|
66 | 66 | Out[9]: 6 |
|
67 | 67 | |
|
68 | 68 | |
|
69 | 69 | A bit of shell code: |
|
70 | 70 | |
|
71 | 71 | .. code-block:: bash |
|
72 | 72 | |
|
73 | 73 | cd /tmp |
|
74 | 74 | echo "My home directory is: $HOME" |
|
75 | 75 | ls |
|
76 | 76 | |
|
77 | 77 | Docstring format |
|
78 | 78 | ================ |
|
79 | 79 | |
|
80 | 80 | Good docstrings are very important. Unfortunately, Python itself only provides |
|
81 | 81 | a rather loose standard for docstrings [PEP257]_, and there is no universally |
|
82 | 82 | accepted convention for all the different parts of a complete docstring. |
|
83 | 83 | However, the NumPy project has established a very reasonable standard, and has |
|
84 | 84 | developed some tools to support the smooth inclusion of such docstrings in |
|
85 | 85 | Sphinx-generated manuals. Rather than inventing yet another pseudo-standard, |
|
86 | 86 | IPython will be henceforth documented using the NumPy conventions; we carry |
|
87 | 87 | copies of some of the NumPy support tools to remain self-contained, but share |
|
88 | 88 | back upstream with NumPy any improvements or fixes we may make to the tools. |
|
89 | 89 | |
|
90 | 90 | The NumPy documentation guidelines [NumPyDocGuide]_ contain detailed |
|
91 | 91 | information on this standard, and for a quick overview, the NumPy example |
|
92 | 92 | docstring [NumPyExampleDocstring]_ is a useful read. |
|
93 | 93 | |
|
94 | 94 | |
|
95 | 95 | For user-facing APIs, we try to be fairly strict about following the above |
|
96 | 96 | standards (even though they mean more verbose and detailed docstrings). |
|
97 | 97 | Wherever you can reasonably expect people to do introspection with:: |
|
98 | 98 | |
|
99 | 99 | In [1]: some_function? |
|
100 | 100 | |
|
101 | 101 | the docstring should follow the NumPy style and be fairly detailed. |
|
102 | 102 | |
|
103 | 103 | For purely internal methods that are only likely to be read by others extending |
|
104 | 104 | IPython itself we are a bit more relaxed, especially for small/short methods |
|
105 | 105 | and functions whose intent is reasonably obvious. We still expect docstrings |
|
106 | 106 | to be written, but they can be simpler. For very short functions with a |
|
107 | 107 | single-line docstring you can use something like:: |
|
108 | 108 | |
|
109 | 109 | def add(a, b): |
|
110 | 110 | """The sum of two numbers. |
|
111 | 111 | """ |
|
112 | 112 | code |
|
113 | 113 | |
|
114 | 114 | and for longer multiline strings:: |
|
115 | 115 | |
|
116 | 116 | def add(a, b): |
|
117 | 117 | """The sum of two numbers. |
|
118 | 118 | |
|
119 | 119 | Here is the rest of the docs. |
|
120 | 120 | """ |
|
121 | 121 | code |
|
122 | 122 | |
|
123 | 123 | |
|
124 | 124 | Here are two additional PEPs of interest regarding documentation of code. |
|
125 | 125 | While both of these were rejected, the ideas therein form much of the basis of |
|
126 | 126 | docutils (the machinery to process reStructuredText): |
|
127 | 127 | |
|
128 | 128 | * `Docstring Processing System Framework <http://www.python.org/peps/pep-0256.html>`_ |
|
129 | 129 | * `Docutils Design Specification <http://www.python.org/peps/pep-0258.html>`_ |
|
130 | 130 | |
|
131 | 131 | .. note:: |
|
132 | 132 | |
|
133 | 133 | In the past IPython used epydoc so currently many docstrings still use |
|
134 | 134 | epydoc conventions. We will update them as we go, but all new code should |
|
135 | 135 | be documented using the NumPy standard. |
|
136 | 136 | |
|
137 | 137 | Building and uploading |
|
138 | 138 | ====================== |
|
139 | 139 | The built docs are stored in a separate repository. Through some github magic, |
|
140 | 140 | they're automatically exposed as a website. It works like this: |
|
141 | 141 | |
|
142 | 142 | * You will need to have sphinx and latex installed. In Ubuntu, install |
|
143 | 143 | ``texlive-latex-recommended texlive-latex-extra texlive-fonts-recommended``. |
|
144 | 144 | Install the latest version of sphinx from PyPI (``pip install sphinx``). |
|
145 | 145 | * Ensure that the development version of IPython is the first in your system |
|
146 | 146 | path. You can either use a virtualenv, or modify your PYTHONPATH. |
|
147 | 147 | * Switch into the docs directory, and run ``make gh-pages``. This will build |
|
148 | 148 | your updated docs as html and pdf, then automatically check out the latest |
|
149 | 149 | version of the docs repository, copy the built docs into it, and commit your |
|
150 | 150 | changes. |
|
151 | 151 | * Open the built docs in a web browser, and check that they're as expected. |
|
152 | 152 | * (When building the docs for a new tagged release, you will have to add its link to |
|
153 | 153 | index.rst, then run ``python build_index.py`` to update index.html. Commit the |
|
154 | 154 | change.) |
|
155 | 155 | * Upload the docs with ``git push``. This only works if you have write access to |
|
156 | 156 | the docs repository. |
|
157 | 157 | * If you are building a version that is not the current dev branch, nor a tagged release, |
|
158 | 158 | then you must run gh-pages.py directly with ``python gh-pages.py <version>``, and *not* |
|
159 | 159 | with ``make gh-pages``. |
|
160 | 160 | |
|
161 | 161 | .. [reStructuredText] reStructuredText. http://docutils.sourceforge.net/rst.html |
|
162 | 162 | .. [Sphinx] Sphinx. http://sphinx.pocoo.org/ |
|
163 | 163 | .. [MatplotlibDocGuide] http://matplotlib.sourceforge.net/devel/documenting_mpl.html |
|
164 | 164 | .. [PEP257] PEP 257. http://www.python.org/peps/pep-0257.html |
|
165 | 165 | .. [NumPyDocGuide] NumPy documentation guide. http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines |
|
166 | 166 | .. [NumPyExampleDocstring] NumPy example docstring. http://projects.scipy.org/numpy/browser/trunk/doc/EXAMPLE_DOCSTRING.txt |
|
167 | 167 |
@@ -1,1577 +1,1578 b'' | |||
|
1 | 1 | ================= |
|
2 | 2 | IPython reference |
|
3 | 3 | ================= |
|
4 | 4 | |
|
5 | 5 | .. warning:: |
|
6 | 6 | |
|
7 | 7 | As of the 0.11 version of IPython, some of the features and APIs |
|
8 | 8 | described in this section have been deprecated or are broken. Our plan |
|
9 | 9 | is to continue to support these features, but they need to be updated |
|
10 | 10 | to take advantage of recent API changes. Furthermore, this section |
|
11 | 11 | of the documentation need to be updated to reflect all of these changes. |
|
12 | 12 | |
|
13 | 13 | .. _command_line_options: |
|
14 | 14 | |
|
15 | 15 | Command-line usage |
|
16 | 16 | ================== |
|
17 | 17 | |
|
18 | 18 | You start IPython with the command:: |
|
19 | 19 | |
|
20 | 20 | $ ipython [options] files |
|
21 | 21 | |
|
22 | 22 | If invoked with no options, it executes all the files listed in sequence |
|
23 | 23 | and drops you into the interpreter while still acknowledging any options |
|
24 | 24 | you may have set in your ipythonrc file. This behavior is different from |
|
25 | 25 | standard Python, which when called as python -i will only execute one |
|
26 | 26 | file and ignore your configuration setup. |
|
27 | 27 | |
|
28 | 28 | Please note that some of the configuration options are not available at |
|
29 | 29 | the command line, simply because they are not practical here. Look into |
|
30 | your ipythonrc configuration file for details on those. This file | |
|
31 |
|
|
|
32 | $HOME resolves to C:\\Documents and Settings\\YourUserName in most | |
|
33 | instances. In the rest of this text, we will refer to this directory as | |
|
34 | IPYTHON_DIR. | |
|
30 | your ipythonrc configuration file for details on those. This file is typically | |
|
31 | installed in the IPYTHON_DIR directory. For Linux | |
|
32 | users, this will be $HOME/.config/ipython, and for other users it will be | |
|
33 | $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and | |
|
34 | Settings\\YourUserName in most instances. | |
|
35 | ||
|
35 | 36 | |
|
36 | 37 | |
|
37 | 38 | |
|
38 | 39 | Special Threading Options |
|
39 | 40 | ------------------------- |
|
40 | 41 | |
|
41 | 42 | Previously IPython had command line options for controlling GUI event loop |
|
42 | 43 | integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython |
|
43 | 44 | version 0.11, these have been deprecated. Please see the new ``%gui`` |
|
44 | 45 | magic command or :ref:`this section <gui_support>` for details on the new |
|
45 | 46 | interface. |
|
46 | 47 | |
|
47 | 48 | Regular Options |
|
48 | 49 | --------------- |
|
49 | 50 | |
|
50 | 51 | After the above threading options have been given, regular options can |
|
51 | 52 | follow in any order. All options can be abbreviated to their shortest |
|
52 | 53 | non-ambiguous form and are case-sensitive. One or two dashes can be |
|
53 | 54 | used. Some options have an alternate short form, indicated after a ``|``. |
|
54 | 55 | |
|
55 | 56 | Most options can also be set from your ipythonrc configuration file. See |
|
56 | 57 | the provided example for more details on what the options do. Options |
|
57 | 58 | given at the command line override the values set in the ipythonrc file. |
|
58 | 59 | |
|
59 | 60 | All options with a [no] prepended can be specified in negated form |
|
60 | 61 | (-nooption instead of -option) to turn the feature off. |
|
61 | 62 | |
|
62 | 63 | -help print a help message and exit. |
|
63 | 64 | |
|
64 | 65 | -pylab |
|
65 | 66 | Deprecated. See :ref:`Matplotlib support <matplotlib_support>` |
|
66 | 67 | for more details. |
|
67 | 68 | |
|
68 | 69 | -autocall <val> |
|
69 | 70 | Make IPython automatically call any callable object even if you |
|
70 | 71 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
71 | 72 | 'str(43)' automatically. The value can be '0' to disable the feature, |
|
72 | 73 | '1' for smart autocall, where it is not applied if there are no more |
|
73 | 74 | arguments on the line, and '2' for full autocall, where all callable |
|
74 | 75 | objects are automatically called (even if no arguments are |
|
75 | 76 | present). The default is '1'. |
|
76 | 77 | |
|
77 | 78 | -[no]autoindent |
|
78 | 79 | Turn automatic indentation on/off. |
|
79 | 80 | |
|
80 | 81 | -[no]automagic |
|
81 | 82 | make magic commands automatic (without needing their first character |
|
82 | 83 | to be %). Type %magic at the IPython prompt for more information. |
|
83 | 84 | |
|
84 | 85 | -[no]autoedit_syntax |
|
85 | 86 | When a syntax error occurs after editing a file, automatically |
|
86 | 87 | open the file to the trouble causing line for convenient |
|
87 | 88 | fixing. |
|
88 | 89 | |
|
89 | 90 | -[no]banner Print the initial information banner (default on). |
|
90 | 91 | |
|
91 | 92 | -c <command> |
|
92 | 93 | execute the given command string. This is similar to the -c |
|
93 | 94 | option in the normal Python interpreter. |
|
94 | 95 | |
|
95 | 96 | -cache_size, cs <n> |
|
96 | 97 | size of the output cache (maximum number of entries to hold in |
|
97 | 98 | memory). The default is 1000, you can change it permanently in your |
|
98 | 99 | config file. Setting it to 0 completely disables the caching system, |
|
99 | 100 | and the minimum value accepted is 20 (if you provide a value less than |
|
100 | 101 | 20, it is reset to 0 and a warning is issued) This limit is defined |
|
101 | 102 | because otherwise you'll spend more time re-flushing a too small cache |
|
102 | 103 | than working. |
|
103 | 104 | |
|
104 | 105 | -classic, cl |
|
105 | 106 | Gives IPython a similar feel to the classic Python |
|
106 | 107 | prompt. |
|
107 | 108 | |
|
108 | 109 | -colors <scheme> |
|
109 | 110 | Color scheme for prompts and exception reporting. Currently |
|
110 | 111 | implemented: NoColor, Linux and LightBG. |
|
111 | 112 | |
|
112 | 113 | -[no]color_info |
|
113 | 114 | IPython can display information about objects via a set of functions, |
|
114 | 115 | and optionally can use colors for this, syntax highlighting source |
|
115 | 116 | code and various other elements. However, because this information is |
|
116 | 117 | passed through a pager (like 'less') and many pagers get confused with |
|
117 | 118 | color codes, this option is off by default. You can test it and turn |
|
118 | 119 | it on permanently in your ipythonrc file if it works for you. As a |
|
119 | 120 | reference, the 'less' pager supplied with Mandrake 8.2 works ok, but |
|
120 | 121 | that in RedHat 7.2 doesn't. |
|
121 | 122 | |
|
122 | 123 | Test it and turn it on permanently if it works with your |
|
123 | 124 | system. The magic function %color_info allows you to toggle this |
|
124 | 125 | interactively for testing. |
|
125 | 126 | |
|
126 | 127 | -[no]debug |
|
127 | 128 | Show information about the loading process. Very useful to pin down |
|
128 | 129 | problems with your configuration files or to get details about |
|
129 | 130 | session restores. |
|
130 | 131 | |
|
131 | 132 | -[no]deep_reload: |
|
132 | 133 | IPython can use the deep_reload module which reloads changes in |
|
133 | 134 | modules recursively (it replaces the reload() function, so you don't |
|
134 | 135 | need to change anything to use it). deep_reload() forces a full |
|
135 | 136 | reload of modules whose code may have changed, which the default |
|
136 | 137 | reload() function does not. |
|
137 | 138 | |
|
138 | 139 | When deep_reload is off, IPython will use the normal reload(), |
|
139 | 140 | but deep_reload will still be available as dreload(). This |
|
140 | 141 | feature is off by default [which means that you have both |
|
141 | 142 | normal reload() and dreload()]. |
|
142 | 143 | |
|
143 | 144 | -editor <name> |
|
144 | 145 | Which editor to use with the %edit command. By default, |
|
145 | 146 | IPython will honor your EDITOR environment variable (if not |
|
146 | 147 | set, vi is the Unix default and notepad the Windows one). |
|
147 | 148 | Since this editor is invoked on the fly by IPython and is |
|
148 | 149 | meant for editing small code snippets, you may want to use a |
|
149 | 150 | small, lightweight editor here (in case your default EDITOR is |
|
150 | 151 | something like Emacs). |
|
151 | 152 | |
|
152 | 153 | -ipythondir <name> |
|
153 | 154 | name of your IPython configuration directory IPYTHON_DIR. This |
|
154 | 155 | can also be specified through the environment variable |
|
155 | 156 | IPYTHON_DIR. |
|
156 | 157 | |
|
157 | 158 | -log, l |
|
158 | 159 | generate a log file of all input. The file is named |
|
159 | 160 | ipython_log.py in your current directory (which prevents logs |
|
160 | 161 | from multiple IPython sessions from trampling each other). You |
|
161 | 162 | can use this to later restore a session by loading your |
|
162 | 163 | logfile as a file to be executed with option -logplay (see |
|
163 | 164 | below). |
|
164 | 165 | |
|
165 | 166 | -logfile, lf <name> specify the name of your logfile. |
|
166 | 167 | |
|
167 | 168 | -logplay, lp <name> |
|
168 | 169 | |
|
169 | 170 | you can replay a previous log. For restoring a session as close as |
|
170 | 171 | possible to the state you left it in, use this option (don't just run |
|
171 | 172 | the logfile). With -logplay, IPython will try to reconstruct the |
|
172 | 173 | previous working environment in full, not just execute the commands in |
|
173 | 174 | the logfile. |
|
174 | 175 | |
|
175 | 176 | When a session is restored, logging is automatically turned on |
|
176 | 177 | again with the name of the logfile it was invoked with (it is |
|
177 | 178 | read from the log header). So once you've turned logging on for |
|
178 | 179 | a session, you can quit IPython and reload it as many times as |
|
179 | 180 | you want and it will continue to log its history and restore |
|
180 | 181 | from the beginning every time. |
|
181 | 182 | |
|
182 | 183 | Caveats: there are limitations in this option. The history |
|
183 | 184 | variables _i*,_* and _dh don't get restored properly. In the |
|
184 | 185 | future we will try to implement full session saving by writing |
|
185 | 186 | and retrieving a 'snapshot' of the memory state of IPython. But |
|
186 | 187 | our first attempts failed because of inherent limitations of |
|
187 | 188 | Python's Pickle module, so this may have to wait. |
|
188 | 189 | |
|
189 | 190 | -[no]messages |
|
190 | 191 | Print messages which IPython collects about its startup |
|
191 | 192 | process (default on). |
|
192 | 193 | |
|
193 | 194 | -[no]pdb |
|
194 | 195 | Automatically call the pdb debugger after every uncaught |
|
195 | 196 | exception. If you are used to debugging using pdb, this puts |
|
196 | 197 | you automatically inside of it after any call (either in |
|
197 | 198 | IPython or in code called by it) which triggers an exception |
|
198 | 199 | which goes uncaught. |
|
199 | 200 | |
|
200 | 201 | -pydb |
|
201 | 202 | Makes IPython use the third party "pydb" package as debugger, |
|
202 | 203 | instead of pdb. Requires that pydb is installed. |
|
203 | 204 | |
|
204 | 205 | -[no]pprint |
|
205 | 206 | ipython can optionally use the pprint (pretty printer) module |
|
206 | 207 | for displaying results. pprint tends to give a nicer display |
|
207 | 208 | of nested data structures. If you like it, you can turn it on |
|
208 | 209 | permanently in your config file (default off). |
|
209 | 210 | |
|
210 | 211 | -profile, p <name> |
|
211 | 212 | |
|
212 | 213 | assume that your config file is ipythonrc-<name> or |
|
213 | 214 | ipy_profile_<name>.py (looks in current dir first, then in |
|
214 | 215 | IPYTHON_DIR). This is a quick way to keep and load multiple |
|
215 | 216 | config files for different tasks, especially if you use the |
|
216 | 217 | include option of config files. You can keep a basic |
|
217 | 218 | IPYTHON_DIR/ipythonrc file and then have other 'profiles' which |
|
218 | 219 | include this one and load extra things for particular |
|
219 | 220 | tasks. For example: |
|
220 | 221 | |
|
221 |
1. $ |
|
|
222 |
2. $ |
|
|
223 |
3. $ |
|
|
222 | 1. $IPYTHON_DIR/ipythonrc : load basic things you always want. | |
|
223 | 2. $IPYTHON_DIR/ipythonrc-math : load (1) and basic math-related modules. | |
|
224 | 3. $IPYTHON_DIR/ipythonrc-numeric : load (1) and Numeric and plotting modules. | |
|
224 | 225 | |
|
225 | 226 | Since it is possible to create an endless loop by having |
|
226 | 227 | circular file inclusions, IPython will stop if it reaches 15 |
|
227 | 228 | recursive inclusions. |
|
228 | 229 | |
|
229 | 230 | -prompt_in1, pi1 <string> |
|
230 | 231 | |
|
231 | 232 | Specify the string used for input prompts. Note that if you are using |
|
232 | 233 | numbered prompts, the number is represented with a '\#' in the |
|
233 | 234 | string. Don't forget to quote strings with spaces embedded in |
|
234 | 235 | them. Default: 'In [\#]:'. The :ref:`prompts section <prompts>` |
|
235 | 236 | discusses in detail all the available escapes to customize your |
|
236 | 237 | prompts. |
|
237 | 238 | |
|
238 | 239 | -prompt_in2, pi2 <string> |
|
239 | 240 | Similar to the previous option, but used for the continuation |
|
240 | 241 | prompts. The special sequence '\D' is similar to '\#', but |
|
241 | 242 | with all digits replaced dots (so you can have your |
|
242 | 243 | continuation prompt aligned with your input prompt). Default: |
|
243 | 244 | ' .\D.:' (note three spaces at the start for alignment with |
|
244 | 245 | 'In [\#]'). |
|
245 | 246 | |
|
246 | 247 | -prompt_out,po <string> |
|
247 | 248 | String used for output prompts, also uses numbers like |
|
248 | 249 | prompt_in1. Default: 'Out[\#]:' |
|
249 | 250 | |
|
250 | 251 | -quick start in bare bones mode (no config file loaded). |
|
251 | 252 | |
|
252 | 253 | -rcfile <name> |
|
253 | 254 | name of your IPython resource configuration file. Normally |
|
254 | 255 | IPython loads ipythonrc (from current directory) or |
|
255 | 256 | IPYTHON_DIR/ipythonrc. |
|
256 | 257 | |
|
257 | 258 | If the loading of your config file fails, IPython starts with |
|
258 | 259 | a bare bones configuration (no modules loaded at all). |
|
259 | 260 | |
|
260 | 261 | -[no]readline |
|
261 | 262 | use the readline library, which is needed to support name |
|
262 | 263 | completion and command history, among other things. It is |
|
263 | 264 | enabled by default, but may cause problems for users of |
|
264 | 265 | X/Emacs in Python comint or shell buffers. |
|
265 | 266 | |
|
266 | 267 | Note that X/Emacs 'eterm' buffers (opened with M-x term) support |
|
267 | 268 | IPython's readline and syntax coloring fine, only 'emacs' (M-x |
|
268 | 269 | shell and C-c !) buffers do not. |
|
269 | 270 | |
|
270 | 271 | -screen_length, sl <n> |
|
271 | 272 | number of lines of your screen. This is used to control |
|
272 | 273 | printing of very long strings. Strings longer than this number |
|
273 | 274 | of lines will be sent through a pager instead of directly |
|
274 | 275 | printed. |
|
275 | 276 | |
|
276 | 277 | The default value for this is 0, which means IPython will |
|
277 | 278 | auto-detect your screen size every time it needs to print certain |
|
278 | 279 | potentially long strings (this doesn't change the behavior of the |
|
279 | 280 | 'print' keyword, it's only triggered internally). If for some |
|
280 | 281 | reason this isn't working well (it needs curses support), specify |
|
281 | 282 | it yourself. Otherwise don't change the default. |
|
282 | 283 | |
|
283 | 284 | -separate_in, si <string> |
|
284 | 285 | |
|
285 | 286 | separator before input prompts. |
|
286 | 287 | Default: '\n' |
|
287 | 288 | |
|
288 | 289 | -separate_out, so <string> |
|
289 | 290 | separator before output prompts. |
|
290 | 291 | Default: nothing. |
|
291 | 292 | |
|
292 | 293 | -separate_out2, so2 |
|
293 | 294 | separator after output prompts. |
|
294 | 295 | Default: nothing. |
|
295 | 296 | For these three options, use the value 0 to specify no separator. |
|
296 | 297 | |
|
297 | 298 | -nosep |
|
298 | 299 | shorthand for '-SeparateIn 0 -SeparateOut 0 -SeparateOut2 |
|
299 | 300 | 0'. Simply removes all input/output separators. |
|
300 | 301 | |
|
301 | 302 | -upgrade |
|
302 | 303 | allows you to upgrade your IPYTHON_DIR configuration when you |
|
303 | 304 | install a new version of IPython. Since new versions may |
|
304 | 305 | include new command line options or example files, this copies |
|
305 | 306 | updated ipythonrc-type files. However, it backs up (with a |
|
306 | 307 | .old extension) all files which it overwrites so that you can |
|
307 | 308 | merge back any customizations you might have in your personal |
|
308 | 309 | files. Note that you should probably use %upgrade instead, |
|
309 | 310 | it's a safer alternative. |
|
310 | 311 | |
|
311 | 312 | |
|
312 | 313 | -Version print version information and exit. |
|
313 | 314 | |
|
314 | 315 | -wxversion <string> |
|
315 | 316 | Deprecated. |
|
316 | 317 | |
|
317 | 318 | -xmode <modename> |
|
318 | 319 | |
|
319 | 320 | Mode for exception reporting. |
|
320 | 321 | |
|
321 | 322 | Valid modes: Plain, Context and Verbose. |
|
322 | 323 | |
|
323 | 324 | * Plain: similar to python's normal traceback printing. |
|
324 | 325 | * Context: prints 5 lines of context source code around each |
|
325 | 326 | line in the traceback. |
|
326 | 327 | * Verbose: similar to Context, but additionally prints the |
|
327 | 328 | variables currently visible where the exception happened |
|
328 | 329 | (shortening their strings if too long). This can potentially be |
|
329 | 330 | very slow, if you happen to have a huge data structure whose |
|
330 | 331 | string representation is complex to compute. Your computer may |
|
331 | 332 | appear to freeze for a while with cpu usage at 100%. If this |
|
332 | 333 | occurs, you can cancel the traceback with Ctrl-C (maybe hitting it |
|
333 | 334 | more than once). |
|
334 | 335 | |
|
335 | 336 | Interactive use |
|
336 | 337 | =============== |
|
337 | 338 | |
|
338 | 339 | Warning: IPython relies on the existence of a global variable called |
|
339 | 340 | _ip which controls the shell itself. If you redefine _ip to anything, |
|
340 | 341 | bizarre behavior will quickly occur. |
|
341 | 342 | |
|
342 | 343 | Other than the above warning, IPython is meant to work as a drop-in |
|
343 | 344 | replacement for the standard interactive interpreter. As such, any code |
|
344 | 345 | which is valid python should execute normally under IPython (cases where |
|
345 | 346 | this is not true should be reported as bugs). It does, however, offer |
|
346 | 347 | many features which are not available at a standard python prompt. What |
|
347 | 348 | follows is a list of these. |
|
348 | 349 | |
|
349 | 350 | |
|
350 | 351 | Caution for Windows users |
|
351 | 352 | ------------------------- |
|
352 | 353 | |
|
353 | 354 | Windows, unfortunately, uses the '\' character as a path |
|
354 | 355 | separator. This is a terrible choice, because '\' also represents the |
|
355 | 356 | escape character in most modern programming languages, including |
|
356 | 357 | Python. For this reason, using '/' character is recommended if you |
|
357 | 358 | have problems with ``\``. However, in Windows commands '/' flags |
|
358 | 359 | options, so you can not use it for the root directory. This means that |
|
359 | 360 | paths beginning at the root must be typed in a contrived manner like: |
|
360 | 361 | ``%copy \opt/foo/bar.txt \tmp`` |
|
361 | 362 | |
|
362 | 363 | .. _magic: |
|
363 | 364 | |
|
364 | 365 | Magic command system |
|
365 | 366 | -------------------- |
|
366 | 367 | |
|
367 | 368 | IPython will treat any line whose first character is a % as a special |
|
368 | 369 | call to a 'magic' function. These allow you to control the behavior of |
|
369 | 370 | IPython itself, plus a lot of system-type features. They are all |
|
370 | 371 | prefixed with a % character, but parameters are given without |
|
371 | 372 | parentheses or quotes. |
|
372 | 373 | |
|
373 | 374 | Example: typing '%cd mydir' (without the quotes) changes you working |
|
374 | 375 | directory to 'mydir', if it exists. |
|
375 | 376 | |
|
376 | 377 | If you have 'automagic' enabled (in your ipythonrc file, via the command |
|
377 | 378 | line option -automagic or with the %automagic function), you don't need |
|
378 | 379 | to type in the % explicitly. IPython will scan its internal list of |
|
379 | 380 | magic functions and call one if it exists. With automagic on you can |
|
380 | 381 | then just type 'cd mydir' to go to directory 'mydir'. The automagic |
|
381 | 382 | system has the lowest possible precedence in name searches, so defining |
|
382 | 383 | an identifier with the same name as an existing magic function will |
|
383 | 384 | shadow it for automagic use. You can still access the shadowed magic |
|
384 | 385 | function by explicitly using the % character at the beginning of the line. |
|
385 | 386 | |
|
386 | 387 | An example (with automagic on) should clarify all this:: |
|
387 | 388 | |
|
388 | 389 | In [1]: cd ipython # %cd is called by automagic |
|
389 | 390 | |
|
390 | 391 | /home/fperez/ipython |
|
391 | 392 | |
|
392 | 393 | In [2]: cd=1 # now cd is just a variable |
|
393 | 394 | |
|
394 | 395 | In [3]: cd .. # and doesn't work as a function anymore |
|
395 | 396 | |
|
396 | 397 | ------------------------------ |
|
397 | 398 | |
|
398 | 399 | File "<console>", line 1 |
|
399 | 400 | |
|
400 | 401 | cd .. |
|
401 | 402 | |
|
402 | 403 | ^ |
|
403 | 404 | |
|
404 | 405 | SyntaxError: invalid syntax |
|
405 | 406 | |
|
406 | 407 | In [4]: %cd .. # but %cd always works |
|
407 | 408 | |
|
408 | 409 | /home/fperez |
|
409 | 410 | |
|
410 | 411 | In [5]: del cd # if you remove the cd variable |
|
411 | 412 | |
|
412 | 413 | In [6]: cd ipython # automagic can work again |
|
413 | 414 | |
|
414 | 415 | /home/fperez/ipython |
|
415 | 416 | |
|
416 | 417 | You can define your own magic functions to extend the system. The |
|
417 | 418 | following example defines a new magic command, %impall:: |
|
418 | 419 | |
|
419 | 420 | import IPython.ipapi |
|
420 | 421 | |
|
421 | 422 | ip = IPython.ipapi.get() |
|
422 | 423 | |
|
423 | 424 | def doimp(self, arg): |
|
424 | 425 | |
|
425 | 426 | ip = self.api |
|
426 | 427 | |
|
427 | 428 | ip.ex("import %s; reload(%s); from %s import *" % ( |
|
428 | 429 | |
|
429 | 430 | arg,arg,arg) |
|
430 | 431 | |
|
431 | 432 | ) |
|
432 | 433 | |
|
433 | 434 | ip.expose_magic('impall', doimp) |
|
434 | 435 | |
|
435 | 436 | You can also define your own aliased names for magic functions. In your |
|
436 | 437 | ipythonrc file, placing a line like:: |
|
437 | 438 | |
|
438 | 439 | execute __IP.magic_cl = __IP.magic_clear |
|
439 | 440 | |
|
440 | 441 | will define %cl as a new name for %clear. |
|
441 | 442 | |
|
442 | 443 | Type %magic for more information, including a list of all available |
|
443 | 444 | magic functions at any time and their docstrings. You can also type |
|
444 | 445 | %magic_function_name? (see sec. 6.4 <#sec:dyn-object-info> for |
|
445 | 446 | information on the '?' system) to get information about any particular |
|
446 | 447 | magic function you are interested in. |
|
447 | 448 | |
|
448 | 449 | The API documentation for the :mod:`IPython.Magic` module contains the full |
|
449 | 450 | docstrings of all currently available magic commands. |
|
450 | 451 | |
|
451 | 452 | |
|
452 | 453 | Access to the standard Python help |
|
453 | 454 | ---------------------------------- |
|
454 | 455 | |
|
455 | 456 | As of Python 2.1, a help system is available with access to object docstrings |
|
456 | 457 | and the Python manuals. Simply type 'help' (no quotes) to access it. You can |
|
457 | 458 | also type help(object) to obtain information about a given object, and |
|
458 | 459 | help('keyword') for information on a keyword. As noted :ref:`here |
|
459 | 460 | <accessing_help>`, you need to properly configure your environment variable |
|
460 | 461 | PYTHONDOCS for this feature to work correctly. |
|
461 | 462 | |
|
462 | 463 | .. _dynamic_object_info: |
|
463 | 464 | |
|
464 | 465 | Dynamic object information |
|
465 | 466 | -------------------------- |
|
466 | 467 | |
|
467 | 468 | Typing ?word or word? prints detailed information about an object. If |
|
468 | 469 | certain strings in the object are too long (docstrings, code, etc.) they |
|
469 | 470 | get snipped in the center for brevity. This system gives access variable |
|
470 | 471 | types and values, full source code for any object (if available), |
|
471 | 472 | function prototypes and other useful information. |
|
472 | 473 | |
|
473 | 474 | Typing ??word or word?? gives access to the full information without |
|
474 | 475 | snipping long strings. Long strings are sent to the screen through the |
|
475 | 476 | less pager if longer than the screen and printed otherwise. On systems |
|
476 | 477 | lacking the less command, IPython uses a very basic internal pager. |
|
477 | 478 | |
|
478 | 479 | The following magic functions are particularly useful for gathering |
|
479 | 480 | information about your working environment. You can get more details by |
|
480 | 481 | typing %magic or querying them individually (use %function_name? with or |
|
481 | 482 | without the %), this is just a summary: |
|
482 | 483 | |
|
483 | 484 | * **%pdoc <object>**: Print (or run through a pager if too long) the |
|
484 | 485 | docstring for an object. If the given object is a class, it will |
|
485 | 486 | print both the class and the constructor docstrings. |
|
486 | 487 | * **%pdef <object>**: Print the definition header for any callable |
|
487 | 488 | object. If the object is a class, print the constructor information. |
|
488 | 489 | * **%psource <object>**: Print (or run through a pager if too long) |
|
489 | 490 | the source code for an object. |
|
490 | 491 | * **%pfile <object>**: Show the entire source file where an object was |
|
491 | 492 | defined via a pager, opening it at the line where the object |
|
492 | 493 | definition begins. |
|
493 | 494 | * **%who/%whos**: These functions give information about identifiers |
|
494 | 495 | you have defined interactively (not things you loaded or defined |
|
495 | 496 | in your configuration files). %who just prints a list of |
|
496 | 497 | identifiers and %whos prints a table with some basic details about |
|
497 | 498 | each identifier. |
|
498 | 499 | |
|
499 | 500 | Note that the dynamic object information functions (?/??, %pdoc, %pfile, |
|
500 | 501 | %pdef, %psource) give you access to documentation even on things which |
|
501 | 502 | are not really defined as separate identifiers. Try for example typing |
|
502 | 503 | {}.get? or after doing import os, type os.path.abspath??. |
|
503 | 504 | |
|
504 | 505 | |
|
505 | 506 | .. _readline: |
|
506 | 507 | |
|
507 | 508 | Readline-based features |
|
508 | 509 | ----------------------- |
|
509 | 510 | |
|
510 | 511 | These features require the GNU readline library, so they won't work if |
|
511 | 512 | your Python installation lacks readline support. We will first describe |
|
512 | 513 | the default behavior IPython uses, and then how to change it to suit |
|
513 | 514 | your preferences. |
|
514 | 515 | |
|
515 | 516 | |
|
516 | 517 | Command line completion |
|
517 | 518 | +++++++++++++++++++++++ |
|
518 | 519 | |
|
519 | 520 | At any time, hitting TAB will complete any available python commands or |
|
520 | 521 | variable names, and show you a list of the possible completions if |
|
521 | 522 | there's no unambiguous one. It will also complete filenames in the |
|
522 | 523 | current directory if no python names match what you've typed so far. |
|
523 | 524 | |
|
524 | 525 | |
|
525 | 526 | Search command history |
|
526 | 527 | ++++++++++++++++++++++ |
|
527 | 528 | |
|
528 | 529 | IPython provides two ways for searching through previous input and thus |
|
529 | 530 | reduce the need for repetitive typing: |
|
530 | 531 | |
|
531 | 532 | 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n |
|
532 | 533 | (next,down) to search through only the history items that match |
|
533 | 534 | what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank |
|
534 | 535 | prompt, they just behave like normal arrow keys. |
|
535 | 536 | 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system |
|
536 | 537 | searches your history for lines that contain what you've typed so |
|
537 | 538 | far, completing as much as it can. |
|
538 | 539 | |
|
539 | 540 | |
|
540 | 541 | Persistent command history across sessions |
|
541 | 542 | ++++++++++++++++++++++++++++++++++++++++++ |
|
542 | 543 | |
|
543 | 544 | IPython will save your input history when it leaves and reload it next |
|
544 | 545 | time you restart it. By default, the history file is named |
|
545 | 546 | $IPYTHON_DIR/history, but if you've loaded a named profile, |
|
546 | 547 | '-PROFILE_NAME' is appended to the name. This allows you to keep |
|
547 | 548 | separate histories related to various tasks: commands related to |
|
548 | 549 | numerical work will not be clobbered by a system shell history, for |
|
549 | 550 | example. |
|
550 | 551 | |
|
551 | 552 | |
|
552 | 553 | Autoindent |
|
553 | 554 | ++++++++++ |
|
554 | 555 | |
|
555 | 556 | IPython can recognize lines ending in ':' and indent the next line, |
|
556 | 557 | while also un-indenting automatically after 'raise' or 'return'. |
|
557 | 558 | |
|
558 | 559 | This feature uses the readline library, so it will honor your ~/.inputrc |
|
559 | 560 | configuration (or whatever file your INPUTRC variable points to). Adding |
|
560 | 561 | the following lines to your .inputrc file can make indenting/unindenting |
|
561 | 562 | more convenient (M-i indents, M-u unindents):: |
|
562 | 563 | |
|
563 | 564 | $if Python |
|
564 | 565 | "\M-i": " " |
|
565 | 566 | "\M-u": "\d\d\d\d" |
|
566 | 567 | $endif |
|
567 | 568 | |
|
568 | 569 | Note that there are 4 spaces between the quote marks after "M-i" above. |
|
569 | 570 | |
|
570 | 571 | Warning: this feature is ON by default, but it can cause problems with |
|
571 | 572 | the pasting of multi-line indented code (the pasted code gets |
|
572 | 573 | re-indented on each line). A magic function %autoindent allows you to |
|
573 | 574 | toggle it on/off at runtime. You can also disable it permanently on in |
|
574 | 575 | your ipythonrc file (set autoindent 0). |
|
575 | 576 | |
|
576 | 577 | |
|
577 | 578 | Customizing readline behavior |
|
578 | 579 | +++++++++++++++++++++++++++++ |
|
579 | 580 | |
|
580 | 581 | All these features are based on the GNU readline library, which has an |
|
581 | 582 | extremely customizable interface. Normally, readline is configured via a |
|
582 | 583 | file which defines the behavior of the library; the details of the |
|
583 | 584 | syntax for this can be found in the readline documentation available |
|
584 | 585 | with your system or on the Internet. IPython doesn't read this file (if |
|
585 | 586 | it exists) directly, but it does support passing to readline valid |
|
586 | 587 | options via a simple interface. In brief, you can customize readline by |
|
587 | 588 | setting the following options in your ipythonrc configuration file (note |
|
588 | 589 | that these options can not be specified at the command line): |
|
589 | 590 | |
|
590 | 591 | * **readline_parse_and_bind**: this option can appear as many times as |
|
591 | 592 | you want, each time defining a string to be executed via a |
|
592 | 593 | readline.parse_and_bind() command. The syntax for valid commands |
|
593 | 594 | of this kind can be found by reading the documentation for the GNU |
|
594 | 595 | readline library, as these commands are of the kind which readline |
|
595 | 596 | accepts in its configuration file. |
|
596 | 597 | * **readline_remove_delims**: a string of characters to be removed |
|
597 | 598 | from the default word-delimiters list used by readline, so that |
|
598 | 599 | completions may be performed on strings which contain them. Do not |
|
599 | 600 | change the default value unless you know what you're doing. |
|
600 | 601 | * **readline_omit__names**: when tab-completion is enabled, hitting |
|
601 | 602 | <tab> after a '.' in a name will complete all attributes of an |
|
602 | 603 | object, including all the special methods whose names include |
|
603 | 604 | double underscores (like __getitem__ or __class__). If you'd |
|
604 | 605 | rather not see these names by default, you can set this option to |
|
605 | 606 | 1. Note that even when this option is set, you can still see those |
|
606 | 607 | names by explicitly typing a _ after the period and hitting <tab>: |
|
607 | 608 | 'name._<tab>' will always complete attribute names starting with '_'. |
|
608 | 609 | |
|
609 | 610 | This option is off by default so that new users see all |
|
610 | 611 | attributes of any objects they are dealing with. |
|
611 | 612 | |
|
612 | 613 | You will find the default values along with a corresponding detailed |
|
613 | 614 | explanation in your ipythonrc file. |
|
614 | 615 | |
|
615 | 616 | |
|
616 | 617 | Session logging and restoring |
|
617 | 618 | ----------------------------- |
|
618 | 619 | |
|
619 | 620 | You can log all input from a session either by starting IPython with the |
|
620 | 621 | command line switches -log or -logfile (see :ref:`here <command_line_options>`) |
|
621 | 622 | or by activating the logging at any moment with the magic function %logstart. |
|
622 | 623 | |
|
623 | 624 | Log files can later be reloaded with the -logplay option and IPython |
|
624 | 625 | will attempt to 'replay' the log by executing all the lines in it, thus |
|
625 | 626 | restoring the state of a previous session. This feature is not quite |
|
626 | 627 | perfect, but can still be useful in many cases. |
|
627 | 628 | |
|
628 | 629 | The log files can also be used as a way to have a permanent record of |
|
629 | 630 | any code you wrote while experimenting. Log files are regular text files |
|
630 | 631 | which you can later open in your favorite text editor to extract code or |
|
631 | 632 | to 'clean them up' before using them to replay a session. |
|
632 | 633 | |
|
633 | 634 | The %logstart function for activating logging in mid-session is used as |
|
634 | 635 | follows: |
|
635 | 636 | |
|
636 | 637 | %logstart [log_name [log_mode]] |
|
637 | 638 | |
|
638 | 639 | If no name is given, it defaults to a file named 'log' in your |
|
639 | 640 | IPYTHON_DIR directory, in 'rotate' mode (see below). |
|
640 | 641 | |
|
641 | 642 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
642 | 643 | history up to that point and then continues logging. |
|
643 | 644 | |
|
644 | 645 | %logstart takes a second optional parameter: logging mode. This can be |
|
645 | 646 | one of (note that the modes are given unquoted): |
|
646 | 647 | |
|
647 | 648 | * [over:] overwrite existing log_name. |
|
648 | 649 | * [backup:] rename (if exists) to log_name~ and start log_name. |
|
649 | 650 | * [append:] well, that says it. |
|
650 | 651 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. |
|
651 | 652 | |
|
652 | 653 | The %logoff and %logon functions allow you to temporarily stop and |
|
653 | 654 | resume logging to a file which had previously been started with |
|
654 | 655 | %logstart. They will fail (with an explanation) if you try to use them |
|
655 | 656 | before logging has been started. |
|
656 | 657 | |
|
657 | 658 | .. _system_shell_access: |
|
658 | 659 | |
|
659 | 660 | System shell access |
|
660 | 661 | ------------------- |
|
661 | 662 | |
|
662 | 663 | Any input line beginning with a ! character is passed verbatim (minus |
|
663 | 664 | the !, of course) to the underlying operating system. For example, |
|
664 | 665 | typing !ls will run 'ls' in the current directory. |
|
665 | 666 | |
|
666 | 667 | Manual capture of command output |
|
667 | 668 | -------------------------------- |
|
668 | 669 | |
|
669 | 670 | If the input line begins with two exclamation marks, !!, the command is |
|
670 | 671 | executed but its output is captured and returned as a python list, split |
|
671 | 672 | on newlines. Any output sent by the subprocess to standard error is |
|
672 | 673 | printed separately, so that the resulting list only captures standard |
|
673 | 674 | output. The !! syntax is a shorthand for the %sx magic command. |
|
674 | 675 | |
|
675 | 676 | Finally, the %sc magic (short for 'shell capture') is similar to %sx, |
|
676 | 677 | but allowing more fine-grained control of the capture details, and |
|
677 | 678 | storing the result directly into a named variable. The direct use of |
|
678 | 679 | %sc is now deprecated, and you should ise the ``var = !cmd`` syntax |
|
679 | 680 | instead. |
|
680 | 681 | |
|
681 | 682 | IPython also allows you to expand the value of python variables when |
|
682 | 683 | making system calls. Any python variable or expression which you prepend |
|
683 | 684 | with $ will get expanded before the system call is made:: |
|
684 | 685 | |
|
685 | 686 | In [1]: pyvar='Hello world' |
|
686 | 687 | In [2]: !echo "A python variable: $pyvar" |
|
687 | 688 | A python variable: Hello world |
|
688 | 689 | |
|
689 | 690 | If you want the shell to actually see a literal $, you need to type it |
|
690 | 691 | twice:: |
|
691 | 692 | |
|
692 | 693 | In [3]: !echo "A system variable: $$HOME" |
|
693 | 694 | A system variable: /home/fperez |
|
694 | 695 | |
|
695 | 696 | You can pass arbitrary expressions, though you'll need to delimit them |
|
696 | 697 | with {} if there is ambiguity as to the extent of the expression:: |
|
697 | 698 | |
|
698 | 699 | In [5]: x=10 |
|
699 | 700 | In [6]: y=20 |
|
700 | 701 | In [13]: !echo $x+y |
|
701 | 702 | 10+y |
|
702 | 703 | In [7]: !echo ${x+y} |
|
703 | 704 | 30 |
|
704 | 705 | |
|
705 | 706 | Even object attributes can be expanded:: |
|
706 | 707 | |
|
707 | 708 | In [12]: !echo $sys.argv |
|
708 | 709 | [/home/fperez/usr/bin/ipython] |
|
709 | 710 | |
|
710 | 711 | |
|
711 | 712 | System command aliases |
|
712 | 713 | ---------------------- |
|
713 | 714 | |
|
714 | 715 | The %alias magic function and the alias option in the ipythonrc |
|
715 | 716 | configuration file allow you to define magic functions which are in fact |
|
716 | 717 | system shell commands. These aliases can have parameters. |
|
717 | 718 | |
|
718 | 719 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
719 | 720 | |
|
720 | 721 | Then, typing '%alias_name params' will execute the system command 'cmd |
|
721 | 722 | params' (from your underlying operating system). |
|
722 | 723 | |
|
723 | 724 | You can also define aliases with parameters using %s specifiers (one per |
|
724 | 725 | parameter). The following example defines the %parts function as an |
|
725 | 726 | alias to the command 'echo first %s second %s' where each %s will be |
|
726 | 727 | replaced by a positional parameter to the call to %parts:: |
|
727 | 728 | |
|
728 | 729 | In [1]: alias parts echo first %s second %s |
|
729 | 730 | In [2]: %parts A B |
|
730 | 731 | first A second B |
|
731 | 732 | In [3]: %parts A |
|
732 | 733 | Incorrect number of arguments: 2 expected. |
|
733 | 734 | parts is an alias to: 'echo first %s second %s' |
|
734 | 735 | |
|
735 | 736 | If called with no parameters, %alias prints the table of currently |
|
736 | 737 | defined aliases. |
|
737 | 738 | |
|
738 | 739 | The %rehash/rehashx magics allow you to load your entire $PATH as |
|
739 | 740 | ipython aliases. See their respective docstrings (or sec. 6.2 |
|
740 | 741 | <#sec:magic> for further details). |
|
741 | 742 | |
|
742 | 743 | |
|
743 | 744 | .. _dreload: |
|
744 | 745 | |
|
745 | 746 | Recursive reload |
|
746 | 747 | ---------------- |
|
747 | 748 | |
|
748 | 749 | The dreload function does a recursive reload of a module: changes made |
|
749 | 750 | to the module since you imported will actually be available without |
|
750 | 751 | having to exit. |
|
751 | 752 | |
|
752 | 753 | |
|
753 | 754 | Verbose and colored exception traceback printouts |
|
754 | 755 | ------------------------------------------------- |
|
755 | 756 | |
|
756 | 757 | IPython provides the option to see very detailed exception tracebacks, |
|
757 | 758 | which can be especially useful when debugging large programs. You can |
|
758 | 759 | run any Python file with the %run function to benefit from these |
|
759 | 760 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can |
|
760 | 761 | be colored (if your terminal supports it) which makes them much easier |
|
761 | 762 | to parse visually. |
|
762 | 763 | |
|
763 | 764 | See the magic xmode and colors functions for details (just type %magic). |
|
764 | 765 | |
|
765 | 766 | These features are basically a terminal version of Ka-Ping Yee's cgitb |
|
766 | 767 | module, now part of the standard Python library. |
|
767 | 768 | |
|
768 | 769 | |
|
769 | 770 | .. _input_caching: |
|
770 | 771 | |
|
771 | 772 | Input caching system |
|
772 | 773 | -------------------- |
|
773 | 774 | |
|
774 | 775 | IPython offers numbered prompts (In/Out) with input and output caching |
|
775 | 776 | (also referred to as 'input history'). All input is saved and can be |
|
776 | 777 | retrieved as variables (besides the usual arrow key recall), in |
|
777 | 778 | addition to the %rep magic command that brings a history entry |
|
778 | 779 | up for editing on the next command line. |
|
779 | 780 | |
|
780 | 781 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
781 | 782 | _i: stores previous input. _ii: next previous. _iii: next-next previous. |
|
782 | 783 | _ih : a list of all input _ih[n] is the input from line n and this list |
|
783 | 784 | is aliased to the global variable In. If you overwrite In with a |
|
784 | 785 | variable of your own, you can remake the assignment to the internal list |
|
785 | 786 | with a simple 'In=_ih'. |
|
786 | 787 | |
|
787 | 788 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
788 | 789 | being the prompt counter), such that |
|
789 | 790 | _i<n> == _ih[<n>] == In[<n>]. |
|
790 | 791 | |
|
791 | 792 | For example, what you typed at prompt 14 is available as _i14, _ih[14] |
|
792 | 793 | and In[14]. |
|
793 | 794 | |
|
794 | 795 | This allows you to easily cut and paste multi line interactive prompts |
|
795 | 796 | by printing them out: they print like a clean string, without prompt |
|
796 | 797 | characters. You can also manipulate them like regular variables (they |
|
797 | 798 | are strings), modify or exec them (typing 'exec _i9' will re-execute the |
|
798 | 799 | contents of input prompt 9, 'exec In[9:14]+In[18]' will re-execute lines |
|
799 | 800 | 9 through 13 and line 18). |
|
800 | 801 | |
|
801 | 802 | You can also re-execute multiple lines of input easily by using the |
|
802 | 803 | magic %macro function (which automates the process and allows |
|
803 | 804 | re-execution without having to type 'exec' every time). The macro system |
|
804 | 805 | also allows you to re-execute previous lines which include magic |
|
805 | 806 | function calls (which require special processing). Type %macro? or see |
|
806 | 807 | sec. 6.2 <#sec:magic> for more details on the macro system. |
|
807 | 808 | |
|
808 | 809 | A history function %hist allows you to see any part of your input |
|
809 | 810 | history by printing a range of the _i variables. |
|
810 | 811 | |
|
811 | 812 | You can also search ('grep') through your history by typing |
|
812 | 813 | '%hist -g somestring'. This also searches through the so called *shadow history*, |
|
813 | 814 | which remembers all the commands (apart from multiline code blocks) |
|
814 | 815 | you have ever entered. Handy for searching for svn/bzr URL's, IP adrresses |
|
815 | 816 | etc. You can bring shadow history entries listed by '%hist -g' up for editing |
|
816 | 817 | (or re-execution by just pressing ENTER) with %rep command. Shadow history |
|
817 | 818 | entries are not available as _iNUMBER variables, and they are identified by |
|
818 | 819 | the '0' prefix in %hist -g output. That is, history entry 12 is a normal |
|
819 | 820 | history entry, but 0231 is a shadow history entry. |
|
820 | 821 | |
|
821 | 822 | Shadow history was added because the readline history is inherently very |
|
822 | 823 | unsafe - if you have multiple IPython sessions open, the last session |
|
823 | 824 | to close will overwrite the history of previountly closed session. Likewise, |
|
824 | 825 | if a crash occurs, history is never saved, whereas shadow history entries |
|
825 | 826 | are added after entering every command (so a command executed |
|
826 | 827 | in another IPython session is immediately available in other IPython |
|
827 | 828 | sessions that are open). |
|
828 | 829 | |
|
829 | 830 | To conserve space, a command can exist in shadow history only once - it doesn't |
|
830 | 831 | make sense to store a common line like "cd .." a thousand times. The idea is |
|
831 | 832 | mainly to provide a reliable place where valuable, hard-to-remember commands can |
|
832 | 833 | always be retrieved, as opposed to providing an exact sequence of commands |
|
833 | 834 | you have entered in actual order. |
|
834 | 835 | |
|
835 | 836 | Because shadow history has all the commands you have ever executed, |
|
836 | 837 | time taken by %hist -g will increase oven time. If it ever starts to take |
|
837 | 838 | too long (or it ends up containing sensitive information like passwords), |
|
838 | 839 | clear the shadow history by `%clear shadow_nuke`. |
|
839 | 840 | |
|
840 | 841 | Time taken to add entries to shadow history should be negligible, but |
|
841 | 842 | in any case, if you start noticing performance degradation after using |
|
842 | 843 | IPython for a long time (or running a script that floods the shadow history!), |
|
843 | 844 | you can 'compress' the shadow history by executing |
|
844 | 845 | `%clear shadow_compress`. In practice, this should never be necessary |
|
845 | 846 | in normal use. |
|
846 | 847 | |
|
847 | 848 | .. _output_caching: |
|
848 | 849 | |
|
849 | 850 | Output caching system |
|
850 | 851 | --------------------- |
|
851 | 852 | |
|
852 | 853 | For output that is returned from actions, a system similar to the input |
|
853 | 854 | cache exists but using _ instead of _i. Only actions that produce a |
|
854 | 855 | result (NOT assignments, for example) are cached. If you are familiar |
|
855 | 856 | with Mathematica, IPython's _ variables behave exactly like |
|
856 | 857 | Mathematica's % variables. |
|
857 | 858 | |
|
858 | 859 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
859 | 860 | |
|
860 | 861 | * [_] (a single underscore) : stores previous output, like Python's |
|
861 | 862 | default interpreter. |
|
862 | 863 | * [__] (two underscores): next previous. |
|
863 | 864 | * [___] (three underscores): next-next previous. |
|
864 | 865 | |
|
865 | 866 | Additionally, global variables named _<n> are dynamically created (<n> |
|
866 | 867 | being the prompt counter), such that the result of output <n> is always |
|
867 | 868 | available as _<n> (don't use the angle brackets, just the number, e.g. |
|
868 | 869 | _21). |
|
869 | 870 | |
|
870 | 871 | These global variables are all stored in a global dictionary (not a |
|
871 | 872 | list, since it only has entries for lines which returned a result) |
|
872 | 873 | available under the names _oh and Out (similar to _ih and In). So the |
|
873 | 874 | output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you |
|
874 | 875 | accidentally overwrite the Out variable you can recover it by typing |
|
875 | 876 | 'Out=_oh' at the prompt. |
|
876 | 877 | |
|
877 | 878 | This system obviously can potentially put heavy memory demands on your |
|
878 | 879 | system, since it prevents Python's garbage collector from removing any |
|
879 | 880 | previously computed results. You can control how many results are kept |
|
880 | 881 | in memory with the option (at the command line or in your ipythonrc |
|
881 | 882 | file) cache_size. If you set it to 0, the whole system is completely |
|
882 | 883 | disabled and the prompts revert to the classic '>>>' of normal Python. |
|
883 | 884 | |
|
884 | 885 | |
|
885 | 886 | Directory history |
|
886 | 887 | ----------------- |
|
887 | 888 | |
|
888 | 889 | Your history of visited directories is kept in the global list _dh, and |
|
889 | 890 | the magic %cd command can be used to go to any entry in that list. The |
|
890 | 891 | %dhist command allows you to view this history. Do ``cd -<TAB`` to |
|
891 | 892 | conventiently view the directory history. |
|
892 | 893 | |
|
893 | 894 | |
|
894 | 895 | Automatic parentheses and quotes |
|
895 | 896 | -------------------------------- |
|
896 | 897 | |
|
897 | 898 | These features were adapted from Nathan Gray's LazyPython. They are |
|
898 | 899 | meant to allow less typing for common situations. |
|
899 | 900 | |
|
900 | 901 | |
|
901 | 902 | Automatic parentheses |
|
902 | 903 | --------------------- |
|
903 | 904 | |
|
904 | 905 | Callable objects (i.e. functions, methods, etc) can be invoked like this |
|
905 | 906 | (notice the commas between the arguments):: |
|
906 | 907 | |
|
907 | 908 | >>> callable_ob arg1, arg2, arg3 |
|
908 | 909 | |
|
909 | 910 | and the input will be translated to this:: |
|
910 | 911 | |
|
911 | 912 | -> callable_ob(arg1, arg2, arg3) |
|
912 | 913 | |
|
913 | 914 | You can force automatic parentheses by using '/' as the first character |
|
914 | 915 | of a line. For example:: |
|
915 | 916 | |
|
916 | 917 | >>> /globals # becomes 'globals()' |
|
917 | 918 | |
|
918 | 919 | Note that the '/' MUST be the first character on the line! This won't work:: |
|
919 | 920 | |
|
920 | 921 | >>> print /globals # syntax error |
|
921 | 922 | |
|
922 | 923 | In most cases the automatic algorithm should work, so you should rarely |
|
923 | 924 | need to explicitly invoke /. One notable exception is if you are trying |
|
924 | 925 | to call a function with a list of tuples as arguments (the parenthesis |
|
925 | 926 | will confuse IPython):: |
|
926 | 927 | |
|
927 | 928 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
928 | 929 | |
|
929 | 930 | but this will work:: |
|
930 | 931 | |
|
931 | 932 | In [2]: /zip (1,2,3),(4,5,6) |
|
932 | 933 | ---> zip ((1,2,3),(4,5,6)) |
|
933 | 934 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
934 | 935 | |
|
935 | 936 | IPython tells you that it has altered your command line by displaying |
|
936 | 937 | the new command line preceded by ->. e.g.:: |
|
937 | 938 | |
|
938 | 939 | In [18]: callable list |
|
939 | 940 | ----> callable (list) |
|
940 | 941 | |
|
941 | 942 | |
|
942 | 943 | Automatic quoting |
|
943 | 944 | ----------------- |
|
944 | 945 | |
|
945 | 946 | You can force automatic quoting of a function's arguments by using ',' |
|
946 | 947 | or ';' as the first character of a line. For example:: |
|
947 | 948 | |
|
948 | 949 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
949 | 950 | |
|
950 | 951 | If you use ';' instead, the whole argument is quoted as a single string |
|
951 | 952 | (while ',' splits on whitespace):: |
|
952 | 953 | |
|
953 | 954 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
954 | 955 | |
|
955 | 956 | >>> ;my_function a b c # becomes my_function("a b c") |
|
956 | 957 | |
|
957 | 958 | Note that the ',' or ';' MUST be the first character on the line! This |
|
958 | 959 | won't work:: |
|
959 | 960 | |
|
960 | 961 | >>> x = ,my_function /home/me # syntax error |
|
961 | 962 | |
|
962 | 963 | IPython as your default Python environment |
|
963 | 964 | ========================================== |
|
964 | 965 | |
|
965 | 966 | Python honors the environment variable PYTHONSTARTUP and will execute at |
|
966 | 967 | startup the file referenced by this variable. If you put at the end of |
|
967 | 968 | this file the following two lines of code:: |
|
968 | 969 | |
|
969 | 970 | import IPython |
|
970 | 971 | IPython.Shell.IPShell().mainloop(sys_exit=1) |
|
971 | 972 | |
|
972 | 973 | then IPython will be your working environment anytime you start Python. |
|
973 | 974 | The sys_exit=1 is needed to have IPython issue a call to sys.exit() when |
|
974 | 975 | it finishes, otherwise you'll be back at the normal Python '>>>' |
|
975 | 976 | prompt. |
|
976 | 977 | |
|
977 | 978 | This is probably useful to developers who manage multiple Python |
|
978 | 979 | versions and don't want to have correspondingly multiple IPython |
|
979 | 980 | versions. Note that in this mode, there is no way to pass IPython any |
|
980 | 981 | command-line options, as those are trapped first by Python itself. |
|
981 | 982 | |
|
982 | 983 | .. _Embedding: |
|
983 | 984 | |
|
984 | 985 | Embedding IPython |
|
985 | 986 | ================= |
|
986 | 987 | |
|
987 | 988 | It is possible to start an IPython instance inside your own Python |
|
988 | 989 | programs. This allows you to evaluate dynamically the state of your |
|
989 | 990 | code, operate with your variables, analyze them, etc. Note however that |
|
990 | 991 | any changes you make to values while in the shell do not propagate back |
|
991 | 992 | to the running code, so it is safe to modify your values because you |
|
992 | 993 | won't break your code in bizarre ways by doing so. |
|
993 | 994 | |
|
994 | 995 | This feature allows you to easily have a fully functional python |
|
995 | 996 | environment for doing object introspection anywhere in your code with a |
|
996 | 997 | simple function call. In some cases a simple print statement is enough, |
|
997 | 998 | but if you need to do more detailed analysis of a code fragment this |
|
998 | 999 | feature can be very valuable. |
|
999 | 1000 | |
|
1000 | 1001 | It can also be useful in scientific computing situations where it is |
|
1001 | 1002 | common to need to do some automatic, computationally intensive part and |
|
1002 | 1003 | then stop to look at data, plots, etc. |
|
1003 | 1004 | Opening an IPython instance will give you full access to your data and |
|
1004 | 1005 | functions, and you can resume program execution once you are done with |
|
1005 | 1006 | the interactive part (perhaps to stop again later, as many times as |
|
1006 | 1007 | needed). |
|
1007 | 1008 | |
|
1008 | 1009 | The following code snippet is the bare minimum you need to include in |
|
1009 | 1010 | your Python programs for this to work (detailed examples follow later):: |
|
1010 | 1011 | |
|
1011 | 1012 | from IPython.Shell import IPShellEmbed |
|
1012 | 1013 | |
|
1013 | 1014 | ipshell = IPShellEmbed() |
|
1014 | 1015 | |
|
1015 | 1016 | ipshell() # this call anywhere in your program will start IPython |
|
1016 | 1017 | |
|
1017 | 1018 | You can run embedded instances even in code which is itself being run at |
|
1018 | 1019 | the IPython interactive prompt with '%run <filename>'. Since it's easy |
|
1019 | 1020 | to get lost as to where you are (in your top-level IPython or in your |
|
1020 | 1021 | embedded one), it's a good idea in such cases to set the in/out prompts |
|
1021 | 1022 | to something different for the embedded instances. The code examples |
|
1022 | 1023 | below illustrate this. |
|
1023 | 1024 | |
|
1024 | 1025 | You can also have multiple IPython instances in your program and open |
|
1025 | 1026 | them separately, for example with different options for data |
|
1026 | 1027 | presentation. If you close and open the same instance multiple times, |
|
1027 | 1028 | its prompt counters simply continue from each execution to the next. |
|
1028 | 1029 | |
|
1029 | 1030 | Please look at the docstrings in the Shell.py module for more details on |
|
1030 | 1031 | the use of this system. |
|
1031 | 1032 | |
|
1032 | 1033 | The following sample file illustrating how to use the embedding |
|
1033 | 1034 | functionality is provided in the examples directory as example-embed.py. |
|
1034 | 1035 | It should be fairly self-explanatory:: |
|
1035 | 1036 | |
|
1036 | 1037 | |
|
1037 | 1038 | #!/usr/bin/env python |
|
1038 | 1039 | |
|
1039 | 1040 | """An example of how to embed an IPython shell into a running program. |
|
1040 | 1041 | |
|
1041 | 1042 | Please see the documentation in the IPython.Shell module for more details. |
|
1042 | 1043 | |
|
1043 | 1044 | The accompanying file example-embed-short.py has quick code fragments for |
|
1044 | 1045 | embedding which you can cut and paste in your code once you understand how |
|
1045 | 1046 | things work. |
|
1046 | 1047 | |
|
1047 | 1048 | The code in this file is deliberately extra-verbose, meant for learning.""" |
|
1048 | 1049 | |
|
1049 | 1050 | # The basics to get you going: |
|
1050 | 1051 | |
|
1051 | 1052 | # IPython sets the __IPYTHON__ variable so you can know if you have nested |
|
1052 | 1053 | # copies running. |
|
1053 | 1054 | |
|
1054 | 1055 | # Try running this code both at the command line and from inside IPython (with |
|
1055 | 1056 | # %run example-embed.py) |
|
1056 | 1057 | try: |
|
1057 | 1058 | __IPYTHON__ |
|
1058 | 1059 | except NameError: |
|
1059 | 1060 | nested = 0 |
|
1060 | 1061 | args = [''] |
|
1061 | 1062 | else: |
|
1062 | 1063 | print "Running nested copies of IPython." |
|
1063 | 1064 | print "The prompts for the nested copy have been modified" |
|
1064 | 1065 | nested = 1 |
|
1065 | 1066 | # what the embedded instance will see as sys.argv: |
|
1066 | 1067 | args = ['-pi1','In <\\#>: ','-pi2',' .\\D.: ', |
|
1067 | 1068 | '-po','Out<\\#>: ','-nosep'] |
|
1068 | 1069 | |
|
1069 | 1070 | # First import the embeddable shell class |
|
1070 | 1071 | from IPython.Shell import IPShellEmbed |
|
1071 | 1072 | |
|
1072 | 1073 | # Now create an instance of the embeddable shell. The first argument is a |
|
1073 | 1074 | # string with options exactly as you would type them if you were starting |
|
1074 | 1075 | # IPython at the system command line. Any parameters you want to define for |
|
1075 | 1076 | # configuration can thus be specified here. |
|
1076 | 1077 | ipshell = IPShellEmbed(args, |
|
1077 | 1078 | banner = 'Dropping into IPython', |
|
1078 | 1079 | exit_msg = 'Leaving Interpreter, back to program.') |
|
1079 | 1080 | |
|
1080 | 1081 | # Make a second instance, you can have as many as you want. |
|
1081 | 1082 | if nested: |
|
1082 | 1083 | args[1] = 'In2<\\#>' |
|
1083 | 1084 | else: |
|
1084 | 1085 | args = ['-pi1','In2<\\#>: ','-pi2',' .\\D.: ', |
|
1085 | 1086 | '-po','Out<\\#>: ','-nosep'] |
|
1086 | 1087 | ipshell2 = IPShellEmbed(args,banner = 'Second IPython instance.') |
|
1087 | 1088 | |
|
1088 | 1089 | print '\nHello. This is printed from the main controller program.\n' |
|
1089 | 1090 | |
|
1090 | 1091 | # You can then call ipshell() anywhere you need it (with an optional |
|
1091 | 1092 | # message): |
|
1092 | 1093 | ipshell('***Called from top level. ' |
|
1093 | 1094 | 'Hit Ctrl-D to exit interpreter and continue program.\n' |
|
1094 | 1095 | 'Note that if you use %kill_embedded, you can fully deactivate\n' |
|
1095 | 1096 | 'This embedded instance so it will never turn on again') |
|
1096 | 1097 | |
|
1097 | 1098 | print '\nBack in caller program, moving along...\n' |
|
1098 | 1099 | |
|
1099 | 1100 | #--------------------------------------------------------------------------- |
|
1100 | 1101 | # More details: |
|
1101 | 1102 | |
|
1102 | 1103 | # IPShellEmbed instances don't print the standard system banner and |
|
1103 | 1104 | # messages. The IPython banner (which actually may contain initialization |
|
1104 | 1105 | # messages) is available as <instance>.IP.BANNER in case you want it. |
|
1105 | 1106 | |
|
1106 | 1107 | # IPShellEmbed instances print the following information everytime they |
|
1107 | 1108 | # start: |
|
1108 | 1109 | |
|
1109 | 1110 | # - A global startup banner. |
|
1110 | 1111 | |
|
1111 | 1112 | # - A call-specific header string, which you can use to indicate where in the |
|
1112 | 1113 | # execution flow the shell is starting. |
|
1113 | 1114 | |
|
1114 | 1115 | # They also print an exit message every time they exit. |
|
1115 | 1116 | |
|
1116 | 1117 | # Both the startup banner and the exit message default to None, and can be set |
|
1117 | 1118 | # either at the instance constructor or at any other time with the |
|
1118 | 1119 | # set_banner() and set_exit_msg() methods. |
|
1119 | 1120 | |
|
1120 | 1121 | # The shell instance can be also put in 'dummy' mode globally or on a per-call |
|
1121 | 1122 | # basis. This gives you fine control for debugging without having to change |
|
1122 | 1123 | # code all over the place. |
|
1123 | 1124 | |
|
1124 | 1125 | # The code below illustrates all this. |
|
1125 | 1126 | |
|
1126 | 1127 | |
|
1127 | 1128 | # This is how the global banner and exit_msg can be reset at any point |
|
1128 | 1129 | ipshell.set_banner('Entering interpreter - New Banner') |
|
1129 | 1130 | ipshell.set_exit_msg('Leaving interpreter - New exit_msg') |
|
1130 | 1131 | |
|
1131 | 1132 | def foo(m): |
|
1132 | 1133 | s = 'spam' |
|
1133 | 1134 | ipshell('***In foo(). Try @whos, or print s or m:') |
|
1134 | 1135 | print 'foo says m = ',m |
|
1135 | 1136 | |
|
1136 | 1137 | def bar(n): |
|
1137 | 1138 | s = 'eggs' |
|
1138 | 1139 | ipshell('***In bar(). Try @whos, or print s or n:') |
|
1139 | 1140 | print 'bar says n = ',n |
|
1140 | 1141 | |
|
1141 | 1142 | # Some calls to the above functions which will trigger IPython: |
|
1142 | 1143 | print 'Main program calling foo("eggs")\n' |
|
1143 | 1144 | foo('eggs') |
|
1144 | 1145 | |
|
1145 | 1146 | # The shell can be put in 'dummy' mode where calls to it silently return. This |
|
1146 | 1147 | # allows you, for example, to globally turn off debugging for a program with a |
|
1147 | 1148 | # single call. |
|
1148 | 1149 | ipshell.set_dummy_mode(1) |
|
1149 | 1150 | print '\nTrying to call IPython which is now "dummy":' |
|
1150 | 1151 | ipshell() |
|
1151 | 1152 | print 'Nothing happened...' |
|
1152 | 1153 | # The global 'dummy' mode can still be overridden for a single call |
|
1153 | 1154 | print '\nOverriding dummy mode manually:' |
|
1154 | 1155 | ipshell(dummy=0) |
|
1155 | 1156 | |
|
1156 | 1157 | # Reactivate the IPython shell |
|
1157 | 1158 | ipshell.set_dummy_mode(0) |
|
1158 | 1159 | |
|
1159 | 1160 | print 'You can even have multiple embedded instances:' |
|
1160 | 1161 | ipshell2() |
|
1161 | 1162 | |
|
1162 | 1163 | print '\nMain program calling bar("spam")\n' |
|
1163 | 1164 | bar('spam') |
|
1164 | 1165 | |
|
1165 | 1166 | print 'Main program finished. Bye!' |
|
1166 | 1167 | |
|
1167 | 1168 | #********************** End of file <example-embed.py> *********************** |
|
1168 | 1169 | |
|
1169 | 1170 | Once you understand how the system functions, you can use the following |
|
1170 | 1171 | code fragments in your programs which are ready for cut and paste:: |
|
1171 | 1172 | |
|
1172 | 1173 | |
|
1173 | 1174 | """Quick code snippets for embedding IPython into other programs. |
|
1174 | 1175 | |
|
1175 | 1176 | See example-embed.py for full details, this file has the bare minimum code for |
|
1176 | 1177 | cut and paste use once you understand how to use the system.""" |
|
1177 | 1178 | |
|
1178 | 1179 | #--------------------------------------------------------------------------- |
|
1179 | 1180 | # This code loads IPython but modifies a few things if it detects it's running |
|
1180 | 1181 | # embedded in another IPython session (helps avoid confusion) |
|
1181 | 1182 | |
|
1182 | 1183 | try: |
|
1183 | 1184 | __IPYTHON__ |
|
1184 | 1185 | except NameError: |
|
1185 | 1186 | argv = [''] |
|
1186 | 1187 | banner = exit_msg = '' |
|
1187 | 1188 | else: |
|
1188 | 1189 | # Command-line options for IPython (a list like sys.argv) |
|
1189 | 1190 | argv = ['-pi1','In <\\#>:','-pi2',' .\\D.:','-po','Out<\\#>:'] |
|
1190 | 1191 | banner = '*** Nested interpreter ***' |
|
1191 | 1192 | exit_msg = '*** Back in main IPython ***' |
|
1192 | 1193 | |
|
1193 | 1194 | # First import the embeddable shell class |
|
1194 | 1195 | from IPython.Shell import IPShellEmbed |
|
1195 | 1196 | # Now create the IPython shell instance. Put ipshell() anywhere in your code |
|
1196 | 1197 | # where you want it to open. |
|
1197 | 1198 | ipshell = IPShellEmbed(argv,banner=banner,exit_msg=exit_msg) |
|
1198 | 1199 | |
|
1199 | 1200 | #--------------------------------------------------------------------------- |
|
1200 | 1201 | # This code will load an embeddable IPython shell always with no changes for |
|
1201 | 1202 | # nested embededings. |
|
1202 | 1203 | |
|
1203 | 1204 | from IPython.Shell import IPShellEmbed |
|
1204 | 1205 | ipshell = IPShellEmbed() |
|
1205 | 1206 | # Now ipshell() will open IPython anywhere in the code. |
|
1206 | 1207 | |
|
1207 | 1208 | #--------------------------------------------------------------------------- |
|
1208 | 1209 | # This code loads an embeddable shell only if NOT running inside |
|
1209 | 1210 | # IPython. Inside IPython, the embeddable shell variable ipshell is just a |
|
1210 | 1211 | # dummy function. |
|
1211 | 1212 | |
|
1212 | 1213 | try: |
|
1213 | 1214 | __IPYTHON__ |
|
1214 | 1215 | except NameError: |
|
1215 | 1216 | from IPython.Shell import IPShellEmbed |
|
1216 | 1217 | ipshell = IPShellEmbed() |
|
1217 | 1218 | # Now ipshell() will open IPython anywhere in the code |
|
1218 | 1219 | else: |
|
1219 | 1220 | # Define a dummy ipshell() so the same code doesn't crash inside an |
|
1220 | 1221 | # interactive IPython |
|
1221 | 1222 | def ipshell(): pass |
|
1222 | 1223 | |
|
1223 | 1224 | #******************* End of file <example-embed-short.py> ******************** |
|
1224 | 1225 | |
|
1225 | 1226 | Using the Python debugger (pdb) |
|
1226 | 1227 | =============================== |
|
1227 | 1228 | |
|
1228 | 1229 | Running entire programs via pdb |
|
1229 | 1230 | ------------------------------- |
|
1230 | 1231 | |
|
1231 | 1232 | pdb, the Python debugger, is a powerful interactive debugger which |
|
1232 | 1233 | allows you to step through code, set breakpoints, watch variables, |
|
1233 | 1234 | etc. IPython makes it very easy to start any script under the control |
|
1234 | 1235 | of pdb, regardless of whether you have wrapped it into a 'main()' |
|
1235 | 1236 | function or not. For this, simply type '%run -d myscript' at an |
|
1236 | 1237 | IPython prompt. See the %run command's documentation (via '%run?' or |
|
1237 | 1238 | in Sec. magic_ for more details, including how to control where pdb |
|
1238 | 1239 | will stop execution first. |
|
1239 | 1240 | |
|
1240 | 1241 | For more information on the use of the pdb debugger, read the included |
|
1241 | 1242 | pdb.doc file (part of the standard Python distribution). On a stock |
|
1242 | 1243 | Linux system it is located at /usr/lib/python2.3/pdb.doc, but the |
|
1243 | 1244 | easiest way to read it is by using the help() function of the pdb module |
|
1244 | 1245 | as follows (in an IPython prompt): |
|
1245 | 1246 | |
|
1246 | 1247 | In [1]: import pdb |
|
1247 | 1248 | In [2]: pdb.help() |
|
1248 | 1249 | |
|
1249 | 1250 | This will load the pdb.doc document in a file viewer for you automatically. |
|
1250 | 1251 | |
|
1251 | 1252 | |
|
1252 | 1253 | Automatic invocation of pdb on exceptions |
|
1253 | 1254 | ----------------------------------------- |
|
1254 | 1255 | |
|
1255 | 1256 | IPython, if started with the -pdb option (or if the option is set in |
|
1256 | 1257 | your rc file) can call the Python pdb debugger every time your code |
|
1257 | 1258 | triggers an uncaught exception. This feature |
|
1258 | 1259 | can also be toggled at any time with the %pdb magic command. This can be |
|
1259 | 1260 | extremely useful in order to find the origin of subtle bugs, because pdb |
|
1260 | 1261 | opens up at the point in your code which triggered the exception, and |
|
1261 | 1262 | while your program is at this point 'dead', all the data is still |
|
1262 | 1263 | available and you can walk up and down the stack frame and understand |
|
1263 | 1264 | the origin of the problem. |
|
1264 | 1265 | |
|
1265 | 1266 | Furthermore, you can use these debugging facilities both with the |
|
1266 | 1267 | embedded IPython mode and without IPython at all. For an embedded shell |
|
1267 | 1268 | (see sec. Embedding_), simply call the constructor with |
|
1268 | 1269 | '-pdb' in the argument string and automatically pdb will be called if an |
|
1269 | 1270 | uncaught exception is triggered by your code. |
|
1270 | 1271 | |
|
1271 | 1272 | For stand-alone use of the feature in your programs which do not use |
|
1272 | 1273 | IPython at all, put the following lines toward the top of your 'main' |
|
1273 | 1274 | routine:: |
|
1274 | 1275 | |
|
1275 | 1276 | import sys |
|
1276 | 1277 | from IPython.core import ultratb |
|
1277 | 1278 | sys.excepthook = ultratb.FormattedTB(mode='Verbose', |
|
1278 | 1279 | color_scheme='Linux', call_pdb=1) |
|
1279 | 1280 | |
|
1280 | 1281 | The mode keyword can be either 'Verbose' or 'Plain', giving either very |
|
1281 | 1282 | detailed or normal tracebacks respectively. The color_scheme keyword can |
|
1282 | 1283 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same |
|
1283 | 1284 | options which can be set in IPython with -colors and -xmode. |
|
1284 | 1285 | |
|
1285 | 1286 | This will give any of your programs detailed, colored tracebacks with |
|
1286 | 1287 | automatic invocation of pdb. |
|
1287 | 1288 | |
|
1288 | 1289 | |
|
1289 | 1290 | Extensions for syntax processing |
|
1290 | 1291 | ================================ |
|
1291 | 1292 | |
|
1292 | 1293 | This isn't for the faint of heart, because the potential for breaking |
|
1293 | 1294 | things is quite high. But it can be a very powerful and useful feature. |
|
1294 | 1295 | In a nutshell, you can redefine the way IPython processes the user input |
|
1295 | 1296 | line to accept new, special extensions to the syntax without needing to |
|
1296 | 1297 | change any of IPython's own code. |
|
1297 | 1298 | |
|
1298 | 1299 | In the IPython/extensions directory you will find some examples |
|
1299 | 1300 | supplied, which we will briefly describe now. These can be used 'as is' |
|
1300 | 1301 | (and both provide very useful functionality), or you can use them as a |
|
1301 | 1302 | starting point for writing your own extensions. |
|
1302 | 1303 | |
|
1303 | 1304 | |
|
1304 | 1305 | Pasting of code starting with '>>> ' or '... ' |
|
1305 | 1306 | ---------------------------------------------- |
|
1306 | 1307 | |
|
1307 | 1308 | In the python tutorial it is common to find code examples which have |
|
1308 | 1309 | been taken from real python sessions. The problem with those is that all |
|
1309 | 1310 | the lines begin with either '>>> ' or '... ', which makes it impossible |
|
1310 | 1311 | to paste them all at once. One must instead do a line by line manual |
|
1311 | 1312 | copying, carefully removing the leading extraneous characters. |
|
1312 | 1313 | |
|
1313 | 1314 | This extension identifies those starting characters and removes them |
|
1314 | 1315 | from the input automatically, so that one can paste multi-line examples |
|
1315 | 1316 | directly into IPython, saving a lot of time. Please look at the file |
|
1316 | 1317 | InterpreterPasteInput.py in the IPython/extensions directory for details |
|
1317 | 1318 | on how this is done. |
|
1318 | 1319 | |
|
1319 | 1320 | IPython comes with a special profile enabling this feature, called |
|
1320 | 1321 | tutorial. Simply start IPython via 'ipython -p tutorial' and the feature |
|
1321 | 1322 | will be available. In a normal IPython session you can activate the |
|
1322 | 1323 | feature by importing the corresponding module with: |
|
1323 | 1324 | In [1]: import IPython.extensions.InterpreterPasteInput |
|
1324 | 1325 | |
|
1325 | 1326 | The following is a 'screenshot' of how things work when this extension |
|
1326 | 1327 | is on, copying an example from the standard tutorial:: |
|
1327 | 1328 | |
|
1328 | 1329 | IPython profile: tutorial |
|
1329 | 1330 | |
|
1330 | 1331 | *** Pasting of code with ">>>" or "..." has been enabled. |
|
1331 | 1332 | |
|
1332 | 1333 | In [1]: >>> def fib2(n): # return Fibonacci series up to n |
|
1333 | 1334 | ...: ... """Return a list containing the Fibonacci series up to |
|
1334 | 1335 | n.""" |
|
1335 | 1336 | ...: ... result = [] |
|
1336 | 1337 | ...: ... a, b = 0, 1 |
|
1337 | 1338 | ...: ... while b < n: |
|
1338 | 1339 | ...: ... result.append(b) # see below |
|
1339 | 1340 | ...: ... a, b = b, a+b |
|
1340 | 1341 | ...: ... return result |
|
1341 | 1342 | ...: |
|
1342 | 1343 | |
|
1343 | 1344 | In [2]: fib2(10) |
|
1344 | 1345 | Out[2]: [1, 1, 2, 3, 5, 8] |
|
1345 | 1346 | |
|
1346 | 1347 | Note that as currently written, this extension does not recognize |
|
1347 | 1348 | IPython's prompts for pasting. Those are more complicated, since the |
|
1348 | 1349 | user can change them very easily, they involve numbers and can vary in |
|
1349 | 1350 | length. One could however extract all the relevant information from the |
|
1350 | 1351 | IPython instance and build an appropriate regular expression. This is |
|
1351 | 1352 | left as an exercise for the reader. |
|
1352 | 1353 | |
|
1353 | 1354 | |
|
1354 | 1355 | Input of physical quantities with units |
|
1355 | 1356 | --------------------------------------- |
|
1356 | 1357 | |
|
1357 | 1358 | The module PhysicalQInput allows a simplified form of input for physical |
|
1358 | 1359 | quantities with units. This file is meant to be used in conjunction with |
|
1359 | 1360 | the PhysicalQInteractive module (in the same directory) and |
|
1360 | 1361 | Physics.PhysicalQuantities from Konrad Hinsen's ScientificPython |
|
1361 | 1362 | (http://dirac.cnrs-orleans.fr/ScientificPython/). |
|
1362 | 1363 | |
|
1363 | 1364 | The Physics.PhysicalQuantities module defines PhysicalQuantity objects, |
|
1364 | 1365 | but these must be declared as instances of a class. For example, to |
|
1365 | 1366 | define v as a velocity of 3 m/s, normally you would write:: |
|
1366 | 1367 | |
|
1367 | 1368 | In [1]: v = PhysicalQuantity(3,'m/s') |
|
1368 | 1369 | |
|
1369 | 1370 | Using the PhysicalQ_Input extension this can be input instead as: |
|
1370 | 1371 | In [1]: v = 3 m/s |
|
1371 | 1372 | which is much more convenient for interactive use (even though it is |
|
1372 | 1373 | blatantly invalid Python syntax). |
|
1373 | 1374 | |
|
1374 | 1375 | The physics profile supplied with IPython (enabled via 'ipython -p |
|
1375 | 1376 | physics') uses these extensions, which you can also activate with: |
|
1376 | 1377 | |
|
1377 | 1378 | from math import * # math MUST be imported BEFORE PhysicalQInteractive |
|
1378 | 1379 | from IPython.extensions.PhysicalQInteractive import * |
|
1379 | 1380 | import IPython.extensions.PhysicalQInput |
|
1380 | 1381 | |
|
1381 | 1382 | .. _gui_support: |
|
1382 | 1383 | |
|
1383 | 1384 | GUI event loop support support |
|
1384 | 1385 | ============================== |
|
1385 | 1386 | |
|
1386 | 1387 | .. versionadded:: 0.11 |
|
1387 | 1388 | The ``%gui`` magic and :mod:`IPython.lib.inputhook`. |
|
1388 | 1389 | |
|
1389 | 1390 | IPython has excellent support for working interactively with Graphical User |
|
1390 | 1391 | Interface (GUI) toolkits, such as wxPython, PyQt4, PyGTK and Tk. This is |
|
1391 | 1392 | implemented using Python's builtin ``PyOSInputHook`` hook. This implementation |
|
1392 | 1393 | is extremely robust compared to our previous threaded based version. The |
|
1393 | 1394 | advantages of this are: |
|
1394 | 1395 | |
|
1395 | 1396 | * GUIs can be enabled and disabled dynamically at runtime. |
|
1396 | 1397 | * The active GUI can be switched dynamically at runtime. |
|
1397 | 1398 | * In some cases, multiple GUIs can run simultaneously with no problems. |
|
1398 | 1399 | * There is a developer API in :mod:`IPython.lib.inputhook` for customizing |
|
1399 | 1400 | all of these things. |
|
1400 | 1401 | |
|
1401 | 1402 | For users, enabling GUI event loop integration is simple. You simple use the |
|
1402 | 1403 | ``%gui`` magic as follows:: |
|
1403 | 1404 | |
|
1404 | 1405 | %gui [-a] [GUINAME] |
|
1405 | 1406 | |
|
1406 | 1407 | With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME`` |
|
1407 | 1408 | arguments are ``wx``, ``qt4``, ``gtk`` and ``tk``. The ``-a`` option will |
|
1408 | 1409 | create and return a running application object for the selected GUI toolkit. |
|
1409 | 1410 | |
|
1410 | 1411 | Thus, to use wxPython interactively and create a running :class:`wx.App` |
|
1411 | 1412 | object, do:: |
|
1412 | 1413 | |
|
1413 | 1414 | %gui -a wx |
|
1414 | 1415 | |
|
1415 | 1416 | For information on IPython's Matplotlib integration (and the ``pylab`` mode) |
|
1416 | 1417 | see :ref:`this section <matplotlib_support>`. |
|
1417 | 1418 | |
|
1418 | 1419 | For developers that want to use IPython's GUI event loop integration in |
|
1419 | 1420 | the form of a library, these capabilities are exposed in library form |
|
1420 | 1421 | in the :mod:`IPython.lib.inputhook`. Interested developers should see the |
|
1421 | 1422 | module docstrings for more information, but there are a few points that |
|
1422 | 1423 | should be mentioned here. |
|
1423 | 1424 | |
|
1424 | 1425 | First, the ``PyOSInputHook`` approach only works in command line settings |
|
1425 | 1426 | where readline is activated. |
|
1426 | 1427 | |
|
1427 | 1428 | Second, when using the ``PyOSInputHook`` approach, a GUI application should |
|
1428 | 1429 | *not* start its event loop. Instead all of this is handled by the |
|
1429 | 1430 | ``PyOSInputHook``. This means that applications that are meant to be used both |
|
1430 | 1431 | in IPython and as standalone apps need to have special code to detects how the |
|
1431 | 1432 | application is being run. We highly recommend using IPython's |
|
1432 | 1433 | :func:`appstart_` functions for this. Here is a simple example that shows the |
|
1433 | 1434 | recommended code that should be at the bottom of a wxPython using GUI |
|
1434 | 1435 | application:: |
|
1435 | 1436 | |
|
1436 | 1437 | try: |
|
1437 | 1438 | from IPython import appstart_wx |
|
1438 | 1439 | appstart_wx(app) |
|
1439 | 1440 | except ImportError: |
|
1440 | 1441 | app.MainLoop() |
|
1441 | 1442 | |
|
1442 | 1443 | This pattern should be used instead of the simple ``app.MainLoop()`` code |
|
1443 | 1444 | that a standalone wxPython application would have. |
|
1444 | 1445 | |
|
1445 | 1446 | Third, unlike previous versions of IPython, we no longer "hijack" (replace |
|
1446 | 1447 | them with no-ops) the event loops. This is done to allow applications that |
|
1447 | 1448 | actually need to run the real event loops to do so. This is often needed to |
|
1448 | 1449 | process pending events at critical points. |
|
1449 | 1450 | |
|
1450 | 1451 | Finally, we also have a number of examples in our source directory |
|
1451 | 1452 | :file:`docs/examples/lib` that demonstrate these capabilities. |
|
1452 | 1453 | |
|
1453 | 1454 | .. _matplotlib_support: |
|
1454 | 1455 | |
|
1455 | 1456 | Plotting with matplotlib |
|
1456 | 1457 | ======================== |
|
1457 | 1458 | |
|
1458 | 1459 | |
|
1459 | 1460 | `Matplotlib`_ provides high quality 2D and |
|
1460 | 1461 | 3D plotting for Python. Matplotlib can produce plots on screen using a variety |
|
1461 | 1462 | of GUI toolkits, including Tk, PyGTK, PyQt4 and wxPython. It also provides a |
|
1462 | 1463 | number of commands useful for scientific computing, all with a syntax |
|
1463 | 1464 | compatible with that of the popular Matlab program. |
|
1464 | 1465 | |
|
1465 | 1466 | Many IPython users have come to rely on IPython's ``-pylab`` mode which |
|
1466 | 1467 | automates the integration of Matplotlib with IPython. We are still in the |
|
1467 | 1468 | process of working with the Matplotlib developers to finalize the new pylab |
|
1468 | 1469 | API, but for now you can use Matplotlib interactively using the following |
|
1469 | 1470 | commands:: |
|
1470 | 1471 | |
|
1471 | 1472 | %gui -a wx |
|
1472 | 1473 | import matplotlib |
|
1473 | 1474 | matplotlib.use('wxagg') |
|
1474 | 1475 | from matplotlib import pylab |
|
1475 | 1476 | pylab.interactive(True) |
|
1476 | 1477 | |
|
1477 | 1478 | All of this will soon be automated as Matplotlib beings to include |
|
1478 | 1479 | new logic that uses our new GUI support. |
|
1479 | 1480 | |
|
1480 | 1481 | .. _interactive_demos: |
|
1481 | 1482 | |
|
1482 | 1483 | Interactive demos with IPython |
|
1483 | 1484 | ============================== |
|
1484 | 1485 | |
|
1485 | 1486 | IPython ships with a basic system for running scripts interactively in |
|
1486 | 1487 | sections, useful when presenting code to audiences. A few tags embedded |
|
1487 | 1488 | in comments (so that the script remains valid Python code) divide a file |
|
1488 | 1489 | into separate blocks, and the demo can be run one block at a time, with |
|
1489 | 1490 | IPython printing (with syntax highlighting) the block before executing |
|
1490 | 1491 | it, and returning to the interactive prompt after each block. The |
|
1491 | 1492 | interactive namespace is updated after each block is run with the |
|
1492 | 1493 | contents of the demo's namespace. |
|
1493 | 1494 | |
|
1494 | 1495 | This allows you to show a piece of code, run it and then execute |
|
1495 | 1496 | interactively commands based on the variables just created. Once you |
|
1496 | 1497 | want to continue, you simply execute the next block of the demo. The |
|
1497 | 1498 | following listing shows the markup necessary for dividing a script into |
|
1498 | 1499 | sections for execution as a demo:: |
|
1499 | 1500 | |
|
1500 | 1501 | |
|
1501 | 1502 | """A simple interactive demo to illustrate the use of IPython's Demo class. |
|
1502 | 1503 | |
|
1503 | 1504 | Any python script can be run as a demo, but that does little more than showing |
|
1504 | 1505 | it on-screen, syntax-highlighted in one shot. If you add a little simple |
|
1505 | 1506 | markup, you can stop at specified intervals and return to the ipython prompt, |
|
1506 | 1507 | resuming execution later. |
|
1507 | 1508 | """ |
|
1508 | 1509 | |
|
1509 | 1510 | print 'Hello, welcome to an interactive IPython demo.' |
|
1510 | 1511 | print 'Executing this block should require confirmation before proceeding,' |
|
1511 | 1512 | print 'unless auto_all has been set to true in the demo object' |
|
1512 | 1513 | |
|
1513 | 1514 | # The mark below defines a block boundary, which is a point where IPython will |
|
1514 | 1515 | # stop execution and return to the interactive prompt. |
|
1515 | 1516 | # Note that in actual interactive execution, |
|
1516 | 1517 | # <demo> --- stop --- |
|
1517 | 1518 | |
|
1518 | 1519 | x = 1 |
|
1519 | 1520 | y = 2 |
|
1520 | 1521 | |
|
1521 | 1522 | # <demo> --- stop --- |
|
1522 | 1523 | |
|
1523 | 1524 | # the mark below makes this block as silent |
|
1524 | 1525 | # <demo> silent |
|
1525 | 1526 | |
|
1526 | 1527 | print 'This is a silent block, which gets executed but not printed.' |
|
1527 | 1528 | |
|
1528 | 1529 | # <demo> --- stop --- |
|
1529 | 1530 | # <demo> auto |
|
1530 | 1531 | print 'This is an automatic block.' |
|
1531 | 1532 | print 'It is executed without asking for confirmation, but printed.' |
|
1532 | 1533 | z = x+y |
|
1533 | 1534 | |
|
1534 | 1535 | print 'z=',x |
|
1535 | 1536 | |
|
1536 | 1537 | # <demo> --- stop --- |
|
1537 | 1538 | # This is just another normal block. |
|
1538 | 1539 | print 'z is now:', z |
|
1539 | 1540 | |
|
1540 | 1541 | print 'bye!' |
|
1541 | 1542 | |
|
1542 | 1543 | In order to run a file as a demo, you must first make a Demo object out |
|
1543 | 1544 | of it. If the file is named myscript.py, the following code will make a |
|
1544 | 1545 | demo:: |
|
1545 | 1546 | |
|
1546 | 1547 | from IPython.demo import Demo |
|
1547 | 1548 | |
|
1548 | 1549 | mydemo = Demo('myscript.py') |
|
1549 | 1550 | |
|
1550 | 1551 | This creates the mydemo object, whose blocks you run one at a time by |
|
1551 | 1552 | simply calling the object with no arguments. If you have autocall active |
|
1552 | 1553 | in IPython (the default), all you need to do is type:: |
|
1553 | 1554 | |
|
1554 | 1555 | mydemo |
|
1555 | 1556 | |
|
1556 | 1557 | and IPython will call it, executing each block. Demo objects can be |
|
1557 | 1558 | restarted, you can move forward or back skipping blocks, re-execute the |
|
1558 | 1559 | last block, etc. Simply use the Tab key on a demo object to see its |
|
1559 | 1560 | methods, and call '?' on them to see their docstrings for more usage |
|
1560 | 1561 | details. In addition, the demo module itself contains a comprehensive |
|
1561 | 1562 | docstring, which you can access via:: |
|
1562 | 1563 | |
|
1563 | 1564 | from IPython import demo |
|
1564 | 1565 | |
|
1565 | 1566 | demo? |
|
1566 | 1567 | |
|
1567 | 1568 | Limitations: It is important to note that these demos are limited to |
|
1568 | 1569 | fairly simple uses. In particular, you can not put division marks in |
|
1569 | 1570 | indented code (loops, if statements, function definitions, etc.) |
|
1570 | 1571 | Supporting something like this would basically require tracking the |
|
1571 | 1572 | internal execution state of the Python interpreter, so only top-level |
|
1572 | 1573 | divisions are allowed. If you want to be able to open an IPython |
|
1573 | 1574 | instance at an arbitrary point in a program, you can use IPython's |
|
1574 | 1575 | embedding facilities, described in detail in Sec. 9 |
|
1575 | 1576 | |
|
1576 | 1577 | .. [Matplotlib] Matplotlib. http://matplotlib.sourceforge.net |
|
1577 | 1578 |
@@ -1,293 +1,293 b'' | |||
|
1 | 1 | .. _ipython_as_shell: |
|
2 | 2 | |
|
3 | 3 | ========================= |
|
4 | 4 | IPython as a system shell |
|
5 | 5 | ========================= |
|
6 | 6 | |
|
7 | 7 | .. warning:: |
|
8 | 8 | |
|
9 | 9 | As of the 0.11 version of IPython, some of the features and APIs |
|
10 | 10 | described in this section have been deprecated or are broken. Our plan |
|
11 | 11 | is to continue to support these features, but they need to be updated |
|
12 | 12 | to take advantage of recent API changes. Furthermore, this section |
|
13 | 13 | of the documentation need to be updated to reflect all of these changes. |
|
14 | 14 | |
|
15 | 15 | Overview |
|
16 | 16 | ======== |
|
17 | 17 | |
|
18 | 18 | The 'sh' profile optimizes IPython for system shell usage. Apart from |
|
19 | 19 | certain job control functionality that is present in unix (ctrl+z does |
|
20 | 20 | "suspend"), the sh profile should provide you with most of the |
|
21 | 21 | functionality you use daily in system shell, and more. Invoke IPython |
|
22 | 22 | in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching |
|
23 | 23 | the "pysh" shortcut in start menu. |
|
24 | 24 | |
|
25 | 25 | If you want to use the features of sh profile as your defaults (which |
|
26 | 26 | might be a good idea if you use other profiles a lot of the time but |
|
27 | 27 | still want the convenience of sh profile), add ``import ipy_profile_sh`` |
|
28 |
to your |
|
|
28 | to your $IPYTHON_DIR/ipy_user_conf.py. | |
|
29 | 29 | |
|
30 | 30 | The 'sh' profile is different from the default profile in that: |
|
31 | 31 | |
|
32 | 32 | * Prompt shows the current directory |
|
33 | 33 | * Spacing between prompts and input is more compact (no padding with |
|
34 | 34 | empty lines). The startup banner is more compact as well. |
|
35 | 35 | * System commands are directly available (in alias table) without |
|
36 | 36 | requesting %rehashx - however, if you install new programs along |
|
37 | 37 | your PATH, you might want to run %rehashx to update the persistent |
|
38 | 38 | alias table |
|
39 | 39 | * Macros are stored in raw format by default. That is, instead of |
|
40 | 40 | '_ip.system("cat foo"), the macro will contain text 'cat foo') |
|
41 | 41 | * Autocall is in full mode |
|
42 | 42 | * Calling "up" does "cd .." |
|
43 | 43 | |
|
44 | 44 | The 'sh' profile is different from the now-obsolete (and unavailable) |
|
45 | 45 | 'pysh' profile in that: |
|
46 | 46 | |
|
47 | 47 | * '$$var = command' and '$var = command' syntax is not supported |
|
48 | 48 | * anymore. Use 'var = !command' instead (incidentally, this is |
|
49 | 49 | * available in all IPython profiles). Note that !!command *will* |
|
50 | 50 | * work. |
|
51 | 51 | |
|
52 | 52 | Aliases |
|
53 | 53 | ======= |
|
54 | 54 | |
|
55 | 55 | All of your $PATH has been loaded as IPython aliases, so you should be |
|
56 | 56 | able to type any normal system command and have it executed. See |
|
57 | 57 | %alias? and %unalias? for details on the alias facilities. See also |
|
58 | 58 | %rehashx? for details on the mechanism used to load $PATH. |
|
59 | 59 | |
|
60 | 60 | |
|
61 | 61 | Directory management |
|
62 | 62 | ==================== |
|
63 | 63 | |
|
64 | 64 | Since each command passed by ipython to the underlying system is executed |
|
65 | 65 | in a subshell which exits immediately, you can NOT use !cd to navigate |
|
66 | 66 | the filesystem. |
|
67 | 67 | |
|
68 | 68 | IPython provides its own builtin '%cd' magic command to move in the |
|
69 | 69 | filesystem (the % is not required with automagic on). It also maintains |
|
70 | 70 | a list of visited directories (use %dhist to see it) and allows direct |
|
71 | 71 | switching to any of them. Type 'cd?' for more details. |
|
72 | 72 | |
|
73 | 73 | %pushd, %popd and %dirs are provided for directory stack handling. |
|
74 | 74 | |
|
75 | 75 | |
|
76 | 76 | Enabled extensions |
|
77 | 77 | ================== |
|
78 | 78 | |
|
79 | 79 | Some extensions, listed below, are enabled as default in this profile. |
|
80 | 80 | |
|
81 | 81 | envpersist |
|
82 | 82 | ---------- |
|
83 | 83 | |
|
84 | 84 | %env can be used to "remember" environment variable manipulations. Examples:: |
|
85 | 85 | |
|
86 | 86 | %env - Show all environment variables |
|
87 | 87 | %env VISUAL=jed - set VISUAL to jed |
|
88 | 88 | %env PATH+=;/foo - append ;foo to PATH |
|
89 | 89 | %env PATH+=;/bar - also append ;bar to PATH |
|
90 | 90 | %env PATH-=/wbin; - prepend /wbin; to PATH |
|
91 | 91 | %env -d VISUAL - forget VISUAL persistent val |
|
92 | 92 | %env -p - print all persistent env modifications |
|
93 | 93 | |
|
94 | 94 | ipy_which |
|
95 | 95 | --------- |
|
96 | 96 | |
|
97 | 97 | %which magic command. Like 'which' in unix, but knows about ipython aliases. |
|
98 | 98 | |
|
99 | 99 | Example:: |
|
100 | 100 | |
|
101 | 101 | [C:/ipython]|14> %which st |
|
102 | 102 | st -> start . |
|
103 | 103 | [C:/ipython]|15> %which d |
|
104 | 104 | d -> dir /w /og /on |
|
105 | 105 | [C:/ipython]|16> %which cp |
|
106 | 106 | cp -> cp |
|
107 | 107 | == c:\bin\cp.exe |
|
108 | 108 | c:\bin\cp.exe |
|
109 | 109 | |
|
110 | 110 | ipy_app_completers |
|
111 | 111 | ------------------ |
|
112 | 112 | |
|
113 | 113 | Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu. |
|
114 | 114 | |
|
115 | 115 | ipy_rehashdir |
|
116 | 116 | ------------- |
|
117 | 117 | |
|
118 | 118 | Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir:: |
|
119 | 119 | |
|
120 | 120 | [~]|22> cd c:/opt/PuTTY/ |
|
121 | 121 | [c:opt/PuTTY]|23> rehashdir . |
|
122 | 122 | <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000'] |
|
123 | 123 | |
|
124 | 124 | Now, you can execute any of those commams directly:: |
|
125 | 125 | |
|
126 | 126 | [c:opt/PuTTY]|24> cd |
|
127 | 127 | [~]|25> putty |
|
128 | 128 | |
|
129 | 129 | (the putty window opens). |
|
130 | 130 | |
|
131 | 131 | If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop:: |
|
132 | 132 | |
|
133 | 133 | [~]|27> for a in _23: |
|
134 | 134 | |..> %store $a |
|
135 | 135 | |..> |
|
136 | 136 | |..> |
|
137 | 137 | Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe') |
|
138 | 138 | Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe') |
|
139 | 139 | Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe') |
|
140 | 140 | Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe') |
|
141 | 141 | ... |
|
142 | 142 | |
|
143 | 143 | mglob |
|
144 | 144 | ----- |
|
145 | 145 | |
|
146 | 146 | Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples:: |
|
147 | 147 | |
|
148 | 148 | [c:/ipython]|9> mglob *.py |
|
149 | 149 | [c:/ipython]|10> mglob *.py rec:*.txt |
|
150 | 150 | [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:. |
|
151 | 151 | |
|
152 | 152 | Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'. |
|
153 | 153 | |
|
154 | 154 | |
|
155 | 155 | Prompt customization |
|
156 | 156 | ==================== |
|
157 | 157 | |
|
158 | 158 | The sh profile uses the following prompt configurations:: |
|
159 | 159 | |
|
160 | 160 | o.prompt_in1= r'\C_LightBlue[\C_LightCyan\Y2\C_LightBlue]\C_Green|\#>' |
|
161 | 161 | o.prompt_in2= r'\C_Green|\C_LightGreen\D\C_Green>' |
|
162 | 162 | |
|
163 | 163 | You can change the prompt configuration to your liking by editing |
|
164 | 164 | ipy_user_conf.py. |
|
165 | 165 | |
|
166 | 166 | String lists |
|
167 | 167 | ============ |
|
168 | 168 | |
|
169 | 169 | String lists (IPython.utils.text.SList) are handy way to process output |
|
170 | 170 | from system commands. They are produced by ``var = !cmd`` syntax. |
|
171 | 171 | |
|
172 | 172 | First, we acquire the output of 'ls -l':: |
|
173 | 173 | |
|
174 | 174 | [Q:doc/examples]|2> lines = !ls -l |
|
175 | 175 | == |
|
176 | 176 | ['total 23', |
|
177 | 177 | '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py', |
|
178 | 178 | '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py', |
|
179 | 179 | '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py', |
|
180 | 180 | '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py', |
|
181 | 181 | '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py', |
|
182 | 182 | '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py', |
|
183 | 183 | '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc'] |
|
184 | 184 | |
|
185 | 185 | Now, let's take a look at the contents of 'lines' (the first number is |
|
186 | 186 | the list element number):: |
|
187 | 187 | |
|
188 | 188 | [Q:doc/examples]|3> lines |
|
189 | 189 | <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: |
|
190 | 190 | |
|
191 | 191 | 0: total 23 |
|
192 | 192 | 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py |
|
193 | 193 | 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py |
|
194 | 194 | 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py |
|
195 | 195 | 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py |
|
196 | 196 | 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py |
|
197 | 197 | 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py |
|
198 | 198 | 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc |
|
199 | 199 | |
|
200 | 200 | Now, let's filter out the 'embed' lines:: |
|
201 | 201 | |
|
202 | 202 | [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1) |
|
203 | 203 | [Q:doc/examples]|5> l2 |
|
204 | 204 | <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: |
|
205 | 205 | |
|
206 | 206 | 0: total 23 |
|
207 | 207 | 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py |
|
208 | 208 | 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py |
|
209 | 209 | 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py |
|
210 | 210 | 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py |
|
211 | 211 | 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc |
|
212 | 212 | |
|
213 | 213 | Now, we want strings having just file names and permissions:: |
|
214 | 214 | |
|
215 | 215 | [Q:doc/examples]|6> l2.fields(8,0) |
|
216 | 216 | <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value: |
|
217 | 217 | |
|
218 | 218 | 0: total |
|
219 | 219 | 1: example-demo.py -rw-rw-rw- |
|
220 | 220 | 2: example-gnuplot.py -rwxrwxrwx |
|
221 | 221 | 3: extension.py -rwxrwxrwx |
|
222 | 222 | 4: seteditor.py -rwxrwxrwx |
|
223 | 223 | 5: seteditor.pyc -rwxrwxrwx |
|
224 | 224 | |
|
225 | 225 | Note how the line with 'total' does not raise IndexError. |
|
226 | 226 | |
|
227 | 227 | If you want to split these (yielding lists), call fields() without |
|
228 | 228 | arguments:: |
|
229 | 229 | |
|
230 | 230 | [Q:doc/examples]|7> _.fields() |
|
231 | 231 | <7> |
|
232 | 232 | [['total'], |
|
233 | 233 | ['example-demo.py', '-rw-rw-rw-'], |
|
234 | 234 | ['example-gnuplot.py', '-rwxrwxrwx'], |
|
235 | 235 | ['extension.py', '-rwxrwxrwx'], |
|
236 | 236 | ['seteditor.py', '-rwxrwxrwx'], |
|
237 | 237 | ['seteditor.pyc', '-rwxrwxrwx']] |
|
238 | 238 | |
|
239 | 239 | If you want to pass these separated with spaces to a command (typical |
|
240 | 240 | for lists if files), use the .s property:: |
|
241 | 241 | |
|
242 | 242 | |
|
243 | 243 | [Q:doc/examples]|13> files = l2.fields(8).s |
|
244 | 244 | [Q:doc/examples]|14> files |
|
245 | 245 | <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc' |
|
246 | 246 | [Q:doc/examples]|15> ls $files |
|
247 | 247 | example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc |
|
248 | 248 | |
|
249 | 249 | SLists are inherited from normal python lists, so every list method is |
|
250 | 250 | available:: |
|
251 | 251 | |
|
252 | 252 | [Q:doc/examples]|21> lines.append('hey') |
|
253 | 253 | |
|
254 | 254 | |
|
255 | 255 | Real world example: remove all files outside version control |
|
256 | 256 | ============================================================ |
|
257 | 257 | |
|
258 | 258 | First, capture output of "hg status":: |
|
259 | 259 | |
|
260 | 260 | [Q:/ipython]|28> out = !hg status |
|
261 | 261 | == |
|
262 | 262 | ['M IPython\\extensions\\ipy_kitcfg.py', |
|
263 | 263 | 'M IPython\\extensions\\ipy_rehashdir.py', |
|
264 | 264 | ... |
|
265 | 265 | '? build\\lib\\IPython\\Debugger.py', |
|
266 | 266 | '? build\\lib\\IPython\\extensions\\InterpreterExec.py', |
|
267 | 267 | '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py', |
|
268 | 268 | ... |
|
269 | 269 | |
|
270 | 270 | (lines starting with ? are not under version control). |
|
271 | 271 | |
|
272 | 272 | :: |
|
273 | 273 | |
|
274 | 274 | [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1) |
|
275 | 275 | [Q:/ipython]|36> junk |
|
276 | 276 | <36> SList (.p, .n, .l, .s, .grep(), .fields() availab |
|
277 | 277 | ... |
|
278 | 278 | 10: build\bdist.win32\winexe\temp\_ctypes.py |
|
279 | 279 | 11: build\bdist.win32\winexe\temp\_hashlib.py |
|
280 | 280 | 12: build\bdist.win32\winexe\temp\_socket.py |
|
281 | 281 | |
|
282 | 282 | Now we can just remove these files by doing 'rm $junk.s'. |
|
283 | 283 | |
|
284 | 284 | The .s, .n, .p properties |
|
285 | 285 | ========================= |
|
286 | 286 | |
|
287 | 287 | The '.s' property returns one string where lines are separated by |
|
288 | 288 | single space (for convenient passing to system commands). The '.n' |
|
289 | 289 | property return one string where the lines are separated by '\n' |
|
290 | 290 | (i.e. the original output of the function). If the items in string |
|
291 | 291 | list are file names, '.p' can be used to get a list of "path" objects |
|
292 | 292 | for convenient file manipulation. |
|
293 | 293 |
@@ -1,237 +1,237 b'' | |||
|
1 | 1 | .. _ip1par: |
|
2 | 2 | |
|
3 | 3 | ============================ |
|
4 | 4 | Overview and getting started |
|
5 | 5 | ============================ |
|
6 | 6 | |
|
7 | 7 | Introduction |
|
8 | 8 | ============ |
|
9 | 9 | |
|
10 | 10 | This section gives an overview of IPython's sophisticated and powerful |
|
11 | 11 | architecture for parallel and distributed computing. This architecture |
|
12 | 12 | abstracts out parallelism in a very general way, which enables IPython to |
|
13 | 13 | support many different styles of parallelism including: |
|
14 | 14 | |
|
15 | 15 | * Single program, multiple data (SPMD) parallelism. |
|
16 | 16 | * Multiple program, multiple data (MPMD) parallelism. |
|
17 | 17 | * Message passing using MPI. |
|
18 | 18 | * Task farming. |
|
19 | 19 | * Data parallel. |
|
20 | 20 | * Combinations of these approaches. |
|
21 | 21 | * Custom user defined approaches. |
|
22 | 22 | |
|
23 | 23 | Most importantly, IPython enables all types of parallel applications to |
|
24 | 24 | be developed, executed, debugged and monitored *interactively*. Hence, |
|
25 | 25 | the ``I`` in IPython. The following are some example usage cases for IPython: |
|
26 | 26 | |
|
27 | 27 | * Quickly parallelize algorithms that are embarrassingly parallel |
|
28 | 28 | using a number of simple approaches. Many simple things can be |
|
29 | 29 | parallelized interactively in one or two lines of code. |
|
30 | 30 | |
|
31 | 31 | * Steer traditional MPI applications on a supercomputer from an |
|
32 | 32 | IPython session on your laptop. |
|
33 | 33 | |
|
34 | 34 | * Analyze and visualize large datasets (that could be remote and/or |
|
35 | 35 | distributed) interactively using IPython and tools like |
|
36 | 36 | matplotlib/TVTK. |
|
37 | 37 | |
|
38 | 38 | * Develop, test and debug new parallel algorithms |
|
39 | 39 | (that may use MPI) interactively. |
|
40 | 40 | |
|
41 | 41 | * Tie together multiple MPI jobs running on different systems into |
|
42 | 42 | one giant distributed and parallel system. |
|
43 | 43 | |
|
44 | 44 | * Start a parallel job on your cluster and then have a remote |
|
45 | 45 | collaborator connect to it and pull back data into their |
|
46 | 46 | local IPython session for plotting and analysis. |
|
47 | 47 | |
|
48 | 48 | * Run a set of tasks on a set of CPUs using dynamic load balancing. |
|
49 | 49 | |
|
50 | 50 | Architecture overview |
|
51 | 51 | ===================== |
|
52 | 52 | |
|
53 | 53 | The IPython architecture consists of three components: |
|
54 | 54 | |
|
55 | 55 | * The IPython engine. |
|
56 | 56 | * The IPython controller. |
|
57 | 57 | * Various controller clients. |
|
58 | 58 | |
|
59 | 59 | These components live in the :mod:`IPython.kernel` package and are |
|
60 | 60 | installed with IPython. They do, however, have additional dependencies |
|
61 | 61 | that must be installed. For more information, see our |
|
62 | 62 | :ref:`installation documentation <install_index>`. |
|
63 | 63 | |
|
64 | 64 | IPython engine |
|
65 | 65 | --------------- |
|
66 | 66 | |
|
67 | 67 | The IPython engine is a Python instance that takes Python commands over a |
|
68 | 68 | network connection. Eventually, the IPython engine will be a full IPython |
|
69 | 69 | interpreter, but for now, it is a regular Python interpreter. The engine |
|
70 | 70 | can also handle incoming and outgoing Python objects sent over a network |
|
71 | 71 | connection. When multiple engines are started, parallel and distributed |
|
72 | 72 | computing becomes possible. An important feature of an IPython engine is |
|
73 | 73 | that it blocks while user code is being executed. Read on for how the |
|
74 | 74 | IPython controller solves this problem to expose a clean asynchronous API |
|
75 | 75 | to the user. |
|
76 | 76 | |
|
77 | 77 | IPython controller |
|
78 | 78 | ------------------ |
|
79 | 79 | |
|
80 | 80 | The IPython controller provides an interface for working with a set of |
|
81 | 81 | engines. At an general level, the controller is a process to which |
|
82 | 82 | IPython engines can connect. For each connected engine, the controller |
|
83 | 83 | manages a queue. All actions that can be performed on the engine go |
|
84 | 84 | through this queue. While the engines themselves block when user code is |
|
85 | 85 | run, the controller hides that from the user to provide a fully |
|
86 | 86 | asynchronous interface to a set of engines. |
|
87 | 87 | |
|
88 | 88 | .. note:: |
|
89 | 89 | |
|
90 | 90 | Because the controller listens on a network port for engines to |
|
91 | 91 | connect to it, it must be started *before* any engines are started. |
|
92 | 92 | |
|
93 | 93 | The controller also provides a single point of contact for users who wish to |
|
94 | 94 | utilize the engines connected to the controller. There are different ways of |
|
95 | 95 | working with a controller. In IPython these ways correspond to different |
|
96 | 96 | interfaces that the controller is adapted to. Currently we have two default |
|
97 | 97 | interfaces to the controller: |
|
98 | 98 | |
|
99 | 99 | * The MultiEngine interface, which provides the simplest possible way of |
|
100 | 100 | working with engines interactively. |
|
101 | 101 | * The Task interface, which presents the engines as a load balanced |
|
102 | 102 | task farming system. |
|
103 | 103 | |
|
104 | 104 | Advanced users can easily add new custom interfaces to enable other |
|
105 | 105 | styles of parallelism. |
|
106 | 106 | |
|
107 | 107 | .. note:: |
|
108 | 108 | |
|
109 | 109 | A single controller and set of engines can be accessed |
|
110 | 110 | through multiple interfaces simultaneously. This opens the |
|
111 | 111 | door for lots of interesting things. |
|
112 | 112 | |
|
113 | 113 | Controller clients |
|
114 | 114 | ------------------ |
|
115 | 115 | |
|
116 | 116 | For each controller interface, there is a corresponding client. These |
|
117 | 117 | clients allow users to interact with a set of engines through the |
|
118 | 118 | interface. Here are the two default clients: |
|
119 | 119 | |
|
120 | 120 | * The :class:`MultiEngineClient` class. |
|
121 | 121 | * The :class:`TaskClient` class. |
|
122 | 122 | |
|
123 | 123 | Security |
|
124 | 124 | -------- |
|
125 | 125 | |
|
126 | 126 | By default (as long as `pyOpenSSL` is installed) all network connections |
|
127 | 127 | between the controller and engines and the controller and clients are secure. |
|
128 | 128 | What does this mean? First of all, all of the connections will be encrypted |
|
129 | 129 | using SSL. Second, the connections are authenticated. We handle authentication |
|
130 | 130 | in a capability based security model [Capability]_. In this model, a |
|
131 | 131 | "capability (known in some systems as a key) is a communicable, unforgeable |
|
132 | 132 | token of authority". Put simply, a capability is like a key to your house. If |
|
133 | 133 | you have the key to your house, you can get in. If not, you can't. |
|
134 | 134 | |
|
135 | 135 | In our architecture, the controller is the only process that listens on |
|
136 | 136 | network ports, and is thus responsible to creating these keys. In IPython, |
|
137 | 137 | these keys are known as Foolscap URLs, or FURLs, because of the underlying |
|
138 | 138 | network protocol we are using. As a user, you don't need to know anything |
|
139 | 139 | about the details of these FURLs, other than that when the controller starts, |
|
140 | 140 | it saves a set of FURLs to files named :file:`something.furl`. The default |
|
141 |
location of these files is the :file:` |
|
|
141 | location of these files is the :file:`$IPYTHON_DIR/cluster_<profile>/security` directory. | |
|
142 | 142 | |
|
143 | 143 | To connect and authenticate to the controller an engine or client simply needs |
|
144 | 144 | to present an appropriate FURL (that was originally created by the controller) |
|
145 | 145 | to the controller. Thus, the FURL files need to be copied to a location where |
|
146 | 146 | the clients and engines can find them. Typically, this is the |
|
147 |
:file:` |
|
|
147 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory on the host where the client/engine is | |
|
148 | 148 | running (which could be a different host than the controller). Once the FURL |
|
149 | 149 | files are copied over, everything should work fine. |
|
150 | 150 | |
|
151 | 151 | Currently, there are three FURL files that the controller creates: |
|
152 | 152 | |
|
153 | 153 | ipcontroller-engine.furl |
|
154 | 154 | This FURL file is the key that gives an engine the ability to connect |
|
155 | 155 | to a controller. |
|
156 | 156 | |
|
157 | 157 | ipcontroller-tc.furl |
|
158 | 158 | This FURL file is the key that a :class:`TaskClient` must use to |
|
159 | 159 | connect to the task interface of a controller. |
|
160 | 160 | |
|
161 | 161 | ipcontroller-mec.furl |
|
162 | 162 | This FURL file is the key that a :class:`MultiEngineClient` must use |
|
163 | 163 | to connect to the multiengine interface of a controller. |
|
164 | 164 | |
|
165 | 165 | More details of how these FURL files are used are given below. |
|
166 | 166 | |
|
167 | 167 | A detailed description of the security model and its implementation in IPython |
|
168 | 168 | can be found :ref:`here <parallelsecurity>`. |
|
169 | 169 | |
|
170 | 170 | Getting Started |
|
171 | 171 | =============== |
|
172 | 172 | |
|
173 | 173 | To use IPython for parallel computing, you need to start one instance of the |
|
174 | 174 | controller and one or more instances of the engine. Initially, it is best to |
|
175 | 175 | simply start a controller and engines on a single host using the |
|
176 | 176 | :command:`ipcluster` command. To start a controller and 4 engines on your |
|
177 | 177 | localhost, just do:: |
|
178 | 178 | |
|
179 | 179 | $ ipcluster local -n 4 |
|
180 | 180 | |
|
181 | 181 | More details about starting the IPython controller and engines can be found |
|
182 | 182 | :ref:`here <parallel_process>` |
|
183 | 183 | |
|
184 | 184 | Once you have started the IPython controller and one or more engines, you |
|
185 | 185 | are ready to use the engines to do something useful. To make sure |
|
186 | 186 | everything is working correctly, try the following commands: |
|
187 | 187 | |
|
188 | 188 | .. sourcecode:: ipython |
|
189 | 189 | |
|
190 | 190 | In [1]: from IPython.kernel import client |
|
191 | 191 | |
|
192 | 192 | In [2]: mec = client.MultiEngineClient() |
|
193 | 193 | |
|
194 | 194 | In [4]: mec.get_ids() |
|
195 | 195 | Out[4]: [0, 1, 2, 3] |
|
196 | 196 | |
|
197 | 197 | In [5]: mec.execute('print "Hello World"') |
|
198 | 198 | Out[5]: |
|
199 | 199 | <Results List> |
|
200 | 200 | [0] In [1]: print "Hello World" |
|
201 | 201 | [0] Out[1]: Hello World |
|
202 | 202 | |
|
203 | 203 | [1] In [1]: print "Hello World" |
|
204 | 204 | [1] Out[1]: Hello World |
|
205 | 205 | |
|
206 | 206 | [2] In [1]: print "Hello World" |
|
207 | 207 | [2] Out[1]: Hello World |
|
208 | 208 | |
|
209 | 209 | [3] In [1]: print "Hello World" |
|
210 | 210 | [3] Out[1]: Hello World |
|
211 | 211 | |
|
212 | 212 | Remember, a client also needs to present a FURL file to the controller. How |
|
213 | 213 | does this happen? When a multiengine client is created with no arguments, the |
|
214 | 214 | client tries to find the corresponding FURL file in the local |
|
215 |
:file:` |
|
|
215 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory. If it finds it, you are set. If you | |
|
216 | 216 | have put the FURL file in a different location or it has a different name, |
|
217 | 217 | create the client like this:: |
|
218 | 218 | |
|
219 | 219 | mec = client.MultiEngineClient('/path/to/my/ipcontroller-mec.furl') |
|
220 | 220 | |
|
221 | 221 | Same thing hold true of creating a task client:: |
|
222 | 222 | |
|
223 | 223 | tc = client.TaskClient('/path/to/my/ipcontroller-tc.furl') |
|
224 | 224 | |
|
225 | 225 | You are now ready to learn more about the :ref:`MultiEngine |
|
226 | 226 | <parallelmultiengine>` and :ref:`Task <paralleltask>` interfaces to the |
|
227 | 227 | controller. |
|
228 | 228 | |
|
229 | 229 | .. note:: |
|
230 | 230 | |
|
231 | 231 | Don't forget that the engine, multiengine client and task client all have |
|
232 | 232 | *different* furl files. You must move *each* of these around to an |
|
233 | 233 | appropriate location so that the engines and clients can use them to |
|
234 | 234 | connect to the controller. |
|
235 | 235 | |
|
236 | 236 | .. [Capability] Capability-based security, http://en.wikipedia.org/wiki/Capability-based_security |
|
237 | 237 |
@@ -1,835 +1,835 b'' | |||
|
1 | 1 | .. _parallelmultiengine: |
|
2 | 2 | |
|
3 | 3 | =============================== |
|
4 | 4 | IPython's multiengine interface |
|
5 | 5 | =============================== |
|
6 | 6 | |
|
7 | 7 | The multiengine interface represents one possible way of working with a set of |
|
8 | 8 | IPython engines. The basic idea behind the multiengine interface is that the |
|
9 | 9 | capabilities of each engine are directly and explicitly exposed to the user. |
|
10 | 10 | Thus, in the multiengine interface, each engine is given an id that is used to |
|
11 | 11 | identify the engine and give it work to do. This interface is very intuitive |
|
12 | 12 | and is designed with interactive usage in mind, and is thus the best place for |
|
13 | 13 | new users of IPython to begin. |
|
14 | 14 | |
|
15 | 15 | Starting the IPython controller and engines |
|
16 | 16 | =========================================== |
|
17 | 17 | |
|
18 | 18 | To follow along with this tutorial, you will need to start the IPython |
|
19 | 19 | controller and four IPython engines. The simplest way of doing this is to use |
|
20 | 20 | the :command:`ipcluster` command:: |
|
21 | 21 | |
|
22 | 22 | $ ipcluster local -n 4 |
|
23 | 23 | |
|
24 | 24 | For more detailed information about starting the controller and engines, see |
|
25 | 25 | our :ref:`introduction <ip1par>` to using IPython for parallel computing. |
|
26 | 26 | |
|
27 | 27 | Creating a ``MultiEngineClient`` instance |
|
28 | 28 | ========================================= |
|
29 | 29 | |
|
30 | 30 | The first step is to import the IPython :mod:`IPython.kernel.client` module |
|
31 | 31 | and then create a :class:`MultiEngineClient` instance: |
|
32 | 32 | |
|
33 | 33 | .. sourcecode:: ipython |
|
34 | 34 | |
|
35 | 35 | In [1]: from IPython.kernel import client |
|
36 | 36 | |
|
37 | 37 | In [2]: mec = client.MultiEngineClient() |
|
38 | 38 | |
|
39 | 39 | This form assumes that the :file:`ipcontroller-mec.furl` is in the |
|
40 |
:file:` |
|
|
40 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory on the client's host. If not, the | |
|
41 | 41 | location of the FURL file must be given as an argument to the |
|
42 | 42 | constructor: |
|
43 | 43 | |
|
44 | 44 | .. sourcecode:: ipython |
|
45 | 45 | |
|
46 | 46 | In [2]: mec = client.MultiEngineClient('/path/to/my/ipcontroller-mec.furl') |
|
47 | 47 | |
|
48 | 48 | To make sure there are engines connected to the controller, use can get a list |
|
49 | 49 | of engine ids: |
|
50 | 50 | |
|
51 | 51 | .. sourcecode:: ipython |
|
52 | 52 | |
|
53 | 53 | In [3]: mec.get_ids() |
|
54 | 54 | Out[3]: [0, 1, 2, 3] |
|
55 | 55 | |
|
56 | 56 | Here we see that there are four engines ready to do work for us. |
|
57 | 57 | |
|
58 | 58 | Quick and easy parallelism |
|
59 | 59 | ========================== |
|
60 | 60 | |
|
61 | 61 | In many cases, you simply want to apply a Python function to a sequence of |
|
62 | 62 | objects, but *in parallel*. The multiengine interface provides two simple ways |
|
63 | 63 | of accomplishing this: a parallel version of :func:`map` and ``@parallel`` |
|
64 | 64 | function decorator. |
|
65 | 65 | |
|
66 | 66 | Parallel map |
|
67 | 67 | ------------ |
|
68 | 68 | |
|
69 | 69 | Python's builtin :func:`map` functions allows a function to be applied to a |
|
70 | 70 | sequence element-by-element. This type of code is typically trivial to |
|
71 | 71 | parallelize. In fact, the multiengine interface in IPython already has a |
|
72 | 72 | parallel version of :meth:`map` that works just like its serial counterpart: |
|
73 | 73 | |
|
74 | 74 | .. sourcecode:: ipython |
|
75 | 75 | |
|
76 | 76 | In [63]: serial_result = map(lambda x:x**10, range(32)) |
|
77 | 77 | |
|
78 | 78 | In [64]: parallel_result = mec.map(lambda x:x**10, range(32)) |
|
79 | 79 | |
|
80 | 80 | In [65]: serial_result==parallel_result |
|
81 | 81 | Out[65]: True |
|
82 | 82 | |
|
83 | 83 | .. note:: |
|
84 | 84 | |
|
85 | 85 | The multiengine interface version of :meth:`map` does not do any load |
|
86 | 86 | balancing. For a load balanced version, see the task interface. |
|
87 | 87 | |
|
88 | 88 | .. seealso:: |
|
89 | 89 | |
|
90 | 90 | The :meth:`map` method has a number of options that can be controlled by |
|
91 | 91 | the :meth:`mapper` method. See its docstring for more information. |
|
92 | 92 | |
|
93 | 93 | Parallel function decorator |
|
94 | 94 | --------------------------- |
|
95 | 95 | |
|
96 | 96 | Parallel functions are just like normal function, but they can be called on |
|
97 | 97 | sequences and *in parallel*. The multiengine interface provides a decorator |
|
98 | 98 | that turns any Python function into a parallel function: |
|
99 | 99 | |
|
100 | 100 | .. sourcecode:: ipython |
|
101 | 101 | |
|
102 | 102 | In [10]: @mec.parallel() |
|
103 | 103 | ....: def f(x): |
|
104 | 104 | ....: return 10.0*x**4 |
|
105 | 105 | ....: |
|
106 | 106 | |
|
107 | 107 | In [11]: f(range(32)) # this is done in parallel |
|
108 | 108 | Out[11]: |
|
109 | 109 | [0.0,10.0,160.0,...] |
|
110 | 110 | |
|
111 | 111 | See the docstring for the :meth:`parallel` decorator for options. |
|
112 | 112 | |
|
113 | 113 | Running Python commands |
|
114 | 114 | ======================= |
|
115 | 115 | |
|
116 | 116 | The most basic type of operation that can be performed on the engines is to |
|
117 | 117 | execute Python code. Executing Python code can be done in blocking or |
|
118 | 118 | non-blocking mode (blocking is default) using the :meth:`execute` method. |
|
119 | 119 | |
|
120 | 120 | Blocking execution |
|
121 | 121 | ------------------ |
|
122 | 122 | |
|
123 | 123 | In blocking mode, the :class:`MultiEngineClient` object (called ``mec`` in |
|
124 | 124 | these examples) submits the command to the controller, which places the |
|
125 | 125 | command in the engines' queues for execution. The :meth:`execute` call then |
|
126 | 126 | blocks until the engines are done executing the command: |
|
127 | 127 | |
|
128 | 128 | .. sourcecode:: ipython |
|
129 | 129 | |
|
130 | 130 | # The default is to run on all engines |
|
131 | 131 | In [4]: mec.execute('a=5') |
|
132 | 132 | Out[4]: |
|
133 | 133 | <Results List> |
|
134 | 134 | [0] In [1]: a=5 |
|
135 | 135 | [1] In [1]: a=5 |
|
136 | 136 | [2] In [1]: a=5 |
|
137 | 137 | [3] In [1]: a=5 |
|
138 | 138 | |
|
139 | 139 | In [5]: mec.execute('b=10') |
|
140 | 140 | Out[5]: |
|
141 | 141 | <Results List> |
|
142 | 142 | [0] In [2]: b=10 |
|
143 | 143 | [1] In [2]: b=10 |
|
144 | 144 | [2] In [2]: b=10 |
|
145 | 145 | [3] In [2]: b=10 |
|
146 | 146 | |
|
147 | 147 | Python commands can be executed on specific engines by calling execute using |
|
148 | 148 | the ``targets`` keyword argument: |
|
149 | 149 | |
|
150 | 150 | .. sourcecode:: ipython |
|
151 | 151 | |
|
152 | 152 | In [6]: mec.execute('c=a+b',targets=[0,2]) |
|
153 | 153 | Out[6]: |
|
154 | 154 | <Results List> |
|
155 | 155 | [0] In [3]: c=a+b |
|
156 | 156 | [2] In [3]: c=a+b |
|
157 | 157 | |
|
158 | 158 | |
|
159 | 159 | In [7]: mec.execute('c=a-b',targets=[1,3]) |
|
160 | 160 | Out[7]: |
|
161 | 161 | <Results List> |
|
162 | 162 | [1] In [3]: c=a-b |
|
163 | 163 | [3] In [3]: c=a-b |
|
164 | 164 | |
|
165 | 165 | |
|
166 | 166 | In [8]: mec.execute('print c') |
|
167 | 167 | Out[8]: |
|
168 | 168 | <Results List> |
|
169 | 169 | [0] In [4]: print c |
|
170 | 170 | [0] Out[4]: 15 |
|
171 | 171 | |
|
172 | 172 | [1] In [4]: print c |
|
173 | 173 | [1] Out[4]: -5 |
|
174 | 174 | |
|
175 | 175 | [2] In [4]: print c |
|
176 | 176 | [2] Out[4]: 15 |
|
177 | 177 | |
|
178 | 178 | [3] In [4]: print c |
|
179 | 179 | [3] Out[4]: -5 |
|
180 | 180 | |
|
181 | 181 | This example also shows one of the most important things about the IPython |
|
182 | 182 | engines: they have a persistent user namespaces. The :meth:`execute` method |
|
183 | 183 | returns a Python ``dict`` that contains useful information: |
|
184 | 184 | |
|
185 | 185 | .. sourcecode:: ipython |
|
186 | 186 | |
|
187 | 187 | In [9]: result_dict = mec.execute('d=10; print d') |
|
188 | 188 | |
|
189 | 189 | In [10]: for r in result_dict: |
|
190 | 190 | ....: print r |
|
191 | 191 | ....: |
|
192 | 192 | ....: |
|
193 | 193 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 0, 'stdout': '10\n'} |
|
194 | 194 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 1, 'stdout': '10\n'} |
|
195 | 195 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 2, 'stdout': '10\n'} |
|
196 | 196 | {'input': {'translated': 'd=10; print d', 'raw': 'd=10; print d'}, 'number': 5, 'id': 3, 'stdout': '10\n'} |
|
197 | 197 | |
|
198 | 198 | Non-blocking execution |
|
199 | 199 | ---------------------- |
|
200 | 200 | |
|
201 | 201 | In non-blocking mode, :meth:`execute` submits the command to be executed and |
|
202 | 202 | then returns a :class:`PendingResult` object immediately. The |
|
203 | 203 | :class:`PendingResult` object gives you a way of getting a result at a later |
|
204 | 204 | time through its :meth:`get_result` method or :attr:`r` attribute. This allows |
|
205 | 205 | you to quickly submit long running commands without blocking your local |
|
206 | 206 | Python/IPython session: |
|
207 | 207 | |
|
208 | 208 | .. sourcecode:: ipython |
|
209 | 209 | |
|
210 | 210 | # In blocking mode |
|
211 | 211 | In [6]: mec.execute('import time') |
|
212 | 212 | Out[6]: |
|
213 | 213 | <Results List> |
|
214 | 214 | [0] In [1]: import time |
|
215 | 215 | [1] In [1]: import time |
|
216 | 216 | [2] In [1]: import time |
|
217 | 217 | [3] In [1]: import time |
|
218 | 218 | |
|
219 | 219 | # In non-blocking mode |
|
220 | 220 | In [7]: pr = mec.execute('time.sleep(10)',block=False) |
|
221 | 221 | |
|
222 | 222 | # Now block for the result |
|
223 | 223 | In [8]: pr.get_result() |
|
224 | 224 | Out[8]: |
|
225 | 225 | <Results List> |
|
226 | 226 | [0] In [2]: time.sleep(10) |
|
227 | 227 | [1] In [2]: time.sleep(10) |
|
228 | 228 | [2] In [2]: time.sleep(10) |
|
229 | 229 | [3] In [2]: time.sleep(10) |
|
230 | 230 | |
|
231 | 231 | # Again in non-blocking mode |
|
232 | 232 | In [9]: pr = mec.execute('time.sleep(10)',block=False) |
|
233 | 233 | |
|
234 | 234 | # Poll to see if the result is ready |
|
235 | 235 | In [10]: pr.get_result(block=False) |
|
236 | 236 | |
|
237 | 237 | # A shorthand for get_result(block=True) |
|
238 | 238 | In [11]: pr.r |
|
239 | 239 | Out[11]: |
|
240 | 240 | <Results List> |
|
241 | 241 | [0] In [3]: time.sleep(10) |
|
242 | 242 | [1] In [3]: time.sleep(10) |
|
243 | 243 | [2] In [3]: time.sleep(10) |
|
244 | 244 | [3] In [3]: time.sleep(10) |
|
245 | 245 | |
|
246 | 246 | Often, it is desirable to wait until a set of :class:`PendingResult` objects |
|
247 | 247 | are done. For this, there is a the method :meth:`barrier`. This method takes a |
|
248 | 248 | tuple of :class:`PendingResult` objects and blocks until all of the associated |
|
249 | 249 | results are ready: |
|
250 | 250 | |
|
251 | 251 | .. sourcecode:: ipython |
|
252 | 252 | |
|
253 | 253 | In [72]: mec.block=False |
|
254 | 254 | |
|
255 | 255 | # A trivial list of PendingResults objects |
|
256 | 256 | In [73]: pr_list = [mec.execute('time.sleep(3)') for i in range(10)] |
|
257 | 257 | |
|
258 | 258 | # Wait until all of them are done |
|
259 | 259 | In [74]: mec.barrier(pr_list) |
|
260 | 260 | |
|
261 | 261 | # Then, their results are ready using get_result or the r attribute |
|
262 | 262 | In [75]: pr_list[0].r |
|
263 | 263 | Out[75]: |
|
264 | 264 | <Results List> |
|
265 | 265 | [0] In [20]: time.sleep(3) |
|
266 | 266 | [1] In [19]: time.sleep(3) |
|
267 | 267 | [2] In [20]: time.sleep(3) |
|
268 | 268 | [3] In [19]: time.sleep(3) |
|
269 | 269 | |
|
270 | 270 | |
|
271 | 271 | The ``block`` and ``targets`` keyword arguments and attributes |
|
272 | 272 | -------------------------------------------------------------- |
|
273 | 273 | |
|
274 | 274 | Most methods in the multiengine interface (like :meth:`execute`) accept |
|
275 | 275 | ``block`` and ``targets`` as keyword arguments. As we have seen above, these |
|
276 | 276 | keyword arguments control the blocking mode and which engines the command is |
|
277 | 277 | applied to. The :class:`MultiEngineClient` class also has :attr:`block` and |
|
278 | 278 | :attr:`targets` attributes that control the default behavior when the keyword |
|
279 | 279 | arguments are not provided. Thus the following logic is used for :attr:`block` |
|
280 | 280 | and :attr:`targets`: |
|
281 | 281 | |
|
282 | 282 | * If no keyword argument is provided, the instance attributes are used. |
|
283 | 283 | * Keyword argument, if provided override the instance attributes. |
|
284 | 284 | |
|
285 | 285 | The following examples demonstrate how to use the instance attributes: |
|
286 | 286 | |
|
287 | 287 | .. sourcecode:: ipython |
|
288 | 288 | |
|
289 | 289 | In [16]: mec.targets = [0,2] |
|
290 | 290 | |
|
291 | 291 | In [17]: mec.block = False |
|
292 | 292 | |
|
293 | 293 | In [18]: pr = mec.execute('a=5') |
|
294 | 294 | |
|
295 | 295 | In [19]: pr.r |
|
296 | 296 | Out[19]: |
|
297 | 297 | <Results List> |
|
298 | 298 | [0] In [6]: a=5 |
|
299 | 299 | [2] In [6]: a=5 |
|
300 | 300 | |
|
301 | 301 | # Note targets='all' means all engines |
|
302 | 302 | In [20]: mec.targets = 'all' |
|
303 | 303 | |
|
304 | 304 | In [21]: mec.block = True |
|
305 | 305 | |
|
306 | 306 | In [22]: mec.execute('b=10; print b') |
|
307 | 307 | Out[22]: |
|
308 | 308 | <Results List> |
|
309 | 309 | [0] In [7]: b=10; print b |
|
310 | 310 | [0] Out[7]: 10 |
|
311 | 311 | |
|
312 | 312 | [1] In [6]: b=10; print b |
|
313 | 313 | [1] Out[6]: 10 |
|
314 | 314 | |
|
315 | 315 | [2] In [7]: b=10; print b |
|
316 | 316 | [2] Out[7]: 10 |
|
317 | 317 | |
|
318 | 318 | [3] In [6]: b=10; print b |
|
319 | 319 | [3] Out[6]: 10 |
|
320 | 320 | |
|
321 | 321 | The :attr:`block` and :attr:`targets` instance attributes also determine the |
|
322 | 322 | behavior of the parallel magic commands. |
|
323 | 323 | |
|
324 | 324 | |
|
325 | 325 | Parallel magic commands |
|
326 | 326 | ----------------------- |
|
327 | 327 | |
|
328 | 328 | We provide a few IPython magic commands (``%px``, ``%autopx`` and ``%result``) |
|
329 | 329 | that make it more pleasant to execute Python commands on the engines |
|
330 | 330 | interactively. These are simply shortcuts to :meth:`execute` and |
|
331 | 331 | :meth:`get_result`. The ``%px`` magic executes a single Python command on the |
|
332 | 332 | engines specified by the :attr:`targets` attribute of the |
|
333 | 333 | :class:`MultiEngineClient` instance (by default this is ``'all'``): |
|
334 | 334 | |
|
335 | 335 | .. sourcecode:: ipython |
|
336 | 336 | |
|
337 | 337 | # Make this MultiEngineClient active for parallel magic commands |
|
338 | 338 | In [23]: mec.activate() |
|
339 | 339 | |
|
340 | 340 | In [24]: mec.block=True |
|
341 | 341 | |
|
342 | 342 | In [25]: import numpy |
|
343 | 343 | |
|
344 | 344 | In [26]: %px import numpy |
|
345 | 345 | Executing command on Controller |
|
346 | 346 | Out[26]: |
|
347 | 347 | <Results List> |
|
348 | 348 | [0] In [8]: import numpy |
|
349 | 349 | [1] In [7]: import numpy |
|
350 | 350 | [2] In [8]: import numpy |
|
351 | 351 | [3] In [7]: import numpy |
|
352 | 352 | |
|
353 | 353 | |
|
354 | 354 | In [27]: %px a = numpy.random.rand(2,2) |
|
355 | 355 | Executing command on Controller |
|
356 | 356 | Out[27]: |
|
357 | 357 | <Results List> |
|
358 | 358 | [0] In [9]: a = numpy.random.rand(2,2) |
|
359 | 359 | [1] In [8]: a = numpy.random.rand(2,2) |
|
360 | 360 | [2] In [9]: a = numpy.random.rand(2,2) |
|
361 | 361 | [3] In [8]: a = numpy.random.rand(2,2) |
|
362 | 362 | |
|
363 | 363 | |
|
364 | 364 | In [28]: %px print numpy.linalg.eigvals(a) |
|
365 | 365 | Executing command on Controller |
|
366 | 366 | Out[28]: |
|
367 | 367 | <Results List> |
|
368 | 368 | [0] In [10]: print numpy.linalg.eigvals(a) |
|
369 | 369 | [0] Out[10]: [ 1.28167017 0.14197338] |
|
370 | 370 | |
|
371 | 371 | [1] In [9]: print numpy.linalg.eigvals(a) |
|
372 | 372 | [1] Out[9]: [-0.14093616 1.27877273] |
|
373 | 373 | |
|
374 | 374 | [2] In [10]: print numpy.linalg.eigvals(a) |
|
375 | 375 | [2] Out[10]: [-0.37023573 1.06779409] |
|
376 | 376 | |
|
377 | 377 | [3] In [9]: print numpy.linalg.eigvals(a) |
|
378 | 378 | [3] Out[9]: [ 0.83664764 -0.25602658] |
|
379 | 379 | |
|
380 | 380 | The ``%result`` magic gets and prints the stdin/stdout/stderr of the last |
|
381 | 381 | command executed on each engine. It is simply a shortcut to the |
|
382 | 382 | :meth:`get_result` method: |
|
383 | 383 | |
|
384 | 384 | .. sourcecode:: ipython |
|
385 | 385 | |
|
386 | 386 | In [29]: %result |
|
387 | 387 | Out[29]: |
|
388 | 388 | <Results List> |
|
389 | 389 | [0] In [10]: print numpy.linalg.eigvals(a) |
|
390 | 390 | [0] Out[10]: [ 1.28167017 0.14197338] |
|
391 | 391 | |
|
392 | 392 | [1] In [9]: print numpy.linalg.eigvals(a) |
|
393 | 393 | [1] Out[9]: [-0.14093616 1.27877273] |
|
394 | 394 | |
|
395 | 395 | [2] In [10]: print numpy.linalg.eigvals(a) |
|
396 | 396 | [2] Out[10]: [-0.37023573 1.06779409] |
|
397 | 397 | |
|
398 | 398 | [3] In [9]: print numpy.linalg.eigvals(a) |
|
399 | 399 | [3] Out[9]: [ 0.83664764 -0.25602658] |
|
400 | 400 | |
|
401 | 401 | The ``%autopx`` magic switches to a mode where everything you type is executed |
|
402 | 402 | on the engines given by the :attr:`targets` attribute: |
|
403 | 403 | |
|
404 | 404 | .. sourcecode:: ipython |
|
405 | 405 | |
|
406 | 406 | In [30]: mec.block=False |
|
407 | 407 | |
|
408 | 408 | In [31]: %autopx |
|
409 | 409 | Auto Parallel Enabled |
|
410 | 410 | Type %autopx to disable |
|
411 | 411 | |
|
412 | 412 | In [32]: max_evals = [] |
|
413 | 413 | <IPython.kernel.multiengineclient.PendingResult object at 0x17b8a70> |
|
414 | 414 | |
|
415 | 415 | In [33]: for i in range(100): |
|
416 | 416 | ....: a = numpy.random.rand(10,10) |
|
417 | 417 | ....: a = a+a.transpose() |
|
418 | 418 | ....: evals = numpy.linalg.eigvals(a) |
|
419 | 419 | ....: max_evals.append(evals[0].real) |
|
420 | 420 | ....: |
|
421 | 421 | ....: |
|
422 | 422 | <IPython.kernel.multiengineclient.PendingResult object at 0x17af8f0> |
|
423 | 423 | |
|
424 | 424 | In [34]: %autopx |
|
425 | 425 | Auto Parallel Disabled |
|
426 | 426 | |
|
427 | 427 | In [35]: mec.block=True |
|
428 | 428 | |
|
429 | 429 | In [36]: px print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
430 | 430 | Executing command on Controller |
|
431 | 431 | Out[36]: |
|
432 | 432 | <Results List> |
|
433 | 433 | [0] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
434 | 434 | [0] Out[13]: Average max eigenvalue is: 10.1387247332 |
|
435 | 435 | |
|
436 | 436 | [1] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
437 | 437 | [1] Out[12]: Average max eigenvalue is: 10.2076902286 |
|
438 | 438 | |
|
439 | 439 | [2] In [13]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
440 | 440 | [2] Out[13]: Average max eigenvalue is: 10.1891484655 |
|
441 | 441 | |
|
442 | 442 | [3] In [12]: print "Average max eigenvalue is: ", sum(max_evals)/len(max_evals) |
|
443 | 443 | [3] Out[12]: Average max eigenvalue is: 10.1158837784 |
|
444 | 444 | |
|
445 | 445 | |
|
446 | 446 | Moving Python objects around |
|
447 | 447 | ============================ |
|
448 | 448 | |
|
449 | 449 | In addition to executing code on engines, you can transfer Python objects to |
|
450 | 450 | and from your IPython session and the engines. In IPython, these operations |
|
451 | 451 | are called :meth:`push` (sending an object to the engines) and :meth:`pull` |
|
452 | 452 | (getting an object from the engines). |
|
453 | 453 | |
|
454 | 454 | Basic push and pull |
|
455 | 455 | ------------------- |
|
456 | 456 | |
|
457 | 457 | Here are some examples of how you use :meth:`push` and :meth:`pull`: |
|
458 | 458 | |
|
459 | 459 | .. sourcecode:: ipython |
|
460 | 460 | |
|
461 | 461 | In [38]: mec.push(dict(a=1.03234,b=3453)) |
|
462 | 462 | Out[38]: [None, None, None, None] |
|
463 | 463 | |
|
464 | 464 | In [39]: mec.pull('a') |
|
465 | 465 | Out[39]: [1.03234, 1.03234, 1.03234, 1.03234] |
|
466 | 466 | |
|
467 | 467 | In [40]: mec.pull('b',targets=0) |
|
468 | 468 | Out[40]: [3453] |
|
469 | 469 | |
|
470 | 470 | In [41]: mec.pull(('a','b')) |
|
471 | 471 | Out[41]: [[1.03234, 3453], [1.03234, 3453], [1.03234, 3453], [1.03234, 3453]] |
|
472 | 472 | |
|
473 | 473 | In [42]: mec.zip_pull(('a','b')) |
|
474 | 474 | Out[42]: [(1.03234, 1.03234, 1.03234, 1.03234), (3453, 3453, 3453, 3453)] |
|
475 | 475 | |
|
476 | 476 | In [43]: mec.push(dict(c='speed')) |
|
477 | 477 | Out[43]: [None, None, None, None] |
|
478 | 478 | |
|
479 | 479 | In [44]: %px print c |
|
480 | 480 | Executing command on Controller |
|
481 | 481 | Out[44]: |
|
482 | 482 | <Results List> |
|
483 | 483 | [0] In [14]: print c |
|
484 | 484 | [0] Out[14]: speed |
|
485 | 485 | |
|
486 | 486 | [1] In [13]: print c |
|
487 | 487 | [1] Out[13]: speed |
|
488 | 488 | |
|
489 | 489 | [2] In [14]: print c |
|
490 | 490 | [2] Out[14]: speed |
|
491 | 491 | |
|
492 | 492 | [3] In [13]: print c |
|
493 | 493 | [3] Out[13]: speed |
|
494 | 494 | |
|
495 | 495 | In non-blocking mode :meth:`push` and :meth:`pull` also return |
|
496 | 496 | :class:`PendingResult` objects: |
|
497 | 497 | |
|
498 | 498 | .. sourcecode:: ipython |
|
499 | 499 | |
|
500 | 500 | In [47]: mec.block=False |
|
501 | 501 | |
|
502 | 502 | In [48]: pr = mec.pull('a') |
|
503 | 503 | |
|
504 | 504 | In [49]: pr.r |
|
505 | 505 | Out[49]: [1.03234, 1.03234, 1.03234, 1.03234] |
|
506 | 506 | |
|
507 | 507 | |
|
508 | 508 | Push and pull for functions |
|
509 | 509 | --------------------------- |
|
510 | 510 | |
|
511 | 511 | Functions can also be pushed and pulled using :meth:`push_function` and |
|
512 | 512 | :meth:`pull_function`: |
|
513 | 513 | |
|
514 | 514 | .. sourcecode:: ipython |
|
515 | 515 | |
|
516 | 516 | In [52]: mec.block=True |
|
517 | 517 | |
|
518 | 518 | In [53]: def f(x): |
|
519 | 519 | ....: return 2.0*x**4 |
|
520 | 520 | ....: |
|
521 | 521 | |
|
522 | 522 | In [54]: mec.push_function(dict(f=f)) |
|
523 | 523 | Out[54]: [None, None, None, None] |
|
524 | 524 | |
|
525 | 525 | In [55]: mec.execute('y = f(4.0)') |
|
526 | 526 | Out[55]: |
|
527 | 527 | <Results List> |
|
528 | 528 | [0] In [15]: y = f(4.0) |
|
529 | 529 | [1] In [14]: y = f(4.0) |
|
530 | 530 | [2] In [15]: y = f(4.0) |
|
531 | 531 | [3] In [14]: y = f(4.0) |
|
532 | 532 | |
|
533 | 533 | |
|
534 | 534 | In [56]: px print y |
|
535 | 535 | Executing command on Controller |
|
536 | 536 | Out[56]: |
|
537 | 537 | <Results List> |
|
538 | 538 | [0] In [16]: print y |
|
539 | 539 | [0] Out[16]: 512.0 |
|
540 | 540 | |
|
541 | 541 | [1] In [15]: print y |
|
542 | 542 | [1] Out[15]: 512.0 |
|
543 | 543 | |
|
544 | 544 | [2] In [16]: print y |
|
545 | 545 | [2] Out[16]: 512.0 |
|
546 | 546 | |
|
547 | 547 | [3] In [15]: print y |
|
548 | 548 | [3] Out[15]: 512.0 |
|
549 | 549 | |
|
550 | 550 | |
|
551 | 551 | Dictionary interface |
|
552 | 552 | -------------------- |
|
553 | 553 | |
|
554 | 554 | As a shorthand to :meth:`push` and :meth:`pull`, the |
|
555 | 555 | :class:`MultiEngineClient` class implements some of the Python dictionary |
|
556 | 556 | interface. This make the remote namespaces of the engines appear as a local |
|
557 | 557 | dictionary. Underneath, this uses :meth:`push` and :meth:`pull`: |
|
558 | 558 | |
|
559 | 559 | .. sourcecode:: ipython |
|
560 | 560 | |
|
561 | 561 | In [50]: mec.block=True |
|
562 | 562 | |
|
563 | 563 | In [51]: mec['a']=['foo','bar'] |
|
564 | 564 | |
|
565 | 565 | In [52]: mec['a'] |
|
566 | 566 | Out[52]: [['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar']] |
|
567 | 567 | |
|
568 | 568 | Scatter and gather |
|
569 | 569 | ------------------ |
|
570 | 570 | |
|
571 | 571 | Sometimes it is useful to partition a sequence and push the partitions to |
|
572 | 572 | different engines. In MPI language, this is know as scatter/gather and we |
|
573 | 573 | follow that terminology. However, it is important to remember that in |
|
574 | 574 | IPython's :class:`MultiEngineClient` class, :meth:`scatter` is from the |
|
575 | 575 | interactive IPython session to the engines and :meth:`gather` is from the |
|
576 | 576 | engines back to the interactive IPython session. For scatter/gather operations |
|
577 | 577 | between engines, MPI should be used: |
|
578 | 578 | |
|
579 | 579 | .. sourcecode:: ipython |
|
580 | 580 | |
|
581 | 581 | In [58]: mec.scatter('a',range(16)) |
|
582 | 582 | Out[58]: [None, None, None, None] |
|
583 | 583 | |
|
584 | 584 | In [59]: px print a |
|
585 | 585 | Executing command on Controller |
|
586 | 586 | Out[59]: |
|
587 | 587 | <Results List> |
|
588 | 588 | [0] In [17]: print a |
|
589 | 589 | [0] Out[17]: [0, 1, 2, 3] |
|
590 | 590 | |
|
591 | 591 | [1] In [16]: print a |
|
592 | 592 | [1] Out[16]: [4, 5, 6, 7] |
|
593 | 593 | |
|
594 | 594 | [2] In [17]: print a |
|
595 | 595 | [2] Out[17]: [8, 9, 10, 11] |
|
596 | 596 | |
|
597 | 597 | [3] In [16]: print a |
|
598 | 598 | [3] Out[16]: [12, 13, 14, 15] |
|
599 | 599 | |
|
600 | 600 | |
|
601 | 601 | In [60]: mec.gather('a') |
|
602 | 602 | Out[60]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] |
|
603 | 603 | |
|
604 | 604 | Other things to look at |
|
605 | 605 | ======================= |
|
606 | 606 | |
|
607 | 607 | How to do parallel list comprehensions |
|
608 | 608 | -------------------------------------- |
|
609 | 609 | |
|
610 | 610 | In many cases list comprehensions are nicer than using the map function. While |
|
611 | 611 | we don't have fully parallel list comprehensions, it is simple to get the |
|
612 | 612 | basic effect using :meth:`scatter` and :meth:`gather`: |
|
613 | 613 | |
|
614 | 614 | .. sourcecode:: ipython |
|
615 | 615 | |
|
616 | 616 | In [66]: mec.scatter('x',range(64)) |
|
617 | 617 | Out[66]: [None, None, None, None] |
|
618 | 618 | |
|
619 | 619 | In [67]: px y = [i**10 for i in x] |
|
620 | 620 | Executing command on Controller |
|
621 | 621 | Out[67]: |
|
622 | 622 | <Results List> |
|
623 | 623 | [0] In [19]: y = [i**10 for i in x] |
|
624 | 624 | [1] In [18]: y = [i**10 for i in x] |
|
625 | 625 | [2] In [19]: y = [i**10 for i in x] |
|
626 | 626 | [3] In [18]: y = [i**10 for i in x] |
|
627 | 627 | |
|
628 | 628 | |
|
629 | 629 | In [68]: y = mec.gather('y') |
|
630 | 630 | |
|
631 | 631 | In [69]: print y |
|
632 | 632 | [0, 1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824,...] |
|
633 | 633 | |
|
634 | 634 | Parallel exceptions |
|
635 | 635 | ------------------- |
|
636 | 636 | |
|
637 | 637 | In the multiengine interface, parallel commands can raise Python exceptions, |
|
638 | 638 | just like serial commands. But, it is a little subtle, because a single |
|
639 | 639 | parallel command can actually raise multiple exceptions (one for each engine |
|
640 | 640 | the command was run on). To express this idea, the MultiEngine interface has a |
|
641 | 641 | :exc:`CompositeError` exception class that will be raised in most cases. The |
|
642 | 642 | :exc:`CompositeError` class is a special type of exception that wraps one or |
|
643 | 643 | more other types of exceptions. Here is how it works: |
|
644 | 644 | |
|
645 | 645 | .. sourcecode:: ipython |
|
646 | 646 | |
|
647 | 647 | In [76]: mec.block=True |
|
648 | 648 | |
|
649 | 649 | In [77]: mec.execute('1/0') |
|
650 | 650 | --------------------------------------------------------------------------- |
|
651 | 651 | CompositeError Traceback (most recent call last) |
|
652 | 652 | |
|
653 | 653 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
654 | 654 | |
|
655 | 655 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) |
|
656 | 656 | 432 targets, block = self._findTargetsAndBlock(targets, block) |
|
657 | 657 | 433 result = blockingCallFromThread(self.smultiengine.execute, lines, |
|
658 | 658 | --> 434 targets=targets, block=block) |
|
659 | 659 | 435 if block: |
|
660 | 660 | 436 result = ResultList(result) |
|
661 | 661 | |
|
662 | 662 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) |
|
663 | 663 | 72 result.raiseException() |
|
664 | 664 | 73 except Exception, e: |
|
665 | 665 | ---> 74 raise e |
|
666 | 666 | 75 return result |
|
667 | 667 | 76 |
|
668 | 668 | |
|
669 | 669 | CompositeError: one or more exceptions from call to method: execute |
|
670 | 670 | [0:execute]: ZeroDivisionError: integer division or modulo by zero |
|
671 | 671 | [1:execute]: ZeroDivisionError: integer division or modulo by zero |
|
672 | 672 | [2:execute]: ZeroDivisionError: integer division or modulo by zero |
|
673 | 673 | [3:execute]: ZeroDivisionError: integer division or modulo by zero |
|
674 | 674 | |
|
675 | 675 | Notice how the error message printed when :exc:`CompositeError` is raised has |
|
676 | 676 | information about the individual exceptions that were raised on each engine. |
|
677 | 677 | If you want, you can even raise one of these original exceptions: |
|
678 | 678 | |
|
679 | 679 | .. sourcecode:: ipython |
|
680 | 680 | |
|
681 | 681 | In [80]: try: |
|
682 | 682 | ....: mec.execute('1/0') |
|
683 | 683 | ....: except client.CompositeError, e: |
|
684 | 684 | ....: e.raise_exception() |
|
685 | 685 | ....: |
|
686 | 686 | ....: |
|
687 | 687 | --------------------------------------------------------------------------- |
|
688 | 688 | ZeroDivisionError Traceback (most recent call last) |
|
689 | 689 | |
|
690 | 690 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
691 | 691 | |
|
692 | 692 | /ipython1-client-r3021/ipython1/kernel/error.pyc in raise_exception(self, excid) |
|
693 | 693 | 156 raise IndexError("an exception with index %i does not exist"%excid) |
|
694 | 694 | 157 else: |
|
695 | 695 | --> 158 raise et, ev, etb |
|
696 | 696 | 159 |
|
697 | 697 | 160 def collect_exceptions(rlist, method): |
|
698 | 698 | |
|
699 | 699 | ZeroDivisionError: integer division or modulo by zero |
|
700 | 700 | |
|
701 | 701 | If you are working in IPython, you can simple type ``%debug`` after one of |
|
702 | 702 | these :exc:`CompositeError` exceptions is raised, and inspect the exception |
|
703 | 703 | instance: |
|
704 | 704 | |
|
705 | 705 | .. sourcecode:: ipython |
|
706 | 706 | |
|
707 | 707 | In [81]: mec.execute('1/0') |
|
708 | 708 | --------------------------------------------------------------------------- |
|
709 | 709 | CompositeError Traceback (most recent call last) |
|
710 | 710 | |
|
711 | 711 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
712 | 712 | |
|
713 | 713 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in execute(self, lines, targets, block) |
|
714 | 714 | 432 targets, block = self._findTargetsAndBlock(targets, block) |
|
715 | 715 | 433 result = blockingCallFromThread(self.smultiengine.execute, lines, |
|
716 | 716 | --> 434 targets=targets, block=block) |
|
717 | 717 | 435 if block: |
|
718 | 718 | 436 result = ResultList(result) |
|
719 | 719 | |
|
720 | 720 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) |
|
721 | 721 | 72 result.raiseException() |
|
722 | 722 | 73 except Exception, e: |
|
723 | 723 | ---> 74 raise e |
|
724 | 724 | 75 return result |
|
725 | 725 | 76 |
|
726 | 726 | |
|
727 | 727 | CompositeError: one or more exceptions from call to method: execute |
|
728 | 728 | [0:execute]: ZeroDivisionError: integer division or modulo by zero |
|
729 | 729 | [1:execute]: ZeroDivisionError: integer division or modulo by zero |
|
730 | 730 | [2:execute]: ZeroDivisionError: integer division or modulo by zero |
|
731 | 731 | [3:execute]: ZeroDivisionError: integer division or modulo by zero |
|
732 | 732 | |
|
733 | 733 | In [82]: %debug |
|
734 | 734 | > |
|
735 | 735 | |
|
736 | 736 | /ipython1-client-r3021/ipython1/kernel/twistedutil.py(74)blockingCallFromThread() |
|
737 | 737 | 73 except Exception, e: |
|
738 | 738 | ---> 74 raise e |
|
739 | 739 | 75 return result |
|
740 | 740 | |
|
741 | 741 | # With the debugger running, e is the exceptions instance. We can tab complete |
|
742 | 742 | # on it and see the extra methods that are available. |
|
743 | 743 | ipdb> e. |
|
744 | 744 | e.__class__ e.__getitem__ e.__new__ e.__setstate__ e.args |
|
745 | 745 | e.__delattr__ e.__getslice__ e.__reduce__ e.__str__ e.elist |
|
746 | 746 | e.__dict__ e.__hash__ e.__reduce_ex__ e.__weakref__ e.message |
|
747 | 747 | e.__doc__ e.__init__ e.__repr__ e._get_engine_str e.print_tracebacks |
|
748 | 748 | e.__getattribute__ e.__module__ e.__setattr__ e._get_traceback e.raise_exception |
|
749 | 749 | ipdb> e.print_tracebacks() |
|
750 | 750 | [0:execute]: |
|
751 | 751 | --------------------------------------------------------------------------- |
|
752 | 752 | ZeroDivisionError Traceback (most recent call last) |
|
753 | 753 | |
|
754 | 754 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
755 | 755 | |
|
756 | 756 | ZeroDivisionError: integer division or modulo by zero |
|
757 | 757 | |
|
758 | 758 | [1:execute]: |
|
759 | 759 | --------------------------------------------------------------------------- |
|
760 | 760 | ZeroDivisionError Traceback (most recent call last) |
|
761 | 761 | |
|
762 | 762 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
763 | 763 | |
|
764 | 764 | ZeroDivisionError: integer division or modulo by zero |
|
765 | 765 | |
|
766 | 766 | [2:execute]: |
|
767 | 767 | --------------------------------------------------------------------------- |
|
768 | 768 | ZeroDivisionError Traceback (most recent call last) |
|
769 | 769 | |
|
770 | 770 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
771 | 771 | |
|
772 | 772 | ZeroDivisionError: integer division or modulo by zero |
|
773 | 773 | |
|
774 | 774 | [3:execute]: |
|
775 | 775 | --------------------------------------------------------------------------- |
|
776 | 776 | ZeroDivisionError Traceback (most recent call last) |
|
777 | 777 | |
|
778 | 778 | /ipython1-client-r3021/docs/examples/<string> in <module>() |
|
779 | 779 | |
|
780 | 780 | ZeroDivisionError: integer division or modulo by zero |
|
781 | 781 | |
|
782 | 782 | .. note:: |
|
783 | 783 | |
|
784 | 784 | The above example appears to be broken right now because of a change in |
|
785 | 785 | how we are using Twisted. |
|
786 | 786 | |
|
787 | 787 | All of this same error handling magic even works in non-blocking mode: |
|
788 | 788 | |
|
789 | 789 | .. sourcecode:: ipython |
|
790 | 790 | |
|
791 | 791 | In [83]: mec.block=False |
|
792 | 792 | |
|
793 | 793 | In [84]: pr = mec.execute('1/0') |
|
794 | 794 | |
|
795 | 795 | In [85]: pr.r |
|
796 | 796 | --------------------------------------------------------------------------- |
|
797 | 797 | CompositeError Traceback (most recent call last) |
|
798 | 798 | |
|
799 | 799 | /ipython1-client-r3021/docs/examples/<ipython console> in <module>() |
|
800 | 800 | |
|
801 | 801 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in _get_r(self) |
|
802 | 802 | 170 |
|
803 | 803 | 171 def _get_r(self): |
|
804 | 804 | --> 172 return self.get_result(block=True) |
|
805 | 805 | 173 |
|
806 | 806 | 174 r = property(_get_r) |
|
807 | 807 | |
|
808 | 808 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_result(self, default, block) |
|
809 | 809 | 131 return self.result |
|
810 | 810 | 132 try: |
|
811 | 811 | --> 133 result = self.client.get_pending_deferred(self.result_id, block) |
|
812 | 812 | 134 except error.ResultNotCompleted: |
|
813 | 813 | 135 return default |
|
814 | 814 | |
|
815 | 815 | /ipython1-client-r3021/ipython1/kernel/multiengineclient.pyc in get_pending_deferred(self, deferredID, block) |
|
816 | 816 | 385 |
|
817 | 817 | 386 def get_pending_deferred(self, deferredID, block): |
|
818 | 818 | --> 387 return blockingCallFromThread(self.smultiengine.get_pending_deferred, deferredID, block) |
|
819 | 819 | 388 |
|
820 | 820 | 389 def barrier(self, pendingResults): |
|
821 | 821 | |
|
822 | 822 | /ipython1-client-r3021/ipython1/kernel/twistedutil.pyc in blockingCallFromThread(f, *a, **kw) |
|
823 | 823 | 72 result.raiseException() |
|
824 | 824 | 73 except Exception, e: |
|
825 | 825 | ---> 74 raise e |
|
826 | 826 | 75 return result |
|
827 | 827 | 76 |
|
828 | 828 | |
|
829 | 829 | CompositeError: one or more exceptions from call to method: execute |
|
830 | 830 | [0:execute]: ZeroDivisionError: integer division or modulo by zero |
|
831 | 831 | [1:execute]: ZeroDivisionError: integer division or modulo by zero |
|
832 | 832 | [2:execute]: ZeroDivisionError: integer division or modulo by zero |
|
833 | 833 | [3:execute]: ZeroDivisionError: integer division or modulo by zero |
|
834 | 834 | |
|
835 | 835 |
@@ -1,389 +1,389 b'' | |||
|
1 | 1 | .. _parallel_process: |
|
2 | 2 | |
|
3 | 3 | =========================================== |
|
4 | 4 | Starting the IPython controller and engines |
|
5 | 5 | =========================================== |
|
6 | 6 | |
|
7 | 7 | To use IPython for parallel computing, you need to start one instance of |
|
8 | 8 | the controller and one or more instances of the engine. The controller |
|
9 | 9 | and each engine can run on different machines or on the same machine. |
|
10 | 10 | Because of this, there are many different possibilities. |
|
11 | 11 | |
|
12 | 12 | Broadly speaking, there are two ways of going about starting a controller and engines: |
|
13 | 13 | |
|
14 | 14 | * In an automated manner using the :command:`ipcluster` command. |
|
15 | 15 | * In a more manual way using the :command:`ipcontroller` and |
|
16 | 16 | :command:`ipengine` commands. |
|
17 | 17 | |
|
18 | 18 | This document describes both of these methods. We recommend that new users |
|
19 | 19 | start with the :command:`ipcluster` command as it simplifies many common usage |
|
20 | 20 | cases. |
|
21 | 21 | |
|
22 | 22 | General considerations |
|
23 | 23 | ====================== |
|
24 | 24 | |
|
25 | 25 | Before delving into the details about how you can start a controller and |
|
26 | 26 | engines using the various methods, we outline some of the general issues that |
|
27 | 27 | come up when starting the controller and engines. These things come up no |
|
28 | 28 | matter which method you use to start your IPython cluster. |
|
29 | 29 | |
|
30 | 30 | Let's say that you want to start the controller on ``host0`` and engines on |
|
31 | 31 | hosts ``host1``-``hostn``. The following steps are then required: |
|
32 | 32 | |
|
33 | 33 | 1. Start the controller on ``host0`` by running :command:`ipcontroller` on |
|
34 | 34 | ``host0``. |
|
35 | 35 | 2. Move the FURL file (:file:`ipcontroller-engine.furl`) created by the |
|
36 | 36 | controller from ``host0`` to hosts ``host1``-``hostn``. |
|
37 | 37 | 3. Start the engines on hosts ``host1``-``hostn`` by running |
|
38 | 38 | :command:`ipengine`. This command has to be told where the FURL file |
|
39 | 39 | (:file:`ipcontroller-engine.furl`) is located. |
|
40 | 40 | |
|
41 | 41 | At this point, the controller and engines will be connected. By default, the |
|
42 | 42 | FURL files created by the controller are put into the |
|
43 |
:file:` |
|
|
43 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory. If the engines share a filesystem with | |
|
44 | 44 | the controller, step 2 can be skipped as the engines will automatically look |
|
45 | 45 | at that location. |
|
46 | 46 | |
|
47 | 47 | The final step required required to actually use the running controller from a |
|
48 | 48 | client is to move the FURL files :file:`ipcontroller-mec.furl` and |
|
49 | 49 | :file:`ipcontroller-tc.furl` from ``host0`` to the host where the clients will |
|
50 |
be run. If these file are put into the :file:` |
|
|
50 | be run. If these file are put into the :file:`$IPYTHON_DIR/cluster_<profile>/security` directory | |
|
51 | 51 | of the client's host, they will be found automatically. Otherwise, the full |
|
52 | 52 | path to them has to be passed to the client's constructor. |
|
53 | 53 | |
|
54 | 54 | Using :command:`ipcluster` |
|
55 | 55 | ========================== |
|
56 | 56 | |
|
57 | 57 | The :command:`ipcluster` command provides a simple way of starting a |
|
58 | 58 | controller and engines in the following situations: |
|
59 | 59 | |
|
60 | 60 | 1. When the controller and engines are all run on localhost. This is useful |
|
61 | 61 | for testing or running on a multicore computer. |
|
62 | 62 | 2. When engines are started using the :command:`mpirun` command that comes |
|
63 | 63 | with most MPI [MPI]_ implementations |
|
64 | 64 | 3. When engines are started using the PBS [PBS]_ batch system. |
|
65 | 65 | 4. When the controller is started on localhost and the engines are started on |
|
66 | 66 | remote nodes using :command:`ssh`. |
|
67 | 67 | |
|
68 | 68 | .. note:: |
|
69 | 69 | |
|
70 | 70 | It is also possible for advanced users to add support to |
|
71 | 71 | :command:`ipcluster` for starting controllers and engines using other |
|
72 | 72 | methods (like Sun's Grid Engine for example). |
|
73 | 73 | |
|
74 | 74 | .. note:: |
|
75 | 75 | |
|
76 | 76 | Currently :command:`ipcluster` requires that the |
|
77 |
:file:` |
|
|
77 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory live on a shared filesystem that is | |
|
78 | 78 | seen by both the controller and engines. If you don't have a shared file |
|
79 | 79 | system you will need to use :command:`ipcontroller` and |
|
80 | 80 | :command:`ipengine` directly. This constraint can be relaxed if you are |
|
81 | 81 | using the :command:`ssh` method to start the cluster. |
|
82 | 82 | |
|
83 | 83 | Underneath the hood, :command:`ipcluster` just uses :command:`ipcontroller` |
|
84 | 84 | and :command:`ipengine` to perform the steps described above. |
|
85 | 85 | |
|
86 | 86 | Using :command:`ipcluster` in local mode |
|
87 | 87 | ---------------------------------------- |
|
88 | 88 | |
|
89 | 89 | To start one controller and 4 engines on localhost, just do:: |
|
90 | 90 | |
|
91 | 91 | $ ipcluster local -n 4 |
|
92 | 92 | |
|
93 | 93 | To see other command line options for the local mode, do:: |
|
94 | 94 | |
|
95 | 95 | $ ipcluster local -h |
|
96 | 96 | |
|
97 | 97 | Using :command:`ipcluster` in mpiexec/mpirun mode |
|
98 | 98 | ------------------------------------------------- |
|
99 | 99 | |
|
100 | 100 | The mpiexec/mpirun mode is useful if you: |
|
101 | 101 | |
|
102 | 102 | 1. Have MPI installed. |
|
103 | 103 | 2. Your systems are configured to use the :command:`mpiexec` or |
|
104 | 104 | :command:`mpirun` commands to start MPI processes. |
|
105 | 105 | |
|
106 | 106 | .. note:: |
|
107 | 107 | |
|
108 | 108 | The preferred command to use is :command:`mpiexec`. However, we also |
|
109 | 109 | support :command:`mpirun` for backwards compatibility. The underlying |
|
110 | 110 | logic used is exactly the same, the only difference being the name of the |
|
111 | 111 | command line program that is called. |
|
112 | 112 | |
|
113 | 113 | If these are satisfied, you can start an IPython cluster using:: |
|
114 | 114 | |
|
115 | 115 | $ ipcluster mpiexec -n 4 |
|
116 | 116 | |
|
117 | 117 | This does the following: |
|
118 | 118 | |
|
119 | 119 | 1. Starts the IPython controller on current host. |
|
120 | 120 | 2. Uses :command:`mpiexec` to start 4 engines. |
|
121 | 121 | |
|
122 | 122 | On newer MPI implementations (such as OpenMPI), this will work even if you |
|
123 | 123 | don't make any calls to MPI or call :func:`MPI_Init`. However, older MPI |
|
124 | 124 | implementations actually require each process to call :func:`MPI_Init` upon |
|
125 | 125 | starting. The easiest way of having this done is to install the mpi4py |
|
126 | 126 | [mpi4py]_ package and then call ipcluster with the ``--mpi`` option:: |
|
127 | 127 | |
|
128 | 128 | $ ipcluster mpiexec -n 4 --mpi=mpi4py |
|
129 | 129 | |
|
130 | 130 | Unfortunately, even this won't work for some MPI implementations. If you are |
|
131 | 131 | having problems with this, you will likely have to use a custom Python |
|
132 | 132 | executable that itself calls :func:`MPI_Init` at the appropriate time. |
|
133 | 133 | Fortunately, mpi4py comes with such a custom Python executable that is easy to |
|
134 | 134 | install and use. However, this custom Python executable approach will not work |
|
135 | 135 | with :command:`ipcluster` currently. |
|
136 | 136 | |
|
137 | 137 | Additional command line options for this mode can be found by doing:: |
|
138 | 138 | |
|
139 | 139 | $ ipcluster mpiexec -h |
|
140 | 140 | |
|
141 | 141 | More details on using MPI with IPython can be found :ref:`here <parallelmpi>`. |
|
142 | 142 | |
|
143 | 143 | |
|
144 | 144 | Using :command:`ipcluster` in PBS mode |
|
145 | 145 | -------------------------------------- |
|
146 | 146 | |
|
147 | 147 | The PBS mode uses the Portable Batch System [PBS]_ to start the engines. To |
|
148 | 148 | use this mode, you first need to create a PBS script template that will be |
|
149 | 149 | used to start the engines. Here is a sample PBS script template: |
|
150 | 150 | |
|
151 | 151 | .. sourcecode:: bash |
|
152 | 152 | |
|
153 | 153 | #PBS -N ipython |
|
154 | 154 | #PBS -j oe |
|
155 | 155 | #PBS -l walltime=00:10:00 |
|
156 | 156 | #PBS -l nodes=${n/4}:ppn=4 |
|
157 | 157 | #PBS -q parallel |
|
158 | 158 | |
|
159 | 159 | cd $$PBS_O_WORKDIR |
|
160 | 160 | export PATH=$$HOME/usr/local/bin |
|
161 | 161 | export PYTHONPATH=$$HOME/usr/local/lib/python2.4/site-packages |
|
162 | 162 | /usr/local/bin/mpiexec -n ${n} ipengine --logfile=$$PBS_O_WORKDIR/ipengine |
|
163 | 163 | |
|
164 | 164 | There are a few important points about this template: |
|
165 | 165 | |
|
166 | 166 | 1. This template will be rendered at runtime using IPython's :mod:`Itpl` |
|
167 | 167 | template engine. |
|
168 | 168 | |
|
169 | 169 | 2. Instead of putting in the actual number of engines, use the notation |
|
170 | 170 | ``${n}`` to indicate the number of engines to be started. You can also uses |
|
171 | 171 | expressions like ``${n/4}`` in the template to indicate the number of |
|
172 | 172 | nodes. |
|
173 | 173 | |
|
174 | 174 | 3. Because ``$`` is a special character used by the template engine, you must |
|
175 | 175 | escape any ``$`` by using ``$$``. This is important when referring to |
|
176 | 176 | environment variables in the template. |
|
177 | 177 | |
|
178 | 178 | 4. Any options to :command:`ipengine` should be given in the batch script |
|
179 | 179 | template. |
|
180 | 180 | |
|
181 | 181 | 5. Depending on the configuration of you system, you may have to set |
|
182 | 182 | environment variables in the script template. |
|
183 | 183 | |
|
184 | 184 | Once you have created such a script, save it with a name like |
|
185 | 185 | :file:`pbs.template`. Now you are ready to start your job:: |
|
186 | 186 | |
|
187 | 187 | $ ipcluster pbs -n 128 --pbs-script=pbs.template |
|
188 | 188 | |
|
189 | 189 | Additional command line options for this mode can be found by doing:: |
|
190 | 190 | |
|
191 | 191 | $ ipcluster pbs -h |
|
192 | 192 | |
|
193 | 193 | Using :command:`ipcluster` in SSH mode |
|
194 | 194 | -------------------------------------- |
|
195 | 195 | |
|
196 | 196 | The SSH mode uses :command:`ssh` to execute :command:`ipengine` on remote |
|
197 | 197 | nodes and the :command:`ipcontroller` on localhost. |
|
198 | 198 | |
|
199 | 199 | When using using this mode it highly recommended that you have set up SSH keys |
|
200 | 200 | and are using ssh-agent [SSH]_ for password-less logins. |
|
201 | 201 | |
|
202 | 202 | To use this mode you need a python file describing the cluster, here is an |
|
203 | 203 | example of such a "clusterfile": |
|
204 | 204 | |
|
205 | 205 | .. sourcecode:: python |
|
206 | 206 | |
|
207 | 207 | send_furl = True |
|
208 | 208 | engines = { 'host1.example.com' : 2, |
|
209 | 209 | 'host2.example.com' : 5, |
|
210 | 210 | 'host3.example.com' : 1, |
|
211 | 211 | 'host4.example.com' : 8 } |
|
212 | 212 | |
|
213 | 213 | Since this is a regular python file usual python syntax applies. Things to |
|
214 | 214 | note: |
|
215 | 215 | |
|
216 | 216 | * The `engines` dict, where the keys is the host we want to run engines on and |
|
217 | 217 | the value is the number of engines to run on that host. |
|
218 | 218 | * send_furl can either be `True` or `False`, if `True` it will copy over the |
|
219 | 219 | furl needed for :command:`ipengine` to each host. |
|
220 | 220 | |
|
221 | 221 | The ``--clusterfile`` command line option lets you specify the file to use for |
|
222 | 222 | the cluster definition. Once you have your cluster file and you can |
|
223 | 223 | :command:`ssh` into the remote hosts with out an password you are ready to |
|
224 | 224 | start your cluster like so: |
|
225 | 225 | |
|
226 | 226 | .. sourcecode:: bash |
|
227 | 227 | |
|
228 | 228 | $ ipcluster ssh --clusterfile /path/to/my/clusterfile.py |
|
229 | 229 | |
|
230 | 230 | |
|
231 | 231 | Two helper shell scripts are used to start and stop :command:`ipengine` on |
|
232 | 232 | remote hosts: |
|
233 | 233 | |
|
234 | 234 | * sshx.sh |
|
235 | 235 | * engine_killer.sh |
|
236 | 236 | |
|
237 | 237 | Defaults for both of these are contained in the source code for |
|
238 | 238 | :command:`ipcluster`. The default scripts are written to a local file in a |
|
239 | 239 | tmep directory and then copied to a temp directory on the remote host and |
|
240 | 240 | executed from there. On most Unix, Linux and OS X systems this is /tmp. |
|
241 | 241 | |
|
242 | 242 | The default sshx.sh is the following: |
|
243 | 243 | |
|
244 | 244 | .. sourcecode:: bash |
|
245 | 245 | |
|
246 | 246 | #!/bin/sh |
|
247 | 247 | "$@" &> /dev/null & |
|
248 | 248 | echo $! |
|
249 | 249 | |
|
250 | 250 | If you want to use a custom sshx.sh script you need to use the ``--sshx`` |
|
251 | 251 | option and specify the file to use. Using a custom sshx.sh file could be |
|
252 | 252 | helpful when you need to setup the environment on the remote host before |
|
253 | 253 | executing :command:`ipengine`. |
|
254 | 254 | |
|
255 | 255 | For a detailed options list: |
|
256 | 256 | |
|
257 | 257 | .. sourcecode:: bash |
|
258 | 258 | |
|
259 | 259 | $ ipcluster ssh -h |
|
260 | 260 | |
|
261 | 261 | Current limitations of the SSH mode of :command:`ipcluster` are: |
|
262 | 262 | |
|
263 | 263 | * Untested on Windows. Would require a working :command:`ssh` on Windows. |
|
264 | 264 | Also, we are using shell scripts to setup and execute commands on remote |
|
265 | 265 | hosts. |
|
266 | 266 | * :command:`ipcontroller` is started on localhost, with no option to start it |
|
267 | 267 | on a remote node. |
|
268 | 268 | |
|
269 | 269 | Using the :command:`ipcontroller` and :command:`ipengine` commands |
|
270 | 270 | ================================================================== |
|
271 | 271 | |
|
272 | 272 | It is also possible to use the :command:`ipcontroller` and :command:`ipengine` |
|
273 | 273 | commands to start your controller and engines. This approach gives you full |
|
274 | 274 | control over all aspects of the startup process. |
|
275 | 275 | |
|
276 | 276 | Starting the controller and engine on your local machine |
|
277 | 277 | -------------------------------------------------------- |
|
278 | 278 | |
|
279 | 279 | To use :command:`ipcontroller` and :command:`ipengine` to start things on your |
|
280 | 280 | local machine, do the following. |
|
281 | 281 | |
|
282 | 282 | First start the controller:: |
|
283 | 283 | |
|
284 | 284 | $ ipcontroller |
|
285 | 285 | |
|
286 | 286 | Next, start however many instances of the engine you want using (repeatedly) |
|
287 | 287 | the command:: |
|
288 | 288 | |
|
289 | 289 | $ ipengine |
|
290 | 290 | |
|
291 | 291 | The engines should start and automatically connect to the controller using the |
|
292 |
FURL files in :file:` |
|
|
292 | FURL files in :file:`$IPYTHON_DIR/cluster_<profile>/security`. You are now ready to use the | |
|
293 | 293 | controller and engines from IPython. |
|
294 | 294 | |
|
295 | 295 | .. warning:: |
|
296 | 296 | |
|
297 | 297 | The order of the above operations is very important. You *must* |
|
298 | 298 | start the controller before the engines, since the engines connect |
|
299 | 299 | to the controller as they get started. |
|
300 | 300 | |
|
301 | 301 | .. note:: |
|
302 | 302 | |
|
303 | 303 | On some platforms (OS X), to put the controller and engine into the |
|
304 | 304 | background you may need to give these commands in the form ``(ipcontroller |
|
305 | 305 | &)`` and ``(ipengine &)`` (with the parentheses) for them to work |
|
306 | 306 | properly. |
|
307 | 307 | |
|
308 | 308 | Starting the controller and engines on different hosts |
|
309 | 309 | ------------------------------------------------------ |
|
310 | 310 | |
|
311 | 311 | When the controller and engines are running on different hosts, things are |
|
312 | 312 | slightly more complicated, but the underlying ideas are the same: |
|
313 | 313 | |
|
314 | 314 | 1. Start the controller on a host using :command:`ipcontroller`. |
|
315 |
2. Copy :file:`ipcontroller-engine.furl` from :file:` |
|
|
315 | 2. Copy :file:`ipcontroller-engine.furl` from :file:`$IPYTHON_DIR/cluster_<profile>/security` on | |
|
316 | 316 | the controller's host to the host where the engines will run. |
|
317 | 317 | 3. Use :command:`ipengine` on the engine's hosts to start the engines. |
|
318 | 318 | |
|
319 | 319 | The only thing you have to be careful of is to tell :command:`ipengine` where |
|
320 | 320 | the :file:`ipcontroller-engine.furl` file is located. There are two ways you |
|
321 | 321 | can do this: |
|
322 | 322 | |
|
323 |
* Put :file:`ipcontroller-engine.furl` in the :file:` |
|
|
323 | * Put :file:`ipcontroller-engine.furl` in the :file:`$IPYTHON_DIR/cluster_<profile>/security` | |
|
324 | 324 | directory on the engine's host, where it will be found automatically. |
|
325 | 325 | * Call :command:`ipengine` with the ``--furl-file=full_path_to_the_file`` |
|
326 | 326 | flag. |
|
327 | 327 | |
|
328 | 328 | The ``--furl-file`` flag works like this:: |
|
329 | 329 | |
|
330 | 330 | $ ipengine --furl-file=/path/to/my/ipcontroller-engine.furl |
|
331 | 331 | |
|
332 | 332 | .. note:: |
|
333 | 333 | |
|
334 | 334 | If the controller's and engine's hosts all have a shared file system |
|
335 |
(:file:` |
|
|
335 | (:file:`$IPYTHON_DIR/cluster_<profile>/security` is the same on all of them), then things | |
|
336 | 336 | will just work! |
|
337 | 337 | |
|
338 | 338 | Make FURL files persistent |
|
339 | 339 | --------------------------- |
|
340 | 340 | |
|
341 | 341 | At fist glance it may seem that that managing the FURL files is a bit |
|
342 | 342 | annoying. Going back to the house and key analogy, copying the FURL around |
|
343 | 343 | each time you start the controller is like having to make a new key every time |
|
344 | 344 | you want to unlock the door and enter your house. As with your house, you want |
|
345 | 345 | to be able to create the key (or FURL file) once, and then simply use it at |
|
346 | 346 | any point in the future. |
|
347 | 347 | |
|
348 | 348 | This is possible, but before you do this, you **must** remove any old FURL |
|
349 |
files in the :file:` |
|
|
349 | files in the :file:`$IPYTHON_DIR/cluster_<profile>/security` directory. | |
|
350 | 350 | |
|
351 | 351 | .. warning:: |
|
352 | 352 | |
|
353 | 353 | You **must** remove old FURL files before using persistent FURL files. |
|
354 | 354 | |
|
355 | 355 | Then, The only thing you have to do is decide what ports the controller will |
|
356 | 356 | listen on for the engines and clients. This is done as follows:: |
|
357 | 357 | |
|
358 | 358 | $ ipcontroller -r --client-port=10101 --engine-port=10102 |
|
359 | 359 | |
|
360 | 360 | These options also work with all of the various modes of |
|
361 | 361 | :command:`ipcluster`:: |
|
362 | 362 | |
|
363 | 363 | $ ipcluster local -n 2 -r --client-port=10101 --engine-port=10102 |
|
364 | 364 | |
|
365 | 365 | Then, just copy the furl files over the first time and you are set. You can |
|
366 | 366 | start and stop the controller and engines any many times as you want in the |
|
367 | 367 | future, just make sure to tell the controller to use the *same* ports. |
|
368 | 368 | |
|
369 | 369 | .. note:: |
|
370 | 370 | |
|
371 | 371 | You may ask the question: what ports does the controller listen on if you |
|
372 | 372 | don't tell is to use specific ones? The default is to use high random port |
|
373 | 373 | numbers. We do this for two reasons: i) to increase security through |
|
374 | 374 | obscurity and ii) to multiple controllers on a given host to start and |
|
375 | 375 | automatically use different ports. |
|
376 | 376 | |
|
377 | 377 | Log files |
|
378 | 378 | --------- |
|
379 | 379 | |
|
380 | 380 | All of the components of IPython have log files associated with them. |
|
381 | 381 | These log files can be extremely useful in debugging problems with |
|
382 |
IPython and can be found in the directory :file:` |
|
|
382 | IPython and can be found in the directory :file:`$IPYTHON_DIR/cluster_<profile>/log`. Sending | |
|
383 | 383 | the log files to us will often help us to debug any problems. |
|
384 | 384 | |
|
385 | 385 | |
|
386 | 386 | .. [PBS] Portable Batch System. http://www.openpbs.org/ |
|
387 | 387 | .. [SSH] SSH-Agent http://en.wikipedia.org/wiki/Ssh-agent |
|
388 | 388 | |
|
389 | 389 |
@@ -1,366 +1,366 b'' | |||
|
1 | 1 | .. _parallelsecurity: |
|
2 | 2 | |
|
3 | 3 | =========================== |
|
4 | 4 | Security details of IPython |
|
5 | 5 | =========================== |
|
6 | 6 | |
|
7 | 7 | IPython's :mod:`IPython.kernel` package exposes the full power of the Python |
|
8 | 8 | interpreter over a TCP/IP network for the purposes of parallel computing. This |
|
9 | 9 | feature brings up the important question of IPython's security model. This |
|
10 | 10 | document gives details about this model and how it is implemented in IPython's |
|
11 | 11 | architecture. |
|
12 | 12 | |
|
13 | 13 | Processs and network topology |
|
14 | 14 | ============================= |
|
15 | 15 | |
|
16 | 16 | To enable parallel computing, IPython has a number of different processes that |
|
17 | 17 | run. These processes are discussed at length in the IPython documentation and |
|
18 | 18 | are summarized here: |
|
19 | 19 | |
|
20 | 20 | * The IPython *engine*. This process is a full blown Python |
|
21 | 21 | interpreter in which user code is executed. Multiple |
|
22 | 22 | engines are started to make parallel computing possible. |
|
23 | 23 | * The IPython *controller*. This process manages a set of |
|
24 | 24 | engines, maintaining a queue for each and presenting |
|
25 | 25 | an asynchronous interface to the set of engines. |
|
26 | 26 | * The IPython *client*. This process is typically an |
|
27 | 27 | interactive Python process that is used to coordinate the |
|
28 | 28 | engines to get a parallel computation done. |
|
29 | 29 | |
|
30 | 30 | Collectively, these three processes are called the IPython *kernel*. |
|
31 | 31 | |
|
32 | 32 | These three processes communicate over TCP/IP connections with a well defined |
|
33 | 33 | topology. The IPython controller is the only process that listens on TCP/IP |
|
34 | 34 | sockets. Upon starting, an engine connects to a controller and registers |
|
35 | 35 | itself with the controller. These engine/controller TCP/IP connections persist |
|
36 | 36 | for the lifetime of each engine. |
|
37 | 37 | |
|
38 | 38 | The IPython client also connects to the controller using one or more TCP/IP |
|
39 | 39 | connections. These connections persist for the lifetime of the client only. |
|
40 | 40 | |
|
41 | 41 | A given IPython controller and set of engines typically has a relatively short |
|
42 | 42 | lifetime. Typically this lifetime corresponds to the duration of a single |
|
43 | 43 | parallel simulation performed by a single user. Finally, the controller, |
|
44 | 44 | engines and client processes typically execute with the permissions of that |
|
45 | 45 | same user. More specifically, the controller and engines are *not* executed as |
|
46 | 46 | root or with any other superuser permissions. |
|
47 | 47 | |
|
48 | 48 | Application logic |
|
49 | 49 | ================= |
|
50 | 50 | |
|
51 | 51 | When running the IPython kernel to perform a parallel computation, a user |
|
52 | 52 | utilizes the IPython client to send Python commands and data through the |
|
53 | 53 | IPython controller to the IPython engines, where those commands are executed |
|
54 | 54 | and the data processed. The design of IPython ensures that the client is the |
|
55 | 55 | only access point for the capabilities of the engines. That is, the only way |
|
56 | 56 | of addressing the engines is through a client. |
|
57 | 57 | |
|
58 | 58 | A user can utilize the client to instruct the IPython engines to execute |
|
59 | 59 | arbitrary Python commands. These Python commands can include calls to the |
|
60 | 60 | system shell, access the filesystem, etc., as required by the user's |
|
61 | 61 | application code. From this perspective, when a user runs an IPython engine on |
|
62 | 62 | a host, that engine has the same capabilities and permissions as the user |
|
63 | 63 | themselves (as if they were logged onto the engine's host with a terminal). |
|
64 | 64 | |
|
65 | 65 | Secure network connections |
|
66 | 66 | ========================== |
|
67 | 67 | |
|
68 | 68 | Overview |
|
69 | 69 | -------- |
|
70 | 70 | |
|
71 | 71 | All TCP/IP connections between the client and controller as well as the |
|
72 | 72 | engines and controller are fully encrypted and authenticated. This section |
|
73 | 73 | describes the details of the encryption and authentication approached used |
|
74 | 74 | within IPython. |
|
75 | 75 | |
|
76 | 76 | IPython uses the Foolscap network protocol [Foolscap]_ for all communications |
|
77 | 77 | between processes. Thus, the details of IPython's security model are directly |
|
78 | 78 | related to those of Foolscap. Thus, much of the following discussion is |
|
79 | 79 | actually just a discussion of the security that is built in to Foolscap. |
|
80 | 80 | |
|
81 | 81 | Encryption |
|
82 | 82 | ---------- |
|
83 | 83 | |
|
84 | 84 | For encryption purposes, IPython and Foolscap use the well known Secure Socket |
|
85 | 85 | Layer (SSL) protocol [RFC5246]_. We use the implementation of this protocol |
|
86 | 86 | provided by the OpenSSL project through the pyOpenSSL [pyOpenSSL]_ Python |
|
87 | 87 | bindings to OpenSSL. |
|
88 | 88 | |
|
89 | 89 | Authentication |
|
90 | 90 | -------------- |
|
91 | 91 | |
|
92 | 92 | IPython clients and engines must also authenticate themselves with the |
|
93 | 93 | controller. This is handled in a capabilities based security model |
|
94 | 94 | [Capability]_. In this model, the controller creates a strong cryptographic |
|
95 | 95 | key or token that represents each set of capability that the controller |
|
96 | 96 | offers. Any party who has this key and presents it to the controller has full |
|
97 | 97 | access to the corresponding capabilities of the controller. This model is |
|
98 | 98 | analogous to using a physical key to gain access to physical items |
|
99 | 99 | (capabilities) behind a locked door. |
|
100 | 100 | |
|
101 | 101 | For a capabilities based authentication system to prevent unauthorized access, |
|
102 | 102 | two things must be ensured: |
|
103 | 103 | |
|
104 | 104 | * The keys must be cryptographically strong. Otherwise attackers could gain |
|
105 | 105 | access by a simple brute force key guessing attack. |
|
106 | 106 | * The actual keys must be distributed only to authorized parties. |
|
107 | 107 | |
|
108 | 108 | The keys in Foolscap are called Foolscap URL's or FURLs. The following section |
|
109 | 109 | gives details about how these FURLs are created in Foolscap. The IPython |
|
110 | 110 | controller creates a number of FURLs for different purposes: |
|
111 | 111 | |
|
112 | 112 | * One FURL that grants IPython engines access to the controller. Also |
|
113 | 113 | implicit in this access is permission to execute code sent by an |
|
114 | 114 | authenticated IPython client. |
|
115 | 115 | * Two or more FURLs that grant IPython clients access to the controller. |
|
116 | 116 | Implicit in this access is permission to give the controller's engine code |
|
117 | 117 | to execute. |
|
118 | 118 | |
|
119 | 119 | Upon starting, the controller creates these different FURLS and writes them |
|
120 |
files in the user-read-only directory :file:`$ |
|
|
120 | files in the user-read-only directory :file:`$IPYTHON_DIR/cluster_default/security`. Thus, | |
|
121 | 121 | only the user who starts the controller has access to the FURLs. |
|
122 | 122 | |
|
123 | 123 | For an IPython client or engine to authenticate with a controller, it must |
|
124 | 124 | present the appropriate FURL to the controller upon connecting. If the |
|
125 | 125 | FURL matches what the controller expects for a given capability, access is |
|
126 | 126 | granted. If not, access is denied. The exchange of FURLs is done after |
|
127 | 127 | encrypted communications channels have been established to prevent attackers |
|
128 | 128 | from capturing them. |
|
129 | 129 | |
|
130 | 130 | .. note:: |
|
131 | 131 | |
|
132 | 132 | The FURL is similar to an unsigned private key in SSH. |
|
133 | 133 | |
|
134 | 134 | Details of the Foolscap handshake |
|
135 | 135 | --------------------------------- |
|
136 | 136 | |
|
137 | 137 | In this section we detail the precise security handshake that takes place at |
|
138 | 138 | the beginning of any network connection in IPython. For the purposes of this |
|
139 | 139 | discussion, the SERVER is the IPython controller process and the CLIENT is the |
|
140 | 140 | IPython engine or client process. |
|
141 | 141 | |
|
142 | 142 | Upon starting, all IPython processes do the following: |
|
143 | 143 | |
|
144 | 144 | 1. Create a public key x509 certificate (ISO/IEC 9594). |
|
145 | 145 | 2. Create a hash of the contents of the certificate using the SHA-1 algorithm. |
|
146 | 146 | The base-32 encoded version of this hash is saved by the process as its |
|
147 | 147 | process id (actually in Foolscap, this is the Tub id, but here refer to |
|
148 | 148 | it as the process id). |
|
149 | 149 | |
|
150 | 150 | Upon starting, the IPython controller also does the following: |
|
151 | 151 | |
|
152 | 152 | 1. Save the x509 certificate to disk in a secure location. The CLIENT |
|
153 | 153 | certificate is never saved to disk. |
|
154 | 154 | 2. Create a FURL for each capability that the controller has. There are |
|
155 | 155 | separate capabilities the controller offers for clients and engines. The |
|
156 | 156 | FURL is created using: a) the process id of the SERVER, b) the IP |
|
157 | 157 | address and port the SERVER is listening on and c) a 160 bit, |
|
158 | 158 | cryptographically secure string that represents the capability (the |
|
159 | 159 | "capability id"). |
|
160 | 160 | 3. The FURLs are saved to disk in a secure location on the SERVER's host. |
|
161 | 161 | |
|
162 | 162 | For a CLIENT to be able to connect to the SERVER and access a capability of |
|
163 | 163 | that SERVER, the CLIENT must have knowledge of the FURL for that SERVER's |
|
164 | 164 | capability. This typically requires that the file containing the FURL be |
|
165 | 165 | moved from the SERVER's host to the CLIENT's host. This is done by the end |
|
166 | 166 | user who started the SERVER and wishes to have a CLIENT connect to the SERVER. |
|
167 | 167 | |
|
168 | 168 | When a CLIENT connects to the SERVER, the following handshake protocol takes |
|
169 | 169 | place: |
|
170 | 170 | |
|
171 | 171 | 1. The CLIENT tells the SERVER what process (or Tub) id it expects the SERVER |
|
172 | 172 | to have. |
|
173 | 173 | 2. If the SERVER has that process id, it notifies the CLIENT that it will now |
|
174 | 174 | enter encrypted mode. If the SERVER has a different id, the SERVER aborts. |
|
175 | 175 | 3. Both CLIENT and SERVER initiate the SSL handshake protocol. |
|
176 | 176 | 4. Both CLIENT and SERVER request the certificate of their peer and verify |
|
177 | 177 | that certificate. If this succeeds, all further communications are |
|
178 | 178 | encrypted. |
|
179 | 179 | 5. Both CLIENT and SERVER send a hello block containing connection parameters |
|
180 | 180 | and their process id. |
|
181 | 181 | 6. The CLIENT and SERVER check that their peer's stated process id matches the |
|
182 | 182 | hash of the x509 certificate the peer presented. If not, the connection is |
|
183 | 183 | aborted. |
|
184 | 184 | 7. The CLIENT verifies that the SERVER's stated id matches the id of the |
|
185 | 185 | SERVER the CLIENT is intending to connect to. If not, the connection is |
|
186 | 186 | aborted. |
|
187 | 187 | 8. The CLIENT and SERVER elect a master who decides on the final connection |
|
188 | 188 | parameters. |
|
189 | 189 | |
|
190 | 190 | The public/private key pair associated with each process's x509 certificate |
|
191 | 191 | are completely hidden from this handshake protocol. There are however, used |
|
192 | 192 | internally by OpenSSL as part of the SSL handshake protocol. Each process |
|
193 | 193 | keeps their own private key hidden and sends its peer only the public key |
|
194 | 194 | (embedded in the certificate). |
|
195 | 195 | |
|
196 | 196 | Finally, when the CLIENT requests access to a particular SERVER capability, |
|
197 | 197 | the following happens: |
|
198 | 198 | |
|
199 | 199 | 1. The CLIENT asks the SERVER for access to a capability by presenting that |
|
200 | 200 | capabilities id. |
|
201 | 201 | 2. If the SERVER has a capability with that id, access is granted. If not, |
|
202 | 202 | access is not granted. |
|
203 | 203 | 3. Once access has been gained, the CLIENT can use the capability. |
|
204 | 204 | |
|
205 | 205 | Specific security vulnerabilities |
|
206 | 206 | ================================= |
|
207 | 207 | |
|
208 | 208 | There are a number of potential security vulnerabilities present in IPython's |
|
209 | 209 | architecture. In this section we discuss those vulnerabilities and detail how |
|
210 | 210 | the security architecture described above prevents them from being exploited. |
|
211 | 211 | |
|
212 | 212 | Unauthorized clients |
|
213 | 213 | -------------------- |
|
214 | 214 | |
|
215 | 215 | The IPython client can instruct the IPython engines to execute arbitrary |
|
216 | 216 | Python code with the permissions of the user who started the engines. If an |
|
217 | 217 | attacker were able to connect their own hostile IPython client to the IPython |
|
218 | 218 | controller, they could instruct the engines to execute code. |
|
219 | 219 | |
|
220 | 220 | This attack is prevented by the capabilities based client authentication |
|
221 | 221 | performed after the encrypted channel has been established. The relevant |
|
222 | 222 | authentication information is encoded into the FURL that clients must |
|
223 | 223 | present to gain access to the IPython controller. By limiting the distribution |
|
224 | 224 | of those FURLs, a user can grant access to only authorized persons. |
|
225 | 225 | |
|
226 | 226 | It is highly unlikely that a client FURL could be guessed by an attacker |
|
227 | 227 | in a brute force guessing attack. A given instance of the IPython controller |
|
228 | 228 | only runs for a relatively short amount of time (on the order of hours). Thus |
|
229 | 229 | an attacker would have only a limited amount of time to test a search space of |
|
230 | 230 | size 2**320. Furthermore, even if a controller were to run for a longer amount |
|
231 | 231 | of time, this search space is quite large (larger for instance than that of |
|
232 | 232 | typical username/password pair). |
|
233 | 233 | |
|
234 | 234 | Unauthorized engines |
|
235 | 235 | -------------------- |
|
236 | 236 | |
|
237 | 237 | If an attacker were able to connect a hostile engine to a user's controller, |
|
238 | 238 | the user might unknowingly send sensitive code or data to the hostile engine. |
|
239 | 239 | This attacker's engine would then have full access to that code and data. |
|
240 | 240 | |
|
241 | 241 | This type of attack is prevented in the same way as the unauthorized client |
|
242 | 242 | attack, through the usage of the capabilities based authentication scheme. |
|
243 | 243 | |
|
244 | 244 | Unauthorized controllers |
|
245 | 245 | ------------------------ |
|
246 | 246 | |
|
247 | 247 | It is also possible that an attacker could try to convince a user's IPython |
|
248 | 248 | client or engine to connect to a hostile IPython controller. That controller |
|
249 | 249 | would then have full access to the code and data sent between the IPython |
|
250 | 250 | client and the IPython engines. |
|
251 | 251 | |
|
252 | 252 | Again, this attack is prevented through the FURLs, which ensure that a |
|
253 | 253 | client or engine connects to the correct controller. It is also important to |
|
254 | 254 | note that the FURLs also encode the IP address and port that the |
|
255 | 255 | controller is listening on, so there is little chance of mistakenly connecting |
|
256 | 256 | to a controller running on a different IP address and port. |
|
257 | 257 | |
|
258 | 258 | When starting an engine or client, a user must specify which FURL to use |
|
259 | 259 | for that connection. Thus, in order to introduce a hostile controller, the |
|
260 | 260 | attacker must convince the user to use the FURLs associated with the |
|
261 | 261 | hostile controller. As long as a user is diligent in only using FURLs from |
|
262 | 262 | trusted sources, this attack is not possible. |
|
263 | 263 | |
|
264 | 264 | Other security measures |
|
265 | 265 | ======================= |
|
266 | 266 | |
|
267 | 267 | A number of other measures are taken to further limit the security risks |
|
268 | 268 | involved in running the IPython kernel. |
|
269 | 269 | |
|
270 | 270 | First, by default, the IPython controller listens on random port numbers. |
|
271 | 271 | While this can be overridden by the user, in the default configuration, an |
|
272 | 272 | attacker would have to do a port scan to even find a controller to attack. |
|
273 | 273 | When coupled with the relatively short running time of a typical controller |
|
274 | 274 | (on the order of hours), an attacker would have to work extremely hard and |
|
275 | 275 | extremely *fast* to even find a running controller to attack. |
|
276 | 276 | |
|
277 | 277 | Second, much of the time, especially when run on supercomputers or clusters, |
|
278 | 278 | the controller is running behind a firewall. Thus, for engines or client to |
|
279 | 279 | connect to the controller: |
|
280 | 280 | |
|
281 | 281 | * The different processes have to all be behind the firewall. |
|
282 | 282 | |
|
283 | 283 | or: |
|
284 | 284 | |
|
285 | 285 | * The user has to use SSH port forwarding to tunnel the |
|
286 | 286 | connections through the firewall. |
|
287 | 287 | |
|
288 | 288 | In either case, an attacker is presented with addition barriers that prevent |
|
289 | 289 | attacking or even probing the system. |
|
290 | 290 | |
|
291 | 291 | Summary |
|
292 | 292 | ======= |
|
293 | 293 | |
|
294 | 294 | IPython's architecture has been carefully designed with security in mind. The |
|
295 | 295 | capabilities based authentication model, in conjunction with the encrypted |
|
296 | 296 | TCP/IP channels, address the core potential vulnerabilities in the system, |
|
297 | 297 | while still enabling user's to use the system in open networks. |
|
298 | 298 | |
|
299 | 299 | Other questions |
|
300 | 300 | =============== |
|
301 | 301 | |
|
302 | 302 | About keys |
|
303 | 303 | ---------- |
|
304 | 304 | |
|
305 | 305 | Can you clarify the roles of the certificate and its keys versus the FURL, |
|
306 | 306 | which is also called a key? |
|
307 | 307 | |
|
308 | 308 | The certificate created by IPython processes is a standard public key x509 |
|
309 | 309 | certificate, that is used by the SSL handshake protocol to setup encrypted |
|
310 | 310 | channel between the controller and the IPython engine or client. This public |
|
311 | 311 | and private key associated with this certificate are used only by the SSL |
|
312 | 312 | handshake protocol in setting up this encrypted channel. |
|
313 | 313 | |
|
314 | 314 | The FURL serves a completely different and independent purpose from the |
|
315 | 315 | key pair associated with the certificate. When we refer to a FURL as a |
|
316 | 316 | key, we are using the word "key" in the capabilities based security model |
|
317 | 317 | sense. This has nothing to do with "key" in the public/private key sense used |
|
318 | 318 | in the SSL protocol. |
|
319 | 319 | |
|
320 | 320 | With that said the FURL is used as an cryptographic key, to grant |
|
321 | 321 | IPython engines and clients access to particular capabilities that the |
|
322 | 322 | controller offers. |
|
323 | 323 | |
|
324 | 324 | Self signed certificates |
|
325 | 325 | ------------------------ |
|
326 | 326 | |
|
327 | 327 | Is the controller creating a self-signed certificate? Is this created for per |
|
328 | 328 | instance/session, one-time-setup or each-time the controller is started? |
|
329 | 329 | |
|
330 | 330 | The Foolscap network protocol, which handles the SSL protocol details, creates |
|
331 | 331 | a self-signed x509 certificate using OpenSSL for each IPython process. The |
|
332 | 332 | lifetime of the certificate is handled differently for the IPython controller |
|
333 | 333 | and the engines/client. |
|
334 | 334 | |
|
335 | 335 | For the IPython engines and client, the certificate is only held in memory for |
|
336 | 336 | the lifetime of its process. It is never written to disk. |
|
337 | 337 | |
|
338 | 338 | For the controller, the certificate can be created anew each time the |
|
339 | 339 | controller starts or it can be created once and reused each time the |
|
340 | 340 | controller starts. If at any point, the certificate is deleted, a new one is |
|
341 | 341 | created the next time the controller starts. |
|
342 | 342 | |
|
343 | 343 | SSL private key |
|
344 | 344 | --------------- |
|
345 | 345 | |
|
346 | 346 | How the private key (associated with the certificate) is distributed? |
|
347 | 347 | |
|
348 | 348 | In the usual implementation of the SSL protocol, the private key is never |
|
349 | 349 | distributed. We follow this standard always. |
|
350 | 350 | |
|
351 | 351 | SSL versus Foolscap authentication |
|
352 | 352 | ---------------------------------- |
|
353 | 353 | |
|
354 | 354 | Many SSL connections only perform one sided authentication (the server to the |
|
355 | 355 | client). How is the client authentication in IPython's system related to SSL |
|
356 | 356 | authentication? |
|
357 | 357 | |
|
358 | 358 | We perform a two way SSL handshake in which both parties request and verify |
|
359 | 359 | the certificate of their peer. This mutual authentication is handled by the |
|
360 | 360 | SSL handshake and is separate and independent from the additional |
|
361 | 361 | authentication steps that the CLIENT and SERVER perform after an encrypted |
|
362 | 362 | channel is established. |
|
363 | 363 | |
|
364 | 364 | .. [RFC5246] <http://tools.ietf.org/html/rfc5246> |
|
365 | 365 | |
|
366 | 366 |
@@ -1,121 +1,121 b'' | |||
|
1 | 1 | .. _paralleltask: |
|
2 | 2 | |
|
3 | 3 | ========================== |
|
4 | 4 | The IPython task interface |
|
5 | 5 | ========================== |
|
6 | 6 | |
|
7 | 7 | The task interface to the controller presents the engines as a fault tolerant, |
|
8 | 8 | dynamic load-balanced system or workers. Unlike the multiengine interface, in |
|
9 | 9 | the task interface, the user have no direct access to individual engines. In |
|
10 | 10 | some ways, this interface is simpler, but in other ways it is more powerful. |
|
11 | 11 | |
|
12 | 12 | Best of all the user can use both of these interfaces running at the same time |
|
13 | 13 | to take advantage or both of their strengths. When the user can break up the |
|
14 | 14 | user's work into segments that do not depend on previous execution, the task |
|
15 | 15 | interface is ideal. But it also has more power and flexibility, allowing the |
|
16 | 16 | user to guide the distribution of jobs, without having to assign tasks to |
|
17 | 17 | engines explicitly. |
|
18 | 18 | |
|
19 | 19 | Starting the IPython controller and engines |
|
20 | 20 | =========================================== |
|
21 | 21 | |
|
22 | 22 | To follow along with this tutorial, you will need to start the IPython |
|
23 | 23 | controller and four IPython engines. The simplest way of doing this is to use |
|
24 | 24 | the :command:`ipcluster` command:: |
|
25 | 25 | |
|
26 | 26 | $ ipcluster local -n 4 |
|
27 | 27 | |
|
28 | 28 | For more detailed information about starting the controller and engines, see |
|
29 | 29 | our :ref:`introduction <ip1par>` to using IPython for parallel computing. |
|
30 | 30 | |
|
31 | 31 | Creating a ``TaskClient`` instance |
|
32 | 32 | ========================================= |
|
33 | 33 | |
|
34 | 34 | The first step is to import the IPython :mod:`IPython.kernel.client` module |
|
35 | 35 | and then create a :class:`TaskClient` instance: |
|
36 | 36 | |
|
37 | 37 | .. sourcecode:: ipython |
|
38 | 38 | |
|
39 | 39 | In [1]: from IPython.kernel import client |
|
40 | 40 | |
|
41 | 41 | In [2]: tc = client.TaskClient() |
|
42 | 42 | |
|
43 | 43 | This form assumes that the :file:`ipcontroller-tc.furl` is in the |
|
44 |
:file:` |
|
|
44 | :file:`$IPYTHON_DIR/cluster_<profile>/security` directory on the client's host. If not, the | |
|
45 | 45 | location of the FURL file must be given as an argument to the |
|
46 | 46 | constructor: |
|
47 | 47 | |
|
48 | 48 | .. sourcecode:: ipython |
|
49 | 49 | |
|
50 | 50 | In [2]: mec = client.TaskClient('/path/to/my/ipcontroller-tc.furl') |
|
51 | 51 | |
|
52 | 52 | Quick and easy parallelism |
|
53 | 53 | ========================== |
|
54 | 54 | |
|
55 | 55 | In many cases, you simply want to apply a Python function to a sequence of |
|
56 | 56 | objects, but *in parallel*. Like the multiengine interface, the task interface |
|
57 | 57 | provides two simple ways of accomplishing this: a parallel version of |
|
58 | 58 | :func:`map` and ``@parallel`` function decorator. However, the verions in the |
|
59 | 59 | task interface have one important difference: they are dynamically load |
|
60 | 60 | balanced. Thus, if the execution time per item varies significantly, you |
|
61 | 61 | should use the versions in the task interface. |
|
62 | 62 | |
|
63 | 63 | Parallel map |
|
64 | 64 | ------------ |
|
65 | 65 | |
|
66 | 66 | The parallel :meth:`map` in the task interface is similar to that in the |
|
67 | 67 | multiengine interface: |
|
68 | 68 | |
|
69 | 69 | .. sourcecode:: ipython |
|
70 | 70 | |
|
71 | 71 | In [63]: serial_result = map(lambda x:x**10, range(32)) |
|
72 | 72 | |
|
73 | 73 | In [64]: parallel_result = tc.map(lambda x:x**10, range(32)) |
|
74 | 74 | |
|
75 | 75 | In [65]: serial_result==parallel_result |
|
76 | 76 | Out[65]: True |
|
77 | 77 | |
|
78 | 78 | Parallel function decorator |
|
79 | 79 | --------------------------- |
|
80 | 80 | |
|
81 | 81 | Parallel functions are just like normal function, but they can be called on |
|
82 | 82 | sequences and *in parallel*. The multiengine interface provides a decorator |
|
83 | 83 | that turns any Python function into a parallel function: |
|
84 | 84 | |
|
85 | 85 | .. sourcecode:: ipython |
|
86 | 86 | |
|
87 | 87 | In [10]: @tc.parallel() |
|
88 | 88 | ....: def f(x): |
|
89 | 89 | ....: return 10.0*x**4 |
|
90 | 90 | ....: |
|
91 | 91 | |
|
92 | 92 | In [11]: f(range(32)) # this is done in parallel |
|
93 | 93 | Out[11]: |
|
94 | 94 | [0.0,10.0,160.0,...] |
|
95 | 95 | |
|
96 | 96 | More details |
|
97 | 97 | ============ |
|
98 | 98 | |
|
99 | 99 | The :class:`TaskClient` has many more powerful features that allow quite a bit |
|
100 | 100 | of flexibility in how tasks are defined and run. The next places to look are |
|
101 | 101 | in the following classes: |
|
102 | 102 | |
|
103 | 103 | * :class:`IPython.kernel.client.TaskClient` |
|
104 | 104 | * :class:`IPython.kernel.client.StringTask` |
|
105 | 105 | * :class:`IPython.kernel.client.MapTask` |
|
106 | 106 | |
|
107 | 107 | The following is an overview of how to use these classes together: |
|
108 | 108 | |
|
109 | 109 | 1. Create a :class:`TaskClient`. |
|
110 | 110 | 2. Create one or more instances of :class:`StringTask` or :class:`MapTask` |
|
111 | 111 | to define your tasks. |
|
112 | 112 | 3. Submit your tasks to using the :meth:`run` method of your |
|
113 | 113 | :class:`TaskClient` instance. |
|
114 | 114 | 4. Use :meth:`TaskClient.get_task_result` to get the results of the |
|
115 | 115 | tasks. |
|
116 | 116 | |
|
117 | 117 | We are in the process of developing more detailed information about the task |
|
118 | 118 | interface. For now, the docstrings of the :class:`TaskClient`, |
|
119 | 119 | :class:`StringTask` and :class:`MapTask` classes should be consulted. |
|
120 | 120 | |
|
121 | 121 |
General Comments 0
You need to be logged in to leave comments.
Login now