Show More
@@ -1,421 +1,421 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | A base class for a configurable application. |
|
4 | 4 | |
|
5 | 5 | Authors: |
|
6 | 6 | |
|
7 | 7 | * Brian Granger |
|
8 | 8 | * Min RK |
|
9 | 9 | """ |
|
10 | 10 | |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | # Copyright (C) 2008-2011 The IPython Development Team |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 15 | # the file COPYING, distributed as part of this software. |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | # Imports |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | import logging |
|
23 | 23 | import os |
|
24 | 24 | import re |
|
25 | 25 | import sys |
|
26 | 26 | from copy import deepcopy |
|
27 | 27 | |
|
28 | 28 | from IPython.config.configurable import SingletonConfigurable |
|
29 | 29 | from IPython.config.loader import ( |
|
30 | 30 | KeyValueConfigLoader, PyFileConfigLoader, Config, ArgumentError |
|
31 | 31 | ) |
|
32 | 32 | |
|
33 | 33 | from IPython.utils.traitlets import ( |
|
34 | 34 | Unicode, List, Int, Enum, Dict, Instance, TraitError |
|
35 | 35 | ) |
|
36 | 36 | from IPython.utils.importstring import import_item |
|
37 | 37 | from IPython.utils.text import indent, wrap_paragraphs, dedent |
|
38 | 38 | |
|
39 | 39 | #----------------------------------------------------------------------------- |
|
40 | 40 | # function for re-wrapping a helpstring |
|
41 | 41 | #----------------------------------------------------------------------------- |
|
42 | 42 | |
|
43 | 43 | #----------------------------------------------------------------------------- |
|
44 | 44 | # Descriptions for the various sections |
|
45 | 45 | #----------------------------------------------------------------------------- |
|
46 | 46 | |
|
47 | 47 | # merge flags&aliases into options |
|
48 | 48 | option_description = """ |
|
49 | 49 | IPython command-line arguments are passed as '--<flag>', or '--<name>=<value>'. |
|
50 | 50 | |
|
51 |
Arguments that take values are actually aliases to full |
|
|
52 |
aliases are listed on the help line. For more information |
|
|
53 | configurables, see '--help-all'. | |
|
51 | Arguments that take values are actually convenience aliases to full | |
|
52 | Configurables, whose aliases are listed on the help line. For more information | |
|
53 | on full configurables, see '--help-all'. | |
|
54 | 54 | """.strip() # trim newlines of front and back |
|
55 | 55 | |
|
56 | 56 | keyvalue_description = """ |
|
57 | 57 | Parameters are set from command-line arguments of the form: |
|
58 | 58 | `--Class.trait=value`. |
|
59 | 59 | This line is evaluated in Python, so simple expressions are allowed, e.g.:: |
|
60 | 60 | `--C.a='range(3)'` For setting C.a=[0,1,2]. |
|
61 | 61 | """.strip() # trim newlines of front and back |
|
62 | 62 | |
|
63 | 63 | subcommand_description = """ |
|
64 | 64 | Subcommands are launched as `{app} cmd [args]`. For information on using |
|
65 | 65 | subcommand 'cmd', do: `{app} cmd -h`. |
|
66 | 66 | """.strip().format(app=os.path.basename(sys.argv[0])) |
|
67 | 67 | # get running program name |
|
68 | 68 | |
|
69 | 69 | #----------------------------------------------------------------------------- |
|
70 | 70 | # Application class |
|
71 | 71 | #----------------------------------------------------------------------------- |
|
72 | 72 | |
|
73 | 73 | |
|
74 | 74 | class ApplicationError(Exception): |
|
75 | 75 | pass |
|
76 | 76 | |
|
77 | 77 | |
|
78 | 78 | class Application(SingletonConfigurable): |
|
79 | 79 | """A singleton application with full configuration support.""" |
|
80 | 80 | |
|
81 | 81 | # The name of the application, will usually match the name of the command |
|
82 | 82 | # line application |
|
83 | 83 | name = Unicode(u'application') |
|
84 | 84 | |
|
85 | 85 | # The description of the application that is printed at the beginning |
|
86 | 86 | # of the help. |
|
87 | 87 | description = Unicode(u'This is an application.') |
|
88 | 88 | # default section descriptions |
|
89 | 89 | option_description = Unicode(option_description) |
|
90 | 90 | keyvalue_description = Unicode(keyvalue_description) |
|
91 | 91 | subcommand_description = Unicode(subcommand_description) |
|
92 | 92 | |
|
93 | 93 | # The usage and example string that goes at the end of the help string. |
|
94 | 94 | examples = Unicode() |
|
95 | 95 | |
|
96 | 96 | # A sequence of Configurable subclasses whose config=True attributes will |
|
97 | 97 | # be exposed at the command line. |
|
98 | 98 | classes = List([]) |
|
99 | 99 | |
|
100 | 100 | # The version string of this application. |
|
101 | 101 | version = Unicode(u'0.0') |
|
102 | 102 | |
|
103 | 103 | # The log level for the application |
|
104 | 104 | log_level = Enum((0,10,20,30,40,50,'DEBUG','INFO','WARN','ERROR','CRITICAL'), |
|
105 | 105 | default_value=logging.WARN, |
|
106 | 106 | config=True, |
|
107 | 107 | help="Set the log level by value or name.") |
|
108 | 108 | def _log_level_changed(self, name, old, new): |
|
109 | 109 | """Adjust the log level when log_level is set.""" |
|
110 | 110 | if isinstance(new, basestring): |
|
111 | 111 | new = getattr(logging, new) |
|
112 | 112 | self.log_level = new |
|
113 | 113 | self.log.setLevel(new) |
|
114 | 114 | |
|
115 | 115 | # the alias map for configurables |
|
116 | 116 | aliases = Dict({'log-level' : 'Application.log_level'}) |
|
117 | 117 | |
|
118 | 118 | # flags for loading Configurables or store_const style flags |
|
119 | 119 | # flags are loaded from this dict by '--key' flags |
|
120 | 120 | # this must be a dict of two-tuples, the first element being the Config/dict |
|
121 | 121 | # and the second being the help string for the flag |
|
122 | 122 | flags = Dict() |
|
123 | 123 | def _flags_changed(self, name, old, new): |
|
124 | 124 | """ensure flags dict is valid""" |
|
125 | 125 | for key,value in new.iteritems(): |
|
126 | 126 | assert len(value) == 2, "Bad flag: %r:%s"%(key,value) |
|
127 | 127 | assert isinstance(value[0], (dict, Config)), "Bad flag: %r:%s"%(key,value) |
|
128 | 128 | assert isinstance(value[1], basestring), "Bad flag: %r:%s"%(key,value) |
|
129 | 129 | |
|
130 | 130 | |
|
131 | 131 | # subcommands for launching other applications |
|
132 | 132 | # if this is not empty, this will be a parent Application |
|
133 | 133 | # this must be a dict of two-tuples, |
|
134 | 134 | # the first element being the application class/import string |
|
135 | 135 | # and the second being the help string for the subcommand |
|
136 | 136 | subcommands = Dict() |
|
137 | 137 | # parse_command_line will initialize a subapp, if requested |
|
138 | 138 | subapp = Instance('IPython.config.application.Application', allow_none=True) |
|
139 | 139 | |
|
140 | 140 | # extra command-line arguments that don't set config values |
|
141 | 141 | extra_args = List(Unicode) |
|
142 | 142 | |
|
143 | 143 | |
|
144 | 144 | def __init__(self, **kwargs): |
|
145 | 145 | SingletonConfigurable.__init__(self, **kwargs) |
|
146 | 146 | # Add my class to self.classes so my attributes appear in command line |
|
147 | 147 | # options. |
|
148 | 148 | self.classes.insert(0, self.__class__) |
|
149 | 149 | |
|
150 | 150 | self.init_logging() |
|
151 | 151 | |
|
152 | 152 | def _config_changed(self, name, old, new): |
|
153 | 153 | SingletonConfigurable._config_changed(self, name, old, new) |
|
154 | 154 | self.log.debug('Config changed:') |
|
155 | 155 | self.log.debug(repr(new)) |
|
156 | 156 | |
|
157 | 157 | def init_logging(self): |
|
158 | 158 | """Start logging for this application. |
|
159 | 159 | |
|
160 | 160 | The default is to log to stdout using a StreaHandler. The log level |
|
161 | 161 | starts at loggin.WARN, but this can be adjusted by setting the |
|
162 | 162 | ``log_level`` attribute. |
|
163 | 163 | """ |
|
164 | 164 | self.log = logging.getLogger(self.__class__.__name__) |
|
165 | 165 | self.log.setLevel(self.log_level) |
|
166 | 166 | if sys.executable.endswith('pythonw.exe'): |
|
167 | 167 | # this should really go to a file, but file-logging is only |
|
168 | 168 | # hooked up in parallel applications |
|
169 | 169 | self._log_handler = logging.StreamHandler(open(os.devnull, 'w')) |
|
170 | 170 | else: |
|
171 | 171 | self._log_handler = logging.StreamHandler() |
|
172 | 172 | self._log_formatter = logging.Formatter("[%(name)s] %(message)s") |
|
173 | 173 | self._log_handler.setFormatter(self._log_formatter) |
|
174 | 174 | self.log.addHandler(self._log_handler) |
|
175 | 175 | |
|
176 | 176 | def initialize(self, argv=None): |
|
177 | 177 | """Do the basic steps to configure me. |
|
178 | 178 | |
|
179 | 179 | Override in subclasses. |
|
180 | 180 | """ |
|
181 | 181 | self.parse_command_line(argv) |
|
182 | 182 | |
|
183 | 183 | |
|
184 | 184 | def start(self): |
|
185 | 185 | """Start the app mainloop. |
|
186 | 186 | |
|
187 | 187 | Override in subclasses. |
|
188 | 188 | """ |
|
189 | 189 | if self.subapp is not None: |
|
190 | 190 | return self.subapp.start() |
|
191 | 191 | |
|
192 | 192 | def print_alias_help(self): |
|
193 | 193 | """Print the alias part of the help.""" |
|
194 | 194 | if not self.aliases: |
|
195 | 195 | return |
|
196 | 196 | |
|
197 | 197 | lines = [] |
|
198 | 198 | classdict = {} |
|
199 | 199 | for cls in self.classes: |
|
200 | 200 | # include all parents (up to, but excluding Configurable) in available names |
|
201 | 201 | for c in cls.mro()[:-3]: |
|
202 | 202 | classdict[c.__name__] = c |
|
203 | 203 | |
|
204 | 204 | for alias, longname in self.aliases.iteritems(): |
|
205 | 205 | classname, traitname = longname.split('.',1) |
|
206 | 206 | cls = classdict[classname] |
|
207 | 207 | |
|
208 | 208 | trait = cls.class_traits(config=True)[traitname] |
|
209 | 209 | help = cls.class_get_trait_help(trait).splitlines() |
|
210 | 210 | # reformat first line |
|
211 | 211 | help[0] = help[0].replace(longname, alias) + ' (%s)'%longname |
|
212 | 212 | lines.extend(help) |
|
213 | 213 | # lines.append('') |
|
214 | 214 | print os.linesep.join(lines) |
|
215 | 215 | |
|
216 | 216 | def print_flag_help(self): |
|
217 | 217 | """Print the flag part of the help.""" |
|
218 | 218 | if not self.flags: |
|
219 | 219 | return |
|
220 | 220 | |
|
221 | 221 | lines = [] |
|
222 | 222 | for m, (cfg,help) in self.flags.iteritems(): |
|
223 | 223 | lines.append('--'+m) |
|
224 | 224 | lines.append(indent(dedent(help.strip()))) |
|
225 | 225 | # lines.append('') |
|
226 | 226 | print os.linesep.join(lines) |
|
227 | 227 | |
|
228 | 228 | def print_options(self): |
|
229 | 229 | if not self.flags and not self.aliases: |
|
230 | 230 | return |
|
231 | 231 | lines = ['Options'] |
|
232 | 232 | lines.append('-'*len(lines[0])) |
|
233 | 233 | lines.append('') |
|
234 | 234 | for p in wrap_paragraphs(self.option_description): |
|
235 | 235 | lines.append(p) |
|
236 | 236 | lines.append('') |
|
237 | 237 | print os.linesep.join(lines) |
|
238 | 238 | self.print_flag_help() |
|
239 | 239 | self.print_alias_help() |
|
240 | 240 | |
|
241 | 241 | |
|
242 | 242 | def print_subcommands(self): |
|
243 | 243 | """Print the subcommand part of the help.""" |
|
244 | 244 | if not self.subcommands: |
|
245 | 245 | return |
|
246 | 246 | |
|
247 | 247 | lines = ["Subcommands"] |
|
248 | 248 | lines.append('-'*len(lines[0])) |
|
249 | 249 | lines.append('') |
|
250 | 250 | for p in wrap_paragraphs(self.subcommand_description): |
|
251 | 251 | lines.append(p) |
|
252 | 252 | lines.append('') |
|
253 | for subc, (cls,help) in self.subcommands.iteritems(): | |
|
254 |
lines.append( |
|
|
253 | for subc, (cls, help) in self.subcommands.iteritems(): | |
|
254 | lines.append(subc) | |
|
255 | 255 | if help: |
|
256 | 256 | lines.append(indent(dedent(help.strip()))) |
|
257 | 257 | lines.append('') |
|
258 | 258 | print os.linesep.join(lines) |
|
259 | 259 | |
|
260 | 260 | def print_help(self, classes=False): |
|
261 | 261 | """Print the help for each Configurable class in self.classes. |
|
262 | 262 | |
|
263 | 263 | If classes=False (the default), only flags and aliases are printed. |
|
264 | 264 | """ |
|
265 | 265 | self.print_subcommands() |
|
266 | 266 | self.print_options() |
|
267 | 267 | |
|
268 | 268 | if classes: |
|
269 | 269 | if self.classes: |
|
270 | 270 | print "Class parameters" |
|
271 | 271 | print "----------------" |
|
272 | 272 | |
|
273 | 273 | for p in wrap_paragraphs(self.keyvalue_description): |
|
274 | 274 | print p |
|
275 | 275 | |
|
276 | 276 | |
|
277 | 277 | for cls in self.classes: |
|
278 | 278 | cls.class_print_help() |
|
279 | 279 | |
|
280 | 280 | else: |
|
281 | 281 | print "To see all available configurables, use `--help-all`" |
|
282 | 282 | |
|
283 | 283 | |
|
284 | 284 | def print_description(self): |
|
285 | 285 | """Print the application description.""" |
|
286 | 286 | for p in wrap_paragraphs(self.description): |
|
287 | 287 | print p |
|
288 | 288 | |
|
289 | 289 | |
|
290 | 290 | def print_examples(self): |
|
291 | 291 | """Print usage and examples. |
|
292 | 292 | |
|
293 | 293 | This usage string goes at the end of the command line help string |
|
294 | 294 | and should contain examples of the application's usage. |
|
295 | 295 | """ |
|
296 | 296 | if self.examples: |
|
297 | 297 | print "Examples" |
|
298 | 298 | print "--------" |
|
299 | 299 | |
|
300 | 300 | print indent(dedent(self.examples.strip())) |
|
301 | 301 | |
|
302 | 302 | |
|
303 | 303 | def print_version(self): |
|
304 | 304 | """Print the version string.""" |
|
305 | 305 | print self.version |
|
306 | 306 | |
|
307 | 307 | def update_config(self, config): |
|
308 | 308 | """Fire the traits events when the config is updated.""" |
|
309 | 309 | # Save a copy of the current config. |
|
310 | 310 | newconfig = deepcopy(self.config) |
|
311 | 311 | # Merge the new config into the current one. |
|
312 | 312 | newconfig._merge(config) |
|
313 | 313 | # Save the combined config as self.config, which triggers the traits |
|
314 | 314 | # events. |
|
315 | 315 | self.config = newconfig |
|
316 | 316 | |
|
317 | 317 | def initialize_subcommand(self, subc, argv=None): |
|
318 | 318 | """Initialize a subcommand with argv.""" |
|
319 | 319 | subapp,help = self.subcommands.get(subc) |
|
320 | 320 | |
|
321 | 321 | if isinstance(subapp, basestring): |
|
322 | 322 | subapp = import_item(subapp) |
|
323 | 323 | |
|
324 | 324 | # clear existing instances |
|
325 | 325 | self.__class__.clear_instance() |
|
326 | 326 | # instantiate |
|
327 | 327 | self.subapp = subapp.instance() |
|
328 | 328 | # and initialize subapp |
|
329 | 329 | self.subapp.initialize(argv) |
|
330 | 330 | |
|
331 | 331 | def parse_command_line(self, argv=None): |
|
332 | 332 | """Parse the command line arguments.""" |
|
333 | 333 | argv = sys.argv[1:] if argv is None else argv |
|
334 | 334 | |
|
335 | 335 | if self.subcommands and len(argv) > 0: |
|
336 | 336 | # we have subcommands, and one may have been specified |
|
337 | 337 | subc, subargv = argv[0], argv[1:] |
|
338 | 338 | if re.match(r'^\w(\-?\w)*$', subc) and subc in self.subcommands: |
|
339 | 339 | # it's a subcommand, and *not* a flag or class parameter |
|
340 | 340 | return self.initialize_subcommand(subc, subargv) |
|
341 | 341 | |
|
342 | 342 | if '-h' in argv or '--help' in argv or '--help-all' in argv: |
|
343 | 343 | self.print_description() |
|
344 | 344 | self.print_help('--help-all' in argv) |
|
345 | 345 | self.print_examples() |
|
346 | 346 | self.exit(0) |
|
347 | 347 | |
|
348 | 348 | if '--version' in argv: |
|
349 | 349 | self.print_version() |
|
350 | 350 | self.exit(0) |
|
351 | 351 | |
|
352 | 352 | loader = KeyValueConfigLoader(argv=argv, aliases=self.aliases, |
|
353 | 353 | flags=self.flags) |
|
354 | 354 | try: |
|
355 | 355 | config = loader.load_config() |
|
356 | 356 | self.update_config(config) |
|
357 | 357 | except (TraitError, ArgumentError) as e: |
|
358 | 358 | self.print_description() |
|
359 | 359 | self.print_help() |
|
360 | 360 | self.print_examples() |
|
361 | 361 | self.log.fatal(str(e)) |
|
362 | 362 | self.exit(1) |
|
363 | 363 | # store unparsed args in extra_args |
|
364 | 364 | self.extra_args = loader.extra_args |
|
365 | 365 | |
|
366 | 366 | def load_config_file(self, filename, path=None): |
|
367 | 367 | """Load a .py based config file by filename and path.""" |
|
368 | 368 | loader = PyFileConfigLoader(filename, path=path) |
|
369 | 369 | config = loader.load_config() |
|
370 | 370 | self.update_config(config) |
|
371 | 371 | |
|
372 | 372 | def generate_config_file(self): |
|
373 | 373 | """generate default config file from Configurables""" |
|
374 | 374 | lines = ["# Configuration file for %s."%self.name] |
|
375 | 375 | lines.append('') |
|
376 | 376 | lines.append('c = get_config()') |
|
377 | 377 | lines.append('') |
|
378 | 378 | for cls in self.classes: |
|
379 | 379 | lines.append(cls.class_config_section()) |
|
380 | 380 | return '\n'.join(lines) |
|
381 | 381 | |
|
382 | 382 | def exit(self, exit_status=0): |
|
383 | 383 | self.log.debug("Exiting application: %s" % self.name) |
|
384 | 384 | sys.exit(exit_status) |
|
385 | 385 | |
|
386 | 386 | #----------------------------------------------------------------------------- |
|
387 | 387 | # utility functions, for convenience |
|
388 | 388 | #----------------------------------------------------------------------------- |
|
389 | 389 | |
|
390 | 390 | def boolean_flag(name, configurable, set_help='', unset_help=''): |
|
391 | 391 | """Helper for building basic --trait, --no-trait flags. |
|
392 | 392 | |
|
393 | 393 | Parameters |
|
394 | 394 | ---------- |
|
395 | 395 | |
|
396 | 396 | name : str |
|
397 | 397 | The name of the flag. |
|
398 | 398 | configurable : str |
|
399 | 399 | The 'Class.trait' string of the trait to be set/unset with the flag |
|
400 | 400 | set_help : unicode |
|
401 | 401 | help string for --name flag |
|
402 | 402 | unset_help : unicode |
|
403 | 403 | help string for --no-name flag |
|
404 | 404 | |
|
405 | 405 | Returns |
|
406 | 406 | ------- |
|
407 | 407 | |
|
408 | 408 | cfg : dict |
|
409 | 409 | A dict with two keys: 'name', and 'no-name', for setting and unsetting |
|
410 | 410 | the trait, respectively. |
|
411 | 411 | """ |
|
412 | 412 | # default helpstrings |
|
413 | 413 | set_help = set_help or "set %s=True"%configurable |
|
414 | 414 | unset_help = unset_help or "set %s=False"%configurable |
|
415 | 415 | |
|
416 | 416 | cls,trait = configurable.split('.') |
|
417 | 417 | |
|
418 | 418 | setter = {cls : {trait : True}} |
|
419 | 419 | unsetter = {cls : {trait : False}} |
|
420 | 420 | return {name : (setter, set_help), 'no-'+name : (unsetter, unset_help)} |
|
421 | 421 |
@@ -1,516 +1,525 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 | ipython [options] [files] | |
|
16 | ========= | |
|
17 | IPython | |
|
18 | ========= | |
|
17 | 19 | |
|
18 | IPython: an enhanced interactive Python shell. | |
|
20 | Tools for Interactive Computing in Python | |
|
21 | ========================================= | |
|
19 | 22 | |
|
20 | 23 | A Python shell with automatic history (input and output), dynamic object |
|
21 | 24 | introspection, easier configuration, command completion, access to the |
|
22 | 25 | system shell and more. IPython can also be embedded in running programs. |
|
23 | 26 | |
|
27 | ||
|
28 | Usage | |
|
29 | ----- | |
|
30 | ||
|
31 | ipython [subcommand] [options] [files] | |
|
32 | ||
|
24 | 33 | If invoked with no options, it executes all the files listed in sequence |
|
25 | 34 | and exits, use -i to enter interactive mode after running the files. Files |
|
26 | 35 | ending in .py will be treated as normal Python, but files ending in .ipy |
|
27 | 36 | can contain special IPython syntax (magic commands, shell expansions, etc.) |
|
28 | 37 | |
|
29 | 38 | Almost all configuration in IPython is available via the command-line. Do |
|
30 | 39 | `ipython --help-all` to see all available options. For persistent |
|
31 |
configuration, |
|
|
40 | configuration, look into your `ipython_config.py` configuration file for | |
|
32 | 41 | details. |
|
33 | 42 | |
|
34 | This file is typically installed in the IPYTHON_DIR directory, and there | |
|
43 | This file is typically installed in the `IPYTHON_DIR` directory, and there | |
|
35 | 44 | is a separate configuration directory for each profile. The default profile |
|
36 | directory will be located in $IPYTHON_DIR/profile_default. For Linux | |
|
37 |
|
|
|
38 |
$HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents |
|
|
39 | Settings\\YourUserName in most instances. | |
|
45 | directory will be located in $IPYTHON_DIR/profile_default. For Linux users, | |
|
46 | IPYTHON_DIR defaults to `$HOME/.config/ipython`, and for other Unix systems | |
|
47 | to `$HOME/.ipython`. For Windows users, $HOME resolves to C:\\Documents | |
|
48 | and Settings\\YourUserName in most instances. | |
|
40 | 49 | |
|
41 | To initialize a profile with the default configuration file, do: | |
|
50 | To initialize a profile with the default configuration file, do:: | |
|
42 | 51 | |
|
43 | 52 | $> ipython profile create |
|
44 | 53 | |
|
45 | and start editing IPYTHON_DIR/profile_default/ipython_config.py | |
|
54 | and start editing `IPYTHON_DIR/profile_default/ipython_config.py` | |
|
46 | 55 | |
|
47 |
In IPython's documentation, we will refer to this directory as |
|
|
48 |
you can change its default location by |
|
|
49 | environment variable. | |
|
56 | In IPython's documentation, we will refer to this directory as | |
|
57 | `IPYTHON_DIR`, you can change its default location by creating an | |
|
58 | environment variable with this name and setting it to the desired path. | |
|
50 | 59 | |
|
51 | 60 | For more information, see the manual available in HTML and PDF in your |
|
52 | 61 | installation, or online at http://ipython.org/documentation.html. |
|
53 | 62 | """ |
|
54 | 63 | |
|
55 | 64 | interactive_usage = """ |
|
56 | 65 | IPython -- An enhanced Interactive Python |
|
57 | 66 | ========================================= |
|
58 | 67 | |
|
59 | 68 | IPython offers a combination of convenient shell features, special commands |
|
60 | 69 | and a history mechanism for both input (command history) and output (results |
|
61 | 70 | caching, similar to Mathematica). It is intended to be a fully compatible |
|
62 | 71 | replacement for the standard Python interpreter, while offering vastly |
|
63 | 72 | improved functionality and flexibility. |
|
64 | 73 | |
|
65 | 74 | At your system command line, type 'ipython -h' to see the command line |
|
66 | 75 | options available. This document only describes interactive features. |
|
67 | 76 | |
|
68 | 77 | MAIN FEATURES |
|
69 | 78 | |
|
70 | 79 | * Access to the standard Python help. As of Python 2.1, a help system is |
|
71 | 80 | available with access to object docstrings and the Python manuals. Simply |
|
72 | 81 | type 'help' (no quotes) to access it. |
|
73 | 82 | |
|
74 | 83 | * Magic commands: type %magic for information on the magic subsystem. |
|
75 | 84 | |
|
76 | 85 | * System command aliases, via the %alias command or the ipythonrc config file. |
|
77 | 86 | |
|
78 | 87 | * Dynamic object information: |
|
79 | 88 | |
|
80 | 89 | Typing ?word or word? prints detailed information about an object. If |
|
81 | 90 | certain strings in the object are too long (docstrings, code, etc.) they get |
|
82 | 91 | snipped in the center for brevity. |
|
83 | 92 | |
|
84 | 93 | Typing ??word or word?? gives access to the full information without |
|
85 | 94 | snipping long strings. Long strings are sent to the screen through the less |
|
86 | 95 | pager if longer than the screen, printed otherwise. |
|
87 | 96 | |
|
88 | 97 | The ?/?? system gives access to the full source code for any object (if |
|
89 | 98 | available), shows function prototypes and other useful information. |
|
90 | 99 | |
|
91 | 100 | If you just want to see an object's docstring, type '%pdoc object' (without |
|
92 | 101 | quotes, and without % if you have automagic on). |
|
93 | 102 | |
|
94 | 103 | Both %pdoc and ?/?? give you access to documentation even on things which are |
|
95 | 104 | not explicitely defined. Try for example typing {}.get? or after import os, |
|
96 | 105 | type os.path.abspath??. The magic functions %pdef, %source and %file operate |
|
97 | 106 | similarly. |
|
98 | 107 | |
|
99 | 108 | * Completion in the local namespace, by typing TAB at the prompt. |
|
100 | 109 | |
|
101 | 110 | At any time, hitting tab will complete any available python commands or |
|
102 | 111 | variable names, and show you a list of the possible completions if there's |
|
103 | 112 | no unambiguous one. It will also complete filenames in the current directory. |
|
104 | 113 | |
|
105 | 114 | This feature requires the readline and rlcomplete modules, so it won't work |
|
106 | 115 | if your Python lacks readline support (such as under Windows). |
|
107 | 116 | |
|
108 | 117 | * Search previous command history in two ways (also requires readline): |
|
109 | 118 | |
|
110 | 119 | - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to |
|
111 | 120 | search through only the history items that match what you've typed so |
|
112 | 121 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like |
|
113 | 122 | normal arrow keys. |
|
114 | 123 | |
|
115 | 124 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches |
|
116 | 125 | your history for lines that match what you've typed so far, completing as |
|
117 | 126 | much as it can. |
|
118 | 127 | |
|
119 | 128 | - %hist: search history by index (this does *not* require readline). |
|
120 | 129 | |
|
121 | 130 | * Persistent command history across sessions. |
|
122 | 131 | |
|
123 | 132 | * Logging of input with the ability to save and restore a working session. |
|
124 | 133 | |
|
125 | 134 | * System escape with !. Typing !ls will run 'ls' in the current directory. |
|
126 | 135 | |
|
127 | 136 | * The reload command does a 'deep' reload of a module: changes made to the |
|
128 | 137 | module since you imported will actually be available without having to exit. |
|
129 | 138 | |
|
130 | 139 | * Verbose and colored exception traceback printouts. See the magic xmode and |
|
131 | 140 | xcolor functions for details (just type %magic). |
|
132 | 141 | |
|
133 | 142 | * Input caching system: |
|
134 | 143 | |
|
135 | 144 | IPython offers numbered prompts (In/Out) with input and output caching. All |
|
136 | 145 | input is saved and can be retrieved as variables (besides the usual arrow |
|
137 | 146 | key recall). |
|
138 | 147 | |
|
139 | 148 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
140 | 149 | _i: stores previous input. |
|
141 | 150 | _ii: next previous. |
|
142 | 151 | _iii: next-next previous. |
|
143 | 152 | _ih : a list of all input _ih[n] is the input from line n. |
|
144 | 153 | |
|
145 | 154 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
146 | 155 | being the prompt counter), such that _i<n> == _ih[<n>] |
|
147 | 156 | |
|
148 | 157 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. |
|
149 | 158 | |
|
150 | 159 | You can create macros which contain multiple input lines from this history, |
|
151 | 160 | for later re-execution, with the %macro function. |
|
152 | 161 | |
|
153 | 162 | The history function %hist allows you to see any part of your input history |
|
154 | 163 | by printing a range of the _i variables. Note that inputs which contain |
|
155 | 164 | magic functions (%) appear in the history with a prepended comment. This is |
|
156 | 165 | because they aren't really valid Python code, so you can't exec them. |
|
157 | 166 | |
|
158 | 167 | * Output caching system: |
|
159 | 168 | |
|
160 | 169 | For output that is returned from actions, a system similar to the input |
|
161 | 170 | cache exists but using _ instead of _i. Only actions that produce a result |
|
162 | 171 | (NOT assignments, for example) are cached. If you are familiar with |
|
163 | 172 | Mathematica, IPython's _ variables behave exactly like Mathematica's % |
|
164 | 173 | variables. |
|
165 | 174 | |
|
166 | 175 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
167 | 176 | _ (one underscore): previous output. |
|
168 | 177 | __ (two underscores): next previous. |
|
169 | 178 | ___ (three underscores): next-next previous. |
|
170 | 179 | |
|
171 | 180 | Global variables named _<n> are dynamically created (<n> being the prompt |
|
172 | 181 | counter), such that the result of output <n> is always available as _<n>. |
|
173 | 182 | |
|
174 | 183 | Finally, a global dictionary named _oh exists with entries for all lines |
|
175 | 184 | which generated output. |
|
176 | 185 | |
|
177 | 186 | * Directory history: |
|
178 | 187 | |
|
179 | 188 | Your history of visited directories is kept in the global list _dh, and the |
|
180 | 189 | magic %cd command can be used to go to any entry in that list. |
|
181 | 190 | |
|
182 | 191 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) |
|
183 | 192 | |
|
184 | 193 | 1. Auto-parentheses |
|
185 | 194 | Callable objects (i.e. functions, methods, etc) can be invoked like |
|
186 | 195 | this (notice the commas between the arguments): |
|
187 | 196 | >>> callable_ob arg1, arg2, arg3 |
|
188 | 197 | and the input will be translated to this: |
|
189 | 198 | --> callable_ob(arg1, arg2, arg3) |
|
190 | 199 | You can force auto-parentheses by using '/' as the first character |
|
191 | 200 | of a line. For example: |
|
192 | 201 | >>> /globals # becomes 'globals()' |
|
193 | 202 | Note that the '/' MUST be the first character on the line! This |
|
194 | 203 | won't work: |
|
195 | 204 | >>> print /globals # syntax error |
|
196 | 205 | |
|
197 | 206 | In most cases the automatic algorithm should work, so you should |
|
198 | 207 | rarely need to explicitly invoke /. One notable exception is if you |
|
199 | 208 | are trying to call a function with a list of tuples as arguments (the |
|
200 | 209 | parenthesis will confuse IPython): |
|
201 | 210 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
202 | 211 | but this will work: |
|
203 | 212 | In [2]: /zip (1,2,3),(4,5,6) |
|
204 | 213 | ------> zip ((1,2,3),(4,5,6)) |
|
205 | 214 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
206 | 215 | |
|
207 | 216 | IPython tells you that it has altered your command line by |
|
208 | 217 | displaying the new command line preceded by -->. e.g.: |
|
209 | 218 | In [18]: callable list |
|
210 | 219 | -------> callable (list) |
|
211 | 220 | |
|
212 | 221 | 2. Auto-Quoting |
|
213 | 222 | You can force auto-quoting of a function's arguments by using ',' as |
|
214 | 223 | the first character of a line. For example: |
|
215 | 224 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
216 | 225 | |
|
217 | 226 | If you use ';' instead, the whole argument is quoted as a single |
|
218 | 227 | string (while ',' splits on whitespace): |
|
219 | 228 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
220 | 229 | >>> ;my_function a b c # becomes my_function("a b c") |
|
221 | 230 | |
|
222 | 231 | Note that the ',' MUST be the first character on the line! This |
|
223 | 232 | won't work: |
|
224 | 233 | >>> x = ,my_function /home/me # syntax error |
|
225 | 234 | """ |
|
226 | 235 | |
|
227 | 236 | interactive_usage_min = """\ |
|
228 | 237 | An enhanced console for Python. |
|
229 | 238 | Some of its features are: |
|
230 | 239 | - Readline support if the readline library is present. |
|
231 | 240 | - Tab completion in the local namespace. |
|
232 | 241 | - Logging of input, see command-line options. |
|
233 | 242 | - System shell escape via ! , eg !ls. |
|
234 | 243 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
235 | 244 | - Keeps track of locally defined variables via %who, %whos. |
|
236 | 245 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
237 | 246 | """ |
|
238 | 247 | |
|
239 | 248 | quick_reference = r""" |
|
240 | 249 | IPython -- An enhanced Interactive Python - Quick Reference Card |
|
241 | 250 | ================================================================ |
|
242 | 251 | |
|
243 | 252 | obj?, obj?? : Get help, or more help for object (also works as |
|
244 | 253 | ?obj, ??obj). |
|
245 | 254 | ?foo.*abc* : List names in 'foo' containing 'abc' in them. |
|
246 | 255 | %magic : Information about IPython's 'magic' % functions. |
|
247 | 256 | |
|
248 | 257 | Magic functions are prefixed by %, and typically take their arguments without |
|
249 | 258 | parentheses, quotes or even commas for convenience. |
|
250 | 259 | |
|
251 | 260 | Example magic function calls: |
|
252 | 261 | |
|
253 | 262 | %alias d ls -F : 'd' is now an alias for 'ls -F' |
|
254 | 263 | alias d ls -F : Works if 'alias' not a python name |
|
255 | 264 | alist = %alias : Get list of aliases to 'alist' |
|
256 | 265 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. |
|
257 | 266 | %cd?? : See help AND source for magic %cd |
|
258 | 267 | |
|
259 | 268 | System commands: |
|
260 | 269 | |
|
261 | 270 | !cp a.txt b/ : System command escape, calls os.system() |
|
262 | 271 | cp a.txt b/ : after %rehashx, most system commands work without ! |
|
263 | 272 | cp ${f}.txt $bar : Variable expansion in magics and system commands |
|
264 | 273 | files = !ls /usr : Capture sytem command output |
|
265 | 274 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' |
|
266 | 275 | |
|
267 | 276 | History: |
|
268 | 277 | |
|
269 | 278 | _i, _ii, _iii : Previous, next previous, next next previous input |
|
270 | 279 | _i4, _ih[2:5] : Input history line 4, lines 2-4 |
|
271 | 280 | exec _i81 : Execute input history line #81 again |
|
272 | 281 | %rep 81 : Edit input history line #81 |
|
273 | 282 | _, __, ___ : previous, next previous, next next previous output |
|
274 | 283 | _dh : Directory history |
|
275 | 284 | _oh : Output history |
|
276 | 285 | %hist : Command history. '%hist -g foo' search history for 'foo' |
|
277 | 286 | |
|
278 | 287 | Autocall: |
|
279 | 288 | |
|
280 | 289 | f 1,2 : f(1,2) |
|
281 | 290 | /f 1,2 : f(1,2) (forced autoparen) |
|
282 | 291 | ,f 1 2 : f("1","2") |
|
283 | 292 | ;f 1 2 : f("1 2") |
|
284 | 293 | |
|
285 | 294 | Remember: TAB completion works in many contexts, not just file names |
|
286 | 295 | or python names. |
|
287 | 296 | |
|
288 | 297 | The following magic functions are currently available: |
|
289 | 298 | |
|
290 | 299 | """ |
|
291 | 300 | |
|
292 | 301 | gui_reference = """\ |
|
293 | 302 | =============================== |
|
294 | 303 | The graphical IPython console |
|
295 | 304 | =============================== |
|
296 | 305 | |
|
297 | 306 | This console is designed to emulate the look, feel and workflow of a terminal |
|
298 | 307 | environment, while adding a number of enhancements that are simply not possible |
|
299 | 308 | in a real terminal, such as inline syntax highlighting, true multiline editing, |
|
300 | 309 | inline graphics and much more. |
|
301 | 310 | |
|
302 | 311 | This quick reference document contains the basic information you'll need to |
|
303 | 312 | know to make the most efficient use of it. For the various command line |
|
304 | 313 | options available at startup, type ``ipython qtconsole --help`` at the command line. |
|
305 | 314 | |
|
306 | 315 | |
|
307 | 316 | Multiline editing |
|
308 | 317 | ================= |
|
309 | 318 | |
|
310 | 319 | The graphical console is capable of true multiline editing, but it also tries |
|
311 | 320 | to behave intuitively like a terminal when possible. If you are used to |
|
312 | 321 | IPyhton's old terminal behavior, you should find the transition painless, and |
|
313 | 322 | once you learn a few basic keybindings it will be a much more efficient |
|
314 | 323 | environment. |
|
315 | 324 | |
|
316 | 325 | For single expressions or indented blocks, the console behaves almost like the |
|
317 | 326 | terminal IPython: single expressions are immediately evaluated, and indented |
|
318 | 327 | blocks are evaluated once a single blank line is entered:: |
|
319 | 328 | |
|
320 | 329 | In [1]: print "Hello IPython!" # Enter was pressed at the end of the line |
|
321 | 330 | Hello IPython! |
|
322 | 331 | |
|
323 | 332 | In [2]: for i in range(10): |
|
324 | 333 | ...: print i, |
|
325 | 334 | ...: |
|
326 | 335 | 0 1 2 3 4 5 6 7 8 9 |
|
327 | 336 | |
|
328 | 337 | If you want to enter more than one expression in a single input block |
|
329 | 338 | (something not possible in the terminal), you can use ``Control-Enter`` at the |
|
330 | 339 | end of your first line instead of ``Enter``. At that point the console goes |
|
331 | 340 | into 'cell mode' and even if your inputs are not indented, it will continue |
|
332 | 341 | accepting arbitrarily many lines until either you enter an extra blank line or |
|
333 | 342 | you hit ``Shift-Enter`` (the key binding that forces execution). When a |
|
334 | 343 | multiline cell is entered, IPython analyzes it and executes its code producing |
|
335 | 344 | an ``Out[n]`` prompt only for the last expression in it, while the rest of the |
|
336 | 345 | cell is executed as if it was a script. An example should clarify this:: |
|
337 | 346 | |
|
338 | 347 | In [3]: x=1 # Hit C-Enter here |
|
339 | 348 | ...: y=2 # from now on, regular Enter is sufficient |
|
340 | 349 | ...: z=3 |
|
341 | 350 | ...: x**2 # This does *not* produce an Out[] value |
|
342 | 351 | ...: x+y+z # Only the last expression does |
|
343 | 352 | ...: |
|
344 | 353 | Out[3]: 6 |
|
345 | 354 | |
|
346 | 355 | The behavior where an extra blank line forces execution is only active if you |
|
347 | 356 | are actually typing at the keyboard each line, and is meant to make it mimic |
|
348 | 357 | the IPython terminal behavior. If you paste a long chunk of input (for example |
|
349 | 358 | a long script copied form an editor or web browser), it can contain arbitrarily |
|
350 | 359 | many intermediate blank lines and they won't cause any problems. As always, |
|
351 | 360 | you can then make it execute by appending a blank line *at the end* or hitting |
|
352 | 361 | ``Shift-Enter`` anywhere within the cell. |
|
353 | 362 | |
|
354 | 363 | With the up arrow key, you can retrieve previous blocks of input that contain |
|
355 | 364 | multiple lines. You can move inside of a multiline cell like you would in any |
|
356 | 365 | text editor. When you want it executed, the simplest thing to do is to hit the |
|
357 | 366 | force execution key, ``Shift-Enter`` (though you can also navigate to the end |
|
358 | 367 | and append a blank line by using ``Enter`` twice). |
|
359 | 368 | |
|
360 | 369 | If you've edited a multiline cell and accidentally navigate out of it with the |
|
361 | 370 | up or down arrow keys, IPython will clear the cell and replace it with the |
|
362 | 371 | contents of the one above or below that you navigated to. If this was an |
|
363 | 372 | accident and you want to retrieve the cell you were editing, use the Undo |
|
364 | 373 | keybinding, ``Control-z``. |
|
365 | 374 | |
|
366 | 375 | |
|
367 | 376 | Key bindings |
|
368 | 377 | ============ |
|
369 | 378 | |
|
370 | 379 | The IPython console supports most of the basic Emacs line-oriented keybindings, |
|
371 | 380 | in addition to some of its own. |
|
372 | 381 | |
|
373 | 382 | The keybinding prefixes mean: |
|
374 | 383 | |
|
375 | 384 | - ``C``: Control |
|
376 | 385 | - ``S``: Shift |
|
377 | 386 | - ``M``: Meta (typically the Alt key) |
|
378 | 387 | |
|
379 | 388 | The keybindings themselves are: |
|
380 | 389 | |
|
381 | 390 | - ``Enter``: insert new line (may cause execution, see above). |
|
382 | 391 | - ``C-Enter``: force new line, *never* causes execution. |
|
383 | 392 | - ``S-Enter``: *force* execution regardless of where cursor is, no newline added. |
|
384 | 393 | - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped). |
|
385 | 394 | - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped). |
|
386 | 395 | - ``C-v``: paste text from clipboard. |
|
387 | 396 | - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows). |
|
388 | 397 | - ``C-S-z``: redo. |
|
389 | 398 | - ``C-o``: move to 'other' area, between pager and terminal. |
|
390 | 399 | - ``C-l``: clear terminal. |
|
391 | 400 | - ``C-a``: go to beginning of line. |
|
392 | 401 | - ``C-e``: go to end of line. |
|
393 | 402 | - ``C-k``: kill from cursor to the end of the line. |
|
394 | 403 | - ``C-y``: yank (paste) |
|
395 | 404 | - ``C-p``: previous line (like up arrow) |
|
396 | 405 | - ``C-n``: next line (like down arrow) |
|
397 | 406 | - ``C-f``: forward (like right arrow) |
|
398 | 407 | - ``C-b``: back (like left arrow) |
|
399 | 408 | - ``C-d``: delete next character. |
|
400 | 409 | - ``M-<``: move to the beginning of the input region. |
|
401 | 410 | - ``M->``: move to the end of the input region. |
|
402 | 411 | - ``M-d``: delete next word. |
|
403 | 412 | - ``M-Backspace``: delete previous word. |
|
404 | 413 | - ``C-.``: force a kernel restart (a confirmation dialog appears). |
|
405 | 414 | - ``C-+``: increase font size. |
|
406 | 415 | - ``C--``: decrease font size. |
|
407 | 416 | |
|
408 | 417 | The IPython pager |
|
409 | 418 | ================= |
|
410 | 419 | |
|
411 | 420 | IPython will show long blocks of text from many sources using a builtin pager. |
|
412 | 421 | You can control where this pager appears with the ``--paging`` command-line |
|
413 | 422 | flag: |
|
414 | 423 | |
|
415 | 424 | - ``inside`` [default]: the pager is overlaid on top of the main terminal. You |
|
416 | 425 | must quit the pager to get back to the terminal (similar to how a pager such |
|
417 | 426 | as ``less`` or ``more`` works). |
|
418 | 427 | |
|
419 | 428 | - ``vsplit``: the console is made double-tall, and the pager appears on the |
|
420 | 429 | bottom area when needed. You can view its contents while using the terminal. |
|
421 | 430 | |
|
422 | 431 | - ``hsplit``: the console is made double-wide, and the pager appears on the |
|
423 | 432 | right area when needed. You can view its contents while using the terminal. |
|
424 | 433 | |
|
425 | 434 | - ``none``: the console never pages output. |
|
426 | 435 | |
|
427 | 436 | If you use the vertical or horizontal paging modes, you can navigate between |
|
428 | 437 | terminal and pager as follows: |
|
429 | 438 | |
|
430 | 439 | - Tab key: goes from pager to terminal (but not the other way around). |
|
431 | 440 | - Control-o: goes from one to another always. |
|
432 | 441 | - Mouse: click on either. |
|
433 | 442 | |
|
434 | 443 | In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the |
|
435 | 444 | focus on the pager area). |
|
436 | 445 | |
|
437 | 446 | Running subprocesses |
|
438 | 447 | ==================== |
|
439 | 448 | |
|
440 | 449 | The graphical IPython console uses the ``pexpect`` module to run subprocesses |
|
441 | 450 | when you type ``!command``. This has a number of advantages (true asynchronous |
|
442 | 451 | output from subprocesses as well as very robust termination of rogue |
|
443 | 452 | subprocesses with ``Control-C``), as well as some limitations. The main |
|
444 | 453 | limitation is that you can *not* interact back with the subprocess, so anything |
|
445 | 454 | that invokes a pager or expects you to type input into it will block and hang |
|
446 | 455 | (you can kill it with ``Control-C``). |
|
447 | 456 | |
|
448 | 457 | We have provided as magics ``%less`` to page files (aliased to ``%more``), |
|
449 | 458 | ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the |
|
450 | 459 | most common commands you'd want to call in your subshell and that would cause |
|
451 | 460 | problems if invoked via ``!cmd``, but you need to be aware of this limitation. |
|
452 | 461 | |
|
453 | 462 | Display |
|
454 | 463 | ======= |
|
455 | 464 | |
|
456 | 465 | The IPython console can now display objects in a variety of formats, including |
|
457 | 466 | HTML, PNG and SVG. This is accomplished using the display functions in |
|
458 | 467 | ``IPython.core.display``:: |
|
459 | 468 | |
|
460 | 469 | In [4]: from IPython.core.display import display, display_html |
|
461 | 470 | |
|
462 | 471 | In [5]: from IPython.core.display import display_png, display_svg |
|
463 | 472 | |
|
464 | 473 | Python objects can simply be passed to these functions and the appropriate |
|
465 | 474 | representations will be displayed in the console as long as the objects know |
|
466 | 475 | how to compute those representations. The easiest way of teaching objects how |
|
467 | 476 | to format themselves in various representations is to define special methods |
|
468 | 477 | such as: ``_repr_html_``, ``_repr_svg_`` and ``_repr_png_``. IPython's display formatters |
|
469 | 478 | can also be given custom formatter functions for various types:: |
|
470 | 479 | |
|
471 | 480 | In [6]: ip = get_ipython() |
|
472 | 481 | |
|
473 | 482 | In [7]: html_formatter = ip.display_formatter.formatters['text/html'] |
|
474 | 483 | |
|
475 | 484 | In [8]: html_formatter.for_type(Foo, foo_to_html) |
|
476 | 485 | |
|
477 | 486 | For further details, see ``IPython.core.formatters``. |
|
478 | 487 | |
|
479 | 488 | Inline matplotlib graphics |
|
480 | 489 | ========================== |
|
481 | 490 | |
|
482 | 491 | The IPython console is capable of displaying matplotlib figures inline, in SVG |
|
483 | 492 | or PNG format. If started with the ``pylab=inline``, then all figures are |
|
484 | 493 | rendered inline automatically (PNG by default). If started with ``--pylab`` |
|
485 | 494 | or ``pylab=<your backend>``, then a GUI backend will be used, but IPython's |
|
486 | 495 | ``display()`` and ``getfigs()`` functions can be used to view plots inline:: |
|
487 | 496 | |
|
488 | 497 | In [9]: display(*getfigs()) # display all figures inline |
|
489 | 498 | |
|
490 | 499 | In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline |
|
491 | 500 | """ |
|
492 | 501 | |
|
493 | 502 | |
|
494 | 503 | quick_guide = """\ |
|
495 | 504 | ? -> Introduction and overview of IPython's features. |
|
496 | 505 | %quickref -> Quick reference. |
|
497 | 506 | help -> Python's own help system. |
|
498 | 507 | object? -> Details about 'object', use 'object??' for extra details. |
|
499 | 508 | """ |
|
500 | 509 | |
|
501 | 510 | gui_note = """\ |
|
502 | 511 | %guiref -> A brief reference about the graphical user interface. |
|
503 | 512 | """ |
|
504 | 513 | |
|
505 | 514 | default_banner_parts = [ |
|
506 | 515 | 'Python %s\n' % (sys.version.split('\n')[0],), |
|
507 | 516 | 'Type "copyright", "credits" or "license" for more information.\n\n', |
|
508 | 517 | 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,), |
|
509 | 518 | quick_guide |
|
510 | 519 | ] |
|
511 | 520 | |
|
512 | 521 | default_gui_banner_parts = default_banner_parts + [gui_note] |
|
513 | 522 | |
|
514 | 523 | default_banner = ''.join(default_banner_parts) |
|
515 | 524 | |
|
516 | 525 | default_gui_banner = ''.join(default_gui_banner_parts) |
@@ -1,247 +1,246 b'' | |||
|
1 | #!/usr/bin/env python | |
|
2 | 1 |
|
|
3 | 2 | """ |
|
4 | 3 | An embedded IPython shell. |
|
5 | 4 | |
|
6 | 5 | Authors: |
|
7 | 6 | |
|
8 | 7 | * Brian Granger |
|
9 | 8 | * Fernando Perez |
|
10 | 9 | |
|
11 | 10 | Notes |
|
12 | 11 | ----- |
|
13 | 12 | """ |
|
14 | 13 | |
|
15 | 14 | #----------------------------------------------------------------------------- |
|
16 | 15 | # Copyright (C) 2008-2009 The IPython Development Team |
|
17 | 16 | # |
|
18 | 17 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | 18 | # the file COPYING, distributed as part of this software. |
|
20 | 19 | #----------------------------------------------------------------------------- |
|
21 | 20 | |
|
22 | 21 | #----------------------------------------------------------------------------- |
|
23 | 22 | # Imports |
|
24 | 23 | #----------------------------------------------------------------------------- |
|
25 | 24 | |
|
26 | 25 | from __future__ import with_statement |
|
27 | 26 | import __main__ |
|
28 | 27 | |
|
29 | 28 | import sys |
|
30 | 29 | from contextlib import nested |
|
31 | 30 | |
|
32 | 31 | from IPython.core import ultratb |
|
33 | 32 | from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell |
|
34 | 33 | from IPython.frontend.terminal.ipapp import load_default_config |
|
35 | 34 | |
|
36 | 35 | from IPython.utils.traitlets import Bool, CBool, Unicode |
|
37 | 36 | from IPython.utils.io import ask_yes_no |
|
38 | 37 | |
|
39 | 38 | |
|
40 | 39 | #----------------------------------------------------------------------------- |
|
41 | 40 | # Classes and functions |
|
42 | 41 | #----------------------------------------------------------------------------- |
|
43 | 42 | |
|
44 | 43 | # This is an additional magic that is exposed in embedded shells. |
|
45 | 44 | def kill_embedded(self,parameter_s=''): |
|
46 | 45 | """%kill_embedded : deactivate for good the current embedded IPython. |
|
47 | 46 | |
|
48 | 47 | This function (after asking for confirmation) sets an internal flag so that |
|
49 | 48 | an embedded IPython will never activate again. This is useful to |
|
50 | 49 | permanently disable a shell that is being called inside a loop: once you've |
|
51 | 50 | figured out what you needed from it, you may then kill it and the program |
|
52 | 51 | will then continue to run without the interactive shell interfering again. |
|
53 | 52 | """ |
|
54 | 53 | |
|
55 | 54 | kill = ask_yes_no("Are you sure you want to kill this embedded instance " |
|
56 | 55 | "(y/n)? [y/N] ",'n') |
|
57 | 56 | if kill: |
|
58 | 57 | self.embedded_active = False |
|
59 | 58 | print "This embedded IPython will not reactivate anymore once you exit." |
|
60 | 59 | |
|
61 | 60 | |
|
62 | 61 | class InteractiveShellEmbed(TerminalInteractiveShell): |
|
63 | 62 | |
|
64 | 63 | dummy_mode = Bool(False) |
|
65 | 64 | exit_msg = Unicode('') |
|
66 | 65 | embedded = CBool(True) |
|
67 | 66 | embedded_active = CBool(True) |
|
68 | 67 | # Like the base class display_banner is not configurable, but here it |
|
69 | 68 | # is True by default. |
|
70 | 69 | display_banner = CBool(True) |
|
71 | 70 | |
|
72 | 71 | def __init__(self, config=None, ipython_dir=None, user_ns=None, |
|
73 | 72 | user_global_ns=None, custom_exceptions=((),None), |
|
74 | 73 | usage=None, banner1=None, banner2=None, |
|
75 | 74 | display_banner=None, exit_msg=u''): |
|
76 | 75 | |
|
77 | 76 | super(InteractiveShellEmbed,self).__init__( |
|
78 | 77 | config=config, ipython_dir=ipython_dir, user_ns=user_ns, |
|
79 | 78 | user_global_ns=user_global_ns, custom_exceptions=custom_exceptions, |
|
80 | 79 | usage=usage, banner1=banner1, banner2=banner2, |
|
81 | 80 | display_banner=display_banner |
|
82 | 81 | ) |
|
83 | 82 | |
|
84 | 83 | self.exit_msg = exit_msg |
|
85 | 84 | self.define_magic("kill_embedded", kill_embedded) |
|
86 | 85 | |
|
87 | 86 | # don't use the ipython crash handler so that user exceptions aren't |
|
88 | 87 | # trapped |
|
89 | 88 | sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, |
|
90 | 89 | mode=self.xmode, |
|
91 | 90 | call_pdb=self.pdb) |
|
92 | 91 | |
|
93 | 92 | def init_sys_modules(self): |
|
94 | 93 | pass |
|
95 | 94 | |
|
96 | 95 | def __call__(self, header='', local_ns=None, global_ns=None, dummy=None, |
|
97 | 96 | stack_depth=1): |
|
98 | 97 | """Activate the interactive interpreter. |
|
99 | 98 | |
|
100 | 99 | __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start |
|
101 | 100 | the interpreter shell with the given local and global namespaces, and |
|
102 | 101 | optionally print a header string at startup. |
|
103 | 102 | |
|
104 | 103 | The shell can be globally activated/deactivated using the |
|
105 | 104 | set/get_dummy_mode methods. This allows you to turn off a shell used |
|
106 | 105 | for debugging globally. |
|
107 | 106 | |
|
108 | 107 | However, *each* time you call the shell you can override the current |
|
109 | 108 | state of dummy_mode with the optional keyword parameter 'dummy'. For |
|
110 | 109 | example, if you set dummy mode on with IPShell.set_dummy_mode(1), you |
|
111 | 110 | can still have a specific call work by making it as IPShell(dummy=0). |
|
112 | 111 | |
|
113 | 112 | The optional keyword parameter dummy controls whether the call |
|
114 | 113 | actually does anything. |
|
115 | 114 | """ |
|
116 | 115 | |
|
117 | 116 | # If the user has turned it off, go away |
|
118 | 117 | if not self.embedded_active: |
|
119 | 118 | return |
|
120 | 119 | |
|
121 | 120 | # Normal exits from interactive mode set this flag, so the shell can't |
|
122 | 121 | # re-enter (it checks this variable at the start of interactive mode). |
|
123 | 122 | self.exit_now = False |
|
124 | 123 | |
|
125 | 124 | # Allow the dummy parameter to override the global __dummy_mode |
|
126 | 125 | if dummy or (dummy != 0 and self.dummy_mode): |
|
127 | 126 | return |
|
128 | 127 | |
|
129 | 128 | if self.has_readline: |
|
130 | 129 | self.set_readline_completer() |
|
131 | 130 | |
|
132 | 131 | # self.banner is auto computed |
|
133 | 132 | if header: |
|
134 | 133 | self.old_banner2 = self.banner2 |
|
135 | 134 | self.banner2 = self.banner2 + '\n' + header + '\n' |
|
136 | 135 | else: |
|
137 | 136 | self.old_banner2 = '' |
|
138 | 137 | |
|
139 | 138 | # Call the embedding code with a stack depth of 1 so it can skip over |
|
140 | 139 | # our call and get the original caller's namespaces. |
|
141 | 140 | self.mainloop(local_ns, global_ns, stack_depth=stack_depth) |
|
142 | 141 | |
|
143 | 142 | self.banner2 = self.old_banner2 |
|
144 | 143 | |
|
145 | 144 | if self.exit_msg is not None: |
|
146 | 145 | print self.exit_msg |
|
147 | 146 | |
|
148 | 147 | def mainloop(self, local_ns=None, global_ns=None, stack_depth=0, |
|
149 | 148 | display_banner=None): |
|
150 | 149 | """Embeds IPython into a running python program. |
|
151 | 150 | |
|
152 | 151 | Input: |
|
153 | 152 | |
|
154 | 153 | - header: An optional header message can be specified. |
|
155 | 154 | |
|
156 | 155 | - local_ns, global_ns: working namespaces. If given as None, the |
|
157 | 156 | IPython-initialized one is updated with __main__.__dict__, so that |
|
158 | 157 | program variables become visible but user-specific configuration |
|
159 | 158 | remains possible. |
|
160 | 159 | |
|
161 | 160 | - stack_depth: specifies how many levels in the stack to go to |
|
162 | 161 | looking for namespaces (when local_ns and global_ns are None). This |
|
163 | 162 | allows an intermediate caller to make sure that this function gets |
|
164 | 163 | the namespace from the intended level in the stack. By default (0) |
|
165 | 164 | it will get its locals and globals from the immediate caller. |
|
166 | 165 | |
|
167 | 166 | Warning: it's possible to use this in a program which is being run by |
|
168 | 167 | IPython itself (via %run), but some funny things will happen (a few |
|
169 | 168 | globals get overwritten). In the future this will be cleaned up, as |
|
170 | 169 | there is no fundamental reason why it can't work perfectly.""" |
|
171 | 170 | |
|
172 | 171 | # Get locals and globals from caller |
|
173 | 172 | if local_ns is None or global_ns is None: |
|
174 | 173 | call_frame = sys._getframe(stack_depth).f_back |
|
175 | 174 | |
|
176 | 175 | if local_ns is None: |
|
177 | 176 | local_ns = call_frame.f_locals |
|
178 | 177 | if global_ns is None: |
|
179 | 178 | global_ns = call_frame.f_globals |
|
180 | 179 | |
|
181 | 180 | # Update namespaces and fire up interpreter |
|
182 | 181 | |
|
183 | 182 | # The global one is easy, we can just throw it in |
|
184 | 183 | self.user_global_ns = global_ns |
|
185 | 184 | |
|
186 | 185 | # but the user/local one is tricky: ipython needs it to store internal |
|
187 | 186 | # data, but we also need the locals. We'll copy locals in the user |
|
188 | 187 | # one, but will track what got copied so we can delete them at exit. |
|
189 | 188 | # This is so that a later embedded call doesn't see locals from a |
|
190 | 189 | # previous call (which most likely existed in a separate scope). |
|
191 | 190 | local_varnames = local_ns.keys() |
|
192 | 191 | self.user_ns.update(local_ns) |
|
193 | 192 | #self.user_ns['local_ns'] = local_ns # dbg |
|
194 | 193 | |
|
195 | 194 | # Patch for global embedding to make sure that things don't overwrite |
|
196 | 195 | # user globals accidentally. Thanks to Richard <rxe@renre-europe.com> |
|
197 | 196 | # FIXME. Test this a bit more carefully (the if.. is new) |
|
198 | 197 | if local_ns is None and global_ns is None: |
|
199 | 198 | self.user_global_ns.update(__main__.__dict__) |
|
200 | 199 | |
|
201 | 200 | # make sure the tab-completer has the correct frame information, so it |
|
202 | 201 | # actually completes using the frame's locals/globals |
|
203 | 202 | self.set_completer_frame() |
|
204 | 203 | |
|
205 | 204 | with nested(self.builtin_trap, self.display_trap): |
|
206 | 205 | self.interact(display_banner=display_banner) |
|
207 | 206 | |
|
208 | 207 | # now, purge out the user namespace from anything we might have added |
|
209 | 208 | # from the caller's local namespace |
|
210 | 209 | delvar = self.user_ns.pop |
|
211 | 210 | for var in local_varnames: |
|
212 | 211 | delvar(var,None) |
|
213 | 212 | |
|
214 | 213 | |
|
215 | 214 | _embedded_shell = None |
|
216 | 215 | |
|
217 | 216 | |
|
218 | 217 | def embed(**kwargs): |
|
219 | 218 | """Call this to embed IPython at the current point in your program. |
|
220 | 219 | |
|
221 | 220 | The first invocation of this will create an :class:`InteractiveShellEmbed` |
|
222 | 221 | instance and then call it. Consecutive calls just call the already |
|
223 | 222 | created instance. |
|
224 | 223 | |
|
225 | 224 | Here is a simple example:: |
|
226 | 225 | |
|
227 | 226 | from IPython import embed |
|
228 | 227 | a = 10 |
|
229 | 228 | b = 20 |
|
230 | 229 | embed('First time') |
|
231 | 230 | c = 30 |
|
232 | 231 | d = 40 |
|
233 | 232 | embed |
|
234 | 233 | |
|
235 | 234 | Full customization can be done by passing a :class:`Struct` in as the |
|
236 | 235 | config argument. |
|
237 | 236 | """ |
|
238 | 237 | config = kwargs.get('config') |
|
239 | 238 | header = kwargs.pop('header', u'') |
|
240 | 239 | if config is None: |
|
241 | 240 | config = load_default_config() |
|
242 | 241 | config.InteractiveShellEmbed = config.TerminalInteractiveShell |
|
243 | 242 | kwargs['config'] = config |
|
244 | 243 | global _embedded_shell |
|
245 | 244 | if _embedded_shell is None: |
|
246 | 245 | _embedded_shell = InteractiveShellEmbed(**kwargs) |
|
247 | 246 | _embedded_shell(header=header, stack_depth=2) |
@@ -1,375 +1,374 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | The :class:`~IPython.core.application.Application` object for the command |
|
5 | 5 | line :command:`ipython` program. |
|
6 | 6 | |
|
7 | 7 | Authors |
|
8 | 8 | ------- |
|
9 | 9 | |
|
10 | 10 | * Brian Granger |
|
11 | 11 | * Fernando Perez |
|
12 | 12 | * Min Ragan-Kelley |
|
13 | 13 | """ |
|
14 | 14 | |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | # Copyright (C) 2008-2010 The IPython Development Team |
|
17 | 17 | # |
|
18 | 18 | # Distributed under the terms of the BSD License. The full license is in |
|
19 | 19 | # the file COPYING, distributed as part of this software. |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | # Imports |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | 26 | from __future__ import absolute_import |
|
27 | 27 | |
|
28 | 28 | import logging |
|
29 | 29 | import os |
|
30 | 30 | import sys |
|
31 | 31 | |
|
32 | 32 | from IPython.config.loader import ( |
|
33 | 33 | Config, PyFileConfigLoader |
|
34 | 34 | ) |
|
35 | 35 | from IPython.config.application import boolean_flag |
|
36 | 36 | from IPython.core import release |
|
37 | 37 | from IPython.core import usage |
|
38 | 38 | from IPython.core.crashhandler import CrashHandler |
|
39 | 39 | from IPython.core.formatters import PlainTextFormatter |
|
40 | 40 | from IPython.core.application import ( |
|
41 | 41 | ProfileDir, BaseIPythonApplication, base_flags, base_aliases |
|
42 | 42 | ) |
|
43 | 43 | from IPython.core.shellapp import ( |
|
44 | 44 | InteractiveShellApp, shell_flags, shell_aliases |
|
45 | 45 | ) |
|
46 | 46 | from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell |
|
47 | 47 | from IPython.lib import inputhook |
|
48 | 48 | from IPython.utils import warn |
|
49 | 49 | from IPython.utils.path import get_ipython_dir, check_for_old_config |
|
50 | 50 | from IPython.utils.traitlets import ( |
|
51 | 51 | Bool, Dict, CaselessStrEnum |
|
52 | 52 | ) |
|
53 | 53 | |
|
54 | 54 | #----------------------------------------------------------------------------- |
|
55 | 55 | # Globals, utilities and helpers |
|
56 | 56 | #----------------------------------------------------------------------------- |
|
57 | 57 | |
|
58 | 58 | #: The default config file name for this application. |
|
59 | 59 | default_config_file_name = u'ipython_config.py' |
|
60 | 60 | |
|
61 | 61 | _examples = """ |
|
62 | 62 | ipython --pylab # start in pylab mode |
|
63 | 63 | ipython --pylab=qt # start in pylab mode with the qt4 backend |
|
64 | 64 | ipython --log-level=DEBUG # set logging to DEBUG |
|
65 | 65 | ipython --profile=foo # start with profile foo |
|
66 | 66 | |
|
67 | 67 | ipython qtconsole # start the qtconsole GUI application |
|
68 | 68 | ipython qtconsole -h # show the help string for the qtconsole subcmd |
|
69 | 69 | |
|
70 | 70 | ipython profile create foo # create profile foo w/ default config files |
|
71 | 71 | ipython profile -h # show the help string for the profile subcmd |
|
72 | 72 | """ |
|
73 | 73 | |
|
74 | 74 | #----------------------------------------------------------------------------- |
|
75 | 75 | # Crash handler for this application |
|
76 | 76 | #----------------------------------------------------------------------------- |
|
77 | 77 | |
|
78 | 78 | class IPAppCrashHandler(CrashHandler): |
|
79 | 79 | """sys.excepthook for IPython itself, leaves a detailed report on disk.""" |
|
80 | 80 | |
|
81 | 81 | def __init__(self, app): |
|
82 | 82 | contact_name = release.authors['Fernando'][0] |
|
83 | 83 | contact_email = release.authors['Fernando'][1] |
|
84 | 84 | bug_tracker = 'http://github.com/ipython/ipython/issues' |
|
85 | 85 | super(IPAppCrashHandler,self).__init__( |
|
86 | 86 | app, contact_name, contact_email, bug_tracker |
|
87 | 87 | ) |
|
88 | 88 | |
|
89 | 89 | def make_report(self,traceback): |
|
90 | 90 | """Return a string containing a crash report.""" |
|
91 | 91 | |
|
92 | 92 | sec_sep = self.section_sep |
|
93 | 93 | # Start with parent report |
|
94 | 94 | report = [super(IPAppCrashHandler, self).make_report(traceback)] |
|
95 | 95 | # Add interactive-specific info we may have |
|
96 | 96 | rpt_add = report.append |
|
97 | 97 | try: |
|
98 | 98 | rpt_add(sec_sep+"History of session input:") |
|
99 | 99 | for line in self.app.shell.user_ns['_ih']: |
|
100 | 100 | rpt_add(line) |
|
101 | 101 | rpt_add('\n*** Last line of input (may not be in above history):\n') |
|
102 | 102 | rpt_add(self.app.shell._last_input_line+'\n') |
|
103 | 103 | except: |
|
104 | 104 | pass |
|
105 | 105 | |
|
106 | 106 | return ''.join(report) |
|
107 | 107 | |
|
108 | 108 | #----------------------------------------------------------------------------- |
|
109 | 109 | # Aliases and Flags |
|
110 | 110 | #----------------------------------------------------------------------------- |
|
111 | 111 | flags = dict(base_flags) |
|
112 | 112 | flags.update(shell_flags) |
|
113 | 113 | addflag = lambda *args: flags.update(boolean_flag(*args)) |
|
114 | 114 | addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax', |
|
115 | 115 | 'Turn on auto editing of files with syntax errors.', |
|
116 | 116 | 'Turn off auto editing of files with syntax errors.' |
|
117 | 117 | ) |
|
118 | 118 | addflag('banner', 'TerminalIPythonApp.display_banner', |
|
119 | 119 | "Display a banner upon starting IPython.", |
|
120 | 120 | "Don't display a banner upon starting IPython." |
|
121 | 121 | ) |
|
122 | 122 | addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit', |
|
123 | 123 | """Set to confirm when you try to exit IPython with an EOF (Control-D |
|
124 | 124 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
125 | 125 | you can force a direct exit without any confirmation.""", |
|
126 | 126 | "Don't prompt the user when exiting." |
|
127 | 127 | ) |
|
128 | 128 | addflag('term-title', 'TerminalInteractiveShell.term_title', |
|
129 | 129 | "Enable auto setting the terminal title.", |
|
130 | 130 | "Disable auto setting the terminal title." |
|
131 | 131 | ) |
|
132 | 132 | classic_config = Config() |
|
133 | 133 | classic_config.InteractiveShell.cache_size = 0 |
|
134 | 134 | classic_config.PlainTextFormatter.pprint = False |
|
135 | 135 | classic_config.InteractiveShell.prompt_in1 = '>>> ' |
|
136 | 136 | classic_config.InteractiveShell.prompt_in2 = '... ' |
|
137 | 137 | classic_config.InteractiveShell.prompt_out = '' |
|
138 | 138 | classic_config.InteractiveShell.separate_in = '' |
|
139 | 139 | classic_config.InteractiveShell.separate_out = '' |
|
140 | 140 | classic_config.InteractiveShell.separate_out2 = '' |
|
141 | 141 | classic_config.InteractiveShell.colors = 'NoColor' |
|
142 | 142 | classic_config.InteractiveShell.xmode = 'Plain' |
|
143 | 143 | |
|
144 | 144 | flags['classic']=( |
|
145 | 145 | classic_config, |
|
146 | 146 | "Gives IPython a similar feel to the classic Python prompt." |
|
147 | 147 | ) |
|
148 | 148 | # # log doesn't make so much sense this way anymore |
|
149 | 149 | # paa('--log','-l', |
|
150 | 150 | # action='store_true', dest='InteractiveShell.logstart', |
|
151 | 151 | # help="Start logging to the default log file (./ipython_log.py).") |
|
152 | 152 | # |
|
153 | 153 | # # quick is harder to implement |
|
154 | 154 | flags['quick']=( |
|
155 | 155 | {'TerminalIPythonApp' : {'quick' : True}}, |
|
156 | 156 | "Enable quick startup with no config files." |
|
157 | 157 | ) |
|
158 | 158 | |
|
159 | 159 | flags['i'] = ( |
|
160 | 160 | {'TerminalIPythonApp' : {'force_interact' : True}}, |
|
161 | 161 | """If running code from the command line, become interactive afterwards. |
|
162 | 162 | Note: can also be given simply as '-i.'""" |
|
163 | 163 | ) |
|
164 | 164 | flags['pylab'] = ( |
|
165 | 165 | {'TerminalIPythonApp' : {'pylab' : 'auto'}}, |
|
166 | 166 | """Pre-load matplotlib and numpy for interactive use with |
|
167 | 167 | the default matplotlib backend.""" |
|
168 | 168 | ) |
|
169 | 169 | |
|
170 | 170 | aliases = dict(base_aliases) |
|
171 | 171 | aliases.update(shell_aliases) |
|
172 | 172 | |
|
173 | 173 | # it's possible we don't want short aliases for *all* of these: |
|
174 | 174 | aliases.update(dict( |
|
175 | 175 | gui='TerminalIPythonApp.gui', |
|
176 | 176 | pylab='TerminalIPythonApp.pylab', |
|
177 | 177 | )) |
|
178 | 178 | |
|
179 | 179 | #----------------------------------------------------------------------------- |
|
180 | 180 | # Main classes and functions |
|
181 | 181 | #----------------------------------------------------------------------------- |
|
182 | 182 | |
|
183 | 183 | class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): |
|
184 | 184 | name = u'ipython' |
|
185 | 185 | description = usage.cl_usage |
|
186 | 186 | default_config_file_name = default_config_file_name |
|
187 | 187 | crash_handler_class = IPAppCrashHandler |
|
188 | 188 | examples = _examples |
|
189 | 189 | |
|
190 | 190 | flags = Dict(flags) |
|
191 | 191 | aliases = Dict(aliases) |
|
192 | 192 | classes = [InteractiveShellApp, TerminalInteractiveShell, ProfileDir, |
|
193 | 193 | PlainTextFormatter] |
|
194 | 194 | subcommands = Dict(dict( |
|
195 | 195 | qtconsole=('IPython.frontend.qt.console.qtconsoleapp.IPythonQtConsoleApp', |
|
196 | 196 | """Launch the IPython Qt Console.""" |
|
197 | 197 | ), |
|
198 | 198 | profile = ("IPython.core.profileapp.ProfileApp", |
|
199 | 199 | "Create and manage IPython profiles.") |
|
200 | 200 | )) |
|
201 | 201 | |
|
202 | 202 | # *do* autocreate requested profile, but don't create the config file. |
|
203 | 203 | auto_create=Bool(True) |
|
204 | 204 | # configurables |
|
205 | 205 | ignore_old_config=Bool(False, config=True, |
|
206 | 206 | help="Suppress warning messages about legacy config files" |
|
207 | 207 | ) |
|
208 | 208 | quick = Bool(False, config=True, |
|
209 | 209 | help="""Start IPython quickly by skipping the loading of config files.""" |
|
210 | 210 | ) |
|
211 | 211 | def _quick_changed(self, name, old, new): |
|
212 | 212 | if new: |
|
213 | 213 | self.load_config_file = lambda *a, **kw: None |
|
214 | 214 | self.ignore_old_config=True |
|
215 | 215 | |
|
216 | 216 | gui = CaselessStrEnum(('qt','wx','gtk'), config=True, |
|
217 | 217 | help="Enable GUI event loop integration ('qt', 'wx', 'gtk')." |
|
218 | 218 | ) |
|
219 | 219 | pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'], |
|
220 | 220 | config=True, |
|
221 | 221 | help="""Pre-load matplotlib and numpy for interactive use, |
|
222 | 222 | selecting a particular matplotlib backend and loop integration. |
|
223 | 223 | """ |
|
224 | 224 | ) |
|
225 | 225 | display_banner = Bool(True, config=True, |
|
226 | 226 | help="Whether to display a banner upon starting IPython." |
|
227 | 227 | ) |
|
228 | 228 | |
|
229 | 229 | # if there is code of files to run from the cmd line, don't interact |
|
230 | 230 | # unless the --i flag (App.force_interact) is true. |
|
231 | 231 | force_interact = Bool(False, config=True, |
|
232 | 232 | help="""If a command or file is given via the command-line, |
|
233 | 233 | e.g. 'ipython foo.py""" |
|
234 | 234 | ) |
|
235 | 235 | def _force_interact_changed(self, name, old, new): |
|
236 | 236 | if new: |
|
237 | 237 | self.interact = True |
|
238 | 238 | |
|
239 | 239 | def _file_to_run_changed(self, name, old, new): |
|
240 | 240 | if new and not self.force_interact: |
|
241 | 241 | self.interact = False |
|
242 | 242 | _code_to_run_changed = _file_to_run_changed |
|
243 | 243 | |
|
244 | 244 | # internal, not-configurable |
|
245 | 245 | interact=Bool(True) |
|
246 | 246 | |
|
247 | 247 | |
|
248 | 248 | def parse_command_line(self, argv=None): |
|
249 | 249 | """override to allow old '-pylab' flag with deprecation warning""" |
|
250 | 250 | |
|
251 | 251 | argv = sys.argv[1:] if argv is None else argv |
|
252 | 252 | |
|
253 | 253 | if '-pylab' in argv: |
|
254 | 254 | # deprecated `-pylab` given, |
|
255 | 255 | # warn and transform into current syntax |
|
256 | 256 | argv = argv[:] # copy, don't clobber |
|
257 | 257 | idx = argv.index('-pylab') |
|
258 | 258 | warn.warn("`-pylab` flag has been deprecated.\n" |
|
259 | 259 | " Use `--pylab` instead, or `--pylab=foo` to specify a backend.") |
|
260 | 260 | sub = '--pylab' |
|
261 | 261 | if len(argv) > idx+1: |
|
262 | 262 | # check for gui arg, as in '-pylab qt' |
|
263 | 263 | gui = argv[idx+1] |
|
264 | 264 | if gui in ('wx', 'qt', 'qt4', 'gtk', 'auto'): |
|
265 | 265 | sub = '--pylab='+gui |
|
266 | 266 | argv.pop(idx+1) |
|
267 | 267 | argv[idx] = sub |
|
268 | 268 | |
|
269 | 269 | return super(TerminalIPythonApp, self).parse_command_line(argv) |
|
270 | 270 | |
|
271 | 271 | def initialize(self, argv=None): |
|
272 | 272 | """Do actions after construct, but before starting the app.""" |
|
273 | 273 | super(TerminalIPythonApp, self).initialize(argv) |
|
274 | 274 | if self.subapp is not None: |
|
275 | 275 | # don't bother initializing further, starting subapp |
|
276 | 276 | return |
|
277 | 277 | if not self.ignore_old_config: |
|
278 | 278 | check_for_old_config(self.ipython_dir) |
|
279 | 279 | # print self.extra_args |
|
280 | 280 | if self.extra_args: |
|
281 | 281 | self.file_to_run = self.extra_args[0] |
|
282 | 282 | # create the shell |
|
283 | 283 | self.init_shell() |
|
284 | 284 | # and draw the banner |
|
285 | 285 | self.init_banner() |
|
286 | 286 | # Now a variety of things that happen after the banner is printed. |
|
287 | 287 | self.init_gui_pylab() |
|
288 | 288 | self.init_extensions() |
|
289 | 289 | self.init_code() |
|
290 | 290 | |
|
291 | 291 | def init_shell(self): |
|
292 | 292 | """initialize the InteractiveShell instance""" |
|
293 | 293 | # I am a little hesitant to put these into InteractiveShell itself. |
|
294 | 294 | # But that might be the place for them |
|
295 | 295 | sys.path.insert(0, '') |
|
296 | 296 | |
|
297 | 297 | # Create an InteractiveShell instance. |
|
298 | 298 | # shell.display_banner should always be False for the terminal |
|
299 | 299 | # based app, because we call shell.show_banner() by hand below |
|
300 | 300 | # so the banner shows *before* all extension loading stuff. |
|
301 | 301 | self.shell = TerminalInteractiveShell.instance(config=self.config, |
|
302 | 302 | display_banner=False, profile_dir=self.profile_dir, |
|
303 | 303 | ipython_dir=self.ipython_dir) |
|
304 | 304 | |
|
305 | 305 | def init_banner(self): |
|
306 | 306 | """optionally display the banner""" |
|
307 | 307 | if self.display_banner and self.interact: |
|
308 | 308 | self.shell.show_banner() |
|
309 | 309 | # Make sure there is a space below the banner. |
|
310 | 310 | if self.log_level <= logging.INFO: print |
|
311 | 311 | |
|
312 | 312 | |
|
313 | 313 | def init_gui_pylab(self): |
|
314 | 314 | """Enable GUI event loop integration, taking pylab into account.""" |
|
315 | 315 | gui = self.gui |
|
316 | 316 | |
|
317 | 317 | # Using `pylab` will also require gui activation, though which toolkit |
|
318 | 318 | # to use may be chosen automatically based on mpl configuration. |
|
319 | 319 | if self.pylab: |
|
320 | 320 | activate = self.shell.enable_pylab |
|
321 | 321 | if self.pylab == 'auto': |
|
322 | 322 | gui = None |
|
323 | 323 | else: |
|
324 | 324 | gui = self.pylab |
|
325 | 325 | else: |
|
326 | 326 | # Enable only GUI integration, no pylab |
|
327 | 327 | activate = inputhook.enable_gui |
|
328 | 328 | |
|
329 | 329 | if gui or self.pylab: |
|
330 | 330 | try: |
|
331 | 331 | self.log.info("Enabling GUI event loop integration, " |
|
332 | 332 | "toolkit=%s, pylab=%s" % (gui, self.pylab) ) |
|
333 | 333 | activate(gui) |
|
334 | 334 | except: |
|
335 | 335 | self.log.warn("Error in enabling GUI event loop integration:") |
|
336 | 336 | self.shell.showtraceback() |
|
337 | 337 | |
|
338 | 338 | def start(self): |
|
339 | 339 | if self.subapp is not None: |
|
340 | 340 | return self.subapp.start() |
|
341 | 341 | # perform any prexec steps: |
|
342 | 342 | if self.interact: |
|
343 | 343 | self.log.debug("Starting IPython's mainloop...") |
|
344 | 344 | self.shell.mainloop() |
|
345 | 345 | else: |
|
346 | 346 | self.log.debug("IPython not interactive...") |
|
347 | 347 | |
|
348 | 348 | |
|
349 | 349 | def load_default_config(ipython_dir=None): |
|
350 | 350 | """Load the default config file from the default ipython_dir. |
|
351 | 351 | |
|
352 | 352 | This is useful for embedded shells. |
|
353 | 353 | """ |
|
354 | 354 | if ipython_dir is None: |
|
355 | 355 | ipython_dir = get_ipython_dir() |
|
356 | 356 | profile_dir = os.path.join(ipython_dir, 'profile_default') |
|
357 | 357 | cl = PyFileConfigLoader(default_config_file_name, profile_dir) |
|
358 | 358 | try: |
|
359 | 359 | config = cl.load_config() |
|
360 | 360 | except IOError: |
|
361 | 361 | # no config found |
|
362 | 362 | config = Config() |
|
363 | 363 | return config |
|
364 | 364 | |
|
365 | 365 | |
|
366 | 366 | def launch_new_instance(): |
|
367 | 367 | """Create and run a full blown IPython instance""" |
|
368 | 368 | app = TerminalIPythonApp.instance() |
|
369 | 369 | app.initialize() |
|
370 | 370 | app.start() |
|
371 | 371 | |
|
372 | 372 | |
|
373 | 373 | if __name__ == '__main__': |
|
374 | 374 | launch_new_instance() |
|
375 |
@@ -1,441 +1,437 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | """Module for interactively running scripts. |
|
3 | 3 | |
|
4 | 4 | This module implements classes for interactively running scripts written for |
|
5 | 5 | any system with a prompt which can be matched by a regexp suitable for |
|
6 | 6 | pexpect. It can be used to run as if they had been typed up interactively, an |
|
7 | 7 | arbitrary series of commands for the target system. |
|
8 | 8 | |
|
9 | 9 | The module includes classes ready for IPython (with the default prompts), |
|
10 | 10 | plain Python and SAGE, but making a new one is trivial. To see how to use it, |
|
11 | 11 | simply run the module as a script: |
|
12 | 12 | |
|
13 | 13 | ./irunner.py --help |
|
14 | 14 | |
|
15 | 15 | |
|
16 | 16 | This is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s script |
|
17 | 17 | contributed on the ipython-user list: |
|
18 | 18 | |
|
19 | 19 | http://scipy.net/pipermail/ipython-user/2006-May/001705.html |
|
20 | 20 | |
|
21 | 21 | |
|
22 | 22 | NOTES: |
|
23 | 23 | |
|
24 | 24 | - This module requires pexpect, available in most linux distros, or which can |
|
25 | 25 | be downloaded from |
|
26 | 26 | |
|
27 | 27 | http://pexpect.sourceforge.net |
|
28 | 28 | |
|
29 | 29 | - Because pexpect only works under Unix or Windows-Cygwin, this has the same |
|
30 | 30 | limitations. This means that it will NOT work under native windows Python. |
|
31 | 31 | """ |
|
32 | 32 | |
|
33 | 33 | # Stdlib imports |
|
34 | 34 | import optparse |
|
35 | 35 | import os |
|
36 | 36 | import sys |
|
37 | 37 | |
|
38 | 38 | # Third-party modules. |
|
39 | 39 | import pexpect |
|
40 | 40 | |
|
41 | 41 | # Global usage strings, to avoid indentation issues when typing it below. |
|
42 | 42 | USAGE = """ |
|
43 | 43 | Interactive script runner, type: %s |
|
44 | 44 | |
|
45 | 45 | runner [opts] script_name |
|
46 | 46 | """ |
|
47 | 47 | |
|
48 | 48 | def pexpect_monkeypatch(): |
|
49 | 49 | """Patch pexpect to prevent unhandled exceptions at VM teardown. |
|
50 | 50 | |
|
51 | 51 | Calling this function will monkeypatch the pexpect.spawn class and modify |
|
52 | 52 | its __del__ method to make it more robust in the face of failures that can |
|
53 | 53 | occur if it is called when the Python VM is shutting down. |
|
54 | 54 | |
|
55 | 55 | Since Python may fire __del__ methods arbitrarily late, it's possible for |
|
56 | 56 | them to execute during the teardown of the Python VM itself. At this |
|
57 | 57 | point, various builtin modules have been reset to None. Thus, the call to |
|
58 | 58 | self.close() will trigger an exception because it tries to call os.close(), |
|
59 | 59 | and os is now None. |
|
60 | 60 | """ |
|
61 | 61 | |
|
62 | 62 | if pexpect.__version__[:3] >= '2.2': |
|
63 | 63 | # No need to patch, fix is already the upstream version. |
|
64 | 64 | return |
|
65 | 65 | |
|
66 | 66 | def __del__(self): |
|
67 | 67 | """This makes sure that no system resources are left open. |
|
68 | 68 | Python only garbage collects Python objects. OS file descriptors |
|
69 | 69 | are not Python objects, so they must be handled explicitly. |
|
70 | 70 | If the child file descriptor was opened outside of this class |
|
71 | 71 | (passed to the constructor) then this does not close it. |
|
72 | 72 | """ |
|
73 | 73 | if not self.closed: |
|
74 | 74 | try: |
|
75 | 75 | self.close() |
|
76 | 76 | except AttributeError: |
|
77 | 77 | pass |
|
78 | 78 | |
|
79 | 79 | pexpect.spawn.__del__ = __del__ |
|
80 | 80 | |
|
81 | 81 | pexpect_monkeypatch() |
|
82 | 82 | |
|
83 | 83 | # The generic runner class |
|
84 | 84 | class InteractiveRunner(object): |
|
85 | 85 | """Class to run a sequence of commands through an interactive program.""" |
|
86 | 86 | |
|
87 | 87 | def __init__(self,program,prompts,args=None,out=sys.stdout,echo=True): |
|
88 | 88 | """Construct a runner. |
|
89 | 89 | |
|
90 | 90 | Inputs: |
|
91 | 91 | |
|
92 | 92 | - program: command to execute the given program. |
|
93 | 93 | |
|
94 | 94 | - prompts: a list of patterns to match as valid prompts, in the |
|
95 | 95 | format used by pexpect. This basically means that it can be either |
|
96 | 96 | a string (to be compiled as a regular expression) or a list of such |
|
97 | 97 | (it must be a true list, as pexpect does type checks). |
|
98 | 98 | |
|
99 | 99 | If more than one prompt is given, the first is treated as the main |
|
100 | 100 | program prompt and the others as 'continuation' prompts, like |
|
101 | 101 | python's. This means that blank lines in the input source are |
|
102 | 102 | ommitted when the first prompt is matched, but are NOT ommitted when |
|
103 | 103 | the continuation one matches, since this is how python signals the |
|
104 | 104 | end of multiline input interactively. |
|
105 | 105 | |
|
106 | 106 | Optional inputs: |
|
107 | 107 | |
|
108 | 108 | - args(None): optional list of strings to pass as arguments to the |
|
109 | 109 | child program. |
|
110 | 110 | |
|
111 | 111 | - out(sys.stdout): if given, an output stream to be used when writing |
|
112 | 112 | output. The only requirement is that it must have a .write() method. |
|
113 | 113 | |
|
114 | 114 | Public members not parameterized in the constructor: |
|
115 | 115 | |
|
116 | 116 | - delaybeforesend(0): Newer versions of pexpect have a delay before |
|
117 | 117 | sending each new input. For our purposes here, it's typically best |
|
118 | 118 | to just set this to zero, but if you encounter reliability problems |
|
119 | 119 | or want an interactive run to pause briefly at each prompt, just |
|
120 | 120 | increase this value (it is measured in seconds). Note that this |
|
121 | 121 | variable is not honored at all by older versions of pexpect. |
|
122 | 122 | """ |
|
123 | 123 | |
|
124 | 124 | self.program = program |
|
125 | 125 | self.prompts = prompts |
|
126 | 126 | if args is None: args = [] |
|
127 | 127 | self.args = args |
|
128 | 128 | self.out = out |
|
129 | 129 | self.echo = echo |
|
130 | 130 | # Other public members which we don't make as parameters, but which |
|
131 | 131 | # users may occasionally want to tweak |
|
132 | 132 | self.delaybeforesend = 0 |
|
133 | 133 | |
|
134 | 134 | # Create child process and hold on to it so we don't have to re-create |
|
135 | 135 | # for every single execution call |
|
136 | 136 | c = self.child = pexpect.spawn(self.program,self.args,timeout=None) |
|
137 | 137 | c.delaybeforesend = self.delaybeforesend |
|
138 | 138 | # pexpect hard-codes the terminal size as (24,80) (rows,columns). |
|
139 | 139 | # This causes problems because any line longer than 80 characters gets |
|
140 | 140 | # completely overwrapped on the printed outptut (even though |
|
141 | 141 | # internally the code runs fine). We reset this to 99 rows X 200 |
|
142 | 142 | # columns (arbitrarily chosen), which should avoid problems in all |
|
143 | 143 | # reasonable cases. |
|
144 | 144 | c.setwinsize(99,200) |
|
145 | 145 | |
|
146 | 146 | def close(self): |
|
147 | 147 | """close child process""" |
|
148 | 148 | |
|
149 | 149 | self.child.close() |
|
150 | 150 | |
|
151 | 151 | def run_file(self,fname,interact=False,get_output=False): |
|
152 | 152 | """Run the given file interactively. |
|
153 | 153 | |
|
154 | 154 | Inputs: |
|
155 | 155 | |
|
156 | 156 | -fname: name of the file to execute. |
|
157 | 157 | |
|
158 | 158 | See the run_source docstring for the meaning of the optional |
|
159 | 159 | arguments.""" |
|
160 | 160 | |
|
161 | 161 | fobj = open(fname,'r') |
|
162 | 162 | try: |
|
163 | 163 | out = self.run_source(fobj,interact,get_output) |
|
164 | 164 | finally: |
|
165 | 165 | fobj.close() |
|
166 | 166 | if get_output: |
|
167 | 167 | return out |
|
168 | 168 | |
|
169 | 169 | def run_source(self,source,interact=False,get_output=False): |
|
170 | 170 | """Run the given source code interactively. |
|
171 | 171 | |
|
172 | 172 | Inputs: |
|
173 | 173 | |
|
174 | 174 | - source: a string of code to be executed, or an open file object we |
|
175 | 175 | can iterate over. |
|
176 | 176 | |
|
177 | 177 | Optional inputs: |
|
178 | 178 | |
|
179 | 179 | - interact(False): if true, start to interact with the running |
|
180 | 180 | program at the end of the script. Otherwise, just exit. |
|
181 | 181 | |
|
182 | 182 | - get_output(False): if true, capture the output of the child process |
|
183 | 183 | (filtering the input commands out) and return it as a string. |
|
184 | 184 | |
|
185 | 185 | Returns: |
|
186 | 186 | A string containing the process output, but only if requested. |
|
187 | 187 | """ |
|
188 | 188 | |
|
189 | 189 | # if the source is a string, chop it up in lines so we can iterate |
|
190 | 190 | # over it just as if it were an open file. |
|
191 | 191 | if not isinstance(source,file): |
|
192 | 192 | source = source.splitlines(True) |
|
193 | 193 | |
|
194 | 194 | if self.echo: |
|
195 | 195 | # normalize all strings we write to use the native OS line |
|
196 | 196 | # separators. |
|
197 | 197 | linesep = os.linesep |
|
198 | 198 | stdwrite = self.out.write |
|
199 | 199 | write = lambda s: stdwrite(s.replace('\r\n',linesep)) |
|
200 | 200 | else: |
|
201 | 201 | # Quiet mode, all writes are no-ops |
|
202 | 202 | write = lambda s: None |
|
203 | 203 | |
|
204 | 204 | c = self.child |
|
205 | 205 | prompts = c.compile_pattern_list(self.prompts) |
|
206 | 206 | prompt_idx = c.expect_list(prompts) |
|
207 | 207 | |
|
208 | 208 | # Flag whether the script ends normally or not, to know whether we can |
|
209 | 209 | # do anything further with the underlying process. |
|
210 | 210 | end_normal = True |
|
211 | 211 | |
|
212 | 212 | # If the output was requested, store it in a list for return at the end |
|
213 | 213 | if get_output: |
|
214 | 214 | output = [] |
|
215 | 215 | store_output = output.append |
|
216 | 216 | |
|
217 | 217 | for cmd in source: |
|
218 | 218 | # skip blank lines for all matches to the 'main' prompt, while the |
|
219 | 219 | # secondary prompts do not |
|
220 | 220 | if prompt_idx==0 and \ |
|
221 | 221 | (cmd.isspace() or cmd.lstrip().startswith('#')): |
|
222 | 222 | write(cmd) |
|
223 | 223 | continue |
|
224 | 224 | |
|
225 | 225 | # write('AFTER: '+c.after) # dbg |
|
226 | 226 | write(c.after) |
|
227 | 227 | c.send(cmd) |
|
228 | 228 | try: |
|
229 | 229 | prompt_idx = c.expect_list(prompts) |
|
230 | 230 | except pexpect.EOF: |
|
231 | 231 | # this will happen if the child dies unexpectedly |
|
232 | 232 | write(c.before) |
|
233 | 233 | end_normal = False |
|
234 | 234 | break |
|
235 | 235 | |
|
236 | 236 | write(c.before) |
|
237 | 237 | |
|
238 | 238 | # With an echoing process, the output we get in c.before contains |
|
239 | 239 | # the command sent, a newline, and then the actual process output |
|
240 | 240 | if get_output: |
|
241 | 241 | store_output(c.before[len(cmd+'\n'):]) |
|
242 | 242 | #write('CMD: <<%s>>' % cmd) # dbg |
|
243 | 243 | #write('OUTPUT: <<%s>>' % output[-1]) # dbg |
|
244 | 244 | |
|
245 | 245 | self.out.flush() |
|
246 | 246 | if end_normal: |
|
247 | 247 | if interact: |
|
248 | 248 | c.send('\n') |
|
249 | 249 | print '<< Starting interactive mode >>', |
|
250 | 250 | try: |
|
251 | 251 | c.interact() |
|
252 | 252 | except OSError: |
|
253 | 253 | # This is what fires when the child stops. Simply print a |
|
254 | 254 | # newline so the system prompt is aligned. The extra |
|
255 | 255 | # space is there to make sure it gets printed, otherwise |
|
256 | 256 | # OS buffering sometimes just suppresses it. |
|
257 | 257 | write(' \n') |
|
258 | 258 | self.out.flush() |
|
259 | 259 | else: |
|
260 | 260 | if interact: |
|
261 | 261 | e="Further interaction is not possible: child process is dead." |
|
262 | 262 | print >> sys.stderr, e |
|
263 | 263 | |
|
264 | 264 | # Leave the child ready for more input later on, otherwise select just |
|
265 | 265 | # hangs on the second invocation. |
|
266 | 266 | if c.isalive(): |
|
267 | 267 | c.send('\n') |
|
268 | 268 | |
|
269 | 269 | # Return any requested output |
|
270 | 270 | if get_output: |
|
271 | 271 | return ''.join(output) |
|
272 | 272 | |
|
273 | 273 | def main(self,argv=None): |
|
274 | 274 | """Run as a command-line script.""" |
|
275 | 275 | |
|
276 | 276 | parser = optparse.OptionParser(usage=USAGE % self.__class__.__name__) |
|
277 | 277 | newopt = parser.add_option |
|
278 | 278 | newopt('-i','--interact',action='store_true',default=False, |
|
279 | 279 | help='Interact with the program after the script is run.') |
|
280 | 280 | |
|
281 | 281 | opts,args = parser.parse_args(argv) |
|
282 | 282 | |
|
283 | 283 | if len(args) != 1: |
|
284 | 284 | print >> sys.stderr,"You must supply exactly one file to run." |
|
285 | 285 | sys.exit(1) |
|
286 | 286 | |
|
287 | 287 | self.run_file(args[0],opts.interact) |
|
288 | 288 | |
|
289 | 289 | |
|
290 | 290 | # Specific runners for particular programs |
|
291 | 291 | class IPythonRunner(InteractiveRunner): |
|
292 | 292 | """Interactive IPython runner. |
|
293 | 293 | |
|
294 | 294 | This initalizes IPython in 'nocolor' mode for simplicity. This lets us |
|
295 | 295 | avoid having to write a regexp that matches ANSI sequences, though pexpect |
|
296 | 296 | does support them. If anyone contributes patches for ANSI color support, |
|
297 | 297 | they will be welcome. |
|
298 | 298 | |
|
299 | 299 | It also sets the prompts manually, since the prompt regexps for |
|
300 | 300 | pexpect need to be matched to the actual prompts, so user-customized |
|
301 | 301 | prompts would break this. |
|
302 | 302 | """ |
|
303 | 303 | |
|
304 | 304 | def __init__(self,program = 'ipython',args=None,out=sys.stdout,echo=True): |
|
305 | 305 | """New runner, optionally passing the ipython command to use.""" |
|
306 | 306 | args0 = ['--colors=NoColor', |
|
307 | 307 | '--no-term-title', |
|
308 | 308 | '--no-autoindent', |
|
309 | 309 | # '--quick' is important, to prevent loading default config: |
|
310 | 310 | '--quick'] |
|
311 | 311 | if args is None: args = args0 |
|
312 | 312 | else: args = args0 + args |
|
313 | 313 | prompts = [r'In \[\d+\]: ',r' \.*: '] |
|
314 | 314 | InteractiveRunner.__init__(self,program,prompts,args,out,echo) |
|
315 | 315 | |
|
316 | 316 | |
|
317 | 317 | class PythonRunner(InteractiveRunner): |
|
318 | 318 | """Interactive Python runner.""" |
|
319 | 319 | |
|
320 | 320 | def __init__(self,program='python',args=None,out=sys.stdout,echo=True): |
|
321 | 321 | """New runner, optionally passing the python command to use.""" |
|
322 | 322 | |
|
323 | 323 | prompts = [r'>>> ',r'\.\.\. '] |
|
324 | 324 | InteractiveRunner.__init__(self,program,prompts,args,out,echo) |
|
325 | 325 | |
|
326 | 326 | |
|
327 | 327 | class SAGERunner(InteractiveRunner): |
|
328 | 328 | """Interactive SAGE runner. |
|
329 | 329 | |
|
330 | 330 | WARNING: this runner only works if you manually configure your SAGE copy |
|
331 | 331 | to use 'colors NoColor' in the ipythonrc config file, since currently the |
|
332 | 332 | prompt matching regexp does not identify color sequences.""" |
|
333 | 333 | |
|
334 | 334 | def __init__(self,program='sage',args=None,out=sys.stdout,echo=True): |
|
335 | 335 | """New runner, optionally passing the sage command to use.""" |
|
336 | 336 | |
|
337 | 337 | prompts = ['sage: ',r'\s*\.\.\. '] |
|
338 | 338 | InteractiveRunner.__init__(self,program,prompts,args,out,echo) |
|
339 | 339 | |
|
340 | 340 | |
|
341 | 341 | class RunnerFactory(object): |
|
342 | 342 | """Code runner factory. |
|
343 | 343 | |
|
344 | 344 | This class provides an IPython code runner, but enforces that only one |
|
345 | 345 | runner is ever instantiated. The runner is created based on the extension |
|
346 | 346 | of the first file to run, and it raises an exception if a runner is later |
|
347 | 347 | requested for a different extension type. |
|
348 | 348 | |
|
349 | 349 | This ensures that we don't generate example files for doctest with a mix of |
|
350 | 350 | python and ipython syntax. |
|
351 | 351 | """ |
|
352 | 352 | |
|
353 | 353 | def __init__(self,out=sys.stdout): |
|
354 | 354 | """Instantiate a code runner.""" |
|
355 | 355 | |
|
356 | 356 | self.out = out |
|
357 | 357 | self.runner = None |
|
358 | 358 | self.runnerClass = None |
|
359 | 359 | |
|
360 | 360 | def _makeRunner(self,runnerClass): |
|
361 | 361 | self.runnerClass = runnerClass |
|
362 | 362 | self.runner = runnerClass(out=self.out) |
|
363 | 363 | return self.runner |
|
364 | 364 | |
|
365 | 365 | def __call__(self,fname): |
|
366 | 366 | """Return a runner for the given filename.""" |
|
367 | 367 | |
|
368 | 368 | if fname.endswith('.py'): |
|
369 | 369 | runnerClass = PythonRunner |
|
370 | 370 | elif fname.endswith('.ipy'): |
|
371 | 371 | runnerClass = IPythonRunner |
|
372 | 372 | else: |
|
373 | 373 | raise ValueError('Unknown file type for Runner: %r' % fname) |
|
374 | 374 | |
|
375 | 375 | if self.runner is None: |
|
376 | 376 | return self._makeRunner(runnerClass) |
|
377 | 377 | else: |
|
378 | 378 | if runnerClass==self.runnerClass: |
|
379 | 379 | return self.runner |
|
380 | 380 | else: |
|
381 | 381 | e='A runner of type %r can not run file %r' % \ |
|
382 | 382 | (self.runnerClass,fname) |
|
383 | 383 | raise ValueError(e) |
|
384 | 384 | |
|
385 | 385 | |
|
386 | 386 | # Global usage string, to avoid indentation issues if typed in a function def. |
|
387 | 387 | MAIN_USAGE = """ |
|
388 | 388 | %prog [options] file_to_run |
|
389 | 389 | |
|
390 | 390 | This is an interface to the various interactive runners available in this |
|
391 | 391 | module. If you want to pass specific options to one of the runners, you need |
|
392 | 392 | to first terminate the main options with a '--', and then provide the runner's |
|
393 | 393 | options. For example: |
|
394 | 394 | |
|
395 | 395 | irunner.py --python -- --help |
|
396 | 396 | |
|
397 | 397 | will pass --help to the python runner. Similarly, |
|
398 | 398 | |
|
399 | 399 | irunner.py --ipython -- --interact script.ipy |
|
400 | 400 | |
|
401 | 401 | will run the script.ipy file under the IPython runner, and then will start to |
|
402 | 402 | interact with IPython at the end of the script (instead of exiting). |
|
403 | 403 | |
|
404 | 404 | The already implemented runners are listed below; adding one for a new program |
|
405 | 405 | is a trivial task, see the source for examples. |
|
406 | ||
|
407 | WARNING: the SAGE runner only works if you manually configure your SAGE copy | |
|
408 | to use 'colors NoColor' in the ipythonrc config file, since currently the | |
|
409 | prompt matching regexp does not identify color sequences. | |
|
410 | 406 | """ |
|
411 | 407 | |
|
412 | 408 | def main(): |
|
413 | 409 | """Run as a command-line script.""" |
|
414 | 410 | |
|
415 | 411 | parser = optparse.OptionParser(usage=MAIN_USAGE) |
|
416 | 412 | newopt = parser.add_option |
|
417 | 413 | parser.set_defaults(mode='ipython') |
|
418 | 414 | newopt('--ipython',action='store_const',dest='mode',const='ipython', |
|
419 | 415 | help='IPython interactive runner (default).') |
|
420 | 416 | newopt('--python',action='store_const',dest='mode',const='python', |
|
421 | 417 | help='Python interactive runner.') |
|
422 | 418 | newopt('--sage',action='store_const',dest='mode',const='sage', |
|
423 | 419 | help='SAGE interactive runner.') |
|
424 | 420 | |
|
425 | 421 | opts,args = parser.parse_args() |
|
426 | 422 | runners = dict(ipython=IPythonRunner, |
|
427 | 423 | python=PythonRunner, |
|
428 | 424 | sage=SAGERunner) |
|
429 | 425 | |
|
430 | 426 | try: |
|
431 | 427 | ext = os.path.splitext(args[0])[-1] |
|
432 | 428 | except IndexError: |
|
433 | 429 | ext = '' |
|
434 | 430 | modes = {'.ipy':'ipython', |
|
435 | 431 | '.py':'python', |
|
436 | 432 | '.sage':'sage'} |
|
437 | 433 | mode = modes.get(ext,opts.mode) |
|
438 | 434 | runners[mode]().main(args) |
|
439 | 435 | |
|
440 | 436 | if __name__ == '__main__': |
|
441 | 437 | main() |
@@ -1,321 +1,322 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Pylab (matplotlib) support utilities. |
|
3 | 3 | |
|
4 | 4 | Authors |
|
5 | 5 | ------- |
|
6 | 6 | |
|
7 | 7 | * Fernando Perez. |
|
8 | 8 | * Brian Granger |
|
9 | 9 | """ |
|
10 | 10 | |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | # Copyright (C) 2009 The IPython Development Team |
|
13 | 13 | # |
|
14 | 14 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | 15 | # the file COPYING, distributed as part of this software. |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | # Imports |
|
20 | 20 | #----------------------------------------------------------------------------- |
|
21 | 21 | |
|
22 | 22 | from cStringIO import StringIO |
|
23 | 23 | |
|
24 | 24 | from IPython.utils.decorators import flag_calls |
|
25 | 25 | |
|
26 | 26 | # If user specifies a GUI, that dictates the backend, otherwise we read the |
|
27 | 27 | # user's mpl default from the mpl rc structure |
|
28 | 28 | backends = {'tk': 'TkAgg', |
|
29 | 29 | 'gtk': 'GTKAgg', |
|
30 | 30 | 'wx': 'WXAgg', |
|
31 | 31 | 'qt': 'Qt4Agg', # qt3 not supported |
|
32 | 32 | 'qt4': 'Qt4Agg', |
|
33 | 33 | 'osx': 'MacOSX', |
|
34 | 34 | 'inline' : 'module://IPython.zmq.pylab.backend_inline'} |
|
35 | 35 | |
|
36 | 36 | # We also need a reverse backends2guis mapping that will properly choose which |
|
37 | 37 | # GUI support to activate based on the desired matplotlib backend. For the |
|
38 | 38 | # most part it's just a reverse of the above dict, but we also need to add a |
|
39 | 39 | # few others that map to the same GUI manually: |
|
40 | 40 | backend2gui = dict(zip(backends.values(), backends.keys())) |
|
41 | 41 | # In the reverse mapping, there are a few extra valid matplotlib backends that |
|
42 | 42 | # map to the same GUI support |
|
43 | 43 | backend2gui['GTK'] = backend2gui['GTKCairo'] = 'gtk' |
|
44 | 44 | backend2gui['WX'] = 'wx' |
|
45 | 45 | backend2gui['CocoaAgg'] = 'osx' |
|
46 | 46 | |
|
47 | 47 | #----------------------------------------------------------------------------- |
|
48 | 48 | # Matplotlib utilities |
|
49 | 49 | #----------------------------------------------------------------------------- |
|
50 | 50 | |
|
51 | 51 | |
|
52 | 52 | def getfigs(*fig_nums): |
|
53 | 53 | """Get a list of matplotlib figures by figure numbers. |
|
54 | 54 | |
|
55 | 55 | If no arguments are given, all available figures are returned. If the |
|
56 | 56 | argument list contains references to invalid figures, a warning is printed |
|
57 | 57 | but the function continues pasting further figures. |
|
58 | 58 | |
|
59 | 59 | Parameters |
|
60 | 60 | ---------- |
|
61 | 61 | figs : tuple |
|
62 | 62 | A tuple of ints giving the figure numbers of the figures to return. |
|
63 | 63 | """ |
|
64 | 64 | from matplotlib._pylab_helpers import Gcf |
|
65 | 65 | if not fig_nums: |
|
66 | 66 | fig_managers = Gcf.get_all_fig_managers() |
|
67 | 67 | return [fm.canvas.figure for fm in fig_managers] |
|
68 | 68 | else: |
|
69 | 69 | figs = [] |
|
70 | 70 | for num in fig_nums: |
|
71 | 71 | f = Gcf.figs.get(num) |
|
72 | 72 | if f is None: |
|
73 | 73 | print('Warning: figure %s not available.' % num) |
|
74 | 74 | else: |
|
75 | 75 | figs.append(f.canvas.figure) |
|
76 | 76 | return figs |
|
77 | 77 | |
|
78 | 78 | |
|
79 | 79 | def figsize(sizex, sizey): |
|
80 | 80 | """Set the default figure size to be [sizex, sizey]. |
|
81 | 81 | |
|
82 | 82 | This is just an easy to remember, convenience wrapper that sets:: |
|
83 | 83 | |
|
84 | 84 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] |
|
85 | 85 | """ |
|
86 | 86 | import matplotlib |
|
87 | 87 | matplotlib.rcParams['figure.figsize'] = [sizex, sizey] |
|
88 | 88 | |
|
89 | 89 | |
|
90 | 90 | def print_figure(fig, fmt='png'): |
|
91 | 91 | """Convert a figure to svg or png for inline display.""" |
|
92 | 92 | # When there's an empty figure, we shouldn't return anything, otherwise we |
|
93 | 93 | # get big blank areas in the qt console. |
|
94 | 94 | if not fig.axes: |
|
95 | 95 | return |
|
96 | 96 | |
|
97 | 97 | fc = fig.get_facecolor() |
|
98 | 98 | ec = fig.get_edgecolor() |
|
99 | 99 | fig.set_facecolor('white') |
|
100 | 100 | fig.set_edgecolor('white') |
|
101 | 101 | try: |
|
102 | 102 | string_io = StringIO() |
|
103 | 103 | # use 72 dpi to match QTConsole's dpi |
|
104 |
fig.canvas.print_figure(string_io, format=fmt, dpi=72 |
|
|
104 | fig.canvas.print_figure(string_io, format=fmt, dpi=72, | |
|
105 | bbox_inches='tight') | |
|
105 | 106 | data = string_io.getvalue() |
|
106 | 107 | finally: |
|
107 | 108 | fig.set_facecolor(fc) |
|
108 | 109 | fig.set_edgecolor(ec) |
|
109 | 110 | return data |
|
110 | 111 | |
|
111 | 112 | |
|
112 | 113 | # We need a little factory function here to create the closure where |
|
113 | 114 | # safe_execfile can live. |
|
114 | 115 | def mpl_runner(safe_execfile): |
|
115 | 116 | """Factory to return a matplotlib-enabled runner for %run. |
|
116 | 117 | |
|
117 | 118 | Parameters |
|
118 | 119 | ---------- |
|
119 | 120 | safe_execfile : function |
|
120 | 121 | This must be a function with the same interface as the |
|
121 | 122 | :meth:`safe_execfile` method of IPython. |
|
122 | 123 | |
|
123 | 124 | Returns |
|
124 | 125 | ------- |
|
125 | 126 | A function suitable for use as the ``runner`` argument of the %run magic |
|
126 | 127 | function. |
|
127 | 128 | """ |
|
128 | 129 | |
|
129 | 130 | def mpl_execfile(fname,*where,**kw): |
|
130 | 131 | """matplotlib-aware wrapper around safe_execfile. |
|
131 | 132 | |
|
132 | 133 | Its interface is identical to that of the :func:`execfile` builtin. |
|
133 | 134 | |
|
134 | 135 | This is ultimately a call to execfile(), but wrapped in safeties to |
|
135 | 136 | properly handle interactive rendering.""" |
|
136 | 137 | |
|
137 | 138 | import matplotlib |
|
138 | 139 | import matplotlib.pylab as pylab |
|
139 | 140 | |
|
140 | 141 | #print '*** Matplotlib runner ***' # dbg |
|
141 | 142 | # turn off rendering until end of script |
|
142 | 143 | is_interactive = matplotlib.rcParams['interactive'] |
|
143 | 144 | matplotlib.interactive(False) |
|
144 | 145 | safe_execfile(fname,*where,**kw) |
|
145 | 146 | matplotlib.interactive(is_interactive) |
|
146 | 147 | # make rendering call now, if the user tried to do it |
|
147 | 148 | if pylab.draw_if_interactive.called: |
|
148 | 149 | pylab.draw() |
|
149 | 150 | pylab.draw_if_interactive.called = False |
|
150 | 151 | |
|
151 | 152 | return mpl_execfile |
|
152 | 153 | |
|
153 | 154 | |
|
154 | 155 | def select_figure_format(shell, fmt): |
|
155 | 156 | """Select figure format for inline backend, either 'png' or 'svg'. |
|
156 | 157 | |
|
157 | 158 | Using this method ensures only one figure format is active at a time. |
|
158 | 159 | """ |
|
159 | 160 | from matplotlib.figure import Figure |
|
160 | 161 | from IPython.zmq.pylab import backend_inline |
|
161 | 162 | |
|
162 | 163 | svg_formatter = shell.display_formatter.formatters['image/svg+xml'] |
|
163 | 164 | png_formatter = shell.display_formatter.formatters['image/png'] |
|
164 | 165 | |
|
165 | 166 | if fmt=='png': |
|
166 | 167 | svg_formatter.type_printers.pop(Figure, None) |
|
167 | 168 | png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png')) |
|
168 | 169 | elif fmt=='svg': |
|
169 | 170 | png_formatter.type_printers.pop(Figure, None) |
|
170 | 171 | svg_formatter.for_type(Figure, lambda fig: print_figure(fig, 'svg')) |
|
171 | 172 | else: |
|
172 | 173 | raise ValueError("supported formats are: 'png', 'svg', not %r"%fmt) |
|
173 | 174 | |
|
174 | 175 | # set the format to be used in the backend() |
|
175 | 176 | backend_inline._figure_format = fmt |
|
176 | 177 | |
|
177 | 178 | #----------------------------------------------------------------------------- |
|
178 | 179 | # Code for initializing matplotlib and importing pylab |
|
179 | 180 | #----------------------------------------------------------------------------- |
|
180 | 181 | |
|
181 | 182 | |
|
182 | 183 | def find_gui_and_backend(gui=None): |
|
183 | 184 | """Given a gui string return the gui and mpl backend. |
|
184 | 185 | |
|
185 | 186 | Parameters |
|
186 | 187 | ---------- |
|
187 | 188 | gui : str |
|
188 | 189 | Can be one of ('tk','gtk','wx','qt','qt4','inline'). |
|
189 | 190 | |
|
190 | 191 | Returns |
|
191 | 192 | ------- |
|
192 | 193 | A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg', |
|
193 | 194 | 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline'). |
|
194 | 195 | """ |
|
195 | 196 | |
|
196 | 197 | import matplotlib |
|
197 | 198 | |
|
198 | 199 | if gui: |
|
199 | 200 | # select backend based on requested gui |
|
200 | 201 | backend = backends[gui] |
|
201 | 202 | else: |
|
202 | 203 | backend = matplotlib.rcParams['backend'] |
|
203 | 204 | # In this case, we need to find what the appropriate gui selection call |
|
204 | 205 | # should be for IPython, so we can activate inputhook accordingly |
|
205 | 206 | gui = backend2gui.get(backend, None) |
|
206 | 207 | return gui, backend |
|
207 | 208 | |
|
208 | 209 | |
|
209 | 210 | def activate_matplotlib(backend): |
|
210 | 211 | """Activate the given backend and set interactive to True.""" |
|
211 | 212 | |
|
212 | 213 | import matplotlib |
|
213 | 214 | if backend.startswith('module://'): |
|
214 | 215 | # Work around bug in matplotlib: matplotlib.use converts the |
|
215 | 216 | # backend_id to lowercase even if a module name is specified! |
|
216 | 217 | matplotlib.rcParams['backend'] = backend |
|
217 | 218 | else: |
|
218 | 219 | matplotlib.use(backend) |
|
219 | 220 | matplotlib.interactive(True) |
|
220 | 221 | |
|
221 | 222 | # This must be imported last in the matplotlib series, after |
|
222 | 223 | # backend/interactivity choices have been made |
|
223 | 224 | import matplotlib.pylab as pylab |
|
224 | 225 | |
|
225 | 226 | # XXX For now leave this commented out, but depending on discussions with |
|
226 | 227 | # mpl-dev, we may be able to allow interactive switching... |
|
227 | 228 | #import matplotlib.pyplot |
|
228 | 229 | #matplotlib.pyplot.switch_backend(backend) |
|
229 | 230 | |
|
230 | 231 | pylab.show._needmain = False |
|
231 | 232 | # We need to detect at runtime whether show() is called by the user. |
|
232 | 233 | # For this, we wrap it into a decorator which adds a 'called' flag. |
|
233 | 234 | pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive) |
|
234 | 235 | |
|
235 | 236 | def import_pylab(user_ns, backend, import_all=True, shell=None): |
|
236 | 237 | """Import the standard pylab symbols into user_ns.""" |
|
237 | 238 | |
|
238 | 239 | # Import numpy as np/pyplot as plt are conventions we're trying to |
|
239 | 240 | # somewhat standardize on. Making them available to users by default |
|
240 | 241 | # will greatly help this. |
|
241 | 242 | s = ("import numpy\n" |
|
242 | 243 | "import matplotlib\n" |
|
243 | 244 | "from matplotlib import pylab, mlab, pyplot\n" |
|
244 | 245 | "np = numpy\n" |
|
245 | 246 | "plt = pyplot\n" |
|
246 | 247 | ) |
|
247 | 248 | exec s in user_ns |
|
248 | 249 | |
|
249 | 250 | if shell is not None: |
|
250 | 251 | exec s in shell.user_ns_hidden |
|
251 | 252 | # If using our svg payload backend, register the post-execution |
|
252 | 253 | # function that will pick up the results for display. This can only be |
|
253 | 254 | # done with access to the real shell object. |
|
254 | 255 | # |
|
255 | 256 | from IPython.zmq.pylab.backend_inline import InlineBackendConfig |
|
256 | 257 | |
|
257 | 258 | cfg = InlineBackendConfig.instance(config=shell.config) |
|
258 | 259 | cfg.shell = shell |
|
259 | 260 | |
|
260 | 261 | if backend == backends['inline']: |
|
261 | 262 | from IPython.zmq.pylab.backend_inline import flush_figures |
|
262 | 263 | from matplotlib import pyplot |
|
263 | 264 | shell.register_post_execute(flush_figures) |
|
264 | 265 | # load inline_rc |
|
265 | 266 | pyplot.rcParams.update(cfg.rc) |
|
266 | 267 | |
|
267 | 268 | # Add 'figsize' to pyplot and to the user's namespace |
|
268 | 269 | user_ns['figsize'] = pyplot.figsize = figsize |
|
269 | 270 | shell.user_ns_hidden['figsize'] = figsize |
|
270 | 271 | |
|
271 | 272 | # Setup the default figure format |
|
272 | 273 | fmt = cfg.figure_format |
|
273 | 274 | select_figure_format(shell, fmt) |
|
274 | 275 | |
|
275 | 276 | # The old pastefig function has been replaced by display |
|
276 | 277 | from IPython.core.display import display |
|
277 | 278 | # Add display and display_png to the user's namespace |
|
278 | 279 | user_ns['display'] = display |
|
279 | 280 | shell.user_ns_hidden['display'] = display |
|
280 | 281 | user_ns['getfigs'] = getfigs |
|
281 | 282 | shell.user_ns_hidden['getfigs'] = getfigs |
|
282 | 283 | |
|
283 | 284 | if import_all: |
|
284 | 285 | s = ("from matplotlib.pylab import *\n" |
|
285 | 286 | "from numpy import *\n") |
|
286 | 287 | exec s in user_ns |
|
287 | 288 | if shell is not None: |
|
288 | 289 | exec s in shell.user_ns_hidden |
|
289 | 290 | |
|
290 | 291 | |
|
291 | 292 | def pylab_activate(user_ns, gui=None, import_all=True): |
|
292 | 293 | """Activate pylab mode in the user's namespace. |
|
293 | 294 | |
|
294 | 295 | Loads and initializes numpy, matplotlib and friends for interactive use. |
|
295 | 296 | |
|
296 | 297 | Parameters |
|
297 | 298 | ---------- |
|
298 | 299 | user_ns : dict |
|
299 | 300 | Namespace where the imports will occur. |
|
300 | 301 | |
|
301 | 302 | gui : optional, string |
|
302 | 303 | A valid gui name following the conventions of the %gui magic. |
|
303 | 304 | |
|
304 | 305 | import_all : optional, boolean |
|
305 | 306 | If true, an 'import *' is done from numpy and pylab. |
|
306 | 307 | |
|
307 | 308 | Returns |
|
308 | 309 | ------- |
|
309 | 310 | The actual gui used (if not given as input, it was obtained from matplotlib |
|
310 | 311 | itself, and will be needed next to configure IPython's gui integration. |
|
311 | 312 | """ |
|
312 | 313 | gui, backend = find_gui_and_backend(gui) |
|
313 | 314 | activate_matplotlib(backend) |
|
314 | 315 | import_pylab(user_ns, backend, import_all) |
|
315 | 316 | |
|
316 | 317 | print """ |
|
317 | 318 | Welcome to pylab, a matplotlib-based Python environment [backend: %s]. |
|
318 | 319 | For more information, type 'help(pylab)'.""" % backend |
|
319 | 320 | |
|
320 | 321 | return gui |
|
321 | 322 |
@@ -1,241 +1,241 b'' | |||
|
1 | 1 | .\" Hey, EMACS: -*- nroff -*- |
|
2 | 2 | .\" First parameter, NAME, should be all caps |
|
3 | 3 | .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection |
|
4 | 4 | .\" other parameters are allowed: see man(7), man(1) |
|
5 |
.TH IPYTHON 1 " |
|
|
5 | .TH IPYTHON 1 "July 15, 2011" | |
|
6 | 6 | .\" Please adjust this date whenever revising the manpage. |
|
7 | 7 | .\" |
|
8 | 8 | .\" Some roff macros, for reference: |
|
9 | 9 | .\" .nh disable hyphenation |
|
10 | 10 | .\" .hy enable hyphenation |
|
11 | 11 | .\" .ad l left justify |
|
12 | 12 | .\" .ad b justify to both left and right margins |
|
13 | 13 | .\" .nf disable filling |
|
14 | 14 | .\" .fi enable filling |
|
15 | 15 | .\" .br insert line break |
|
16 | 16 | .\" .sp <n> insert n+1 empty lines |
|
17 | 17 | .\" for manpage-specific macros, see man(7) and groff_man(7) |
|
18 | 18 | .\" .SH section heading |
|
19 | 19 | .\" .SS secondary section heading |
|
20 | 20 | .\" |
|
21 | 21 | .\" |
|
22 | 22 | .\" To preview this page as plain text: nroff -man ipython.1 |
|
23 | 23 | .\" |
|
24 | 24 | .SH NAME |
|
25 |
ipython \- |
|
|
25 | ipython \- Tools for Interactive Computing in Python. | |
|
26 | 26 | .SH SYNOPSIS |
|
27 | 27 | .B ipython |
|
28 | 28 | .RI [ options ] " files" ... |
|
29 | 29 | .SH DESCRIPTION |
|
30 | An interactive Python shell with automatic history (input and output), | |
|
31 |
|
|
|
32 |
|
|
|
33 | scientific computing tools, and more. | |
|
30 | An interactive Python shell with automatic history (input and output), dynamic | |
|
31 | object introspection, easier configuration, command completion, access to the | |
|
32 | system shell, integration with numerical and scientific computing tools, and | |
|
33 | more. | |
|
34 | 34 | . |
|
35 | 35 | .SH REGULAR OPTIONS |
|
36 | 36 | All options that take values, must be of the form '\-\-name=value', but |
|
37 | 37 | flags that take no arguments are allowed a single '\-' to allow common |
|
38 | 38 | patterns like: 'ipython -i myscript.py'. To pass arguments to scripts, |
|
39 | 39 | rather than to IPython, specify them after '--'. |
|
40 | 40 | .br |
|
41 | 41 | .sp 1 |
|
42 | 42 | All options can also be set from your ipython_config.py configuration file. |
|
43 | 43 | See the provided examples for assistance. Options given on the |
|
44 | 44 | commandline override the values set in ipython_config.py. To generate |
|
45 | 45 | the default config file, do `ipython profile create`. |
|
46 | 46 | .br |
|
47 | 47 | .sp 1 |
|
48 | 48 | All options with a [no] prepended can be specified in negated form |
|
49 | 49 | (\\--no\-option instead of \-\-option) to turn the feature off. |
|
50 | 50 | .TP |
|
51 | 51 | .B \-h, \-\-help |
|
52 | 52 | Show summary of options. |
|
53 | 53 | .B \-\-no-autoindent |
|
54 | 54 | Turn off autoindenting. |
|
55 | 55 | .TP |
|
56 | 56 | .B \-\-autoedit-syntax |
|
57 | 57 | Turn on auto editing of files with syntax errors. |
|
58 | 58 | .TP |
|
59 | 59 | .B \-\-pylab |
|
60 | 60 | Pre-load matplotlib and numpy for interactive use with |
|
61 | 61 | the default matplotlib backend. |
|
62 | 62 | .TP |
|
63 | 63 | .B \-\-confirm-exit |
|
64 | 64 | Set to confirm when you try to exit IPython with an EOF (Control-D |
|
65 | 65 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
66 | 66 | you can force a direct exit without any confirmation. |
|
67 | 67 | .TP |
|
68 | 68 | .B \-\-deep-reload |
|
69 | 69 | Enable deep (recursive) reloading by default. IPython can use the |
|
70 | 70 | deep_reload module which reloads changes in modules recursively (it |
|
71 | 71 | replaces the reload() function, so you don't need to change anything to |
|
72 | 72 | use it). deep_reload() forces a full reload of modules whose code may |
|
73 | 73 | have changed, which the default reload() function does not. When |
|
74 | 74 | deep_reload is off, IPython will use the normal reload(), but |
|
75 | 75 | deep_reload will still be available as dreload(). This feature is off |
|
76 | 76 | by default [which means that you have both normal reload() and |
|
77 | 77 | dreload()]. |
|
78 | 78 | .TP |
|
79 | 79 | .B \-\-no-autoedit-syntax |
|
80 | 80 | Turn off auto editing of files with syntax errors. |
|
81 | 81 | .TP |
|
82 | 82 | .B \-\-term-title |
|
83 | 83 | Enable auto setting the terminal title. |
|
84 | 84 | .TP |
|
85 | 85 | .B \-\-no-confirm-exit |
|
86 | 86 | Don't prompt the user when exiting. |
|
87 | 87 | .TP |
|
88 | 88 | .B \-\-autoindent |
|
89 | 89 | Turn on autoindenting. |
|
90 | 90 | .TP |
|
91 | 91 | .B \-\-classic |
|
92 | 92 | Gives IPython a similar feel to the classic Python prompt. |
|
93 | 93 | .TP |
|
94 | 94 | .B \-\-no-automagic |
|
95 | 95 | Turn off the auto calling of magic commands. |
|
96 | 96 | .TP |
|
97 | 97 | .B \-\-banner |
|
98 | 98 | Display a banner upon starting IPython. |
|
99 | 99 | .TP |
|
100 | 100 | .B \-\-automagic |
|
101 | 101 | Turn on the auto calling of magic commands. Type %%magic at the |
|
102 | 102 | IPython prompt for more information. |
|
103 | 103 | .TP |
|
104 | 104 | .B \-\-no-deep-reload |
|
105 | 105 | Disable deep (recursive) reloading by default. |
|
106 | 106 | .TP |
|
107 | 107 | .B \-\-no-term-title |
|
108 | 108 | Disable auto setting the terminal title. |
|
109 | 109 | .TP |
|
110 | 110 | .B \-\-nosep |
|
111 | 111 | Eliminate all spacing between prompts. |
|
112 | 112 | .TP |
|
113 | 113 | .B \-\-i |
|
114 | 114 | also works as '-i' |
|
115 | 115 | If running code from the command line, become interactive afterwards. |
|
116 | 116 | .TP |
|
117 | 117 | .B \-\-debug |
|
118 | 118 | set log level to logging.DEBUG (maximize logging output) |
|
119 | 119 | .TP |
|
120 | 120 | .B \-\-pprint |
|
121 | 121 | Enable auto pretty printing of results. |
|
122 | 122 | .TP |
|
123 | 123 | .B \-\-quiet |
|
124 | 124 | set log level to logging.CRITICAL (minimize logging output) |
|
125 | 125 | .TP |
|
126 | 126 | .B \-\-pdb |
|
127 | 127 | Enable auto calling the pdb debugger after every exception. |
|
128 | 128 | .TP |
|
129 | 129 | .B \-\-color-info |
|
130 | 130 | IPython can display information about objects via a set of func- |
|
131 | 131 | tions, and optionally can use colors for this, syntax highlighting |
|
132 | 132 | source code and various other elements. However, because this |
|
133 | 133 | information is passed through a pager (like 'less') and many pagers get |
|
134 | 134 | confused with color codes, this option is off by default. You can test |
|
135 | 135 | it and turn it on permanently in your ipython_config.py file if it |
|
136 | 136 | works for you. Test it and turn it on permanently if it works with |
|
137 | 137 | your system. The magic function %%color_info allows you to toggle this |
|
138 | 138 | interactively for testing. |
|
139 | 139 | .TP |
|
140 | 140 | .B \-\-init |
|
141 | 141 | Initialize profile with default config files |
|
142 | 142 | .TP |
|
143 | 143 | .B \-\-no-pdb |
|
144 | 144 | Disable auto calling the pdb debugger after every exception. |
|
145 | 145 | .TP |
|
146 | 146 | .B \-\-quick |
|
147 | 147 | Enable quick startup with no config files. |
|
148 | 148 | .TP |
|
149 | 149 | .B \-\-no-color-info |
|
150 | 150 | Disable using colors for info related things. |
|
151 | 151 | .TP |
|
152 | 152 | .B \-\-no-pprint |
|
153 | 153 | Disable auto auto pretty printing of results. |
|
154 | 154 | .TP |
|
155 | 155 | .B \-\-no-banner |
|
156 | 156 | Don't display a banner upon starting IPython. |
|
157 | 157 | .TP |
|
158 | 158 | .B \-\-profile=<Unicode> (BaseIPythonApplication.profile) |
|
159 | 159 | Default: u'default' |
|
160 | 160 | The IPython profile to use. |
|
161 | 161 | .TP |
|
162 | 162 | .B \-\-c=<Unicode> (InteractiveShellApp.code_to_run) |
|
163 | 163 | Default: '' |
|
164 | 164 | Execute the given command string. |
|
165 | 165 | .TP |
|
166 | 166 | .B \-\-logappend=<Unicode> (InteractiveShell.logappend) |
|
167 | 167 | Default: '' |
|
168 | 168 | Start logging to the given file in append mode. |
|
169 | 169 | .TP |
|
170 | 170 | .B \-\-autocall=<Enum> (InteractiveShell.autocall) |
|
171 | 171 | Default: 1 |
|
172 | 172 | Choices: (0, 1, 2) |
|
173 | 173 | Make IPython automatically call any callable object even if you didn't type |
|
174 | 174 | explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically. |
|
175 | 175 | The value can be '0' to disable the feature, '1' for 'smart' autocall, where |
|
176 | 176 | it is not applied if there are no more arguments on the line, and '2' for |
|
177 | 177 | 'full' autocall, where all callable objects are automatically called (even |
|
178 | 178 | if no arguments are present). The default is '1'. |
|
179 | 179 | .TP |
|
180 | 180 | .B \-\-ipython-dir=<Unicode> (BaseIPythonApplication.ipython_dir) |
|
181 | 181 | Default: u'/Users/minrk/.ipython' |
|
182 | 182 | The name of the IPython directory. This directory is used for logging |
|
183 | 183 | configuration (through profiles), history storage, etc. The default is |
|
184 | 184 | usually $HOME/.ipython. This options can also be specified through the |
|
185 | 185 | environment variable IPYTHON_DIR. |
|
186 | 186 | .TP |
|
187 | 187 | .B \-\-gui=<CaselessStrEnum> (TerminalIPythonApp.gui) |
|
188 | 188 | Default: None |
|
189 | 189 | Choices: ('qt', 'wx', 'gtk') |
|
190 | 190 | Enable GUI event loop integration ('qt', 'wx', 'gtk'). |
|
191 | 191 | .TP |
|
192 | 192 | .B \-\-pylab=<CaselessStrEnum> (TerminalIPythonApp.pylab) |
|
193 | 193 | Default: None |
|
194 | 194 | Choices: ['tk', 'qt', 'wx', 'gtk', 'osx', 'auto'] |
|
195 | 195 | Pre-load matplotlib and numpy for interactive use, selecting a particular |
|
196 | 196 | matplotlib backend and loop integration. |
|
197 | 197 | .TP |
|
198 | 198 | .B \-\-ext=<Unicode> (InteractiveShellApp.extra_extension) |
|
199 | 199 | Default: '' |
|
200 | 200 | dotted module name of an IPython extension to load. |
|
201 | 201 | .TP |
|
202 | 202 | .B \-\-log-level=<Enum> (Application.log_level) |
|
203 | 203 | Default: 30 |
|
204 | 204 | Choices: (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL') |
|
205 | 205 | Set the log level by value or name. |
|
206 | 206 | .TP |
|
207 | 207 | .B \-\-colors=<CaselessStrEnum> (InteractiveShell.colors) |
|
208 | 208 | Default: 'LightBG' |
|
209 | 209 | Choices: ('NoColor', 'LightBG', 'Linux') |
|
210 | 210 | Set the color scheme (NoColor, Linux, or LightBG). |
|
211 | 211 | .TP |
|
212 | 212 | .B \-\-cache-size=<Int> (InteractiveShell.cache_size) |
|
213 | 213 | Default: 1000 |
|
214 | 214 | Set the size of the output cache. The default is 1000, you can change it |
|
215 | 215 | permanently in your config file. Setting it to 0 completely disables the |
|
216 | 216 | caching system, and the minimum value accepted is 20 (if you provide a value |
|
217 | 217 | less than 20, it is reset to 0 and a warning is issued). This limit is |
|
218 | 218 | defined because otherwise you'll spend more time re-flushing a too small |
|
219 | 219 | cache than working |
|
220 | 220 | .TP |
|
221 | 221 | .B \-\-logfile=<Unicode> (InteractiveShell.logfile) |
|
222 | 222 | Default: '' |
|
223 | 223 | The name of the logfile to use. |
|
224 | 224 | . |
|
225 | 225 | .SH EMBEDDING |
|
226 | 226 | It is possible to start an IPython instance inside your own Python |
|
227 | 227 | programs. In the documentation example files there are some |
|
228 | 228 | illustrations on how to do this. |
|
229 | 229 | .br |
|
230 | 230 | .sp 1 |
|
231 | 231 | This feature allows you to evalutate dynamically the state of your |
|
232 | 232 | code, operate with your variables, analyze them, etc. Note however |
|
233 | 233 | that any changes you make to values while in the shell do NOT |
|
234 | 234 | propagate back to the running code, so it is safe to modify your |
|
235 | 235 | values because you won't break your code in bizarre ways by doing so. |
|
236 | 236 | .SH AUTHOR |
|
237 | 237 | IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier |
|
238 | 238 | code by Janko Hauser <jh@comunit.de> and Nathaniel Gray |
|
239 | 239 | <n8gray@caltech.edu>. This manual page was written by Jack Moffitt |
|
240 | 240 | <jack@xiph.org>, for the Debian project (but may be used by others), and updated by |
|
241 | 241 | Min Ragan-Kelley <benjaminrk@gmail.com> for 0.11. |
@@ -1,49 +1,49 b'' | |||
|
1 |
.TH IRUNNER 1 " |
|
|
1 | .TH IRUNNER 1 "July 15, 2011" "" "" | |
|
2 | 2 | .SH NAME |
|
3 | 3 | \fBirunner \- interactive runner interface |
|
4 | 4 | .SH SYNOPSIS |
|
5 | 5 | .nf |
|
6 | 6 | .fam C |
|
7 | 7 | \fBirunner\fP [\fIoptions\fP] \fIfile_to_run\fP |
|
8 | 8 | .fam T |
|
9 | 9 | .fi |
|
10 | 10 | .SH DESCRIPTION |
|
11 | 11 | irunner is an interface to the various interactive runners |
|
12 | 12 | available in IPython's \fBirunner\fP module. |
|
13 | 13 | .PP |
|
14 | 14 | The already implemented runners are listed below; adding |
|
15 | 15 | one for a new program is a trivial task, see the source |
|
16 | 16 | for examples. |
|
17 | 17 | .SH OPTIONS |
|
18 | 18 | .TP |
|
19 | 19 | .B |
|
20 | 20 | \-h, \-\-help |
|
21 | 21 | show this help message and exit |
|
22 | 22 | .TP |
|
23 | 23 | .B |
|
24 | 24 | \-\-ipython |
|
25 | 25 | IPython interactive runner (default). |
|
26 | 26 | .TP |
|
27 | 27 | .B |
|
28 | 28 | \-\-python |
|
29 | 29 | Python interactive runner. |
|
30 | 30 | .TP |
|
31 | 31 | .B |
|
32 | 32 | \-\-sage |
|
33 | 33 | SAGE interactive runner. |
|
34 | 34 | .SH EXAMPLE |
|
35 | 35 | irunner.py \-\-python \-\- \-\-help |
|
36 | 36 | will pass \-\-help to the python runner. |
|
37 | 37 | Similarly, |
|
38 | 38 | irunner.py \-\-ipython \-\- \-\-interact script.ipy |
|
39 | 39 | .SH SEE ALSO |
|
40 | 40 | .BR ipython(1) |
|
41 | 41 | .br |
|
42 | 42 | .SH AUTHOR |
|
43 | 43 | \fBirunner\fP is an extension of Ken Schutte <kschutte-AT-csail.mit.edu>'s |
|
44 | 44 | script contributed on the ipython-user list: |
|
45 | 45 | http://scipy.net/pipermail/ipython-user/2006-May/001705.html |
|
46 | 46 | .PP |
|
47 | 47 | This manual page was written by Bernd Zeimetz <bernd@bzed.de>, for the Debian |
|
48 | 48 | project (but may be used by others). Modified by Fernando Perez |
|
49 | 49 | <Fernando.Perez@berkeley.edu> for inclusion in IPython. |
@@ -1,38 +1,39 b'' | |||
|
1 | 1 | .\" Hey, EMACS: -*- nroff -*- |
|
2 | 2 | .\" First parameter, NAME, should be all caps |
|
3 | 3 | .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection |
|
4 | 4 | .\" other parameters are allowed: see man(7), man(1) |
|
5 |
.TH PYCOLOR 1 " |
|
|
5 | .TH PYCOLOR 1 "July 15, 2011" | |
|
6 | 6 | .\" Please adjust this date whenever revising the manpage. |
|
7 | 7 | .\" |
|
8 | 8 | .\" Some roff macros, for reference: |
|
9 | 9 | .\" .nh disable hyphenation |
|
10 | 10 | .\" .hy enable hyphenation |
|
11 | 11 | .\" .ad l left justify |
|
12 | 12 | .\" .ad b justify to both left and right margins |
|
13 | 13 | .\" .nf disable filling |
|
14 | 14 | .\" .fi enable filling |
|
15 | 15 | .\" .br insert line break |
|
16 | 16 | .\" .sp <n> insert n+1 empty lines |
|
17 | 17 | .\" for manpage-specific macros, see man(7) |
|
18 | 18 | .SH NAME |
|
19 | 19 | pycolor \- Colorize a python file or stdin using ANSI and print to stdout. |
|
20 | 20 | .SH SYNOPSIS |
|
21 | 21 | .B pycolor |
|
22 | 22 | .RI [ options ] |
|
23 | 23 | .RI [ file ] |
|
24 | 24 | .SH DESCRIPTION |
|
25 | 25 | Prints a colorized version of the input file (or standard input if no file is |
|
26 | 26 | given, or the file name - is given) to standard out. |
|
27 | 27 | .SH OPTIONS |
|
28 | 28 | .TP |
|
29 | 29 | .B \-h, \-\-help |
|
30 | 30 | Output a brief help message. |
|
31 | 31 | .TP |
|
32 | 32 | .B \-s, \-\-scheme <scheme> |
|
33 | Give the color scheme to use. Currently only Linux (default), | |
|
34 |
|
|
|
33 | Give the color scheme to use. Currently only Linux (default), LightBG, and | |
|
34 | NoColor are implemented. | |
|
35 | 35 | .SH AUTHOR |
|
36 | pycolor was written by Fernando Perez <fperez@colorado.edu>. | |
|
36 | pycolor is part of the IPython project (http://ipython.org). | |
|
37 | 37 | This manual page was written by Jack Moffitt <jack@xiph.org>, |
|
38 | for the Debian project (but may be used by others). | |
|
38 | for the Debian project (but may be used by others). Updated by Fernando Perez | |
|
39 | <fernando.perez@berkeley.edu>. |
General Comments 0
You need to be logged in to leave comments.
Login now