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