##// END OF EJS Templates
Unify command-line usage information in one place....
Fernando Perez -
Show More
@@ -1,404 +1,422 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 An application for IPython.
5 5
6 6 All top-level applications should use the classes in this module for
7 7 handling configuration and creating componenets.
8 8
9 9 The job of an :class:`Application` is to create the master configuration
10 10 object and then create the components, passing the config to them.
11 11
12 12 Authors:
13 13
14 14 * Brian Granger
15 15 * Fernando Perez
16 16
17 17 Notes
18 18 -----
19 19 """
20 20
21 21 #-----------------------------------------------------------------------------
22 22 # Copyright (C) 2008-2009 The IPython Development Team
23 23 #
24 24 # Distributed under the terms of the BSD License. The full license is in
25 25 # the file COPYING, distributed as part of this software.
26 26 #-----------------------------------------------------------------------------
27 27
28 28 #-----------------------------------------------------------------------------
29 29 # Imports
30 30 #-----------------------------------------------------------------------------
31 31
32 32 import logging
33 33 import os
34 34 import sys
35 35
36 36 from IPython.core import release, crashhandler
37 37 from IPython.utils.genutils import get_ipython_dir, get_ipython_package_dir
38 38 from IPython.config.loader import (
39 39 PyFileConfigLoader,
40 40 ArgParseConfigLoader,
41 41 Config,
42 42 NoConfigDefault
43 43 )
44 44
45 45 #-----------------------------------------------------------------------------
46 46 # Classes and functions
47 47 #-----------------------------------------------------------------------------
48 48
49 49 class ApplicationError(Exception):
50 50 pass
51 51
52 52
53 53 app_cl_args = (
54 (('--ipython-dir', ), dict(
55 dest='Global.ipython_dir',type=unicode,
56 help='Set to override default location of Global.ipython_dir.',
57 default=NoConfigDefault,
58 metavar='Global.ipython_dir') ),
59 (('-p', '--profile',), dict(
60 dest='Global.profile',type=unicode,
61 help='The string name of the ipython profile to be used.',
62 default=NoConfigDefault,
63 metavar='Global.profile') ),
64 (('--log-level',), dict(
65 dest="Global.log_level",type=int,
66 help='Set the log level (0,10,20,30,40,50). Default is 30.',
67 default=NoConfigDefault,
68 metavar='Global.log_level')),
69 (('--config-file',), dict(
70 dest='Global.config_file',type=unicode,
71 help='Set the config file name to override default.',
72 default=NoConfigDefault,
73 metavar='Global.config_file')),
54 (('--ipython-dir', ), dict(
55 dest='Global.ipython_dir',type=unicode,
56 help=
57 """Set to override default location of the IPython directory
58 IPYTHON_DIR, stored as Global.ipython_dir. This can also be specified
59 through the environment variable IPYTHON_DIR.""",
60 default=NoConfigDefault,
61 metavar='Global.ipython_dir') ),
62 (('-p', '--profile',), dict(
63 dest='Global.profile',type=unicode,
64 help=
65 """The string name of the ipython profile to be used. Assume that your
66 config file is ipython_config-<name>.py (looks in current dir first,
67 then in IPYTHON_DIR). This is a quick way to keep and load multiple
68 config files for different tasks, especially if include your basic one
69 in your more specialized ones. You can keep a basic
70 IPYTHON_DIR/ipython_config.py file and then have other 'profiles' which
71 include this one and load extra things for particular tasks.""",
72 default=NoConfigDefault,
73 metavar='Global.profile') ),
74 (('--log-level',), dict(
75 dest="Global.log_level",type=int,
76 help='Set the log level (0,10,20,30,40,50). Default is 30.',
77 default=NoConfigDefault,
78 metavar='Global.log_level')),
79 (('--config-file',), dict(
80 dest='Global.config_file',type=unicode,
81 help=
82 """Set the config file name to override default. Normally IPython
83 loads ipython_config.py (from current directory) or
84 IPYTHON_DIR/ipython_config.py. If the loading of your config file
85 fails, IPython starts with a bare bones configuration (no modules
86 loaded at all).""",
87 default=NoConfigDefault,
88 metavar='Global.config_file')),
74 89 )
75 90
76 91 class Application(object):
77 92 """Load a config, construct components and set them running."""
78 93
79 94 name = u'ipython'
80 95 description = 'IPython: an enhanced interactive Python shell.'
81
96 #: usage message printed by argparse. If None, auto-generate
97 usage = None
82 98 config_file_name = u'ipython_config.py'
83 99 # Track the default and actual separately because some messages are
84 100 # only printed if we aren't using the default.
85 101 default_config_file_name = config_file_name
86 102 default_log_level = logging.WARN
87 103 # Set by --profile option
88 104 profile_name = None
89 105 #: User's ipython directory, typically ~/.ipython/
90 106 ipython_dir = None
91 107 #: A reference to the argv to be used (typically ends up being sys.argv[1:])
92 108 argv = None
93 109 #: Default command line arguments. Subclasses should create a new tuple
94 110 #: that *includes* these.
95 111 cl_arguments = app_cl_args
96 112
97 113 # Private attributes
98 114 _exiting = False
99 115 _initialized = False
100 116
101 117 # Class choices for things that will be instantiated at runtime.
102 118 _CrashHandler = crashhandler.CrashHandler
103 119
104 120 def __init__(self, argv=None):
105 121 self.argv = sys.argv[1:] if argv is None else argv
106 122 self.init_logger()
107 123
108 124 def init_logger(self):
109 125 self.log = logging.getLogger(self.__class__.__name__)
110 126 # This is used as the default until the command line arguments are read.
111 127 self.log.setLevel(self.default_log_level)
112 128 self._log_handler = logging.StreamHandler()
113 129 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
114 130 self._log_handler.setFormatter(self._log_formatter)
115 131 self.log.addHandler(self._log_handler)
116 132
117 133 def _set_log_level(self, level):
118 134 self.log.setLevel(level)
119 135
120 136 def _get_log_level(self):
121 137 return self.log.level
122 138
123 139 log_level = property(_get_log_level, _set_log_level)
124 140
125 141 def initialize(self):
126 142 """Start the application."""
127 143
128 144 if self._initialized:
129 145 return
130 146
131 147 # The first part is protected with an 'attempt' wrapper, that will log
132 148 # failures with the basic system traceback machinery. Once our crash
133 149 # handler is in place, we can let any subsequent exception propagate,
134 150 # as our handler will log it with much better detail than the default.
135 151 self.attempt(self.create_crash_handler)
136 152 self.create_default_config()
137 153 self.log_default_config()
138 154 self.set_default_config_log_level()
139 155 self.pre_load_command_line_config()
140 156 self.load_command_line_config()
141 157 self.set_command_line_config_log_level()
142 158 self.post_load_command_line_config()
143 159 self.log_command_line_config()
144 160 self.find_ipython_dir()
145 161 self.find_resources()
146 162 self.find_config_file_name()
147 163 self.find_config_file_paths()
148 164 self.pre_load_file_config()
149 165 self.load_file_config()
150 166 self.set_file_config_log_level()
151 167 self.post_load_file_config()
152 168 self.log_file_config()
153 169 self.merge_configs()
154 170 self.log_master_config()
155 171 self.pre_construct()
156 172 self.construct()
157 173 self.post_construct()
158 174 self._initialized = True
159 175
160 176 def start(self):
161 177 self.initialize()
162 178 self.start_app()
163 179
164 180 #-------------------------------------------------------------------------
165 181 # Various stages of Application creation
166 182 #-------------------------------------------------------------------------
167 183
168 184 def create_crash_handler(self):
169 185 """Create a crash handler, typically setting sys.excepthook to it."""
170 186 self.crash_handler = self._CrashHandler(self, self.name)
171 187 sys.excepthook = self.crash_handler
172 188
173 189 def create_default_config(self):
174 190 """Create defaults that can't be set elsewhere.
175 191
176 192 For the most part, we try to set default in the class attributes
177 193 of Components. But, defaults the top-level Application (which is
178 194 not a HasTraitlets or Component) are not set in this way. Instead
179 195 we set them here. The Global section is for variables like this that
180 196 don't belong to a particular component.
181 197 """
182 198 c = Config()
183 199 c.Global.ipython_dir = get_ipython_dir()
184 200 c.Global.log_level = self.log_level
185 201 self.default_config = c
186 202
187 203 def log_default_config(self):
188 204 self.log.debug('Default config loaded:')
189 205 self.log.debug(repr(self.default_config))
190 206
191 207 def set_default_config_log_level(self):
192 208 try:
193 209 self.log_level = self.default_config.Global.log_level
194 210 except AttributeError:
195 211 # Fallback to the default_log_level class attribute
196 212 pass
197 213
198 214 def create_command_line_config(self):
199 215 """Create and return a command line config loader."""
200 216 return ArgParseConfigLoader(self.argv, self.cl_arguments,
201 217 description=self.description,
202 version=release.version)
218 version=release.version,
219 usage=self.usage,
220 )
203 221
204 222 def pre_load_command_line_config(self):
205 223 """Do actions just before loading the command line config."""
206 224 pass
207 225
208 226 def load_command_line_config(self):
209 227 """Load the command line config."""
210 228 loader = self.create_command_line_config()
211 229 self.command_line_config = loader.load_config()
212 230 self.extra_args = loader.get_extra_args()
213 231
214 232 def set_command_line_config_log_level(self):
215 233 try:
216 234 self.log_level = self.command_line_config.Global.log_level
217 235 except AttributeError:
218 236 pass
219 237
220 238 def post_load_command_line_config(self):
221 239 """Do actions just after loading the command line config."""
222 240 pass
223 241
224 242 def log_command_line_config(self):
225 243 self.log.debug("Command line config loaded:")
226 244 self.log.debug(repr(self.command_line_config))
227 245
228 246 def find_ipython_dir(self):
229 247 """Set the IPython directory.
230 248
231 249 This sets ``self.ipython_dir``, but the actual value that is passed to
232 250 the application is kept in either ``self.default_config`` or
233 251 ``self.command_line_config``. This also adds ``self.ipython_dir`` to
234 252 ``sys.path`` so config files there can be referenced by other config
235 253 files.
236 254 """
237 255
238 256 try:
239 257 self.ipython_dir = self.command_line_config.Global.ipython_dir
240 258 except AttributeError:
241 259 self.ipython_dir = self.default_config.Global.ipython_dir
242 260 sys.path.append(os.path.abspath(self.ipython_dir))
243 261 if not os.path.isdir(self.ipython_dir):
244 262 os.makedirs(self.ipython_dir, mode=0777)
245 263 self.log.debug("IPYTHON_DIR set to: %s" % self.ipython_dir)
246 264
247 265 def find_resources(self):
248 266 """Find other resources that need to be in place.
249 267
250 268 Things like cluster directories need to be in place to find the
251 269 config file. These happen right after the IPython directory has
252 270 been set.
253 271 """
254 272 pass
255 273
256 274 def find_config_file_name(self):
257 275 """Find the config file name for this application.
258 276
259 277 This must set ``self.config_file_name`` to the filename of the
260 278 config file to use (just the filename). The search paths for the
261 279 config file are set in :meth:`find_config_file_paths` and then passed
262 280 to the config file loader where they are resolved to an absolute path.
263 281
264 282 If a profile has been set at the command line, this will resolve it.
265 283 """
266 284
267 285 try:
268 286 self.config_file_name = self.command_line_config.Global.config_file
269 287 except AttributeError:
270 288 pass
271 289
272 290 try:
273 291 self.profile_name = self.command_line_config.Global.profile
274 292 except AttributeError:
275 293 pass
276 294 else:
277 295 name_parts = self.config_file_name.split('.')
278 296 name_parts.insert(1, u'_' + self.profile_name + u'.')
279 297 self.config_file_name = ''.join(name_parts)
280 298
281 299 def find_config_file_paths(self):
282 300 """Set the search paths for resolving the config file.
283 301
284 302 This must set ``self.config_file_paths`` to a sequence of search
285 303 paths to pass to the config file loader.
286 304 """
287 305 # Include our own profiles directory last, so that users can still find
288 306 # our shipped copies of builtin profiles even if they don't have them
289 307 # in their local ipython directory.
290 308 prof_dir = os.path.join(get_ipython_package_dir(), 'config', 'profile')
291 309 self.config_file_paths = (os.getcwd(), self.ipython_dir, prof_dir)
292 310
293 311 def pre_load_file_config(self):
294 312 """Do actions before the config file is loaded."""
295 313 pass
296 314
297 315 def load_file_config(self):
298 316 """Load the config file.
299 317
300 318 This tries to load the config file from disk. If successful, the
301 319 ``CONFIG_FILE`` config variable is set to the resolved config file
302 320 location. If not successful, an empty config is used.
303 321 """
304 322 self.log.debug("Attempting to load config file: %s" %
305 323 self.config_file_name)
306 324 loader = PyFileConfigLoader(self.config_file_name,
307 325 path=self.config_file_paths)
308 326 try:
309 327 self.file_config = loader.load_config()
310 328 self.file_config.Global.config_file = loader.full_filename
311 329 except IOError:
312 330 # Only warn if the default config file was NOT being used.
313 331 if not self.config_file_name==self.default_config_file_name:
314 332 self.log.warn("Config file not found, skipping: %s" %
315 333 self.config_file_name, exc_info=True)
316 334 self.file_config = Config()
317 335 except:
318 336 self.log.warn("Error loading config file: %s" %
319 337 self.config_file_name, exc_info=True)
320 338 self.file_config = Config()
321 339
322 340 def set_file_config_log_level(self):
323 341 # We need to keeep self.log_level updated. But we only use the value
324 342 # of the file_config if a value was not specified at the command
325 343 # line, because the command line overrides everything.
326 344 if not hasattr(self.command_line_config.Global, 'log_level'):
327 345 try:
328 346 self.log_level = self.file_config.Global.log_level
329 347 except AttributeError:
330 348 pass # Use existing value
331 349
332 350 def post_load_file_config(self):
333 351 """Do actions after the config file is loaded."""
334 352 pass
335 353
336 354 def log_file_config(self):
337 355 if hasattr(self.file_config.Global, 'config_file'):
338 356 self.log.debug("Config file loaded: %s" %
339 357 self.file_config.Global.config_file)
340 358 self.log.debug(repr(self.file_config))
341 359
342 360 def merge_configs(self):
343 361 """Merge the default, command line and file config objects."""
344 362 config = Config()
345 363 config._merge(self.default_config)
346 364 config._merge(self.file_config)
347 365 config._merge(self.command_line_config)
348 366 self.master_config = config
349 367
350 368 def log_master_config(self):
351 369 self.log.debug("Master config created:")
352 370 self.log.debug(repr(self.master_config))
353 371
354 372 def pre_construct(self):
355 373 """Do actions after the config has been built, but before construct."""
356 374 pass
357 375
358 376 def construct(self):
359 377 """Construct the main components that make up this app."""
360 378 self.log.debug("Constructing components for application")
361 379
362 380 def post_construct(self):
363 381 """Do actions after construct, but before starting the app."""
364 382 pass
365 383
366 384 def start_app(self):
367 385 """Actually start the app."""
368 386 self.log.debug("Starting application")
369 387
370 388 #-------------------------------------------------------------------------
371 389 # Utility methods
372 390 #-------------------------------------------------------------------------
373 391
374 392 def abort(self):
375 393 """Abort the starting of the application."""
376 394 if self._exiting:
377 395 pass
378 396 else:
379 397 self.log.critical("Aborting application: %s" % self.name, exc_info=True)
380 398 self._exiting = True
381 399 sys.exit(1)
382 400
383 401 def exit(self, exit_status=0):
384 402 if self._exiting:
385 403 pass
386 404 else:
387 405 self.log.debug("Exiting application: %s" % self.name)
388 406 self._exiting = True
389 407 sys.exit(exit_status)
390 408
391 409 def attempt(self, func, action='abort'):
392 410 try:
393 411 func()
394 412 except SystemExit:
395 413 raise
396 414 except:
397 415 if action == 'abort':
398 416 self.log.critical("Aborting application: %s" % self.name,
399 417 exc_info=True)
400 418 self.abort()
401 419 raise
402 420 elif action == 'exit':
403 421 self.exit(0)
404 422
@@ -1,576 +1,674 b''
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 The :class:`~IPython.core.application.Application` object for the command
5 5 line :command:`ipython` program.
6 6
7 Authors:
7 Authors
8 -------
8 9
9 10 * Brian Granger
10 11 * Fernando Perez
11
12 Notes
13 -----
14 12 """
15 13
16 14 #-----------------------------------------------------------------------------
17 # Copyright (C) 2008-2009 The IPython Development Team
15 # Copyright (C) 2008-2010 The IPython Development Team
18 16 #
19 17 # Distributed under the terms of the BSD License. The full license is in
20 18 # the file COPYING, distributed as part of this software.
21 19 #-----------------------------------------------------------------------------
22 20
23 21 #-----------------------------------------------------------------------------
24 22 # Imports
25 23 #-----------------------------------------------------------------------------
24 from __future__ import absolute_import
26 25
27 26 import logging
28 27 import os
29 28 import sys
30 29
31 30 from IPython.core import crashhandler
32 31 from IPython.core import release
33 32 from IPython.core.application import Application
34 33 from IPython.core.error import UsageError
35 34 from IPython.core.iplib import InteractiveShell
36 35 from IPython.core.pylabtools import pylab_activate
37 36 from IPython.config.loader import (
38 37 NoConfigDefault,
39 38 Config,
40 39 PyFileConfigLoader
41 40 )
42 41 from IPython.lib import inputhook
43 42 from IPython.utils.genutils import filefind, get_ipython_dir
43 from . import usage
44 44
45 45 #-----------------------------------------------------------------------------
46 # Utilities and helpers
46 # Globals, utilities and helpers
47 47 #-----------------------------------------------------------------------------
48 48
49 ipython_desc = """
50 A Python shell with automatic history (input and output), dynamic object
51 introspection, easier configuration, command completion, access to the system
52 shell and more.
53 """
54
55 #-----------------------------------------------------------------------------
56 # Main classes and functions
57 #-----------------------------------------------------------------------------
49 default_config_file_name = u'ipython_config.py'
58 50
59 51 cl_args = (
60 52 (('--autocall',), dict(
61 53 type=int, dest='InteractiveShell.autocall', default=NoConfigDefault,
62 help='Set the autocall value (0,1,2).',
54 help=
55 """Make IPython automatically call any callable object even if you
56 didn't type explicit parentheses. For example, 'str 43' becomes
57 'str(43)' automatically. The value can be '0' to disable the feature,
58 '1' for 'smart' autocall, where it is not applied if there are no more
59 arguments on the line, and '2' for 'full' autocall, where all callable
60 objects are automatically called (even if no arguments are present).
61 The default is '1'.""",
63 62 metavar='InteractiveShell.autocall')
64 63 ),
65 64 (('--autoindent',), dict(
66 action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault,
65 action='store_true', dest='InteractiveShell.autoindent',
66 default=NoConfigDefault,
67 67 help='Turn on autoindenting.')
68 68 ),
69 69 (('--no-autoindent',), dict(
70 action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault,
70 action='store_false', dest='InteractiveShell.autoindent',
71 default=NoConfigDefault,
71 72 help='Turn off autoindenting.')
72 73 ),
73 74 (('--automagic',), dict(
74 action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault,
75 help='Turn on the auto calling of magic commands.')
76 ),
75 action='store_true', dest='InteractiveShell.automagic',
76 default=NoConfigDefault,
77 help='Turn on the auto calling of magic commands.'
78 'Type %%magic at the IPython prompt for more information.')
79 ),
77 80 (('--no-automagic',), dict(
78 action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault,
81 action='store_false', dest='InteractiveShell.automagic',
82 default=NoConfigDefault,
79 83 help='Turn off the auto calling of magic commands.')
80 84 ),
81 85 (('--autoedit-syntax',), dict(
82 action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
86 action='store_true', dest='InteractiveShell.autoedit_syntax',
87 default=NoConfigDefault,
83 88 help='Turn on auto editing of files with syntax errors.')
84 89 ),
85 90 (('--no-autoedit-syntax',), dict(
86 action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
91 action='store_false', dest='InteractiveShell.autoedit_syntax',
92 default=NoConfigDefault,
87 93 help='Turn off auto editing of files with syntax errors.')
88 94 ),
89 95 (('--banner',), dict(
90 action='store_true', dest='Global.display_banner', default=NoConfigDefault,
96 action='store_true', dest='Global.display_banner',
97 default=NoConfigDefault,
91 98 help='Display a banner upon starting IPython.')
92 99 ),
93 100 (('--no-banner',), dict(
94 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
101 action='store_false', dest='Global.display_banner',
102 default=NoConfigDefault,
95 103 help="Don't display a banner upon starting IPython.")
96 104 ),
97 105 (('--cache-size',), dict(
98 106 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
99 help="Set the size of the output cache.",
107 help=
108 """Set the size of the output cache. The default is 1000, you can
109 change it permanently in your config file. Setting it to 0 completely
110 disables the caching system, and the minimum value accepted is 20 (if
111 you provide a value less than 20, it is reset to 0 and a warning is
112 issued). This limit is defined because otherwise you'll spend more
113 time re-flushing a too small cache than working.
114 """,
100 115 metavar='InteractiveShell.cache_size')
101 116 ),
102 117 (('--classic',), dict(
103 118 action='store_true', dest='Global.classic', default=NoConfigDefault,
104 119 help="Gives IPython a similar feel to the classic Python prompt.")
105 120 ),
106 121 (('--colors',), dict(
107 122 type=str, dest='InteractiveShell.colors', default=NoConfigDefault,
108 123 help="Set the color scheme (NoColor, Linux, and LightBG).",
109 124 metavar='InteractiveShell.colors')
110 125 ),
111 126 (('--color-info',), dict(
112 action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault,
113 help="Enable using colors for info related things.")
127 action='store_true', dest='InteractiveShell.color_info',
128 default=NoConfigDefault,
129 help=
130 """IPython can display information about objects via a set of func-
131 tions, and optionally can use colors for this, syntax highlighting
132 source code and various other elements. However, because this
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
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
137 your system. The magic function %%color_info allows you to toggle this
138 inter- actively for testing."""
139 )
114 140 ),
115 141 (('--no-color-info',), dict(
116 action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault,
142 action='store_false', dest='InteractiveShell.color_info',
143 default=NoConfigDefault,
117 144 help="Disable using colors for info related things.")
118 145 ),
119 146 (('--confirm-exit',), dict(
120 action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
121 help="Prompt the user when existing.")
147 action='store_true', dest='InteractiveShell.confirm_exit',
148 default=NoConfigDefault,
149 help=
150 """Set to confirm when you try to exit IPython with an EOF (Control-D
151 in Unix, Control-Z/Enter in Windows). By typing 'exit', 'quit' or
152 '%%Exit', you can force a direct exit without any confirmation.
153 """
154 )
122 155 ),
123 156 (('--no-confirm-exit',), dict(
124 action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
125 help="Don't prompt the user when existing.")
157 action='store_false', dest='InteractiveShell.confirm_exit',
158 default=NoConfigDefault,
159 help="Don't prompt the user when exiting.")
126 160 ),
127 161 (('--deep-reload',), dict(
128 action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
129 help="Enable deep (recursive) reloading by default.")
162 action='store_true', dest='InteractiveShell.deep_reload',
163 default=NoConfigDefault,
164 help=
165 """Enable deep (recursive) reloading by default. IPython can use the
166 deep_reload module which reloads changes in modules recursively (it
167 replaces the reload() function, so you don't need to change anything to
168 use it). deep_reload() forces a full reload of modules whose code may
169 have changed, which the default reload() function does not. When
170 deep_reload is off, IPython will use the normal reload(), but
171 deep_reload will still be available as dreload(). This fea- ture is off
172 by default [which means that you have both normal reload() and
173 dreload()].""")
130 174 ),
131 175 (('--no-deep-reload',), dict(
132 action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
176 action='store_false', dest='InteractiveShell.deep_reload',
177 default=NoConfigDefault,
133 178 help="Disable deep (recursive) reloading by default.")
134 179 ),
135 180 (('--editor',), dict(
136 181 type=str, dest='InteractiveShell.editor', default=NoConfigDefault,
137 182 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
138 183 metavar='InteractiveShell.editor')
139 184 ),
140 185 (('--log','-l'), dict(
141 action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault,
142 help="Start logging to the default file (./ipython_log.py).")
186 action='store_true', dest='InteractiveShell.logstart',
187 default=NoConfigDefault,
188 help="Start logging to the default log file (./ipython_log.py).")
143 189 ),
144 190 (('--logfile','-lf'), dict(
145 191 type=unicode, dest='InteractiveShell.logfile', default=NoConfigDefault,
146 help="Start logging to logfile.",
192 help="Start logging to logfile with this name.",
147 193 metavar='InteractiveShell.logfile')
148 194 ),
149 195 (('--log-append','-la'), dict(
150 type=unicode, dest='InteractiveShell.logappend', default=NoConfigDefault,
151 help="Start logging to the give file in append mode.",
196 type=unicode, dest='InteractiveShell.logappend',
197 default=NoConfigDefault,
198 help="Start logging to the given file in append mode.",
152 199 metavar='InteractiveShell.logfile')
153 200 ),
154 201 (('--pdb',), dict(
155 action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault,
202 action='store_true', dest='InteractiveShell.pdb',
203 default=NoConfigDefault,
156 204 help="Enable auto calling the pdb debugger after every exception.")
157 205 ),
158 206 (('--no-pdb',), dict(
159 action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault,
207 action='store_false', dest='InteractiveShell.pdb',
208 default=NoConfigDefault,
160 209 help="Disable auto calling the pdb debugger after every exception.")
161 210 ),
162 211 (('--pprint',), dict(
163 action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault,
212 action='store_true', dest='InteractiveShell.pprint',
213 default=NoConfigDefault,
164 214 help="Enable auto pretty printing of results.")
165 215 ),
166 216 (('--no-pprint',), dict(
167 action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault,
217 action='store_false', dest='InteractiveShell.pprint',
218 default=NoConfigDefault,
168 219 help="Disable auto auto pretty printing of results.")
169 220 ),
170 221 (('--prompt-in1','-pi1'), dict(
171 222 type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault,
172 help="Set the main input prompt ('In [\#]: ')",
223 help=
224 """Set the main input prompt ('In [\#]: '). Note that if you are using
225 numbered prompts, the number is represented with a '\#' in the string.
226 Don't forget to quote strings with spaces embedded in them. Most
227 bash-like escapes can be used to customize IPython's prompts, as well
228 as a few additional ones which are IPython-spe- cific. All valid
229 prompt escapes are described in detail in the Customization section of
230 the IPython manual.""",
173 231 metavar='InteractiveShell.prompt_in1')
174 232 ),
175 233 (('--prompt-in2','-pi2'), dict(
176 234 type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault,
177 help="Set the secondary input prompt (' .\D.: ')",
235 help=
236 """Set the secondary input prompt (' .\D.: '). Similar to the previous
237 option, but used for the continuation prompts. The special sequence
238 '\D' is similar to '\#', but with all digits replaced by dots (so you
239 can have your continuation prompt aligned with your input prompt).
240 Default: ' .\D.: ' (note three spaces at the start for alignment with
241 'In [\#]')""",
178 242 metavar='InteractiveShell.prompt_in2')
179 243 ),
180 244 (('--prompt-out','-po'), dict(
181 245 type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault,
182 246 help="Set the output prompt ('Out[\#]:')",
183 247 metavar='InteractiveShell.prompt_out')
184 248 ),
185 249 (('--quick',), dict(
186 250 action='store_true', dest='Global.quick', default=NoConfigDefault,
187 251 help="Enable quick startup with no config files.")
188 252 ),
189 253 (('--readline',), dict(
190 action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault,
254 action='store_true', dest='InteractiveShell.readline_use',
255 default=NoConfigDefault,
191 256 help="Enable readline for command line usage.")
192 257 ),
193 258 (('--no-readline',), dict(
194 action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault,
259 action='store_false', dest='InteractiveShell.readline_use',
260 default=NoConfigDefault,
195 261 help="Disable readline for command line usage.")
196 262 ),
197 263 (('--screen-length','-sl'), dict(
198 type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault,
199 help='Number of lines on screen, used to control printing of long strings.',
264 type=int, dest='InteractiveShell.screen_length',
265 default=NoConfigDefault,
266 help=
267 """Number of lines of your screen, used to control printing of very
268 long strings. Strings longer than this number of lines will be sent
269 through a pager instead of directly printed. The default value for
270 this is 0, which means IPython will auto-detect your screen size every
271 time it needs to print certain potentially long strings (this doesn't
272 change the behavior of the 'print' keyword, it's only triggered
273 internally). If for some reason this isn't working well (it needs
274 curses support), specify it yourself. Otherwise don't change the
275 default.""",
200 276 metavar='InteractiveShell.screen_length')
201 277 ),
202 278 (('--separate-in','-si'), dict(
203 279 type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault,
204 help="Separator before input prompts. Default '\n'.",
280 help="Separator before input prompts. Default '\\n'.",
205 281 metavar='InteractiveShell.separate_in')
206 282 ),
207 283 (('--separate-out','-so'), dict(
208 type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault,
284 type=str, dest='InteractiveShell.separate_out',
285 default=NoConfigDefault,
209 286 help="Separator before output prompts. Default 0 (nothing).",
210 287 metavar='InteractiveShell.separate_out')
211 288 ),
212 289 (('--separate-out2','-so2'), dict(
213 type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault,
290 type=str, dest='InteractiveShell.separate_out2',
291 default=NoConfigDefault,
214 292 help="Separator after output prompts. Default 0 (nonight).",
215 293 metavar='InteractiveShell.separate_out2')
216 294 ),
217 295 (('-no-sep',), dict(
218 296 action='store_true', dest='Global.nosep', default=NoConfigDefault,
219 297 help="Eliminate all spacing between prompts.")
220 298 ),
221 299 (('--term-title',), dict(
222 action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault,
300 action='store_true', dest='InteractiveShell.term_title',
301 default=NoConfigDefault,
223 302 help="Enable auto setting the terminal title.")
224 303 ),
225 304 (('--no-term-title',), dict(
226 action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault,
305 action='store_false', dest='InteractiveShell.term_title',
306 default=NoConfigDefault,
227 307 help="Disable auto setting the terminal title.")
228 308 ),
229 309 (('--xmode',), dict(
230 310 type=str, dest='InteractiveShell.xmode', default=NoConfigDefault,
231 help="Exception mode ('Plain','Context','Verbose')",
311 help=
312 """Exception reporting mode ('Plain','Context','Verbose'). Plain:
313 similar to python's normal traceback printing. Context: prints 5 lines
314 of context source code around each line in the traceback. Verbose:
315 similar to Context, but additionally prints the variables currently
316 visible where the exception happened (shortening their strings if too
317 long). This can potentially be very slow, if you happen to have a huge
318 data structure whose string representation is complex to compute.
319 Your computer may appear to freeze for a while with cpu usage at 100%%.
320 If this occurs, you can cancel the traceback with Ctrl-C (maybe hitting
321 it more than once).
322 """,
232 323 metavar='InteractiveShell.xmode')
233 324 ),
234 325 (('--ext',), dict(
235 326 type=str, dest='Global.extra_extension', default=NoConfigDefault,
236 327 help="The dotted module name of an IPython extension to load.",
237 328 metavar='Global.extra_extension')
238 329 ),
239 330 (('-c',), dict(
240 331 type=str, dest='Global.code_to_run', default=NoConfigDefault,
241 332 help="Execute the given command string.",
242 333 metavar='Global.code_to_run')
243 334 ),
244 335 (('-i',), dict(
245 action='store_true', dest='Global.force_interact', default=NoConfigDefault,
246 help="If running code from the command line, become interactive afterwards.")
336 action='store_true', dest='Global.force_interact',
337 default=NoConfigDefault,
338 help=
339 "If running code from the command line, become interactive afterwards."
340 )
247 341 ),
248 342
249 343 # Options to start with GUI control enabled from the beginning
250 344 (('--gui',), dict(
251 345 type=str, dest='Global.gui', default=NoConfigDefault,
252 346 help="Enable GUI event loop integration ('qt', 'wx', 'gtk').",
253 347 metavar='gui-mode')
254 348 ),
255 349
256 350 (('--pylab','-pylab'), dict(
257 351 type=str, dest='Global.pylab', default=NoConfigDefault,
258 352 nargs='?', const='auto', metavar='gui-mode',
259 353 help="Pre-load matplotlib and numpy for interactive use. "+
260 354 "If no value is given, the gui backend is matplotlib's, else use "+
261 355 "one of: ['tk', 'qt', 'wx', 'gtk'].")
262 356 ),
263 357
264 358 # Legacy GUI options. Leave them in for backwards compatibility, but the
265 359 # 'thread' names are really a misnomer now.
266 360 (('--wthread','-wthread'), dict(
267 361 action='store_true', dest='Global.wthread', default=NoConfigDefault,
268 362 help="Enable wxPython event loop integration "+
269 363 "(DEPRECATED, use --gui wx)")
270 364 ),
271 365 (('--q4thread','--qthread','-q4thread','-qthread'), dict(
272 366 action='store_true', dest='Global.q4thread', default=NoConfigDefault,
273 367 help="Enable Qt4 event loop integration. Qt3 is no longer supported. "+
274 368 "(DEPRECATED, use --gui qt)")
275 369 ),
276 370 (('--gthread','-gthread'), dict(
277 371 action='store_true', dest='Global.gthread', default=NoConfigDefault,
278 372 help="Enable GTK event loop integration. "+
279 373 "(DEPRECATED, use --gui gtk)")
280 374 ),
281 375 )
282 376
283
284 default_config_file_name = u'ipython_config.py'
377 #-----------------------------------------------------------------------------
378 # Main classes and functions
379 #-----------------------------------------------------------------------------
285 380
286 381 class IPythonApp(Application):
287 382 name = u'ipython'
288 description = 'IPython: an enhanced interactive Python shell.'
383 #: argparse formats better the 'usage' than the 'description' field
384 description = None
385 #: usage message printed by argparse. If None, auto-generate
386 usage = usage.cl_usage
387
289 388 config_file_name = default_config_file_name
290 389
291 390 cl_arguments = Application.cl_arguments + cl_args
292 391
293 392 # Private and configuration attributes
294 393 _CrashHandler = crashhandler.IPythonCrashHandler
295 394
296 395 def __init__(self, argv=None, **shell_params):
297 396 """Create a new IPythonApp.
298 397
299 398 Parameters
300 399 ----------
301 400 argv : optional, list
302 401 If given, used as the command-line argv environment to read arguments
303 402 from.
304 403
305 404 shell_params : optional, dict
306 405 All other keywords are passed to the :class:`iplib.InteractiveShell`
307 406 constructor.
308 407 """
309 408 super(IPythonApp, self).__init__(argv)
310 409 self.shell_params = shell_params
311 410
312
313 411 def create_default_config(self):
314 412 super(IPythonApp, self).create_default_config()
315 413 # Eliminate multiple lookups
316 414 Global = self.default_config.Global
317 415
318 416 # Set all default values
319 417 Global.display_banner = True
320 418
321 419 # If the -c flag is given or a file is given to run at the cmd line
322 420 # like "ipython foo.py", normally we exit without starting the main
323 421 # loop. The force_interact config variable allows a user to override
324 422 # this and interact. It is also set by the -i cmd line flag, just
325 423 # like Python.
326 424 Global.force_interact = False
327 425
328 426 # By default always interact by starting the IPython mainloop.
329 427 Global.interact = True
330 428
331 429 # No GUI integration by default
332 430 Global.gui = False
333 431 # Pylab off by default
334 432 Global.pylab = False
335 433
336 434 # Deprecated versions of gui support that used threading, we support
337 435 # them just for bacwards compatibility as an alternate spelling for
338 436 # '--gui X'
339 437 Global.qthread = False
340 438 Global.q4thread = False
341 439 Global.wthread = False
342 440 Global.gthread = False
343 441
344 442 def load_file_config(self):
345 443 if hasattr(self.command_line_config.Global, 'quick'):
346 444 if self.command_line_config.Global.quick:
347 445 self.file_config = Config()
348 446 return
349 447 super(IPythonApp, self).load_file_config()
350 448
351 449 def post_load_file_config(self):
352 450 if hasattr(self.command_line_config.Global, 'extra_extension'):
353 451 if not hasattr(self.file_config.Global, 'extensions'):
354 452 self.file_config.Global.extensions = []
355 453 self.file_config.Global.extensions.append(
356 454 self.command_line_config.Global.extra_extension)
357 455 del self.command_line_config.Global.extra_extension
358 456
359 457 def pre_construct(self):
360 458 config = self.master_config
361 459
362 460 if hasattr(config.Global, 'classic'):
363 461 if config.Global.classic:
364 462 config.InteractiveShell.cache_size = 0
365 463 config.InteractiveShell.pprint = 0
366 464 config.InteractiveShell.prompt_in1 = '>>> '
367 465 config.InteractiveShell.prompt_in2 = '... '
368 466 config.InteractiveShell.prompt_out = ''
369 467 config.InteractiveShell.separate_in = \
370 468 config.InteractiveShell.separate_out = \
371 469 config.InteractiveShell.separate_out2 = ''
372 470 config.InteractiveShell.colors = 'NoColor'
373 471 config.InteractiveShell.xmode = 'Plain'
374 472
375 473 if hasattr(config.Global, 'nosep'):
376 474 if config.Global.nosep:
377 475 config.InteractiveShell.separate_in = \
378 476 config.InteractiveShell.separate_out = \
379 477 config.InteractiveShell.separate_out2 = ''
380 478
381 479 # if there is code of files to run from the cmd line, don't interact
382 480 # unless the -i flag (Global.force_interact) is true.
383 481 code_to_run = config.Global.get('code_to_run','')
384 482 file_to_run = False
385 483 if len(self.extra_args)>=1:
386 484 if self.extra_args[0]:
387 485 file_to_run = True
388 486 if file_to_run or code_to_run:
389 487 if not config.Global.force_interact:
390 488 config.Global.interact = False
391 489
392 490 def construct(self):
393 491 # I am a little hesitant to put these into InteractiveShell itself.
394 492 # But that might be the place for them
395 493 sys.path.insert(0, '')
396 494
397 495 # Create an InteractiveShell instance
398 496 self.shell = InteractiveShell(None, self.master_config,
399 497 **self.shell_params )
400 498
401 499 def post_construct(self):
402 500 """Do actions after construct, but before starting the app."""
403 501 config = self.master_config
404 502
405 503 # shell.display_banner should always be False for the terminal
406 504 # based app, because we call shell.show_banner() by hand below
407 505 # so the banner shows *before* all extension loading stuff.
408 506 self.shell.display_banner = False
409 507
410 508 if config.Global.display_banner and \
411 509 config.Global.interact:
412 510 self.shell.show_banner()
413 511
414 512 # Make sure there is a space below the banner.
415 513 if self.log_level <= logging.INFO: print
416 514
417 515 # Now a variety of things that happen after the banner is printed.
418 516 self._enable_gui_pylab()
419 517 self._load_extensions()
420 518 self._run_exec_lines()
421 519 self._run_exec_files()
422 520 self._run_cmd_line_code()
423 521 self._configure_xmode()
424 522
425 523 def _enable_gui_pylab(self):
426 524 """Enable GUI event loop integration, taking pylab into account."""
427 525 Global = self.master_config.Global
428 526
429 527 # Select which gui to use
430 528 if Global.gui:
431 529 gui = Global.gui
432 530 # The following are deprecated, but there's likely to be a lot of use
433 531 # of this form out there, so we might as well support it for now. But
434 532 # the --gui option above takes precedence.
435 533 elif Global.wthread:
436 534 gui = inputhook.GUI_WX
437 535 elif Global.qthread:
438 536 gui = inputhook.GUI_QT
439 537 elif Global.gthread:
440 538 gui = inputhook.GUI_GTK
441 539 else:
442 540 gui = None
443 541
444 542 # Using --pylab will also require gui activation, though which toolkit
445 543 # to use may be chosen automatically based on mpl configuration.
446 544 if Global.pylab:
447 545 activate = self.shell.enable_pylab
448 546 if Global.pylab == 'auto':
449 547 gui = None
450 548 else:
451 549 gui = Global.pylab
452 550 else:
453 551 # Enable only GUI integration, no pylab
454 552 activate = inputhook.enable_gui
455 553
456 554 if gui or Global.pylab:
457 555 try:
458 556 self.log.info("Enabling GUI event loop integration, "
459 557 "toolkit=%s, pylab=%s" % (gui, Global.pylab) )
460 558 activate(gui)
461 559 except:
462 560 self.log.warn("Error in enabling GUI event loop integration:")
463 561 self.shell.showtraceback()
464 562
465 563 def _load_extensions(self):
466 564 """Load all IPython extensions in Global.extensions.
467 565
468 566 This uses the :meth:`InteractiveShell.load_extensions` to load all
469 567 the extensions listed in ``self.master_config.Global.extensions``.
470 568 """
471 569 try:
472 570 if hasattr(self.master_config.Global, 'extensions'):
473 571 self.log.debug("Loading IPython extensions...")
474 572 extensions = self.master_config.Global.extensions
475 573 for ext in extensions:
476 574 try:
477 575 self.log.info("Loading IPython extension: %s" % ext)
478 576 self.shell.load_extension(ext)
479 577 except:
480 578 self.log.warn("Error in loading extension: %s" % ext)
481 579 self.shell.showtraceback()
482 580 except:
483 581 self.log.warn("Unknown error in loading extensions:")
484 582 self.shell.showtraceback()
485 583
486 584 def _run_exec_lines(self):
487 585 """Run lines of code in Global.exec_lines in the user's namespace."""
488 586 try:
489 587 if hasattr(self.master_config.Global, 'exec_lines'):
490 588 self.log.debug("Running code from Global.exec_lines...")
491 589 exec_lines = self.master_config.Global.exec_lines
492 590 for line in exec_lines:
493 591 try:
494 592 self.log.info("Running code in user namespace: %s" % line)
495 593 self.shell.runlines(line)
496 594 except:
497 595 self.log.warn("Error in executing line in user namespace: %s" % line)
498 596 self.shell.showtraceback()
499 597 except:
500 598 self.log.warn("Unknown error in handling Global.exec_lines:")
501 599 self.shell.showtraceback()
502 600
503 601 def _exec_file(self, fname):
504 602 full_filename = filefind(fname, [u'.', self.ipython_dir])
505 603 if os.path.isfile(full_filename):
506 604 if full_filename.endswith(u'.py'):
507 605 self.log.info("Running file in user namespace: %s" % full_filename)
508 606 self.shell.safe_execfile(full_filename, self.shell.user_ns)
509 607 elif full_filename.endswith('.ipy'):
510 608 self.log.info("Running file in user namespace: %s" % full_filename)
511 609 self.shell.safe_execfile_ipy(full_filename)
512 610 else:
513 611 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
514 612
515 613 def _run_exec_files(self):
516 614 try:
517 615 if hasattr(self.master_config.Global, 'exec_files'):
518 616 self.log.debug("Running files in Global.exec_files...")
519 617 exec_files = self.master_config.Global.exec_files
520 618 for fname in exec_files:
521 619 self._exec_file(fname)
522 620 except:
523 621 self.log.warn("Unknown error in handling Global.exec_files:")
524 622 self.shell.showtraceback()
525 623
526 624 def _run_cmd_line_code(self):
527 625 if hasattr(self.master_config.Global, 'code_to_run'):
528 626 line = self.master_config.Global.code_to_run
529 627 try:
530 628 self.log.info("Running code given at command line (-c): %s" % line)
531 629 self.shell.runlines(line)
532 630 except:
533 631 self.log.warn("Error in executing line in user namespace: %s" % line)
534 632 self.shell.showtraceback()
535 633 return
536 634 # Like Python itself, ignore the second if the first of these is present
537 635 try:
538 636 fname = self.extra_args[0]
539 637 except:
540 638 pass
541 639 else:
542 640 try:
543 641 self._exec_file(fname)
544 642 except:
545 643 self.log.warn("Error in executing file in user namespace: %s" % fname)
546 644 self.shell.showtraceback()
547 645
548 646 def _configure_xmode(self):
549 647 # XXX - shouldn't this be read from the config? I'm still a little
550 648 # lost with all the details of handling the new config guys...
551 649 self.shell.InteractiveTB.set_mode(mode=self.shell.xmode)
552 650
553 651 def start_app(self):
554 652 if self.master_config.Global.interact:
555 653 self.log.debug("Starting IPython's mainloop...")
556 654 self.shell.mainloop()
557 655 else:
558 656 self.log.debug("IPython not interactive, start_app is no-op...")
559 657
560 658
561 659 def load_default_config(ipython_dir=None):
562 660 """Load the default config file from the default ipython_dir.
563 661
564 662 This is useful for embedded shells.
565 663 """
566 664 if ipython_dir is None:
567 665 ipython_dir = get_ipython_dir()
568 666 cl = PyFileConfigLoader(default_config_file_name, ipython_dir)
569 667 config = cl.load_config()
570 668 return config
571 669
572 670
573 671 def launch_new_instance():
574 672 """Create and run a full blown IPython instance"""
575 673 app = IPythonApp()
576 674 app.start()
@@ -1,588 +1,297 b''
1 1 # -*- coding: utf-8 -*-
2 #*****************************************************************************
3 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
2 """Usage information for the main IPython applications.
3 """
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008-2010 The IPython Development Team
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
4 7 #
5 8 # Distributed under the terms of the BSD License. The full license is in
6 9 # the file COPYING, distributed as part of this software.
7 #*****************************************************************************
10 #-----------------------------------------------------------------------------
8 11
9 12 import sys
10 13 from IPython.core import release
11 14
12 __doc__ = """
13 IPython -- An enhanced Interactive Python
14 =========================================
15 cl_usage = """\
16 ipython [options] [files]
15 17
16 A Python shell with automatic history (input and output), dynamic object
17 introspection, easier configuration, command completion, access to the system
18 shell and more.
19
20 IPython can also be embedded in running programs. See EMBEDDING below.
21
22
23 USAGE
24 ipython [options] files
25
26 If invoked with no options, it executes all the files listed in
27 sequence and drops you into the interpreter while still acknowledging
28 any options you may have set in your ipythonrc file. This behavior is
29 different from standard Python, which when called as python -i will
30 only execute one file and will ignore your configuration setup.
31
32 Please note that some of the configuration options are not available at
33 the command line, simply because they are not practical here. Look into
34 your ipythonrc configuration file for details on those. This file
35 typically installed in the $HOME/.ipython directory.
36
37 For Windows users, $HOME resolves to C:\\Documents and
38 Settings\\YourUserName in most instances, and _ipython is used instead
39 of .ipython, since some Win32 programs have problems with dotted names
40 in directories.
41
42 In the rest of this text, we will refer to this directory as
43 IPYTHON_DIR.
44
45 REGULAR OPTIONS
46 After the above threading options have been given, regular options can
47 follow in any order. All options can be abbreviated to their shortest
48 non-ambiguous form and are case-sensitive. One or two dashes can be
49 used. Some options have an alternate short form, indicated after a |.
50
51 Most options can also be set from your ipythonrc configuration file.
52 See the provided examples for assistance. Options given on the comman-
53 dline override the values set in the ipythonrc file.
54
55 All options with a [no] prepended can be specified in negated form
56 (using -nooption instead of -option) to turn the feature off.
57
58 -h, --help
59 Show summary of options.
60
61 -autocall <val>
62 Make IPython automatically call any callable object even if you
63 didn't type explicit parentheses. For example, 'str 43' becomes
64 'str(43)' automatically. The value can be '0' to disable the
65 feature, '1' for 'smart' autocall, where it is not applied if
66 there are no more arguments on the line, and '2' for 'full'
67 autocall, where all callable objects are automatically called
68 (even if no arguments are present). The default is '1'.
69
70 -[no]autoindent
71 Turn automatic indentation on/off.
72
73 -[no]automagic
74 Make magic commands automatic (without needing their first char-
75 acter to be %). Type %magic at the IPython prompt for more
76 information.
77
78 -[no]autoedit_syntax
79 When a syntax error occurs after editing a file, automatically
80 open the file to the trouble causing line for convenient fixing.
81
82 -[no]banner
83 Print the intial information banner (default on).
84
85 -c <command>
86 Execute the given command string, and set sys.argv to ['c'].
87 This is similar to the -c option in the normal Python inter-
88 preter.
89
90 -cache_size|cs <n>
91 Size of the output cache (maximum number of entries to hold in
92 memory). The default is 1000, you can change it permanently in
93 your config file. Setting it to 0 completely disables the
94 caching system, and the minimum value accepted is 20 (if you
95 provide a value less than 20, it is reset to 0 and a warning is
96 issued). This limit is defined because otherwise you'll spend
97 more time re-flushing a too small cache than working.
98
99 -classic|cl
100 Gives IPython a similar feel to the classic Python prompt.
101
102 -colors <scheme>
103 Color scheme for prompts and exception reporting. Currently
104 implemented: NoColor, Linux, and LightBG.
105
106 -[no]color_info
107 IPython can display information about objects via a set of func-
108 tions, and optionally can use colors for this, syntax highlight-
109 ing source code and various other elements. However, because
110 this information is passed through a pager (like 'less') and
111 many pagers get confused with color codes, this option is off by
112 default. You can test it and turn it on permanently in your
113 ipythonrc file if it works for you. As a reference, the 'less'
114 pager supplied with Mandrake 8.2 works ok, but that in RedHat
115 7.2 doesn't.
116
117 Test it and turn it on permanently if it works with your system.
118 The magic function @color_info allows you to toggle this inter-
119 actively for testing.
120
121 -[no]confirm_exit
122 Set to confirm when you try to exit IPython with an EOF (Con-
123 trol-D in Unix, Control-Z/Enter in Windows). Note that using the
124 magic functions @Exit or @Quit you can force a direct exit,
125 bypassing any confirmation.
126
127 -[no]debug
128 Show information about the loading process. Very useful to pin
129 down problems with your configuration files or to get details
130 about session restores.
131
132 -[no]deep_reload
133 IPython can use the deep_reload module which reloads changes in
134 modules recursively (it replaces the reload() function, so you
135 don't need to change anything to use it). deep_reload() forces a
136 full reload of modules whose code may have changed, which the
137 default reload() function does not.
138
139 When deep_reload is off, IPython will use the normal reload(),
140 but deep_reload will still be available as dreload(). This fea-
141 ture is off by default [which means that you have both normal
142 reload() and dreload()].
143
144 -editor <name>
145 Which editor to use with the @edit command. By default, IPython
146 will honor your EDITOR environment variable (if not set, vi is
147 the Unix default and notepad the Windows one). Since this editor
148 is invoked on the fly by IPython and is meant for editing small
149 code snippets, you may want to use a small, lightweight editor
150 here (in case your default EDITOR is something like Emacs).
151
152 -ipythondir <name>
153 The name of your IPython configuration directory IPYTHON_DIR.
154 This can also be specified through the environment variable
155 IPYTHON_DIR.
156
157 -log|l Generate a log file of all input. The file is named
158 ipython_log.py in your current directory (which prevents logs
159 from multiple IPython sessions from trampling each other). You
160 can use this to later restore a session by loading your logfile
161 as a file to be executed with option -logplay (see below).
162
163 -logfile|lf
164 Specify the name of your logfile.
165
166 -logplay|lp
167 Replay a previous log. For restoring a session as close as pos-
168 sible to the state you left it in, use this option (don't just
169 run the logfile). With -logplay, IPython will try to reconstruct
170 the previous working environment in full, not just execute the
171 commands in the logfile.
172 When a session is restored, logging is automatically turned on
173 again with the name of the logfile it was invoked with (it is
174 read from the log header). So once you've turned logging on for
175 a session, you can quit IPython and reload it as many times as
176 you want and it will continue to log its history and restore
177 from the beginning every time.
178
179 Caveats: there are limitations in this option. The history vari-
180 ables _i*,_* and _dh don't get restored properly. In the future
181 we will try to implement full session saving by writing and
182 retrieving a failed because of inherent limitations of Python's
183 Pickle module, so this may have to wait.
184
185 -[no]messages
186 Print messages which IPython collects about its startup process
187 (default on).
188
189 -[no]pdb
190 Automatically call the pdb debugger after every uncaught excep-
191 tion. If you are used to debugging using pdb, this puts you
192 automatically inside of it after any call (either in IPython or
193 in code called by it) which triggers an exception which goes
194 uncaught.
195
196 -[no]pprint
197 IPython can optionally use the pprint (pretty printer) module
198 for displaying results. pprint tends to give a nicer display of
199 nested data structures. If you like it, you can turn it on per-
200 manently in your config file (default off).
201
202 -profile|p <name>
203 Assume that your config file is ipythonrc-<name> (looks in cur-
204 rent dir first, then in IPYTHON_DIR). This is a quick way to keep
205 and load multiple config files for different tasks, especially
206 if you use the include option of config files. You can keep a
207 basic IPYTHON_DIR/ipythonrc file and then have other 'profiles'
208 which include this one and load extra things for particular
209 tasks. For example:
210
211 1) $HOME/.ipython/ipythonrc : load basic things you always want.
212 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math-
213 related modules.
214 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and
215 plotting modules.
216
217 Since it is possible to create an endless loop by having circu-
218 lar file inclusions, IPython will stop if it reaches 15 recur-
219 sive inclusions.
220
221 -prompt_in1|pi1 <string>
222 Specify the string used for input prompts. Note that if you are
223 using numbered prompts, the number is represented with a '\#' in
224 the string. Don't forget to quote strings with spaces embedded
225 in them. Default: 'In [\#]: '.
226
227 Most bash-like escapes can be used to customize IPython's
228 prompts, as well as a few additional ones which are IPython-spe-
229 cific. All valid prompt escapes are described in detail in the
230 Customization section of the IPython HTML/PDF manual.
231
232 -prompt_in2|pi2 <string>
233 Similar to the previous option, but used for the continuation
234 prompts. The special sequence '\D' is similar to '\#', but with
235 all digits replaced dots (so you can have your continuation
236 prompt aligned with your input prompt). Default: ' .\D.: '
237 (note three spaces at the start for alignment with 'In [\#]').
238
239 -prompt_out|po <string>
240 String used for output prompts, also uses numbers like
241 prompt_in1. Default: 'Out[\#]:'.
242
243 -quick Start in bare bones mode (no config file loaded).
244
245 -rcfile <name>
246 Name of your IPython resource configuration file. normally
247 IPython loads ipythonrc (from current directory) or
248 IPYTHON_DIR/ipythonrc. If the loading of your config file fails,
249 IPython starts with a bare bones configuration (no modules
250 loaded at all).
251
252 -[no]readline
253 Use the readline library, which is needed to support name com-
254 pletion and command history, among other things. It is enabled
255 by default, but may cause problems for users of X/Emacs in
256 Python comint or shell buffers.
257
258 Note that emacs 'eterm' buffers (opened with M-x term) support
259 IPython's readline and syntax coloring fine, only 'emacs' (M-x
260 shell and C-c !) buffers do not.
261
262 -screen_length|sl <n>
263 Number of lines of your screen. This is used to control print-
264 ing of very long strings. Strings longer than this number of
265 lines will be sent through a pager instead of directly printed.
266
267 The default value for this is 0, which means IPython will auto-
268 detect your screen size every time it needs to print certain
269 potentially long strings (this doesn't change the behavior of
270 the 'print' keyword, it's only triggered internally). If for
271 some reason this isn't working well (it needs curses support),
272 specify it yourself. Otherwise don't change the default.
273
274 -separate_in|si <string>
275 Separator before input prompts. Default '0.
276
277 -separate_out|so <string>
278 Separator before output prompts. Default: 0 (nothing).
279
280 -separate_out2|so2 <string>
281 Separator after output prompts. Default: 0 (nothing).
282
283 -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'.
284 Simply removes all input/output separators.
285
286 -upgrade
287 Allows you to upgrade your IPYTHON_DIR configuration when you
288 install a new version of IPython. Since new versions may
289 include new command lines options or example files, this copies
290 updated ipythonrc-type files. However, it backs up (with a .old
291 extension) all files which it overwrites so that you can merge
292 back any custimizations you might have in your personal files.
293
294 -Version
295 Print version information and exit.
296
297 -wxversion <string>
298 Select a specific version of wxPython (used in conjunction with
299 -wthread). Requires the wxversion module, part of recent
300 wxPython distributions.
301
302 -xmode <modename>
303 Mode for exception reporting. The valid modes are Plain, Con-
304 text, and Verbose.
305
306 - Plain: similar to python's normal traceback printing.
307
308 - Context: prints 5 lines of context source code around each
309 line in the traceback.
310
311 - Verbose: similar to Context, but additionally prints the vari-
312 ables currently visible where the exception happened (shortening
313 their strings if too long). This can potentially be very slow,
314 if you happen to have a huge data structure whose string repre-
315 sentation is complex to compute. Your computer may appear to
316 freeze for a while with cpu usage at 100%. If this occurs, you
317 can cancel the traceback with Ctrl-C (maybe hitting it more than
318 once).
319
320
321 EMBEDDING
322 It is possible to start an IPython instance inside your own Python pro-
323 grams. In the documentation example files there are some illustrations
324 on how to do this.
325
326 This feature allows you to evalutate dynamically the state of your
327 code, operate with your variables, analyze them, etc. Note however
328 that any changes you make to values while in the shell do NOT propagate
329 back to the running code, so it is safe to modify your values because
330 you won't break your code in bizarre ways by doing so.
331 """
18 IPython: an enhanced interactive Python shell.
19
20 A Python shell with automatic history (input and output), dynamic object
21 introspection, easier configuration, command completion, access to the
22 system shell and more. IPython can also be embedded in running programs.
332 23
333 cmd_line_usage = __doc__
24 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
26 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.)
28
29 Please note that some of the configuration options are not available at the
30 command line, simply because they are not practical here. Look into your
31 ipython_config.py configuration file for details on those.
32
33 This file typically installed in the $HOME/.ipython directory. For Windows
34 users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most
35 instances.
36
37 In IPython's documentation, we will refer to this directory as IPYTHON_DIR,
38 you can change its default location by setting any path you want in this
39 environment variable.
40
41 For more information, see the manual available in HTML and PDF in your
42 installation, or online at http://ipython.scipy.org.
43 """
334 44
335 #---------------------------------------------------------------------------
336 45 interactive_usage = """
337 46 IPython -- An enhanced Interactive Python
338 47 =========================================
339 48
340 49 IPython offers a combination of convenient shell features, special commands
341 50 and a history mechanism for both input (command history) and output (results
342 51 caching, similar to Mathematica). It is intended to be a fully compatible
343 52 replacement for the standard Python interpreter, while offering vastly
344 53 improved functionality and flexibility.
345 54
346 55 At your system command line, type 'ipython -help' to see the command line
347 56 options available. This document only describes interactive features.
348 57
349 58 Warning: IPython relies on the existence of a global variable called __IP which
350 59 controls the shell itself. If you redefine __IP to anything, bizarre behavior
351 60 will quickly occur.
352 61
353 62 MAIN FEATURES
354 63
355 64 * Access to the standard Python help. As of Python 2.1, a help system is
356 65 available with access to object docstrings and the Python manuals. Simply
357 66 type 'help' (no quotes) to access it.
358 67
359 68 * Magic commands: type %magic for information on the magic subsystem.
360 69
361 70 * System command aliases, via the %alias command or the ipythonrc config file.
362 71
363 72 * Dynamic object information:
364 73
365 74 Typing ?word or word? prints detailed information about an object. If
366 75 certain strings in the object are too long (docstrings, code, etc.) they get
367 76 snipped in the center for brevity.
368 77
369 78 Typing ??word or word?? gives access to the full information without
370 79 snipping long strings. Long strings are sent to the screen through the less
371 80 pager if longer than the screen, printed otherwise.
372 81
373 82 The ?/?? system gives access to the full source code for any object (if
374 83 available), shows function prototypes and other useful information.
375 84
376 85 If you just want to see an object's docstring, type '%pdoc object' (without
377 86 quotes, and without % if you have automagic on).
378 87
379 88 Both %pdoc and ?/?? give you access to documentation even on things which are
380 89 not explicitely defined. Try for example typing {}.get? or after import os,
381 90 type os.path.abspath??. The magic functions %pdef, %source and %file operate
382 91 similarly.
383 92
384 93 * Completion in the local namespace, by typing TAB at the prompt.
385 94
386 95 At any time, hitting tab will complete any available python commands or
387 96 variable names, and show you a list of the possible completions if there's
388 97 no unambiguous one. It will also complete filenames in the current directory.
389 98
390 99 This feature requires the readline and rlcomplete modules, so it won't work
391 100 if your Python lacks readline support (such as under Windows).
392 101
393 102 * Search previous command history in two ways (also requires readline):
394 103
395 104 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
396 105 search through only the history items that match what you've typed so
397 106 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
398 107 normal arrow keys.
399 108
400 109 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
401 110 your history for lines that match what you've typed so far, completing as
402 111 much as it can.
403 112
404 113 * Persistent command history across sessions (readline required).
405 114
406 115 * Logging of input with the ability to save and restore a working session.
407 116
408 117 * System escape with !. Typing !ls will run 'ls' in the current directory.
409 118
410 119 * The reload command does a 'deep' reload of a module: changes made to the
411 120 module since you imported will actually be available without having to exit.
412 121
413 122 * Verbose and colored exception traceback printouts. See the magic xmode and
414 123 xcolor functions for details (just type %magic).
415 124
416 125 * Input caching system:
417 126
418 127 IPython offers numbered prompts (In/Out) with input and output caching. All
419 128 input is saved and can be retrieved as variables (besides the usual arrow
420 129 key recall).
421 130
422 131 The following GLOBAL variables always exist (so don't overwrite them!):
423 132 _i: stores previous input.
424 133 _ii: next previous.
425 134 _iii: next-next previous.
426 135 _ih : a list of all input _ih[n] is the input from line n.
427 136
428 137 Additionally, global variables named _i<n> are dynamically created (<n>
429 138 being the prompt counter), such that _i<n> == _ih[<n>]
430 139
431 140 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
432 141
433 142 You can create macros which contain multiple input lines from this history,
434 143 for later re-execution, with the %macro function.
435 144
436 145 The history function %hist allows you to see any part of your input history
437 146 by printing a range of the _i variables. Note that inputs which contain
438 147 magic functions (%) appear in the history with a prepended comment. This is
439 148 because they aren't really valid Python code, so you can't exec them.
440 149
441 150 * Output caching system:
442 151
443 152 For output that is returned from actions, a system similar to the input
444 153 cache exists but using _ instead of _i. Only actions that produce a result
445 154 (NOT assignments, for example) are cached. If you are familiar with
446 155 Mathematica, IPython's _ variables behave exactly like Mathematica's %
447 156 variables.
448 157
449 158 The following GLOBAL variables always exist (so don't overwrite them!):
450 159 _ (one underscore): previous output.
451 160 __ (two underscores): next previous.
452 161 ___ (three underscores): next-next previous.
453 162
454 163 Global variables named _<n> are dynamically created (<n> being the prompt
455 164 counter), such that the result of output <n> is always available as _<n>.
456 165
457 166 Finally, a global dictionary named _oh exists with entries for all lines
458 167 which generated output.
459 168
460 169 * Directory history:
461 170
462 171 Your history of visited directories is kept in the global list _dh, and the
463 172 magic %cd command can be used to go to any entry in that list.
464 173
465 174 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
466 175
467 176 1. Auto-parentheses
468 177 Callable objects (i.e. functions, methods, etc) can be invoked like
469 178 this (notice the commas between the arguments):
470 179 >>> callable_ob arg1, arg2, arg3
471 180 and the input will be translated to this:
472 181 --> callable_ob(arg1, arg2, arg3)
473 182 You can force auto-parentheses by using '/' as the first character
474 183 of a line. For example:
475 184 >>> /globals # becomes 'globals()'
476 185 Note that the '/' MUST be the first character on the line! This
477 186 won't work:
478 187 >>> print /globals # syntax error
479 188
480 189 In most cases the automatic algorithm should work, so you should
481 190 rarely need to explicitly invoke /. One notable exception is if you
482 191 are trying to call a function with a list of tuples as arguments (the
483 192 parenthesis will confuse IPython):
484 193 In [1]: zip (1,2,3),(4,5,6) # won't work
485 194 but this will work:
486 195 In [2]: /zip (1,2,3),(4,5,6)
487 196 ------> zip ((1,2,3),(4,5,6))
488 197 Out[2]= [(1, 4), (2, 5), (3, 6)]
489 198
490 199 IPython tells you that it has altered your command line by
491 200 displaying the new command line preceded by -->. e.g.:
492 201 In [18]: callable list
493 202 -------> callable (list)
494 203
495 204 2. Auto-Quoting
496 205 You can force auto-quoting of a function's arguments by using ',' as
497 206 the first character of a line. For example:
498 207 >>> ,my_function /home/me # becomes my_function("/home/me")
499 208
500 209 If you use ';' instead, the whole argument is quoted as a single
501 210 string (while ',' splits on whitespace):
502 211 >>> ,my_function a b c # becomes my_function("a","b","c")
503 212 >>> ;my_function a b c # becomes my_function("a b c")
504 213
505 214 Note that the ',' MUST be the first character on the line! This
506 215 won't work:
507 216 >>> x = ,my_function /home/me # syntax error
508 217 """
509 218
510 219 interactive_usage_min = """\
511 220 An enhanced console for Python.
512 221 Some of its features are:
513 222 - Readline support if the readline library is present.
514 223 - Tab completion in the local namespace.
515 224 - Logging of input, see command-line options.
516 225 - System shell escape via ! , eg !ls.
517 226 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
518 227 - Keeps track of locally defined variables via %who, %whos.
519 228 - Show object information with a ? eg ?x or x? (use ?? for more info).
520 229 """
521 230
522 231 quick_reference = r"""
523 232 IPython -- An enhanced Interactive Python - Quick Reference Card
524 233 ================================================================
525 234
526 235 obj?, obj?? : Get help, or more help for object (also works as
527 236 ?obj, ??obj).
528 237 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
529 238 %magic : Information about IPython's 'magic' % functions.
530 239
531 240 Magic functions are prefixed by %, and typically take their arguments without
532 241 parentheses, quotes or even commas for convenience.
533 242
534 243 Example magic function calls:
535 244
536 245 %alias d ls -F : 'd' is now an alias for 'ls -F'
537 246 alias d ls -F : Works if 'alias' not a python name
538 247 alist = %alias : Get list of aliases to 'alist'
539 248 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
540 249 %cd?? : See help AND source for magic %cd
541 250
542 251 System commands:
543 252
544 253 !cp a.txt b/ : System command escape, calls os.system()
545 254 cp a.txt b/ : after %rehashx, most system commands work without !
546 255 cp ${f}.txt $bar : Variable expansion in magics and system commands
547 256 files = !ls /usr : Capture sytem command output
548 257 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
549 258
550 259 History:
551 260
552 261 _i, _ii, _iii : Previous, next previous, next next previous input
553 262 _i4, _ih[2:5] : Input history line 4, lines 2-4
554 263 exec _i81 : Execute input history line #81 again
555 264 %rep 81 : Edit input history line #81
556 265 _, __, ___ : previous, next previous, next next previous output
557 266 _dh : Directory history
558 267 _oh : Output history
559 268 %hist : Command history. '%hist -g foo' search history for 'foo'
560 269
561 270 Autocall:
562 271
563 272 f 1,2 : f(1,2)
564 273 /f 1,2 : f(1,2) (forced autoparen)
565 274 ,f 1 2 : f("1","2")
566 275 ;f 1 2 : f("1 2")
567 276
568 277 Remember: TAB completion works in many contexts, not just file names
569 278 or python names.
570 279
571 280 The following magic functions are currently available:
572 281
573 282 """
574 283
575 284 quick_guide = """\
576 285 ? -> Introduction and overview of IPython's features.
577 286 %quickref -> Quick reference.
578 287 help -> Python's own help system.
579 288 object? -> Details about 'object'. ?object also works, ?? prints more."""
580 289
581 290 default_banner_parts = [
582 291 'Python %s' % (sys.version.split('\n')[0],),
583 292 'Type "copyright", "credits" or "license" for more information.\n',
584 293 'IPython %s -- An enhanced Interactive Python.' % (release.version,),
585 294 quick_guide
586 295 ]
587 296
588 297 default_banner = '\n'.join(default_banner_parts)
General Comments 0
You need to be logged in to leave comments. Login now