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