##// END OF EJS Templates
IPYTHON_DIR -> IPYTHONDIR in comments and documentation
Bradley M. Froehle -
Show More
@@ -1,336 +1,336 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 An application for IPython.
3 An application for IPython.
4
4
5 All top-level applications should use the classes in this module for
5 All top-level applications should use the classes in this module for
6 handling configuration and creating componenets.
6 handling configuration and creating componenets.
7
7
8 The job of an :class:`Application` is to create the master configuration
8 The job of an :class:`Application` is to create the master configuration
9 object and then create the configurable objects, passing the config to them.
9 object and then create the configurable objects, passing the config to them.
10
10
11 Authors:
11 Authors:
12
12
13 * Brian Granger
13 * Brian Granger
14 * Fernando Perez
14 * Fernando Perez
15 * Min RK
15 * Min RK
16
16
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2011 The IPython Development Team
20 # Copyright (C) 2008-2011 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Imports
27 # Imports
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 import atexit
30 import atexit
31 import glob
31 import glob
32 import logging
32 import logging
33 import os
33 import os
34 import shutil
34 import shutil
35 import sys
35 import sys
36
36
37 from IPython.config.application import Application, catch_config_error
37 from IPython.config.application import Application, catch_config_error
38 from IPython.config.configurable import Configurable
38 from IPython.config.configurable import Configurable
39 from IPython.config.loader import Config, ConfigFileNotFound
39 from IPython.config.loader import Config, ConfigFileNotFound
40 from IPython.core import release, crashhandler
40 from IPython.core import release, crashhandler
41 from IPython.core.profiledir import ProfileDir, ProfileDirError
41 from IPython.core.profiledir import ProfileDir, ProfileDirError
42 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
42 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
43 from IPython.utils.traitlets import List, Unicode, Type, Bool, Dict
43 from IPython.utils.traitlets import List, Unicode, Type, Bool, Dict
44 from IPython.utils import py3compat
44 from IPython.utils import py3compat
45
45
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47 # Classes and functions
47 # Classes and functions
48 #-----------------------------------------------------------------------------
48 #-----------------------------------------------------------------------------
49
49
50
50
51 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
52 # Base Application Class
52 # Base Application Class
53 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
54
54
55 # aliases and flags
55 # aliases and flags
56
56
57 base_aliases = {
57 base_aliases = {
58 'profile' : 'BaseIPythonApplication.profile',
58 'profile' : 'BaseIPythonApplication.profile',
59 'ipython-dir' : 'BaseIPythonApplication.ipython_dir',
59 'ipython-dir' : 'BaseIPythonApplication.ipython_dir',
60 'log-level' : 'Application.log_level',
60 'log-level' : 'Application.log_level',
61 }
61 }
62
62
63 base_flags = dict(
63 base_flags = dict(
64 debug = ({'Application' : {'log_level' : logging.DEBUG}},
64 debug = ({'Application' : {'log_level' : logging.DEBUG}},
65 "set log level to logging.DEBUG (maximize logging output)"),
65 "set log level to logging.DEBUG (maximize logging output)"),
66 quiet = ({'Application' : {'log_level' : logging.CRITICAL}},
66 quiet = ({'Application' : {'log_level' : logging.CRITICAL}},
67 "set log level to logging.CRITICAL (minimize logging output)"),
67 "set log level to logging.CRITICAL (minimize logging output)"),
68 init = ({'BaseIPythonApplication' : {
68 init = ({'BaseIPythonApplication' : {
69 'copy_config_files' : True,
69 'copy_config_files' : True,
70 'auto_create' : True}
70 'auto_create' : True}
71 }, """Initialize profile with default config files. This is equivalent
71 }, """Initialize profile with default config files. This is equivalent
72 to running `ipython profile create <profile>` prior to startup.
72 to running `ipython profile create <profile>` prior to startup.
73 """)
73 """)
74 )
74 )
75
75
76
76
77 class BaseIPythonApplication(Application):
77 class BaseIPythonApplication(Application):
78
78
79 name = Unicode(u'ipython')
79 name = Unicode(u'ipython')
80 description = Unicode(u'IPython: an enhanced interactive Python shell.')
80 description = Unicode(u'IPython: an enhanced interactive Python shell.')
81 version = Unicode(release.version)
81 version = Unicode(release.version)
82
82
83 aliases = Dict(base_aliases)
83 aliases = Dict(base_aliases)
84 flags = Dict(base_flags)
84 flags = Dict(base_flags)
85 classes = List([ProfileDir])
85 classes = List([ProfileDir])
86
86
87 # Track whether the config_file has changed,
87 # Track whether the config_file has changed,
88 # because some logic happens only if we aren't using the default.
88 # because some logic happens only if we aren't using the default.
89 config_file_specified = Bool(False)
89 config_file_specified = Bool(False)
90
90
91 config_file_name = Unicode(u'ipython_config.py')
91 config_file_name = Unicode(u'ipython_config.py')
92 def _config_file_name_default(self):
92 def _config_file_name_default(self):
93 return self.name.replace('-','_') + u'_config.py'
93 return self.name.replace('-','_') + u'_config.py'
94 def _config_file_name_changed(self, name, old, new):
94 def _config_file_name_changed(self, name, old, new):
95 if new != old:
95 if new != old:
96 self.config_file_specified = True
96 self.config_file_specified = True
97
97
98 # The directory that contains IPython's builtin profiles.
98 # The directory that contains IPython's builtin profiles.
99 builtin_profile_dir = Unicode(
99 builtin_profile_dir = Unicode(
100 os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
100 os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
101 )
101 )
102
102
103 config_file_paths = List(Unicode)
103 config_file_paths = List(Unicode)
104 def _config_file_paths_default(self):
104 def _config_file_paths_default(self):
105 return [os.getcwdu()]
105 return [os.getcwdu()]
106
106
107 profile = Unicode(u'default', config=True,
107 profile = Unicode(u'default', config=True,
108 help="""The IPython profile to use."""
108 help="""The IPython profile to use."""
109 )
109 )
110
110
111 def _profile_changed(self, name, old, new):
111 def _profile_changed(self, name, old, new):
112 self.builtin_profile_dir = os.path.join(
112 self.builtin_profile_dir = os.path.join(
113 get_ipython_package_dir(), u'config', u'profile', new
113 get_ipython_package_dir(), u'config', u'profile', new
114 )
114 )
115
115
116 ipython_dir = Unicode(get_ipython_dir(), config=True,
116 ipython_dir = Unicode(get_ipython_dir(), config=True,
117 help="""
117 help="""
118 The name of the IPython directory. This directory is used for logging
118 The name of the IPython directory. This directory is used for logging
119 configuration (through profiles), history storage, etc. The default
119 configuration (through profiles), history storage, etc. The default
120 is usually $HOME/.ipython. This options can also be specified through
120 is usually $HOME/.ipython. This options can also be specified through
121 the environment variable IPYTHON_DIR.
121 the environment variable IPYTHONDIR.
122 """
122 """
123 )
123 )
124
124
125 overwrite = Bool(False, config=True,
125 overwrite = Bool(False, config=True,
126 help="""Whether to overwrite existing config files when copying""")
126 help="""Whether to overwrite existing config files when copying""")
127 auto_create = Bool(False, config=True,
127 auto_create = Bool(False, config=True,
128 help="""Whether to create profile dir if it doesn't exist""")
128 help="""Whether to create profile dir if it doesn't exist""")
129
129
130 config_files = List(Unicode)
130 config_files = List(Unicode)
131 def _config_files_default(self):
131 def _config_files_default(self):
132 return [u'ipython_config.py']
132 return [u'ipython_config.py']
133
133
134 copy_config_files = Bool(False, config=True,
134 copy_config_files = Bool(False, config=True,
135 help="""Whether to install the default config files into the profile dir.
135 help="""Whether to install the default config files into the profile dir.
136 If a new profile is being created, and IPython contains config files for that
136 If a new profile is being created, and IPython contains config files for that
137 profile, then they will be staged into the new directory. Otherwise,
137 profile, then they will be staged into the new directory. Otherwise,
138 default config files will be automatically generated.
138 default config files will be automatically generated.
139 """)
139 """)
140
140
141 verbose_crash = Bool(False, config=True,
141 verbose_crash = Bool(False, config=True,
142 help="""Create a massive crash report when IPython enconters what may be an
142 help="""Create a massive crash report when IPython enconters what may be an
143 internal error. The default is to append a short message to the
143 internal error. The default is to append a short message to the
144 usual traceback""")
144 usual traceback""")
145
145
146 # The class to use as the crash handler.
146 # The class to use as the crash handler.
147 crash_handler_class = Type(crashhandler.CrashHandler)
147 crash_handler_class = Type(crashhandler.CrashHandler)
148
148
149 def __init__(self, **kwargs):
149 def __init__(self, **kwargs):
150 super(BaseIPythonApplication, self).__init__(**kwargs)
150 super(BaseIPythonApplication, self).__init__(**kwargs)
151 # ensure even default IPYTHON_DIR exists
151 # ensure even default IPYTHONDIR exists
152 if not os.path.exists(self.ipython_dir):
152 if not os.path.exists(self.ipython_dir):
153 self._ipython_dir_changed('ipython_dir', self.ipython_dir, self.ipython_dir)
153 self._ipython_dir_changed('ipython_dir', self.ipython_dir, self.ipython_dir)
154
154
155 #-------------------------------------------------------------------------
155 #-------------------------------------------------------------------------
156 # Various stages of Application creation
156 # Various stages of Application creation
157 #-------------------------------------------------------------------------
157 #-------------------------------------------------------------------------
158
158
159 def init_crash_handler(self):
159 def init_crash_handler(self):
160 """Create a crash handler, typically setting sys.excepthook to it."""
160 """Create a crash handler, typically setting sys.excepthook to it."""
161 self.crash_handler = self.crash_handler_class(self)
161 self.crash_handler = self.crash_handler_class(self)
162 sys.excepthook = self.excepthook
162 sys.excepthook = self.excepthook
163 def unset_crashhandler():
163 def unset_crashhandler():
164 sys.excepthook = sys.__excepthook__
164 sys.excepthook = sys.__excepthook__
165 atexit.register(unset_crashhandler)
165 atexit.register(unset_crashhandler)
166
166
167 def excepthook(self, etype, evalue, tb):
167 def excepthook(self, etype, evalue, tb):
168 """this is sys.excepthook after init_crashhandler
168 """this is sys.excepthook after init_crashhandler
169
169
170 set self.verbose_crash=True to use our full crashhandler, instead of
170 set self.verbose_crash=True to use our full crashhandler, instead of
171 a regular traceback with a short message (crash_handler_lite)
171 a regular traceback with a short message (crash_handler_lite)
172 """
172 """
173
173
174 if self.verbose_crash:
174 if self.verbose_crash:
175 return self.crash_handler(etype, evalue, tb)
175 return self.crash_handler(etype, evalue, tb)
176 else:
176 else:
177 return crashhandler.crash_handler_lite(etype, evalue, tb)
177 return crashhandler.crash_handler_lite(etype, evalue, tb)
178
178
179 def _ipython_dir_changed(self, name, old, new):
179 def _ipython_dir_changed(self, name, old, new):
180 if old in sys.path:
180 if old in sys.path:
181 sys.path.remove(old)
181 sys.path.remove(old)
182 sys.path.append(os.path.abspath(new))
182 sys.path.append(os.path.abspath(new))
183 if not os.path.isdir(new):
183 if not os.path.isdir(new):
184 os.makedirs(new, mode=0777)
184 os.makedirs(new, mode=0777)
185 readme = os.path.join(new, 'README')
185 readme = os.path.join(new, 'README')
186 if not os.path.exists(readme):
186 if not os.path.exists(readme):
187 path = os.path.join(get_ipython_package_dir(), u'config', u'profile')
187 path = os.path.join(get_ipython_package_dir(), u'config', u'profile')
188 shutil.copy(os.path.join(path, 'README'), readme)
188 shutil.copy(os.path.join(path, 'README'), readme)
189 self.log.debug("IPYTHON_DIR set to: %s" % new)
189 self.log.debug("IPYTHON_DIR set to: %s" % new)
190
190
191 def load_config_file(self, suppress_errors=True):
191 def load_config_file(self, suppress_errors=True):
192 """Load the config file.
192 """Load the config file.
193
193
194 By default, errors in loading config are handled, and a warning
194 By default, errors in loading config are handled, and a warning
195 printed on screen. For testing, the suppress_errors option is set
195 printed on screen. For testing, the suppress_errors option is set
196 to False, so errors will make tests fail.
196 to False, so errors will make tests fail.
197 """
197 """
198 self.log.debug("Searching path %s for config files", self.config_file_paths)
198 self.log.debug("Searching path %s for config files", self.config_file_paths)
199 base_config = 'ipython_config.py'
199 base_config = 'ipython_config.py'
200 self.log.debug("Attempting to load config file: %s" %
200 self.log.debug("Attempting to load config file: %s" %
201 base_config)
201 base_config)
202 try:
202 try:
203 Application.load_config_file(
203 Application.load_config_file(
204 self,
204 self,
205 base_config,
205 base_config,
206 path=self.config_file_paths
206 path=self.config_file_paths
207 )
207 )
208 except ConfigFileNotFound:
208 except ConfigFileNotFound:
209 # ignore errors loading parent
209 # ignore errors loading parent
210 self.log.debug("Config file %s not found", base_config)
210 self.log.debug("Config file %s not found", base_config)
211 pass
211 pass
212 if self.config_file_name == base_config:
212 if self.config_file_name == base_config:
213 # don't load secondary config
213 # don't load secondary config
214 return
214 return
215 self.log.debug("Attempting to load config file: %s" %
215 self.log.debug("Attempting to load config file: %s" %
216 self.config_file_name)
216 self.config_file_name)
217 try:
217 try:
218 Application.load_config_file(
218 Application.load_config_file(
219 self,
219 self,
220 self.config_file_name,
220 self.config_file_name,
221 path=self.config_file_paths
221 path=self.config_file_paths
222 )
222 )
223 except ConfigFileNotFound:
223 except ConfigFileNotFound:
224 # Only warn if the default config file was NOT being used.
224 # Only warn if the default config file was NOT being used.
225 if self.config_file_specified:
225 if self.config_file_specified:
226 msg = self.log.warn
226 msg = self.log.warn
227 else:
227 else:
228 msg = self.log.debug
228 msg = self.log.debug
229 msg("Config file not found, skipping: %s", self.config_file_name)
229 msg("Config file not found, skipping: %s", self.config_file_name)
230 except:
230 except:
231 # For testing purposes.
231 # For testing purposes.
232 if not suppress_errors:
232 if not suppress_errors:
233 raise
233 raise
234 self.log.warn("Error loading config file: %s" %
234 self.log.warn("Error loading config file: %s" %
235 self.config_file_name, exc_info=True)
235 self.config_file_name, exc_info=True)
236
236
237 def init_profile_dir(self):
237 def init_profile_dir(self):
238 """initialize the profile dir"""
238 """initialize the profile dir"""
239 try:
239 try:
240 # location explicitly specified:
240 # location explicitly specified:
241 location = self.config.ProfileDir.location
241 location = self.config.ProfileDir.location
242 except AttributeError:
242 except AttributeError:
243 # location not specified, find by profile name
243 # location not specified, find by profile name
244 try:
244 try:
245 p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
245 p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
246 except ProfileDirError:
246 except ProfileDirError:
247 # not found, maybe create it (always create default profile)
247 # not found, maybe create it (always create default profile)
248 if self.auto_create or self.profile=='default':
248 if self.auto_create or self.profile=='default':
249 try:
249 try:
250 p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
250 p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
251 except ProfileDirError:
251 except ProfileDirError:
252 self.log.fatal("Could not create profile: %r"%self.profile)
252 self.log.fatal("Could not create profile: %r"%self.profile)
253 self.exit(1)
253 self.exit(1)
254 else:
254 else:
255 self.log.info("Created profile dir: %r"%p.location)
255 self.log.info("Created profile dir: %r"%p.location)
256 else:
256 else:
257 self.log.fatal("Profile %r not found."%self.profile)
257 self.log.fatal("Profile %r not found."%self.profile)
258 self.exit(1)
258 self.exit(1)
259 else:
259 else:
260 self.log.info("Using existing profile dir: %r"%p.location)
260 self.log.info("Using existing profile dir: %r"%p.location)
261 else:
261 else:
262 # location is fully specified
262 # location is fully specified
263 try:
263 try:
264 p = ProfileDir.find_profile_dir(location, self.config)
264 p = ProfileDir.find_profile_dir(location, self.config)
265 except ProfileDirError:
265 except ProfileDirError:
266 # not found, maybe create it
266 # not found, maybe create it
267 if self.auto_create:
267 if self.auto_create:
268 try:
268 try:
269 p = ProfileDir.create_profile_dir(location, self.config)
269 p = ProfileDir.create_profile_dir(location, self.config)
270 except ProfileDirError:
270 except ProfileDirError:
271 self.log.fatal("Could not create profile directory: %r"%location)
271 self.log.fatal("Could not create profile directory: %r"%location)
272 self.exit(1)
272 self.exit(1)
273 else:
273 else:
274 self.log.info("Creating new profile dir: %r"%location)
274 self.log.info("Creating new profile dir: %r"%location)
275 else:
275 else:
276 self.log.fatal("Profile directory %r not found."%location)
276 self.log.fatal("Profile directory %r not found."%location)
277 self.exit(1)
277 self.exit(1)
278 else:
278 else:
279 self.log.info("Using existing profile dir: %r"%location)
279 self.log.info("Using existing profile dir: %r"%location)
280
280
281 self.profile_dir = p
281 self.profile_dir = p
282 self.config_file_paths.append(p.location)
282 self.config_file_paths.append(p.location)
283
283
284 def init_config_files(self):
284 def init_config_files(self):
285 """[optionally] copy default config files into profile dir."""
285 """[optionally] copy default config files into profile dir."""
286 # copy config files
286 # copy config files
287 path = self.builtin_profile_dir
287 path = self.builtin_profile_dir
288 if self.copy_config_files:
288 if self.copy_config_files:
289 src = self.profile
289 src = self.profile
290
290
291 cfg = self.config_file_name
291 cfg = self.config_file_name
292 if path and os.path.exists(os.path.join(path, cfg)):
292 if path and os.path.exists(os.path.join(path, cfg)):
293 self.log.warn("Staging %r from %s into %r [overwrite=%s]"%(
293 self.log.warn("Staging %r from %s into %r [overwrite=%s]"%(
294 cfg, src, self.profile_dir.location, self.overwrite)
294 cfg, src, self.profile_dir.location, self.overwrite)
295 )
295 )
296 self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
296 self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
297 else:
297 else:
298 self.stage_default_config_file()
298 self.stage_default_config_file()
299 else:
299 else:
300 # Still stage *bundled* config files, but not generated ones
300 # Still stage *bundled* config files, but not generated ones
301 # This is necessary for `ipython profile=sympy` to load the profile
301 # This is necessary for `ipython profile=sympy` to load the profile
302 # on the first go
302 # on the first go
303 files = glob.glob(os.path.join(path, '*.py'))
303 files = glob.glob(os.path.join(path, '*.py'))
304 for fullpath in files:
304 for fullpath in files:
305 cfg = os.path.basename(fullpath)
305 cfg = os.path.basename(fullpath)
306 if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
306 if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
307 # file was copied
307 # file was copied
308 self.log.warn("Staging bundled %s from %s into %r"%(
308 self.log.warn("Staging bundled %s from %s into %r"%(
309 cfg, self.profile, self.profile_dir.location)
309 cfg, self.profile, self.profile_dir.location)
310 )
310 )
311
311
312
312
313 def stage_default_config_file(self):
313 def stage_default_config_file(self):
314 """auto generate default config file, and stage it into the profile."""
314 """auto generate default config file, and stage it into the profile."""
315 s = self.generate_config_file()
315 s = self.generate_config_file()
316 fname = os.path.join(self.profile_dir.location, self.config_file_name)
316 fname = os.path.join(self.profile_dir.location, self.config_file_name)
317 if self.overwrite or not os.path.exists(fname):
317 if self.overwrite or not os.path.exists(fname):
318 self.log.warn("Generating default config file: %r"%(fname))
318 self.log.warn("Generating default config file: %r"%(fname))
319 with open(fname, 'w') as f:
319 with open(fname, 'w') as f:
320 f.write(s)
320 f.write(s)
321
321
322 @catch_config_error
322 @catch_config_error
323 def initialize(self, argv=None):
323 def initialize(self, argv=None):
324 # don't hook up crash handler before parsing command-line
324 # don't hook up crash handler before parsing command-line
325 self.parse_command_line(argv)
325 self.parse_command_line(argv)
326 self.init_crash_handler()
326 self.init_crash_handler()
327 if self.subapp is not None:
327 if self.subapp is not None:
328 # stop here if subapp is taking over
328 # stop here if subapp is taking over
329 return
329 return
330 cl_config = self.config
330 cl_config = self.config
331 self.init_profile_dir()
331 self.init_profile_dir()
332 self.init_config_files()
332 self.init_config_files()
333 self.load_config_file()
333 self.load_config_file()
334 # enforce cl-opts override configfile opts:
334 # enforce cl-opts override configfile opts:
335 self.update_config(cl_config)
335 self.update_config(cl_config)
336
336
@@ -1,293 +1,293 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 An application for managing IPython profiles.
3 An application for managing IPython profiles.
4
4
5 To be invoked as the `ipython profile` subcommand.
5 To be invoked as the `ipython profile` subcommand.
6
6
7 Authors:
7 Authors:
8
8
9 * Min RK
9 * Min RK
10
10
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2011 The IPython Development Team
14 # Copyright (C) 2008-2011 The IPython Development Team
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Imports
21 # Imports
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 import logging
24 import logging
25 import os
25 import os
26
26
27 from IPython.config.application import Application, boolean_flag
27 from IPython.config.application import Application, boolean_flag
28 from IPython.core.application import (
28 from IPython.core.application import (
29 BaseIPythonApplication, base_flags, base_aliases
29 BaseIPythonApplication, base_flags, base_aliases
30 )
30 )
31 from IPython.core.profiledir import ProfileDir
31 from IPython.core.profiledir import ProfileDir
32 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
32 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
33 from IPython.utils.traitlets import Unicode, Bool, Dict
33 from IPython.utils.traitlets import Unicode, Bool, Dict
34
34
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36 # Constants
36 # Constants
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38
38
39 create_help = """Create an IPython profile by name
39 create_help = """Create an IPython profile by name
40
40
41 Create an ipython profile directory by its name or
41 Create an ipython profile directory by its name or
42 profile directory path. Profile directories contain
42 profile directory path. Profile directories contain
43 configuration, log and security related files and are named
43 configuration, log and security related files and are named
44 using the convention 'profile_<name>'. By default they are
44 using the convention 'profile_<name>'. By default they are
45 located in your ipython directory. Once created, you will
45 located in your ipython directory. Once created, you will
46 can edit the configuration files in the profile
46 can edit the configuration files in the profile
47 directory to configure IPython. Most users will create a
47 directory to configure IPython. Most users will create a
48 profile directory by name,
48 profile directory by name,
49 `ipython profile create myprofile`, which will put the directory
49 `ipython profile create myprofile`, which will put the directory
50 in `<ipython_dir>/profile_myprofile`.
50 in `<ipython_dir>/profile_myprofile`.
51 """
51 """
52 list_help = """List available IPython profiles
52 list_help = """List available IPython profiles
53
53
54 List all available profiles, by profile location, that can
54 List all available profiles, by profile location, that can
55 be found in the current working directly or in the ipython
55 be found in the current working directly or in the ipython
56 directory. Profile directories are named using the convention
56 directory. Profile directories are named using the convention
57 'profile_<profile>'.
57 'profile_<profile>'.
58 """
58 """
59 profile_help = """Manage IPython profiles
59 profile_help = """Manage IPython profiles
60
60
61 Profile directories contain
61 Profile directories contain
62 configuration, log and security related files and are named
62 configuration, log and security related files and are named
63 using the convention 'profile_<name>'. By default they are
63 using the convention 'profile_<name>'. By default they are
64 located in your ipython directory. You can create profiles
64 located in your ipython directory. You can create profiles
65 with `ipython profile create <name>`, or see the profiles you
65 with `ipython profile create <name>`, or see the profiles you
66 already have with `ipython profile list`
66 already have with `ipython profile list`
67
67
68 To get started configuring IPython, simply do:
68 To get started configuring IPython, simply do:
69
69
70 $> ipython profile create
70 $> ipython profile create
71
71
72 and IPython will create the default profile in <ipython_dir>/profile_default,
72 and IPython will create the default profile in <ipython_dir>/profile_default,
73 where you can edit ipython_config.py to start configuring IPython.
73 where you can edit ipython_config.py to start configuring IPython.
74
74
75 """
75 """
76
76
77 _list_examples = "ipython profile list # list all profiles"
77 _list_examples = "ipython profile list # list all profiles"
78
78
79 _create_examples = """
79 _create_examples = """
80 ipython profile create foo # create profile foo w/ default config files
80 ipython profile create foo # create profile foo w/ default config files
81 ipython profile create foo --reset # restage default config files over current
81 ipython profile create foo --reset # restage default config files over current
82 ipython profile create foo --parallel # also stage parallel config files
82 ipython profile create foo --parallel # also stage parallel config files
83 """
83 """
84
84
85 _main_examples = """
85 _main_examples = """
86 ipython profile create -h # show the help string for the create subcommand
86 ipython profile create -h # show the help string for the create subcommand
87 ipython profile list -h # show the help string for the list subcommand
87 ipython profile list -h # show the help string for the list subcommand
88 """
88 """
89
89
90 #-----------------------------------------------------------------------------
90 #-----------------------------------------------------------------------------
91 # Profile Application Class (for `ipython profile` subcommand)
91 # Profile Application Class (for `ipython profile` subcommand)
92 #-----------------------------------------------------------------------------
92 #-----------------------------------------------------------------------------
93
93
94
94
95 def list_profiles_in(path):
95 def list_profiles_in(path):
96 """list profiles in a given root directory"""
96 """list profiles in a given root directory"""
97 files = os.listdir(path)
97 files = os.listdir(path)
98 profiles = []
98 profiles = []
99 for f in files:
99 for f in files:
100 full_path = os.path.join(path, f)
100 full_path = os.path.join(path, f)
101 if os.path.isdir(full_path) and f.startswith('profile_'):
101 if os.path.isdir(full_path) and f.startswith('profile_'):
102 profiles.append(f.split('_',1)[-1])
102 profiles.append(f.split('_',1)[-1])
103 return profiles
103 return profiles
104
104
105
105
106 def list_bundled_profiles():
106 def list_bundled_profiles():
107 """list profiles that are bundled with IPython."""
107 """list profiles that are bundled with IPython."""
108 path = os.path.join(get_ipython_package_dir(), u'config', u'profile')
108 path = os.path.join(get_ipython_package_dir(), u'config', u'profile')
109 files = os.listdir(path)
109 files = os.listdir(path)
110 profiles = []
110 profiles = []
111 for profile in files:
111 for profile in files:
112 full_path = os.path.join(path, profile)
112 full_path = os.path.join(path, profile)
113 if os.path.isdir(full_path) and profile != "__pycache__":
113 if os.path.isdir(full_path) and profile != "__pycache__":
114 profiles.append(profile)
114 profiles.append(profile)
115 return profiles
115 return profiles
116
116
117
117
118 class ProfileList(Application):
118 class ProfileList(Application):
119 name = u'ipython-profile'
119 name = u'ipython-profile'
120 description = list_help
120 description = list_help
121 examples = _list_examples
121 examples = _list_examples
122
122
123 aliases = Dict({
123 aliases = Dict({
124 'ipython-dir' : 'ProfileList.ipython_dir',
124 'ipython-dir' : 'ProfileList.ipython_dir',
125 'log-level' : 'Application.log_level',
125 'log-level' : 'Application.log_level',
126 })
126 })
127 flags = Dict(dict(
127 flags = Dict(dict(
128 debug = ({'Application' : {'log_level' : 0}},
128 debug = ({'Application' : {'log_level' : 0}},
129 "Set Application.log_level to 0, maximizing log output."
129 "Set Application.log_level to 0, maximizing log output."
130 )
130 )
131 ))
131 ))
132
132
133 ipython_dir = Unicode(get_ipython_dir(), config=True,
133 ipython_dir = Unicode(get_ipython_dir(), config=True,
134 help="""
134 help="""
135 The name of the IPython directory. This directory is used for logging
135 The name of the IPython directory. This directory is used for logging
136 configuration (through profiles), history storage, etc. The default
136 configuration (through profiles), history storage, etc. The default
137 is usually $HOME/.ipython. This options can also be specified through
137 is usually $HOME/.ipython. This options can also be specified through
138 the environment variable IPYTHON_DIR.
138 the environment variable IPYTHONDIR.
139 """
139 """
140 )
140 )
141
141
142
142
143 def _print_profiles(self, profiles):
143 def _print_profiles(self, profiles):
144 """print list of profiles, indented."""
144 """print list of profiles, indented."""
145 for profile in profiles:
145 for profile in profiles:
146 print ' %s' % profile
146 print ' %s' % profile
147
147
148 def list_profile_dirs(self):
148 def list_profile_dirs(self):
149 profiles = list_bundled_profiles()
149 profiles = list_bundled_profiles()
150 if profiles:
150 if profiles:
151 print
151 print
152 print "Available profiles in IPython:"
152 print "Available profiles in IPython:"
153 self._print_profiles(profiles)
153 self._print_profiles(profiles)
154 print
154 print
155 print " The first request for a bundled profile will copy it"
155 print " The first request for a bundled profile will copy it"
156 print " into your IPython directory (%s)," % self.ipython_dir
156 print " into your IPython directory (%s)," % self.ipython_dir
157 print " where you can customize it."
157 print " where you can customize it."
158
158
159 profiles = list_profiles_in(self.ipython_dir)
159 profiles = list_profiles_in(self.ipython_dir)
160 if profiles:
160 if profiles:
161 print
161 print
162 print "Available profiles in %s:" % self.ipython_dir
162 print "Available profiles in %s:" % self.ipython_dir
163 self._print_profiles(profiles)
163 self._print_profiles(profiles)
164
164
165 profiles = list_profiles_in(os.getcwdu())
165 profiles = list_profiles_in(os.getcwdu())
166 if profiles:
166 if profiles:
167 print
167 print
168 print "Available profiles in current directory (%s):" % os.getcwdu()
168 print "Available profiles in current directory (%s):" % os.getcwdu()
169 self._print_profiles(profiles)
169 self._print_profiles(profiles)
170
170
171 print
171 print
172 print "To use any of the above profiles, start IPython with:"
172 print "To use any of the above profiles, start IPython with:"
173 print " ipython --profile=<name>"
173 print " ipython --profile=<name>"
174 print
174 print
175
175
176 def start(self):
176 def start(self):
177 self.list_profile_dirs()
177 self.list_profile_dirs()
178
178
179
179
180 create_flags = {}
180 create_flags = {}
181 create_flags.update(base_flags)
181 create_flags.update(base_flags)
182 # don't include '--init' flag, which implies running profile create in other apps
182 # don't include '--init' flag, which implies running profile create in other apps
183 create_flags.pop('init')
183 create_flags.pop('init')
184 create_flags['reset'] = ({'ProfileCreate': {'overwrite' : True}},
184 create_flags['reset'] = ({'ProfileCreate': {'overwrite' : True}},
185 "reset config files in this profile to the defaults.")
185 "reset config files in this profile to the defaults.")
186 create_flags['parallel'] = ({'ProfileCreate': {'parallel' : True}},
186 create_flags['parallel'] = ({'ProfileCreate': {'parallel' : True}},
187 "Include the config files for parallel "
187 "Include the config files for parallel "
188 "computing apps (ipengine, ipcontroller, etc.)")
188 "computing apps (ipengine, ipcontroller, etc.)")
189
189
190
190
191 class ProfileCreate(BaseIPythonApplication):
191 class ProfileCreate(BaseIPythonApplication):
192 name = u'ipython-profile'
192 name = u'ipython-profile'
193 description = create_help
193 description = create_help
194 examples = _create_examples
194 examples = _create_examples
195 auto_create = Bool(True, config=False)
195 auto_create = Bool(True, config=False)
196
196
197 def _copy_config_files_default(self):
197 def _copy_config_files_default(self):
198 return True
198 return True
199
199
200 parallel = Bool(False, config=True,
200 parallel = Bool(False, config=True,
201 help="whether to include parallel computing config files")
201 help="whether to include parallel computing config files")
202 def _parallel_changed(self, name, old, new):
202 def _parallel_changed(self, name, old, new):
203 parallel_files = [ 'ipcontroller_config.py',
203 parallel_files = [ 'ipcontroller_config.py',
204 'ipengine_config.py',
204 'ipengine_config.py',
205 'ipcluster_config.py'
205 'ipcluster_config.py'
206 ]
206 ]
207 if new:
207 if new:
208 for cf in parallel_files:
208 for cf in parallel_files:
209 self.config_files.append(cf)
209 self.config_files.append(cf)
210 else:
210 else:
211 for cf in parallel_files:
211 for cf in parallel_files:
212 if cf in self.config_files:
212 if cf in self.config_files:
213 self.config_files.remove(cf)
213 self.config_files.remove(cf)
214
214
215 def parse_command_line(self, argv):
215 def parse_command_line(self, argv):
216 super(ProfileCreate, self).parse_command_line(argv)
216 super(ProfileCreate, self).parse_command_line(argv)
217 # accept positional arg as profile name
217 # accept positional arg as profile name
218 if self.extra_args:
218 if self.extra_args:
219 self.profile = self.extra_args[0]
219 self.profile = self.extra_args[0]
220
220
221 flags = Dict(create_flags)
221 flags = Dict(create_flags)
222
222
223 classes = [ProfileDir]
223 classes = [ProfileDir]
224
224
225 def init_config_files(self):
225 def init_config_files(self):
226 super(ProfileCreate, self).init_config_files()
226 super(ProfileCreate, self).init_config_files()
227 # use local imports, since these classes may import from here
227 # use local imports, since these classes may import from here
228 from IPython.frontend.terminal.ipapp import TerminalIPythonApp
228 from IPython.frontend.terminal.ipapp import TerminalIPythonApp
229 apps = [TerminalIPythonApp]
229 apps = [TerminalIPythonApp]
230 try:
230 try:
231 from IPython.frontend.qt.console.qtconsoleapp import IPythonQtConsoleApp
231 from IPython.frontend.qt.console.qtconsoleapp import IPythonQtConsoleApp
232 except Exception:
232 except Exception:
233 # this should be ImportError, but under weird circumstances
233 # this should be ImportError, but under weird circumstances
234 # this might be an AttributeError, or possibly others
234 # this might be an AttributeError, or possibly others
235 # in any case, nothing should cause the profile creation to crash.
235 # in any case, nothing should cause the profile creation to crash.
236 pass
236 pass
237 else:
237 else:
238 apps.append(IPythonQtConsoleApp)
238 apps.append(IPythonQtConsoleApp)
239 try:
239 try:
240 from IPython.frontend.html.notebook.notebookapp import NotebookApp
240 from IPython.frontend.html.notebook.notebookapp import NotebookApp
241 except ImportError:
241 except ImportError:
242 pass
242 pass
243 except Exception:
243 except Exception:
244 self.log.debug('Unexpected error when importing NotebookApp',
244 self.log.debug('Unexpected error when importing NotebookApp',
245 exc_info=True
245 exc_info=True
246 )
246 )
247 else:
247 else:
248 apps.append(NotebookApp)
248 apps.append(NotebookApp)
249 if self.parallel:
249 if self.parallel:
250 from IPython.parallel.apps.ipcontrollerapp import IPControllerApp
250 from IPython.parallel.apps.ipcontrollerapp import IPControllerApp
251 from IPython.parallel.apps.ipengineapp import IPEngineApp
251 from IPython.parallel.apps.ipengineapp import IPEngineApp
252 from IPython.parallel.apps.ipclusterapp import IPClusterStart
252 from IPython.parallel.apps.ipclusterapp import IPClusterStart
253 from IPython.parallel.apps.iploggerapp import IPLoggerApp
253 from IPython.parallel.apps.iploggerapp import IPLoggerApp
254 apps.extend([
254 apps.extend([
255 IPControllerApp,
255 IPControllerApp,
256 IPEngineApp,
256 IPEngineApp,
257 IPClusterStart,
257 IPClusterStart,
258 IPLoggerApp,
258 IPLoggerApp,
259 ])
259 ])
260 for App in apps:
260 for App in apps:
261 app = App()
261 app = App()
262 app.config.update(self.config)
262 app.config.update(self.config)
263 app.log = self.log
263 app.log = self.log
264 app.overwrite = self.overwrite
264 app.overwrite = self.overwrite
265 app.copy_config_files=True
265 app.copy_config_files=True
266 app.profile = self.profile
266 app.profile = self.profile
267 app.init_profile_dir()
267 app.init_profile_dir()
268 app.init_config_files()
268 app.init_config_files()
269
269
270 def stage_default_config_file(self):
270 def stage_default_config_file(self):
271 pass
271 pass
272
272
273
273
274 class ProfileApp(Application):
274 class ProfileApp(Application):
275 name = u'ipython-profile'
275 name = u'ipython-profile'
276 description = profile_help
276 description = profile_help
277 examples = _main_examples
277 examples = _main_examples
278
278
279 subcommands = Dict(dict(
279 subcommands = Dict(dict(
280 create = (ProfileCreate, "Create a new profile dir with default config files"),
280 create = (ProfileCreate, "Create a new profile dir with default config files"),
281 list = (ProfileList, "List existing profiles")
281 list = (ProfileList, "List existing profiles")
282 ))
282 ))
283
283
284 def start(self):
284 def start(self):
285 if self.subapp is None:
285 if self.subapp is None:
286 print "No subcommand specified. Must specify one of: %s"%(self.subcommands.keys())
286 print "No subcommand specified. Must specify one of: %s"%(self.subcommands.keys())
287 print
287 print
288 self.print_description()
288 self.print_description()
289 self.print_subcommands()
289 self.print_subcommands()
290 self.exit(1)
290 self.exit(1)
291 else:
291 else:
292 return self.subapp.start()
292 return self.subapp.start()
293
293
@@ -1,535 +1,535 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Usage information for the main IPython applications.
2 """Usage information for the main IPython applications.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008-2011 The IPython Development Team
5 # Copyright (C) 2008-2011 The IPython Development Team
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 import sys
12 import sys
13 from IPython.core import release
13 from IPython.core import release
14
14
15 cl_usage = """\
15 cl_usage = """\
16 =========
16 =========
17 IPython
17 IPython
18 =========
18 =========
19
19
20 Tools for Interactive Computing in Python
20 Tools for Interactive Computing in Python
21 =========================================
21 =========================================
22
22
23 A Python shell with automatic history (input and output), dynamic object
23 A Python shell with automatic history (input and output), dynamic object
24 introspection, easier configuration, command completion, access to the
24 introspection, easier configuration, command completion, access to the
25 system shell and more. IPython can also be embedded in running programs.
25 system shell and more. IPython can also be embedded in running programs.
26
26
27
27
28 Usage
28 Usage
29
29
30 ipython [subcommand] [options] [files]
30 ipython [subcommand] [options] [files]
31
31
32 If invoked with no options, it executes all the files listed in sequence
32 If invoked with no options, it executes all the files listed in sequence
33 and exits, use -i to enter interactive mode after running the files. Files
33 and exits, use -i to enter interactive mode after running the files. Files
34 ending in .py will be treated as normal Python, but files ending in .ipy
34 ending in .py will be treated as normal Python, but files ending in .ipy
35 can contain special IPython syntax (magic commands, shell expansions, etc.)
35 can contain special IPython syntax (magic commands, shell expansions, etc.)
36
36
37 Almost all configuration in IPython is available via the command-line. Do
37 Almost all configuration in IPython is available via the command-line. Do
38 `ipython --help-all` to see all available options. For persistent
38 `ipython --help-all` to see all available options. For persistent
39 configuration, look into your `ipython_config.py` configuration file for
39 configuration, look into your `ipython_config.py` configuration file for
40 details.
40 details.
41
41
42 This file is typically installed in the `IPYTHON_DIR` directory, and there
42 This file is typically installed in the `IPYTHONDIR` directory, and there
43 is a separate configuration directory for each profile. The default profile
43 is a separate configuration directory for each profile. The default profile
44 directory will be located in $IPYTHON_DIR/profile_default. For Linux users,
44 directory will be located in $IPYTHONDIR/profile_default. For Linux users,
45 IPYTHON_DIR defaults to `$HOME/.config/ipython`, and for other Unix systems
45 IPYTHONDIR defaults to `$HOME/.config/ipython`, and for other Unix systems
46 to `$HOME/.ipython`. For Windows users, $HOME resolves to C:\\Documents
46 to `$HOME/.ipython`. For Windows users, $HOME resolves to C:\\Documents
47 and Settings\\YourUserName in most instances.
47 and Settings\\YourUserName in most instances.
48
48
49 To initialize a profile with the default configuration file, do::
49 To initialize a profile with the default configuration file, do::
50
50
51 $> ipython profile create
51 $> ipython profile create
52
52
53 and start editing `IPYTHON_DIR/profile_default/ipython_config.py`
53 and start editing `IPYTHONDIR/profile_default/ipython_config.py`
54
54
55 In IPython's documentation, we will refer to this directory as
55 In IPython's documentation, we will refer to this directory as
56 `IPYTHON_DIR`, you can change its default location by creating an
56 `IPYTHONDIR`, you can change its default location by creating an
57 environment variable with this name and setting it to the desired path.
57 environment variable with this name and setting it to the desired path.
58
58
59 For more information, see the manual available in HTML and PDF in your
59 For more information, see the manual available in HTML and PDF in your
60 installation, or online at http://ipython.org/documentation.html.
60 installation, or online at http://ipython.org/documentation.html.
61 """
61 """
62
62
63 interactive_usage = """
63 interactive_usage = """
64 IPython -- An enhanced Interactive Python
64 IPython -- An enhanced Interactive Python
65 =========================================
65 =========================================
66
66
67 IPython offers a combination of convenient shell features, special commands
67 IPython offers a combination of convenient shell features, special commands
68 and a history mechanism for both input (command history) and output (results
68 and a history mechanism for both input (command history) and output (results
69 caching, similar to Mathematica). It is intended to be a fully compatible
69 caching, similar to Mathematica). It is intended to be a fully compatible
70 replacement for the standard Python interpreter, while offering vastly
70 replacement for the standard Python interpreter, while offering vastly
71 improved functionality and flexibility.
71 improved functionality and flexibility.
72
72
73 At your system command line, type 'ipython -h' to see the command line
73 At your system command line, type 'ipython -h' to see the command line
74 options available. This document only describes interactive features.
74 options available. This document only describes interactive features.
75
75
76 MAIN FEATURES
76 MAIN FEATURES
77
77
78 * Access to the standard Python help. As of Python 2.1, a help system is
78 * Access to the standard Python help. As of Python 2.1, a help system is
79 available with access to object docstrings and the Python manuals. Simply
79 available with access to object docstrings and the Python manuals. Simply
80 type 'help' (no quotes) to access it.
80 type 'help' (no quotes) to access it.
81
81
82 * Magic commands: type %magic for information on the magic subsystem.
82 * Magic commands: type %magic for information on the magic subsystem.
83
83
84 * System command aliases, via the %alias command or the configuration file(s).
84 * System command aliases, via the %alias command or the configuration file(s).
85
85
86 * Dynamic object information:
86 * Dynamic object information:
87
87
88 Typing ?word or word? prints detailed information about an object. If
88 Typing ?word or word? prints detailed information about an object. If
89 certain strings in the object are too long (docstrings, code, etc.) they get
89 certain strings in the object are too long (docstrings, code, etc.) they get
90 snipped in the center for brevity.
90 snipped in the center for brevity.
91
91
92 Typing ??word or word?? gives access to the full information without
92 Typing ??word or word?? gives access to the full information without
93 snipping long strings. Long strings are sent to the screen through the less
93 snipping long strings. Long strings are sent to the screen through the less
94 pager if longer than the screen, printed otherwise.
94 pager if longer than the screen, printed otherwise.
95
95
96 The ?/?? system gives access to the full source code for any object (if
96 The ?/?? system gives access to the full source code for any object (if
97 available), shows function prototypes and other useful information.
97 available), shows function prototypes and other useful information.
98
98
99 If you just want to see an object's docstring, type '%pdoc object' (without
99 If you just want to see an object's docstring, type '%pdoc object' (without
100 quotes, and without % if you have automagic on).
100 quotes, and without % if you have automagic on).
101
101
102 Both %pdoc and ?/?? give you access to documentation even on things which are
102 Both %pdoc and ?/?? give you access to documentation even on things which are
103 not explicitely defined. Try for example typing {}.get? or after import os,
103 not explicitely defined. Try for example typing {}.get? or after import os,
104 type os.path.abspath??. The magic functions %pdef, %source and %file operate
104 type os.path.abspath??. The magic functions %pdef, %source and %file operate
105 similarly.
105 similarly.
106
106
107 * Completion in the local namespace, by typing TAB at the prompt.
107 * Completion in the local namespace, by typing TAB at the prompt.
108
108
109 At any time, hitting tab will complete any available python commands or
109 At any time, hitting tab will complete any available python commands or
110 variable names, and show you a list of the possible completions if there's
110 variable names, and show you a list of the possible completions if there's
111 no unambiguous one. It will also complete filenames in the current directory.
111 no unambiguous one. It will also complete filenames in the current directory.
112
112
113 This feature requires the readline and rlcomplete modules, so it won't work
113 This feature requires the readline and rlcomplete modules, so it won't work
114 if your Python lacks readline support (such as under Windows).
114 if your Python lacks readline support (such as under Windows).
115
115
116 * Search previous command history in two ways (also requires readline):
116 * Search previous command history in two ways (also requires readline):
117
117
118 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
118 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
119 search through only the history items that match what you've typed so
119 search through only the history items that match what you've typed so
120 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
120 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
121 normal arrow keys.
121 normal arrow keys.
122
122
123 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
123 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
124 your history for lines that match what you've typed so far, completing as
124 your history for lines that match what you've typed so far, completing as
125 much as it can.
125 much as it can.
126
126
127 - %hist: search history by index (this does *not* require readline).
127 - %hist: search history by index (this does *not* require readline).
128
128
129 * Persistent command history across sessions.
129 * Persistent command history across sessions.
130
130
131 * Logging of input with the ability to save and restore a working session.
131 * Logging of input with the ability to save and restore a working session.
132
132
133 * System escape with !. Typing !ls will run 'ls' in the current directory.
133 * System escape with !. Typing !ls will run 'ls' in the current directory.
134
134
135 * The reload command does a 'deep' reload of a module: changes made to the
135 * The reload command does a 'deep' reload of a module: changes made to the
136 module since you imported will actually be available without having to exit.
136 module since you imported will actually be available without having to exit.
137
137
138 * Verbose and colored exception traceback printouts. See the magic xmode and
138 * Verbose and colored exception traceback printouts. See the magic xmode and
139 xcolor functions for details (just type %magic).
139 xcolor functions for details (just type %magic).
140
140
141 * Input caching system:
141 * Input caching system:
142
142
143 IPython offers numbered prompts (In/Out) with input and output caching. All
143 IPython offers numbered prompts (In/Out) with input and output caching. All
144 input is saved and can be retrieved as variables (besides the usual arrow
144 input is saved and can be retrieved as variables (besides the usual arrow
145 key recall).
145 key recall).
146
146
147 The following GLOBAL variables always exist (so don't overwrite them!):
147 The following GLOBAL variables always exist (so don't overwrite them!):
148 _i: stores previous input.
148 _i: stores previous input.
149 _ii: next previous.
149 _ii: next previous.
150 _iii: next-next previous.
150 _iii: next-next previous.
151 _ih : a list of all input _ih[n] is the input from line n.
151 _ih : a list of all input _ih[n] is the input from line n.
152
152
153 Additionally, global variables named _i<n> are dynamically created (<n>
153 Additionally, global variables named _i<n> are dynamically created (<n>
154 being the prompt counter), such that _i<n> == _ih[<n>]
154 being the prompt counter), such that _i<n> == _ih[<n>]
155
155
156 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
156 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
157
157
158 You can create macros which contain multiple input lines from this history,
158 You can create macros which contain multiple input lines from this history,
159 for later re-execution, with the %macro function.
159 for later re-execution, with the %macro function.
160
160
161 The history function %hist allows you to see any part of your input history
161 The history function %hist allows you to see any part of your input history
162 by printing a range of the _i variables. Note that inputs which contain
162 by printing a range of the _i variables. Note that inputs which contain
163 magic functions (%) appear in the history with a prepended comment. This is
163 magic functions (%) appear in the history with a prepended comment. This is
164 because they aren't really valid Python code, so you can't exec them.
164 because they aren't really valid Python code, so you can't exec them.
165
165
166 * Output caching system:
166 * Output caching system:
167
167
168 For output that is returned from actions, a system similar to the input
168 For output that is returned from actions, a system similar to the input
169 cache exists but using _ instead of _i. Only actions that produce a result
169 cache exists but using _ instead of _i. Only actions that produce a result
170 (NOT assignments, for example) are cached. If you are familiar with
170 (NOT assignments, for example) are cached. If you are familiar with
171 Mathematica, IPython's _ variables behave exactly like Mathematica's %
171 Mathematica, IPython's _ variables behave exactly like Mathematica's %
172 variables.
172 variables.
173
173
174 The following GLOBAL variables always exist (so don't overwrite them!):
174 The following GLOBAL variables always exist (so don't overwrite them!):
175 _ (one underscore): previous output.
175 _ (one underscore): previous output.
176 __ (two underscores): next previous.
176 __ (two underscores): next previous.
177 ___ (three underscores): next-next previous.
177 ___ (three underscores): next-next previous.
178
178
179 Global variables named _<n> are dynamically created (<n> being the prompt
179 Global variables named _<n> are dynamically created (<n> being the prompt
180 counter), such that the result of output <n> is always available as _<n>.
180 counter), such that the result of output <n> is always available as _<n>.
181
181
182 Finally, a global dictionary named _oh exists with entries for all lines
182 Finally, a global dictionary named _oh exists with entries for all lines
183 which generated output.
183 which generated output.
184
184
185 * Directory history:
185 * Directory history:
186
186
187 Your history of visited directories is kept in the global list _dh, and the
187 Your history of visited directories is kept in the global list _dh, and the
188 magic %cd command can be used to go to any entry in that list.
188 magic %cd command can be used to go to any entry in that list.
189
189
190 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
190 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
191
191
192 1. Auto-parentheses
192 1. Auto-parentheses
193 Callable objects (i.e. functions, methods, etc) can be invoked like
193 Callable objects (i.e. functions, methods, etc) can be invoked like
194 this (notice the commas between the arguments):
194 this (notice the commas between the arguments):
195 In [1]: callable_ob arg1, arg2, arg3
195 In [1]: callable_ob arg1, arg2, arg3
196 and the input will be translated to this:
196 and the input will be translated to this:
197 ------> callable_ob(arg1, arg2, arg3)
197 ------> callable_ob(arg1, arg2, arg3)
198 This feature is off by default (in rare cases it can produce
198 This feature is off by default (in rare cases it can produce
199 undesirable side-effects), but you can activate it at the command-line
199 undesirable side-effects), but you can activate it at the command-line
200 by starting IPython with `--autocall 1`, set it permanently in your
200 by starting IPython with `--autocall 1`, set it permanently in your
201 configuration file, or turn on at runtime with `%autocall 1`.
201 configuration file, or turn on at runtime with `%autocall 1`.
202
202
203 You can force auto-parentheses by using '/' as the first character
203 You can force auto-parentheses by using '/' as the first character
204 of a line. For example:
204 of a line. For example:
205 In [1]: /globals # becomes 'globals()'
205 In [1]: /globals # becomes 'globals()'
206 Note that the '/' MUST be the first character on the line! This
206 Note that the '/' MUST be the first character on the line! This
207 won't work:
207 won't work:
208 In [2]: print /globals # syntax error
208 In [2]: print /globals # syntax error
209
209
210 In most cases the automatic algorithm should work, so you should
210 In most cases the automatic algorithm should work, so you should
211 rarely need to explicitly invoke /. One notable exception is if you
211 rarely need to explicitly invoke /. One notable exception is if you
212 are trying to call a function with a list of tuples as arguments (the
212 are trying to call a function with a list of tuples as arguments (the
213 parenthesis will confuse IPython):
213 parenthesis will confuse IPython):
214 In [1]: zip (1,2,3),(4,5,6) # won't work
214 In [1]: zip (1,2,3),(4,5,6) # won't work
215 but this will work:
215 but this will work:
216 In [2]: /zip (1,2,3),(4,5,6)
216 In [2]: /zip (1,2,3),(4,5,6)
217 ------> zip ((1,2,3),(4,5,6))
217 ------> zip ((1,2,3),(4,5,6))
218 Out[2]= [(1, 4), (2, 5), (3, 6)]
218 Out[2]= [(1, 4), (2, 5), (3, 6)]
219
219
220 IPython tells you that it has altered your command line by
220 IPython tells you that it has altered your command line by
221 displaying the new command line preceded by -->. e.g.:
221 displaying the new command line preceded by -->. e.g.:
222 In [18]: callable list
222 In [18]: callable list
223 -------> callable (list)
223 -------> callable (list)
224
224
225 2. Auto-Quoting
225 2. Auto-Quoting
226 You can force auto-quoting of a function's arguments by using ',' as
226 You can force auto-quoting of a function's arguments by using ',' as
227 the first character of a line. For example:
227 the first character of a line. For example:
228 In [1]: ,my_function /home/me # becomes my_function("/home/me")
228 In [1]: ,my_function /home/me # becomes my_function("/home/me")
229
229
230 If you use ';' instead, the whole argument is quoted as a single
230 If you use ';' instead, the whole argument is quoted as a single
231 string (while ',' splits on whitespace):
231 string (while ',' splits on whitespace):
232 In [2]: ,my_function a b c # becomes my_function("a","b","c")
232 In [2]: ,my_function a b c # becomes my_function("a","b","c")
233 In [3]: ;my_function a b c # becomes my_function("a b c")
233 In [3]: ;my_function a b c # becomes my_function("a b c")
234
234
235 Note that the ',' MUST be the first character on the line! This
235 Note that the ',' MUST be the first character on the line! This
236 won't work:
236 won't work:
237 In [4]: x = ,my_function /home/me # syntax error
237 In [4]: x = ,my_function /home/me # syntax error
238 """
238 """
239
239
240 interactive_usage_min = """\
240 interactive_usage_min = """\
241 An enhanced console for Python.
241 An enhanced console for Python.
242 Some of its features are:
242 Some of its features are:
243 - Readline support if the readline library is present.
243 - Readline support if the readline library is present.
244 - Tab completion in the local namespace.
244 - Tab completion in the local namespace.
245 - Logging of input, see command-line options.
245 - Logging of input, see command-line options.
246 - System shell escape via ! , eg !ls.
246 - System shell escape via ! , eg !ls.
247 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
247 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
248 - Keeps track of locally defined variables via %who, %whos.
248 - Keeps track of locally defined variables via %who, %whos.
249 - Show object information with a ? eg ?x or x? (use ?? for more info).
249 - Show object information with a ? eg ?x or x? (use ?? for more info).
250 """
250 """
251
251
252 quick_reference = r"""
252 quick_reference = r"""
253 IPython -- An enhanced Interactive Python - Quick Reference Card
253 IPython -- An enhanced Interactive Python - Quick Reference Card
254 ================================================================
254 ================================================================
255
255
256 obj?, obj?? : Get help, or more help for object (also works as
256 obj?, obj?? : Get help, or more help for object (also works as
257 ?obj, ??obj).
257 ?obj, ??obj).
258 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
258 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
259 %magic : Information about IPython's 'magic' % functions.
259 %magic : Information about IPython's 'magic' % functions.
260
260
261 Magic functions are prefixed by %, and typically take their arguments without
261 Magic functions are prefixed by %, and typically take their arguments without
262 parentheses, quotes or even commas for convenience.
262 parentheses, quotes or even commas for convenience.
263
263
264 Example magic function calls:
264 Example magic function calls:
265
265
266 %alias d ls -F : 'd' is now an alias for 'ls -F'
266 %alias d ls -F : 'd' is now an alias for 'ls -F'
267 alias d ls -F : Works if 'alias' not a python name
267 alias d ls -F : Works if 'alias' not a python name
268 alist = %alias : Get list of aliases to 'alist'
268 alist = %alias : Get list of aliases to 'alist'
269 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
269 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
270 %cd?? : See help AND source for magic %cd
270 %cd?? : See help AND source for magic %cd
271
271
272 System commands:
272 System commands:
273
273
274 !cp a.txt b/ : System command escape, calls os.system()
274 !cp a.txt b/ : System command escape, calls os.system()
275 cp a.txt b/ : after %rehashx, most system commands work without !
275 cp a.txt b/ : after %rehashx, most system commands work without !
276 cp ${f}.txt $bar : Variable expansion in magics and system commands
276 cp ${f}.txt $bar : Variable expansion in magics and system commands
277 files = !ls /usr : Capture sytem command output
277 files = !ls /usr : Capture sytem command output
278 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
278 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
279
279
280 History:
280 History:
281
281
282 _i, _ii, _iii : Previous, next previous, next next previous input
282 _i, _ii, _iii : Previous, next previous, next next previous input
283 _i4, _ih[2:5] : Input history line 4, lines 2-4
283 _i4, _ih[2:5] : Input history line 4, lines 2-4
284 exec _i81 : Execute input history line #81 again
284 exec _i81 : Execute input history line #81 again
285 %rep 81 : Edit input history line #81
285 %rep 81 : Edit input history line #81
286 _, __, ___ : previous, next previous, next next previous output
286 _, __, ___ : previous, next previous, next next previous output
287 _dh : Directory history
287 _dh : Directory history
288 _oh : Output history
288 _oh : Output history
289 %hist : Command history. '%hist -g foo' search history for 'foo'
289 %hist : Command history. '%hist -g foo' search history for 'foo'
290
290
291 Autocall:
291 Autocall:
292
292
293 f 1,2 : f(1,2) # Off by default, enable with %autocall magic.
293 f 1,2 : f(1,2) # Off by default, enable with %autocall magic.
294 /f 1,2 : f(1,2) (forced autoparen)
294 /f 1,2 : f(1,2) (forced autoparen)
295 ,f 1 2 : f("1","2")
295 ,f 1 2 : f("1","2")
296 ;f 1 2 : f("1 2")
296 ;f 1 2 : f("1 2")
297
297
298 Remember: TAB completion works in many contexts, not just file names
298 Remember: TAB completion works in many contexts, not just file names
299 or python names.
299 or python names.
300
300
301 The following magic functions are currently available:
301 The following magic functions are currently available:
302
302
303 """
303 """
304
304
305 gui_reference = """\
305 gui_reference = """\
306 ===============================
306 ===============================
307 The graphical IPython console
307 The graphical IPython console
308 ===============================
308 ===============================
309
309
310 This console is designed to emulate the look, feel and workflow of a terminal
310 This console is designed to emulate the look, feel and workflow of a terminal
311 environment, while adding a number of enhancements that are simply not possible
311 environment, while adding a number of enhancements that are simply not possible
312 in a real terminal, such as inline syntax highlighting, true multiline editing,
312 in a real terminal, such as inline syntax highlighting, true multiline editing,
313 inline graphics and much more.
313 inline graphics and much more.
314
314
315 This quick reference document contains the basic information you'll need to
315 This quick reference document contains the basic information you'll need to
316 know to make the most efficient use of it. For the various command line
316 know to make the most efficient use of it. For the various command line
317 options available at startup, type ``ipython qtconsole --help`` at the command line.
317 options available at startup, type ``ipython qtconsole --help`` at the command line.
318
318
319
319
320 Multiline editing
320 Multiline editing
321 =================
321 =================
322
322
323 The graphical console is capable of true multiline editing, but it also tries
323 The graphical console is capable of true multiline editing, but it also tries
324 to behave intuitively like a terminal when possible. If you are used to
324 to behave intuitively like a terminal when possible. If you are used to
325 IPython's old terminal behavior, you should find the transition painless, and
325 IPython's old terminal behavior, you should find the transition painless, and
326 once you learn a few basic keybindings it will be a much more efficient
326 once you learn a few basic keybindings it will be a much more efficient
327 environment.
327 environment.
328
328
329 For single expressions or indented blocks, the console behaves almost like the
329 For single expressions or indented blocks, the console behaves almost like the
330 terminal IPython: single expressions are immediately evaluated, and indented
330 terminal IPython: single expressions are immediately evaluated, and indented
331 blocks are evaluated once a single blank line is entered::
331 blocks are evaluated once a single blank line is entered::
332
332
333 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
333 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
334 Hello IPython!
334 Hello IPython!
335
335
336 In [2]: for i in range(10):
336 In [2]: for i in range(10):
337 ...: print i,
337 ...: print i,
338 ...:
338 ...:
339 0 1 2 3 4 5 6 7 8 9
339 0 1 2 3 4 5 6 7 8 9
340
340
341 If you want to enter more than one expression in a single input block
341 If you want to enter more than one expression in a single input block
342 (something not possible in the terminal), you can use ``Control-Enter`` at the
342 (something not possible in the terminal), you can use ``Control-Enter`` at the
343 end of your first line instead of ``Enter``. At that point the console goes
343 end of your first line instead of ``Enter``. At that point the console goes
344 into 'cell mode' and even if your inputs are not indented, it will continue
344 into 'cell mode' and even if your inputs are not indented, it will continue
345 accepting arbitrarily many lines until either you enter an extra blank line or
345 accepting arbitrarily many lines until either you enter an extra blank line or
346 you hit ``Shift-Enter`` (the key binding that forces execution). When a
346 you hit ``Shift-Enter`` (the key binding that forces execution). When a
347 multiline cell is entered, IPython analyzes it and executes its code producing
347 multiline cell is entered, IPython analyzes it and executes its code producing
348 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
348 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
349 cell is executed as if it was a script. An example should clarify this::
349 cell is executed as if it was a script. An example should clarify this::
350
350
351 In [3]: x=1 # Hit C-Enter here
351 In [3]: x=1 # Hit C-Enter here
352 ...: y=2 # from now on, regular Enter is sufficient
352 ...: y=2 # from now on, regular Enter is sufficient
353 ...: z=3
353 ...: z=3
354 ...: x**2 # This does *not* produce an Out[] value
354 ...: x**2 # This does *not* produce an Out[] value
355 ...: x+y+z # Only the last expression does
355 ...: x+y+z # Only the last expression does
356 ...:
356 ...:
357 Out[3]: 6
357 Out[3]: 6
358
358
359 The behavior where an extra blank line forces execution is only active if you
359 The behavior where an extra blank line forces execution is only active if you
360 are actually typing at the keyboard each line, and is meant to make it mimic
360 are actually typing at the keyboard each line, and is meant to make it mimic
361 the IPython terminal behavior. If you paste a long chunk of input (for example
361 the IPython terminal behavior. If you paste a long chunk of input (for example
362 a long script copied form an editor or web browser), it can contain arbitrarily
362 a long script copied form an editor or web browser), it can contain arbitrarily
363 many intermediate blank lines and they won't cause any problems. As always,
363 many intermediate blank lines and they won't cause any problems. As always,
364 you can then make it execute by appending a blank line *at the end* or hitting
364 you can then make it execute by appending a blank line *at the end* or hitting
365 ``Shift-Enter`` anywhere within the cell.
365 ``Shift-Enter`` anywhere within the cell.
366
366
367 With the up arrow key, you can retrieve previous blocks of input that contain
367 With the up arrow key, you can retrieve previous blocks of input that contain
368 multiple lines. You can move inside of a multiline cell like you would in any
368 multiple lines. You can move inside of a multiline cell like you would in any
369 text editor. When you want it executed, the simplest thing to do is to hit the
369 text editor. When you want it executed, the simplest thing to do is to hit the
370 force execution key, ``Shift-Enter`` (though you can also navigate to the end
370 force execution key, ``Shift-Enter`` (though you can also navigate to the end
371 and append a blank line by using ``Enter`` twice).
371 and append a blank line by using ``Enter`` twice).
372
372
373 If you've edited a multiline cell and accidentally navigate out of it with the
373 If you've edited a multiline cell and accidentally navigate out of it with the
374 up or down arrow keys, IPython will clear the cell and replace it with the
374 up or down arrow keys, IPython will clear the cell and replace it with the
375 contents of the one above or below that you navigated to. If this was an
375 contents of the one above or below that you navigated to. If this was an
376 accident and you want to retrieve the cell you were editing, use the Undo
376 accident and you want to retrieve the cell you were editing, use the Undo
377 keybinding, ``Control-z``.
377 keybinding, ``Control-z``.
378
378
379
379
380 Key bindings
380 Key bindings
381 ============
381 ============
382
382
383 The IPython console supports most of the basic Emacs line-oriented keybindings,
383 The IPython console supports most of the basic Emacs line-oriented keybindings,
384 in addition to some of its own.
384 in addition to some of its own.
385
385
386 The keybinding prefixes mean:
386 The keybinding prefixes mean:
387
387
388 - ``C``: Control
388 - ``C``: Control
389 - ``S``: Shift
389 - ``S``: Shift
390 - ``M``: Meta (typically the Alt key)
390 - ``M``: Meta (typically the Alt key)
391
391
392 The keybindings themselves are:
392 The keybindings themselves are:
393
393
394 - ``Enter``: insert new line (may cause execution, see above).
394 - ``Enter``: insert new line (may cause execution, see above).
395 - ``C-Enter``: *force* new line, *never* causes execution.
395 - ``C-Enter``: *force* new line, *never* causes execution.
396 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
396 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
397 - ``Up``: step backwards through the history.
397 - ``Up``: step backwards through the history.
398 - ``Down``: step forwards through the history.
398 - ``Down``: step forwards through the history.
399 - ``S-Up``: search backwards through the history (like ``C-r`` in bash).
399 - ``S-Up``: search backwards through the history (like ``C-r`` in bash).
400 - ``S-Down``: search forwards through the history.
400 - ``S-Down``: search forwards through the history.
401 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
401 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
402 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
402 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
403 - ``C-v``: paste text from clipboard.
403 - ``C-v``: paste text from clipboard.
404 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
404 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
405 - ``C-S-z``: redo.
405 - ``C-S-z``: redo.
406 - ``C-o``: move to 'other' area, between pager and terminal.
406 - ``C-o``: move to 'other' area, between pager and terminal.
407 - ``C-l``: clear terminal.
407 - ``C-l``: clear terminal.
408 - ``C-a``: go to beginning of line.
408 - ``C-a``: go to beginning of line.
409 - ``C-e``: go to end of line.
409 - ``C-e``: go to end of line.
410 - ``C-u``: kill from cursor to the begining of the line.
410 - ``C-u``: kill from cursor to the begining of the line.
411 - ``C-k``: kill from cursor to the end of the line.
411 - ``C-k``: kill from cursor to the end of the line.
412 - ``C-y``: yank (paste)
412 - ``C-y``: yank (paste)
413 - ``C-p``: previous line (like up arrow)
413 - ``C-p``: previous line (like up arrow)
414 - ``C-n``: next line (like down arrow)
414 - ``C-n``: next line (like down arrow)
415 - ``C-f``: forward (like right arrow)
415 - ``C-f``: forward (like right arrow)
416 - ``C-b``: back (like left arrow)
416 - ``C-b``: back (like left arrow)
417 - ``C-d``: delete next character, or exits if input is empty
417 - ``C-d``: delete next character, or exits if input is empty
418 - ``M-<``: move to the beginning of the input region.
418 - ``M-<``: move to the beginning of the input region.
419 - ``M->``: move to the end of the input region.
419 - ``M->``: move to the end of the input region.
420 - ``M-d``: delete next word.
420 - ``M-d``: delete next word.
421 - ``M-Backspace``: delete previous word.
421 - ``M-Backspace``: delete previous word.
422 - ``C-.``: force a kernel restart (a confirmation dialog appears).
422 - ``C-.``: force a kernel restart (a confirmation dialog appears).
423 - ``C-+``: increase font size.
423 - ``C-+``: increase font size.
424 - ``C--``: decrease font size.
424 - ``C--``: decrease font size.
425 - ``C-M-Space``: toggle full screen. (Command-Control-Space on Mac OS X)
425 - ``C-M-Space``: toggle full screen. (Command-Control-Space on Mac OS X)
426
426
427 The IPython pager
427 The IPython pager
428 =================
428 =================
429
429
430 IPython will show long blocks of text from many sources using a builtin pager.
430 IPython will show long blocks of text from many sources using a builtin pager.
431 You can control where this pager appears with the ``--paging`` command-line
431 You can control where this pager appears with the ``--paging`` command-line
432 flag:
432 flag:
433
433
434 - ``inside`` [default]: the pager is overlaid on top of the main terminal. You
434 - ``inside`` [default]: the pager is overlaid on top of the main terminal. You
435 must quit the pager to get back to the terminal (similar to how a pager such
435 must quit the pager to get back to the terminal (similar to how a pager such
436 as ``less`` or ``more`` works).
436 as ``less`` or ``more`` works).
437
437
438 - ``vsplit``: the console is made double-tall, and the pager appears on the
438 - ``vsplit``: the console is made double-tall, and the pager appears on the
439 bottom area when needed. You can view its contents while using the terminal.
439 bottom area when needed. You can view its contents while using the terminal.
440
440
441 - ``hsplit``: the console is made double-wide, and the pager appears on the
441 - ``hsplit``: the console is made double-wide, and the pager appears on the
442 right area when needed. You can view its contents while using the terminal.
442 right area when needed. You can view its contents while using the terminal.
443
443
444 - ``none``: the console never pages output.
444 - ``none``: the console never pages output.
445
445
446 If you use the vertical or horizontal paging modes, you can navigate between
446 If you use the vertical or horizontal paging modes, you can navigate between
447 terminal and pager as follows:
447 terminal and pager as follows:
448
448
449 - Tab key: goes from pager to terminal (but not the other way around).
449 - Tab key: goes from pager to terminal (but not the other way around).
450 - Control-o: goes from one to another always.
450 - Control-o: goes from one to another always.
451 - Mouse: click on either.
451 - Mouse: click on either.
452
452
453 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
453 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
454 focus on the pager area).
454 focus on the pager area).
455
455
456 Running subprocesses
456 Running subprocesses
457 ====================
457 ====================
458
458
459 The graphical IPython console uses the ``pexpect`` module to run subprocesses
459 The graphical IPython console uses the ``pexpect`` module to run subprocesses
460 when you type ``!command``. This has a number of advantages (true asynchronous
460 when you type ``!command``. This has a number of advantages (true asynchronous
461 output from subprocesses as well as very robust termination of rogue
461 output from subprocesses as well as very robust termination of rogue
462 subprocesses with ``Control-C``), as well as some limitations. The main
462 subprocesses with ``Control-C``), as well as some limitations. The main
463 limitation is that you can *not* interact back with the subprocess, so anything
463 limitation is that you can *not* interact back with the subprocess, so anything
464 that invokes a pager or expects you to type input into it will block and hang
464 that invokes a pager or expects you to type input into it will block and hang
465 (you can kill it with ``Control-C``).
465 (you can kill it with ``Control-C``).
466
466
467 We have provided as magics ``%less`` to page files (aliased to ``%more``),
467 We have provided as magics ``%less`` to page files (aliased to ``%more``),
468 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
468 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
469 most common commands you'd want to call in your subshell and that would cause
469 most common commands you'd want to call in your subshell and that would cause
470 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
470 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
471
471
472 Display
472 Display
473 =======
473 =======
474
474
475 The IPython console can now display objects in a variety of formats, including
475 The IPython console can now display objects in a variety of formats, including
476 HTML, PNG and SVG. This is accomplished using the display functions in
476 HTML, PNG and SVG. This is accomplished using the display functions in
477 ``IPython.core.display``::
477 ``IPython.core.display``::
478
478
479 In [4]: from IPython.core.display import display, display_html
479 In [4]: from IPython.core.display import display, display_html
480
480
481 In [5]: from IPython.core.display import display_png, display_svg
481 In [5]: from IPython.core.display import display_png, display_svg
482
482
483 Python objects can simply be passed to these functions and the appropriate
483 Python objects can simply be passed to these functions and the appropriate
484 representations will be displayed in the console as long as the objects know
484 representations will be displayed in the console as long as the objects know
485 how to compute those representations. The easiest way of teaching objects how
485 how to compute those representations. The easiest way of teaching objects how
486 to format themselves in various representations is to define special methods
486 to format themselves in various representations is to define special methods
487 such as: ``_repr_html_``, ``_repr_svg_`` and ``_repr_png_``. IPython's display formatters
487 such as: ``_repr_html_``, ``_repr_svg_`` and ``_repr_png_``. IPython's display formatters
488 can also be given custom formatter functions for various types::
488 can also be given custom formatter functions for various types::
489
489
490 In [6]: ip = get_ipython()
490 In [6]: ip = get_ipython()
491
491
492 In [7]: html_formatter = ip.display_formatter.formatters['text/html']
492 In [7]: html_formatter = ip.display_formatter.formatters['text/html']
493
493
494 In [8]: html_formatter.for_type(Foo, foo_to_html)
494 In [8]: html_formatter.for_type(Foo, foo_to_html)
495
495
496 For further details, see ``IPython.core.formatters``.
496 For further details, see ``IPython.core.formatters``.
497
497
498 Inline matplotlib graphics
498 Inline matplotlib graphics
499 ==========================
499 ==========================
500
500
501 The IPython console is capable of displaying matplotlib figures inline, in SVG
501 The IPython console is capable of displaying matplotlib figures inline, in SVG
502 or PNG format. If started with the ``pylab=inline``, then all figures are
502 or PNG format. If started with the ``pylab=inline``, then all figures are
503 rendered inline automatically (PNG by default). If started with ``--pylab``
503 rendered inline automatically (PNG by default). If started with ``--pylab``
504 or ``pylab=<your backend>``, then a GUI backend will be used, but IPython's
504 or ``pylab=<your backend>``, then a GUI backend will be used, but IPython's
505 ``display()`` and ``getfigs()`` functions can be used to view plots inline::
505 ``display()`` and ``getfigs()`` functions can be used to view plots inline::
506
506
507 In [9]: display(*getfigs()) # display all figures inline
507 In [9]: display(*getfigs()) # display all figures inline
508
508
509 In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline
509 In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline
510 """
510 """
511
511
512
512
513 quick_guide = """\
513 quick_guide = """\
514 ? -> Introduction and overview of IPython's features.
514 ? -> Introduction and overview of IPython's features.
515 %quickref -> Quick reference.
515 %quickref -> Quick reference.
516 help -> Python's own help system.
516 help -> Python's own help system.
517 object? -> Details about 'object', use 'object??' for extra details.
517 object? -> Details about 'object', use 'object??' for extra details.
518 """
518 """
519
519
520 gui_note = """\
520 gui_note = """\
521 %guiref -> A brief reference about the graphical user interface.
521 %guiref -> A brief reference about the graphical user interface.
522 """
522 """
523
523
524 default_banner_parts = [
524 default_banner_parts = [
525 'Python %s\n' % (sys.version.split('\n')[0],),
525 'Python %s\n' % (sys.version.split('\n')[0],),
526 'Type "copyright", "credits" or "license" for more information.\n\n',
526 'Type "copyright", "credits" or "license" for more information.\n\n',
527 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
527 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
528 quick_guide
528 quick_guide
529 ]
529 ]
530
530
531 default_gui_banner_parts = default_banner_parts + [gui_note]
531 default_gui_banner_parts = default_banner_parts + [gui_note]
532
532
533 default_banner = ''.join(default_banner_parts)
533 default_banner = ''.join(default_banner_parts)
534
534
535 default_gui_banner = ''.join(default_gui_banner_parts)
535 default_gui_banner = ''.join(default_gui_banner_parts)
@@ -1,464 +1,464 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for path handling.
3 Utilities for path handling.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import os
17 import os
18 import sys
18 import sys
19 import tempfile
19 import tempfile
20 import warnings
20 import warnings
21 from hashlib import md5
21 from hashlib import md5
22
22
23 import IPython
23 import IPython
24 from IPython.utils.process import system
24 from IPython.utils.process import system
25 from IPython.utils.importstring import import_item
25 from IPython.utils.importstring import import_item
26 from IPython.utils import py3compat
26 from IPython.utils import py3compat
27
27
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 # Code
29 # Code
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31
31
32 fs_encoding = sys.getfilesystemencoding()
32 fs_encoding = sys.getfilesystemencoding()
33
33
34 def _get_long_path_name(path):
34 def _get_long_path_name(path):
35 """Dummy no-op."""
35 """Dummy no-op."""
36 return path
36 return path
37
37
38 def _writable_dir(path):
38 def _writable_dir(path):
39 """Whether `path` is a directory, to which the user has write access."""
39 """Whether `path` is a directory, to which the user has write access."""
40 return os.path.isdir(path) and os.access(path, os.W_OK)
40 return os.path.isdir(path) and os.access(path, os.W_OK)
41
41
42 if sys.platform == 'win32':
42 if sys.platform == 'win32':
43 def _get_long_path_name(path):
43 def _get_long_path_name(path):
44 """Get a long path name (expand ~) on Windows using ctypes.
44 """Get a long path name (expand ~) on Windows using ctypes.
45
45
46 Examples
46 Examples
47 --------
47 --------
48
48
49 >>> get_long_path_name('c:\\docume~1')
49 >>> get_long_path_name('c:\\docume~1')
50 u'c:\\\\Documents and Settings'
50 u'c:\\\\Documents and Settings'
51
51
52 """
52 """
53 try:
53 try:
54 import ctypes
54 import ctypes
55 except ImportError:
55 except ImportError:
56 raise ImportError('you need to have ctypes installed for this to work')
56 raise ImportError('you need to have ctypes installed for this to work')
57 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
57 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
58 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
58 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
59 ctypes.c_uint ]
59 ctypes.c_uint ]
60
60
61 buf = ctypes.create_unicode_buffer(260)
61 buf = ctypes.create_unicode_buffer(260)
62 rv = _GetLongPathName(path, buf, 260)
62 rv = _GetLongPathName(path, buf, 260)
63 if rv == 0 or rv > 260:
63 if rv == 0 or rv > 260:
64 return path
64 return path
65 else:
65 else:
66 return buf.value
66 return buf.value
67
67
68
68
69 def get_long_path_name(path):
69 def get_long_path_name(path):
70 """Expand a path into its long form.
70 """Expand a path into its long form.
71
71
72 On Windows this expands any ~ in the paths. On other platforms, it is
72 On Windows this expands any ~ in the paths. On other platforms, it is
73 a null operation.
73 a null operation.
74 """
74 """
75 return _get_long_path_name(path)
75 return _get_long_path_name(path)
76
76
77
77
78 def unquote_filename(name, win32=(sys.platform=='win32')):
78 def unquote_filename(name, win32=(sys.platform=='win32')):
79 """ On Windows, remove leading and trailing quotes from filenames.
79 """ On Windows, remove leading and trailing quotes from filenames.
80 """
80 """
81 if win32:
81 if win32:
82 if name.startswith(("'", '"')) and name.endswith(("'", '"')):
82 if name.startswith(("'", '"')) and name.endswith(("'", '"')):
83 name = name[1:-1]
83 name = name[1:-1]
84 return name
84 return name
85
85
86
86
87 def get_py_filename(name, force_win32=None):
87 def get_py_filename(name, force_win32=None):
88 """Return a valid python filename in the current directory.
88 """Return a valid python filename in the current directory.
89
89
90 If the given name is not a file, it adds '.py' and searches again.
90 If the given name is not a file, it adds '.py' and searches again.
91 Raises IOError with an informative message if the file isn't found.
91 Raises IOError with an informative message if the file isn't found.
92
92
93 On Windows, apply Windows semantics to the filename. In particular, remove
93 On Windows, apply Windows semantics to the filename. In particular, remove
94 any quoting that has been applied to it. This option can be forced for
94 any quoting that has been applied to it. This option can be forced for
95 testing purposes.
95 testing purposes.
96 """
96 """
97
97
98 name = os.path.expanduser(name)
98 name = os.path.expanduser(name)
99 if force_win32 is None:
99 if force_win32 is None:
100 win32 = (sys.platform == 'win32')
100 win32 = (sys.platform == 'win32')
101 else:
101 else:
102 win32 = force_win32
102 win32 = force_win32
103 name = unquote_filename(name, win32=win32)
103 name = unquote_filename(name, win32=win32)
104 if not os.path.isfile(name) and not name.endswith('.py'):
104 if not os.path.isfile(name) and not name.endswith('.py'):
105 name += '.py'
105 name += '.py'
106 if os.path.isfile(name):
106 if os.path.isfile(name):
107 return name
107 return name
108 else:
108 else:
109 raise IOError,'File `%r` not found.' % name
109 raise IOError,'File `%r` not found.' % name
110
110
111
111
112 def filefind(filename, path_dirs=None):
112 def filefind(filename, path_dirs=None):
113 """Find a file by looking through a sequence of paths.
113 """Find a file by looking through a sequence of paths.
114
114
115 This iterates through a sequence of paths looking for a file and returns
115 This iterates through a sequence of paths looking for a file and returns
116 the full, absolute path of the first occurence of the file. If no set of
116 the full, absolute path of the first occurence of the file. If no set of
117 path dirs is given, the filename is tested as is, after running through
117 path dirs is given, the filename is tested as is, after running through
118 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
118 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
119
119
120 filefind('myfile.txt')
120 filefind('myfile.txt')
121
121
122 will find the file in the current working dir, but::
122 will find the file in the current working dir, but::
123
123
124 filefind('~/myfile.txt')
124 filefind('~/myfile.txt')
125
125
126 Will find the file in the users home directory. This function does not
126 Will find the file in the users home directory. This function does not
127 automatically try any paths, such as the cwd or the user's home directory.
127 automatically try any paths, such as the cwd or the user's home directory.
128
128
129 Parameters
129 Parameters
130 ----------
130 ----------
131 filename : str
131 filename : str
132 The filename to look for.
132 The filename to look for.
133 path_dirs : str, None or sequence of str
133 path_dirs : str, None or sequence of str
134 The sequence of paths to look for the file in. If None, the filename
134 The sequence of paths to look for the file in. If None, the filename
135 need to be absolute or be in the cwd. If a string, the string is
135 need to be absolute or be in the cwd. If a string, the string is
136 put into a sequence and the searched. If a sequence, walk through
136 put into a sequence and the searched. If a sequence, walk through
137 each element and join with ``filename``, calling :func:`expandvars`
137 each element and join with ``filename``, calling :func:`expandvars`
138 and :func:`expanduser` before testing for existence.
138 and :func:`expanduser` before testing for existence.
139
139
140 Returns
140 Returns
141 -------
141 -------
142 Raises :exc:`IOError` or returns absolute path to file.
142 Raises :exc:`IOError` or returns absolute path to file.
143 """
143 """
144
144
145 # If paths are quoted, abspath gets confused, strip them...
145 # If paths are quoted, abspath gets confused, strip them...
146 filename = filename.strip('"').strip("'")
146 filename = filename.strip('"').strip("'")
147 # If the input is an absolute path, just check it exists
147 # If the input is an absolute path, just check it exists
148 if os.path.isabs(filename) and os.path.isfile(filename):
148 if os.path.isabs(filename) and os.path.isfile(filename):
149 return filename
149 return filename
150
150
151 if path_dirs is None:
151 if path_dirs is None:
152 path_dirs = ("",)
152 path_dirs = ("",)
153 elif isinstance(path_dirs, basestring):
153 elif isinstance(path_dirs, basestring):
154 path_dirs = (path_dirs,)
154 path_dirs = (path_dirs,)
155
155
156 for path in path_dirs:
156 for path in path_dirs:
157 if path == '.': path = os.getcwdu()
157 if path == '.': path = os.getcwdu()
158 testname = expand_path(os.path.join(path, filename))
158 testname = expand_path(os.path.join(path, filename))
159 if os.path.isfile(testname):
159 if os.path.isfile(testname):
160 return os.path.abspath(testname)
160 return os.path.abspath(testname)
161
161
162 raise IOError("File %r does not exist in any of the search paths: %r" %
162 raise IOError("File %r does not exist in any of the search paths: %r" %
163 (filename, path_dirs) )
163 (filename, path_dirs) )
164
164
165
165
166 class HomeDirError(Exception):
166 class HomeDirError(Exception):
167 pass
167 pass
168
168
169
169
170 def get_home_dir(require_writable=False):
170 def get_home_dir(require_writable=False):
171 """Return the 'home' directory, as a unicode string.
171 """Return the 'home' directory, as a unicode string.
172
172
173 * First, check for frozen env in case of py2exe
173 * First, check for frozen env in case of py2exe
174 * Otherwise, defer to os.path.expanduser('~')
174 * Otherwise, defer to os.path.expanduser('~')
175
175
176 See stdlib docs for how this is determined.
176 See stdlib docs for how this is determined.
177 $HOME is first priority on *ALL* platforms.
177 $HOME is first priority on *ALL* platforms.
178
178
179 Parameters
179 Parameters
180 ----------
180 ----------
181
181
182 require_writable : bool [default: False]
182 require_writable : bool [default: False]
183 if True:
183 if True:
184 guarantees the return value is a writable directory, otherwise
184 guarantees the return value is a writable directory, otherwise
185 raises HomeDirError
185 raises HomeDirError
186 if False:
186 if False:
187 The path is resolved, but it is not guaranteed to exist or be writable.
187 The path is resolved, but it is not guaranteed to exist or be writable.
188 """
188 """
189
189
190 # first, check py2exe distribution root directory for _ipython.
190 # first, check py2exe distribution root directory for _ipython.
191 # This overrides all. Normally does not exist.
191 # This overrides all. Normally does not exist.
192
192
193 if hasattr(sys, "frozen"): #Is frozen by py2exe
193 if hasattr(sys, "frozen"): #Is frozen by py2exe
194 if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
194 if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
195 root, rest = IPython.__file__.lower().split('library.zip')
195 root, rest = IPython.__file__.lower().split('library.zip')
196 else:
196 else:
197 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
197 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
198 root=os.path.abspath(root).rstrip('\\')
198 root=os.path.abspath(root).rstrip('\\')
199 if _writable_dir(os.path.join(root, '_ipython')):
199 if _writable_dir(os.path.join(root, '_ipython')):
200 os.environ["IPYKITROOT"] = root
200 os.environ["IPYKITROOT"] = root
201 return py3compat.cast_unicode(root, fs_encoding)
201 return py3compat.cast_unicode(root, fs_encoding)
202
202
203 homedir = os.path.expanduser('~')
203 homedir = os.path.expanduser('~')
204 # Next line will make things work even when /home/ is a symlink to
204 # Next line will make things work even when /home/ is a symlink to
205 # /usr/home as it is on FreeBSD, for example
205 # /usr/home as it is on FreeBSD, for example
206 homedir = os.path.realpath(homedir)
206 homedir = os.path.realpath(homedir)
207
207
208 if not _writable_dir(homedir) and os.name == 'nt':
208 if not _writable_dir(homedir) and os.name == 'nt':
209 # expanduser failed, use the registry to get the 'My Documents' folder.
209 # expanduser failed, use the registry to get the 'My Documents' folder.
210 try:
210 try:
211 import _winreg as wreg
211 import _winreg as wreg
212 key = wreg.OpenKey(
212 key = wreg.OpenKey(
213 wreg.HKEY_CURRENT_USER,
213 wreg.HKEY_CURRENT_USER,
214 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
214 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
215 )
215 )
216 homedir = wreg.QueryValueEx(key,'Personal')[0]
216 homedir = wreg.QueryValueEx(key,'Personal')[0]
217 key.Close()
217 key.Close()
218 except:
218 except:
219 pass
219 pass
220
220
221 if (not require_writable) or _writable_dir(homedir):
221 if (not require_writable) or _writable_dir(homedir):
222 return py3compat.cast_unicode(homedir, fs_encoding)
222 return py3compat.cast_unicode(homedir, fs_encoding)
223 else:
223 else:
224 raise HomeDirError('%s is not a writable dir, '
224 raise HomeDirError('%s is not a writable dir, '
225 'set $HOME environment variable to override' % homedir)
225 'set $HOME environment variable to override' % homedir)
226
226
227 def get_xdg_dir():
227 def get_xdg_dir():
228 """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
228 """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
229
229
230 This is only for posix (Linux,Unix,OS X, etc) systems.
230 This is only for posix (Linux,Unix,OS X, etc) systems.
231 """
231 """
232
232
233 env = os.environ
233 env = os.environ
234
234
235 if os.name == 'posix':
235 if os.name == 'posix':
236 # Linux, Unix, AIX, OS X
236 # Linux, Unix, AIX, OS X
237 # use ~/.config if empty OR not set
237 # use ~/.config if empty OR not set
238 xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
238 xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
239 if xdg and _writable_dir(xdg):
239 if xdg and _writable_dir(xdg):
240 return py3compat.cast_unicode(xdg, fs_encoding)
240 return py3compat.cast_unicode(xdg, fs_encoding)
241
241
242 return None
242 return None
243
243
244
244
245 def get_ipython_dir():
245 def get_ipython_dir():
246 """Get the IPython directory for this platform and user.
246 """Get the IPython directory for this platform and user.
247
247
248 This uses the logic in `get_home_dir` to find the home directory
248 This uses the logic in `get_home_dir` to find the home directory
249 and then adds .ipython to the end of the path.
249 and then adds .ipython to the end of the path.
250 """
250 """
251
251
252 env = os.environ
252 env = os.environ
253 pjoin = os.path.join
253 pjoin = os.path.join
254
254
255
255
256 ipdir_def = '.ipython'
256 ipdir_def = '.ipython'
257 xdg_def = 'ipython'
257 xdg_def = 'ipython'
258
258
259 home_dir = get_home_dir()
259 home_dir = get_home_dir()
260 xdg_dir = get_xdg_dir()
260 xdg_dir = get_xdg_dir()
261
261
262 # import pdb; pdb.set_trace() # dbg
262 # import pdb; pdb.set_trace() # dbg
263 ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None))
263 ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None))
264 if ipdir is None:
264 if ipdir is None:
265 # not set explicitly, use XDG_CONFIG_HOME or HOME
265 # not set explicitly, use XDG_CONFIG_HOME or HOME
266 home_ipdir = pjoin(home_dir, ipdir_def)
266 home_ipdir = pjoin(home_dir, ipdir_def)
267 if xdg_dir:
267 if xdg_dir:
268 # use XDG, as long as the user isn't already
268 # use XDG, as long as the user isn't already
269 # using $HOME/.ipython and *not* XDG/ipython
269 # using $HOME/.ipython and *not* XDG/ipython
270
270
271 xdg_ipdir = pjoin(xdg_dir, xdg_def)
271 xdg_ipdir = pjoin(xdg_dir, xdg_def)
272
272
273 if _writable_dir(xdg_ipdir) or not _writable_dir(home_ipdir):
273 if _writable_dir(xdg_ipdir) or not _writable_dir(home_ipdir):
274 ipdir = xdg_ipdir
274 ipdir = xdg_ipdir
275
275
276 if ipdir is None:
276 if ipdir is None:
277 # not using XDG
277 # not using XDG
278 ipdir = home_ipdir
278 ipdir = home_ipdir
279
279
280 ipdir = os.path.normpath(os.path.expanduser(ipdir))
280 ipdir = os.path.normpath(os.path.expanduser(ipdir))
281
281
282 if os.path.exists(ipdir) and not _writable_dir(ipdir):
282 if os.path.exists(ipdir) and not _writable_dir(ipdir):
283 # ipdir exists, but is not writable
283 # ipdir exists, but is not writable
284 warnings.warn("IPython dir '%s' is not a writable location,"
284 warnings.warn("IPython dir '%s' is not a writable location,"
285 " using a temp directory."%ipdir)
285 " using a temp directory."%ipdir)
286 ipdir = tempfile.mkdtemp()
286 ipdir = tempfile.mkdtemp()
287 elif not os.path.exists(ipdir):
287 elif not os.path.exists(ipdir):
288 parent = ipdir.rsplit(os.path.sep, 1)[0]
288 parent = ipdir.rsplit(os.path.sep, 1)[0]
289 if not _writable_dir(parent):
289 if not _writable_dir(parent):
290 # ipdir does not exist and parent isn't writable
290 # ipdir does not exist and parent isn't writable
291 warnings.warn("IPython parent '%s' is not a writable location,"
291 warnings.warn("IPython parent '%s' is not a writable location,"
292 " using a temp directory."%parent)
292 " using a temp directory."%parent)
293 ipdir = tempfile.mkdtemp()
293 ipdir = tempfile.mkdtemp()
294
294
295 return py3compat.cast_unicode(ipdir, fs_encoding)
295 return py3compat.cast_unicode(ipdir, fs_encoding)
296
296
297
297
298 def get_ipython_package_dir():
298 def get_ipython_package_dir():
299 """Get the base directory where IPython itself is installed."""
299 """Get the base directory where IPython itself is installed."""
300 ipdir = os.path.dirname(IPython.__file__)
300 ipdir = os.path.dirname(IPython.__file__)
301 return py3compat.cast_unicode(ipdir, fs_encoding)
301 return py3compat.cast_unicode(ipdir, fs_encoding)
302
302
303
303
304 def get_ipython_module_path(module_str):
304 def get_ipython_module_path(module_str):
305 """Find the path to an IPython module in this version of IPython.
305 """Find the path to an IPython module in this version of IPython.
306
306
307 This will always find the version of the module that is in this importable
307 This will always find the version of the module that is in this importable
308 IPython package. This will always return the path to the ``.py``
308 IPython package. This will always return the path to the ``.py``
309 version of the module.
309 version of the module.
310 """
310 """
311 if module_str == 'IPython':
311 if module_str == 'IPython':
312 return os.path.join(get_ipython_package_dir(), '__init__.py')
312 return os.path.join(get_ipython_package_dir(), '__init__.py')
313 mod = import_item(module_str)
313 mod = import_item(module_str)
314 the_path = mod.__file__.replace('.pyc', '.py')
314 the_path = mod.__file__.replace('.pyc', '.py')
315 the_path = the_path.replace('.pyo', '.py')
315 the_path = the_path.replace('.pyo', '.py')
316 return py3compat.cast_unicode(the_path, fs_encoding)
316 return py3compat.cast_unicode(the_path, fs_encoding)
317
317
318 def locate_profile(profile='default'):
318 def locate_profile(profile='default'):
319 """Find the path to the folder associated with a given profile.
319 """Find the path to the folder associated with a given profile.
320
320
321 I.e. find $IPYTHON_DIR/profile_whatever.
321 I.e. find $IPYTHONDIR/profile_whatever.
322 """
322 """
323 from IPython.core.profiledir import ProfileDir, ProfileDirError
323 from IPython.core.profiledir import ProfileDir, ProfileDirError
324 try:
324 try:
325 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
325 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
326 except ProfileDirError:
326 except ProfileDirError:
327 # IOError makes more sense when people are expecting a path
327 # IOError makes more sense when people are expecting a path
328 raise IOError("Couldn't find profile %r" % profile)
328 raise IOError("Couldn't find profile %r" % profile)
329 return pd.location
329 return pd.location
330
330
331 def expand_path(s):
331 def expand_path(s):
332 """Expand $VARS and ~names in a string, like a shell
332 """Expand $VARS and ~names in a string, like a shell
333
333
334 :Examples:
334 :Examples:
335
335
336 In [2]: os.environ['FOO']='test'
336 In [2]: os.environ['FOO']='test'
337
337
338 In [3]: expand_path('variable FOO is $FOO')
338 In [3]: expand_path('variable FOO is $FOO')
339 Out[3]: 'variable FOO is test'
339 Out[3]: 'variable FOO is test'
340 """
340 """
341 # This is a pretty subtle hack. When expand user is given a UNC path
341 # This is a pretty subtle hack. When expand user is given a UNC path
342 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
342 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
343 # the $ to get (\\server\share\%username%). I think it considered $
343 # the $ to get (\\server\share\%username%). I think it considered $
344 # alone an empty var. But, we need the $ to remains there (it indicates
344 # alone an empty var. But, we need the $ to remains there (it indicates
345 # a hidden share).
345 # a hidden share).
346 if os.name=='nt':
346 if os.name=='nt':
347 s = s.replace('$\\', 'IPYTHON_TEMP')
347 s = s.replace('$\\', 'IPYTHON_TEMP')
348 s = os.path.expandvars(os.path.expanduser(s))
348 s = os.path.expandvars(os.path.expanduser(s))
349 if os.name=='nt':
349 if os.name=='nt':
350 s = s.replace('IPYTHON_TEMP', '$\\')
350 s = s.replace('IPYTHON_TEMP', '$\\')
351 return s
351 return s
352
352
353
353
354 def target_outdated(target,deps):
354 def target_outdated(target,deps):
355 """Determine whether a target is out of date.
355 """Determine whether a target is out of date.
356
356
357 target_outdated(target,deps) -> 1/0
357 target_outdated(target,deps) -> 1/0
358
358
359 deps: list of filenames which MUST exist.
359 deps: list of filenames which MUST exist.
360 target: single filename which may or may not exist.
360 target: single filename which may or may not exist.
361
361
362 If target doesn't exist or is older than any file listed in deps, return
362 If target doesn't exist or is older than any file listed in deps, return
363 true, otherwise return false.
363 true, otherwise return false.
364 """
364 """
365 try:
365 try:
366 target_time = os.path.getmtime(target)
366 target_time = os.path.getmtime(target)
367 except os.error:
367 except os.error:
368 return 1
368 return 1
369 for dep in deps:
369 for dep in deps:
370 dep_time = os.path.getmtime(dep)
370 dep_time = os.path.getmtime(dep)
371 if dep_time > target_time:
371 if dep_time > target_time:
372 #print "For target",target,"Dep failed:",dep # dbg
372 #print "For target",target,"Dep failed:",dep # dbg
373 #print "times (dep,tar):",dep_time,target_time # dbg
373 #print "times (dep,tar):",dep_time,target_time # dbg
374 return 1
374 return 1
375 return 0
375 return 0
376
376
377
377
378 def target_update(target,deps,cmd):
378 def target_update(target,deps,cmd):
379 """Update a target with a given command given a list of dependencies.
379 """Update a target with a given command given a list of dependencies.
380
380
381 target_update(target,deps,cmd) -> runs cmd if target is outdated.
381 target_update(target,deps,cmd) -> runs cmd if target is outdated.
382
382
383 This is just a wrapper around target_outdated() which calls the given
383 This is just a wrapper around target_outdated() which calls the given
384 command if target is outdated."""
384 command if target is outdated."""
385
385
386 if target_outdated(target,deps):
386 if target_outdated(target,deps):
387 system(cmd)
387 system(cmd)
388
388
389 def filehash(path):
389 def filehash(path):
390 """Make an MD5 hash of a file, ignoring any differences in line
390 """Make an MD5 hash of a file, ignoring any differences in line
391 ending characters."""
391 ending characters."""
392 with open(path, "rU") as f:
392 with open(path, "rU") as f:
393 return md5(py3compat.str_to_bytes(f.read())).hexdigest()
393 return md5(py3compat.str_to_bytes(f.read())).hexdigest()
394
394
395 # If the config is unmodified from the default, we'll just delete it.
395 # If the config is unmodified from the default, we'll just delete it.
396 # These are consistent for 0.10.x, thankfully. We're not going to worry about
396 # These are consistent for 0.10.x, thankfully. We're not going to worry about
397 # older versions.
397 # older versions.
398 old_config_md5 = {'ipy_user_conf.py': 'fc108bedff4b9a00f91fa0a5999140d3',
398 old_config_md5 = {'ipy_user_conf.py': 'fc108bedff4b9a00f91fa0a5999140d3',
399 'ipythonrc': '12a68954f3403eea2eec09dc8fe5a9b5'}
399 'ipythonrc': '12a68954f3403eea2eec09dc8fe5a9b5'}
400
400
401 def check_for_old_config(ipython_dir=None):
401 def check_for_old_config(ipython_dir=None):
402 """Check for old config files, and present a warning if they exist.
402 """Check for old config files, and present a warning if they exist.
403
403
404 A link to the docs of the new config is included in the message.
404 A link to the docs of the new config is included in the message.
405
405
406 This should mitigate confusion with the transition to the new
406 This should mitigate confusion with the transition to the new
407 config system in 0.11.
407 config system in 0.11.
408 """
408 """
409 if ipython_dir is None:
409 if ipython_dir is None:
410 ipython_dir = get_ipython_dir()
410 ipython_dir = get_ipython_dir()
411
411
412 old_configs = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py']
412 old_configs = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py']
413 warned = False
413 warned = False
414 for cfg in old_configs:
414 for cfg in old_configs:
415 f = os.path.join(ipython_dir, cfg)
415 f = os.path.join(ipython_dir, cfg)
416 if os.path.exists(f):
416 if os.path.exists(f):
417 if filehash(f) == old_config_md5.get(cfg, ''):
417 if filehash(f) == old_config_md5.get(cfg, ''):
418 os.unlink(f)
418 os.unlink(f)
419 else:
419 else:
420 warnings.warn("Found old IPython config file %r (modified by user)"%f)
420 warnings.warn("Found old IPython config file %r (modified by user)"%f)
421 warned = True
421 warned = True
422
422
423 if warned:
423 if warned:
424 warnings.warn("""
424 warnings.warn("""
425 The IPython configuration system has changed as of 0.11, and these files will
425 The IPython configuration system has changed as of 0.11, and these files will
426 be ignored. See http://ipython.github.com/ipython-doc/dev/config for details
426 be ignored. See http://ipython.github.com/ipython-doc/dev/config for details
427 of the new config system.
427 of the new config system.
428 To start configuring IPython, do `ipython profile create`, and edit
428 To start configuring IPython, do `ipython profile create`, and edit
429 `ipython_config.py` in <ipython_dir>/profile_default.
429 `ipython_config.py` in <ipython_dir>/profile_default.
430 If you need to leave the old config files in place for an older version of
430 If you need to leave the old config files in place for an older version of
431 IPython and want to suppress this warning message, set
431 IPython and want to suppress this warning message, set
432 `c.InteractiveShellApp.ignore_old_config=True` in the new config.""")
432 `c.InteractiveShellApp.ignore_old_config=True` in the new config.""")
433
433
434 def get_security_file(filename, profile='default'):
434 def get_security_file(filename, profile='default'):
435 """Return the absolute path of a security file given by filename and profile
435 """Return the absolute path of a security file given by filename and profile
436
436
437 This allows users and developers to find security files without
437 This allows users and developers to find security files without
438 knowledge of the IPython directory structure. The search path
438 knowledge of the IPython directory structure. The search path
439 will be ['.', profile.security_dir]
439 will be ['.', profile.security_dir]
440
440
441 Parameters
441 Parameters
442 ----------
442 ----------
443
443
444 filename : str
444 filename : str
445 The file to be found. If it is passed as an absolute path, it will
445 The file to be found. If it is passed as an absolute path, it will
446 simply be returned.
446 simply be returned.
447 profile : str [default: 'default']
447 profile : str [default: 'default']
448 The name of the profile to search. Leaving this unspecified
448 The name of the profile to search. Leaving this unspecified
449 The file to be found. If it is passed as an absolute path, fname will
449 The file to be found. If it is passed as an absolute path, fname will
450 simply be returned.
450 simply be returned.
451
451
452 Returns
452 Returns
453 -------
453 -------
454 Raises :exc:`IOError` if file not found or returns absolute path to file.
454 Raises :exc:`IOError` if file not found or returns absolute path to file.
455 """
455 """
456 # import here, because profiledir also imports from utils.path
456 # import here, because profiledir also imports from utils.path
457 from IPython.core.profiledir import ProfileDir
457 from IPython.core.profiledir import ProfileDir
458 try:
458 try:
459 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
459 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
460 except Exception:
460 except Exception:
461 # will raise ProfileDirError if no such profile
461 # will raise ProfileDirError if no such profile
462 raise IOError("Profile %r not found")
462 raise IOError("Profile %r not found")
463 return filefind(filename, ['.', pd.security_dir])
463 return filefind(filename, ['.', pd.security_dir])
464
464
@@ -1,48 +1,48 b''
1 .TH IPCLUSTER 1 "July 15, 2011" "" ""
1 .TH IPCLUSTER 1 "July 15, 2011" "" ""
2 .SH NAME
2 .SH NAME
3 \fBipcluster \- IPython parallel computing cluster control tool
3 \fBipcluster \- IPython parallel computing cluster control tool
4 .SH SYNOPSIS
4 .SH SYNOPSIS
5 .nf
5 .nf
6 .fam C
6 .fam C
7 \fBipcluster\fP {\fmpiexec,local,mpirun,pbs,ssh\fP} [\fIoptions\fP]
7 \fBipcluster\fP {\fmpiexec,local,mpirun,pbs,ssh\fP} [\fIoptions\fP]
8 .fam T
8 .fam T
9 .fi
9 .fi
10 .SH DESCRIPTION
10 .SH DESCRIPTION
11 ipcluster is a control tool for IPython's parallel computing functions.
11 ipcluster is a control tool for IPython's parallel computing functions.
12
12
13 IPython cluster startup. This starts a controller and engines using various
13 IPython cluster startup. This starts a controller and engines using various
14 approaches. Use the IPYTHON_DIR environment variable to change your IPython
14 approaches. Use the IPYTHONDIR environment variable to change your IPython
15 directory from the default of ~/.ipython or ~/.config/ipython. The log and security
15 directory from the default of ~/.ipython or ~/.config/ipython. The log and security
16 subdirectories of your IPython directory will be used by this script for log
16 subdirectories of your IPython directory will be used by this script for log
17 files and security files.
17 files and security files.
18 .SH POSITIONAL ARGUMENTS
18 .SH POSITIONAL ARGUMENTS
19
19
20 The first positional argument should be one of: {start, stop, engines},
20 The first positional argument should be one of: {start, stop, engines},
21 which are the available subcommands.
21 which are the available subcommands.
22
22
23 For detailed help on each, type "ipcluster CMD \-\-help". Briefly:
23 For detailed help on each, type "ipcluster CMD \-\-help". Briefly:
24
24
25 start start an IPython cluster
25 start start an IPython cluster
26 stop stop a running IPython cluster
26 stop stop a running IPython cluster
27 engines add a number of engines to a running cluster
27 engines add a number of engines to a running cluster
28 .SH OPTIONS
28 .SH OPTIONS
29 .TP
29 .TP
30 .B
30 .B
31 \-h, \-\-help
31 \-h, \-\-help
32 show help message and exit
32 show help message and exit
33 .SH EXAMPLE
33 .SH EXAMPLE
34 ipcluster start \-\-n=4
34 ipcluster start \-\-n=4
35
35
36 This command will start 4 IPython engines on the local computer.
36 This command will start 4 IPython engines on the local computer.
37 .SH SEE ALSO
37 .SH SEE ALSO
38 .BR ipython(1),
38 .BR ipython(1),
39 .BR ipcontroller(1),
39 .BR ipcontroller(1),
40 .BR ipengine(1)
40 .BR ipengine(1)
41 .br
41 .br
42 .SH AUTHOR
42 .SH AUTHOR
43 \fBipcluster\fP is a tool that ships with IPython, created by
43 \fBipcluster\fP is a tool that ships with IPython, created by
44 the IPython Development Team.
44 the IPython Development Team.
45 .PP
45 .PP
46 This manual page was written by Stephan Peijnik <debian@sp.or.at>,
46 This manual page was written by Stephan Peijnik <debian@sp.or.at>,
47 for the Debian project (but may be used by others). Modified by Fernando Perez
47 for the Debian project (but may be used by others). Modified by Fernando Perez
48 <Fernando.Perez@berkeley.edu> for inclusion in IPython.
48 <Fernando.Perez@berkeley.edu> for inclusion in IPython.
@@ -1,164 +1,164 b''
1 .TH IPCONTROLLER 1 "October 29, 2008" "" ""
1 .TH IPCONTROLLER 1 "October 29, 2008" "" ""
2 .SH NAME
2 .SH NAME
3 \fBipcontroller \- IPython parallel computing controller control tool
3 \fBipcontroller \- IPython parallel computing controller control tool
4 .SH SYNOPSIS
4 .SH SYNOPSIS
5 .nf
5 .nf
6 .fam C
6 .fam C
7 \fBipengine\fP [\fIoptions\fP]
7 \fBipengine\fP [\fIoptions\fP]
8 .fam T
8 .fam T
9 .fi
9 .fi
10 .SH DESCRIPTION
10 .SH DESCRIPTION
11 ipcontroller is a control tool for IPython's parallel computing functions.
11 ipcontroller is a control tool for IPython's parallel computing functions.
12 .SH OPTIONS
12 .SH OPTIONS
13 .TP
13 .TP
14 .B
14 .B
15 \-h, \-\-help
15 \-h, \-\-help
16 show this help message and exit
16 show this help message and exit
17 .TP
17 .TP
18 .B
18 .B
19 .TP
19 .TP
20 .B \-\-no\-secure
20 .B \-\-no\-secure
21 Don't authenticate messages.
21 Don't authenticate messages.
22 .TP
22 .TP
23 .B \-\-usethreads
23 .B \-\-usethreads
24 Use threads instead of processes for the schedulers
24 Use threads instead of processes for the schedulers
25 .TP
25 .TP
26 .B \-\-init
26 .B \-\-init
27 Initialize profile with default config files
27 Initialize profile with default config files
28 .TP
28 .TP
29 .B \-\-log\-to\-file
29 .B \-\-log\-to\-file
30 send log output to a file
30 send log output to a file
31 .TP
31 .TP
32 .B \-\-reuse
32 .B \-\-reuse
33 reuse existing json connection files
33 reuse existing json connection files
34 .TP
34 .TP
35 .B \-\-mongodb
35 .B \-\-mongodb
36 use the MongoDB backend
36 use the MongoDB backend
37 .TP
37 .TP
38 .B \-\-quiet
38 .B \-\-quiet
39 set log level to logging.CRITICAL (minimize logging output)
39 set log level to logging.CRITICAL (minimize logging output)
40 .TP
40 .TP
41 .B \-\-debug
41 .B \-\-debug
42 set log level to logging.DEBUG (maximize logging output)
42 set log level to logging.DEBUG (maximize logging output)
43 .TP
43 .TP
44 .B \-\-sqlitedb
44 .B \-\-sqlitedb
45 use the SQLiteDB backend
45 use the SQLiteDB backend
46 .TP
46 .TP
47 .B \-\-dictdb
47 .B \-\-dictdb
48 use the in-memory DictDB backend
48 use the in-memory DictDB backend
49 .TP
49 .TP
50 .B \-\-secure
50 .B \-\-secure
51 Use HMAC digests for authentication of messages.
51 Use HMAC digests for authentication of messages.
52 .TP
52 .TP
53 .B \-\-profile=<Unicode> (BaseIPythonApplication.profile)
53 .B \-\-profile=<Unicode> (BaseIPythonApplication.profile)
54 Default: u'default'
54 Default: u'default'
55 The IPython profile to use.
55 The IPython profile to use.
56 .TP
56 .TP
57 .B \-\-hwm=<Int> (TaskScheduler.hwm)
57 .B \-\-hwm=<Int> (TaskScheduler.hwm)
58 Default: 0
58 Default: 0
59 .br
59 .br
60 specify the High Water Mark (HWM) for the downstream socket in the Task
60 specify the High Water Mark (HWM) for the downstream socket in the Task
61 scheduler. This is the maximum number of allowed outstanding tasks on each
61 scheduler. This is the maximum number of allowed outstanding tasks on each
62 engine.
62 engine.
63 .TP
63 .TP
64 .B \-\-secure=<Bool> (IPControllerApp.secure)
64 .B \-\-secure=<Bool> (IPControllerApp.secure)
65 Default: True
65 Default: True
66 Whether to use HMAC digests for extra message authentication.
66 Whether to use HMAC digests for extra message authentication.
67 .TP
67 .TP
68 .B \-\-ip=<Unicode> (HubFactory.ip)
68 .B \-\-ip=<Unicode> (HubFactory.ip)
69 Default: '127.0.0.1'
69 Default: '127.0.0.1'
70 The IP address for registration. This is generally either '127.0.0.1' for
70 The IP address for registration. This is generally either '127.0.0.1' for
71 loopback only or '*' for all interfaces. [default: '127.0.0.1']
71 loopback only or '*' for all interfaces. [default: '127.0.0.1']
72 .TP
72 .TP
73 .B \-\-log\-url=<Unicode> (BaseParallelApplication.log_url)
73 .B \-\-log\-url=<Unicode> (BaseParallelApplication.log_url)
74 Default: ''
74 Default: ''
75 The ZMQ URL of the iplogger to aggregate logging.
75 The ZMQ URL of the iplogger to aggregate logging.
76 .TP
76 .TP
77 .B \-\-work\-dir=<Unicode> (BaseParallelApplication.work_dir)
77 .B \-\-work\-dir=<Unicode> (BaseParallelApplication.work_dir)
78 Default: u'/Users/minrk/dev/ip/mine/docs/man'
78 Default: u'/Users/minrk/dev/ip/mine/docs/man'
79 Set the working dir for the process.
79 Set the working dir for the process.
80 .TP
80 .TP
81 .B \-\-port=<Int> (HubFactory.regport)
81 .B \-\-port=<Int> (HubFactory.regport)
82 Default: 0
82 Default: 0
83 The port on which the Hub listens for registration.
83 The port on which the Hub listens for registration.
84 .TP
84 .TP
85 .B \-\-profile\-dir=<Unicode> (ProfileDir.location)
85 .B \-\-profile\-dir=<Unicode> (ProfileDir.location)
86 Default: u''
86 Default: u''
87 Set the profile location directly. This overrides the logic used by the
87 Set the profile location directly. This overrides the logic used by the
88 `profile` option.
88 `profile` option.
89 .TP
89 .TP
90 .B \-\-ident=<CBytes> (Session.session)
90 .B \-\-ident=<CBytes> (Session.session)
91 Default: ''
91 Default: ''
92 The UUID identifying this session.
92 The UUID identifying this session.
93 .TP
93 .TP
94 .B \-\-log\-to\-file=<Bool> (BaseParallelApplication.log_to_file)
94 .B \-\-log\-to\-file=<Bool> (BaseParallelApplication.log_to_file)
95 Default: False
95 Default: False
96 whether to log to a file
96 whether to log to a file
97 .TP
97 .TP
98 .B \-\-ipython\-dir=<Unicode> (BaseIPythonApplication.ipython_dir)
98 .B \-\-ipython\-dir=<Unicode> (BaseIPythonApplication.ipython_dir)
99 Default: u'/Users/minrk/.ipython'
99 Default: u'/Users/minrk/.ipython'
100 The name of the IPython directory. This directory is used for logging
100 The name of the IPython directory. This directory is used for logging
101 configuration (through profiles), history storage, etc. The default is
101 configuration (through profiles), history storage, etc. The default is
102 usually $HOME/.ipython. This options can also be specified through the
102 usually $HOME/.ipython. This options can also be specified through the
103 environment variable IPYTHON_DIR.
103 environment variable IPYTHONDIR.
104 .TP
104 .TP
105 .B \-\-url=<Unicode> (HubFactory.url)
105 .B \-\-url=<Unicode> (HubFactory.url)
106 Default: ''
106 Default: ''
107 The 0MQ url used for registration. This sets transport, ip, and port in one
107 The 0MQ url used for registration. This sets transport, ip, and port in one
108 variable. For example: url='tcp://127.0.0.1:12345' or url='epgm://*:90210'
108 variable. For example: url='tcp://127.0.0.1:12345' or url='epgm://*:90210'
109 .TP
109 .TP
110 .B \-\-user=<Unicode> (Session.username)
110 .B \-\-user=<Unicode> (Session.username)
111 Default: 'minrk'
111 Default: 'minrk'
112 Username for the Session. Default is your system username.
112 Username for the Session. Default is your system username.
113 .TP
113 .TP
114 .B \-\-ping=<CFloat> (HeartMonitor.period)
114 .B \-\-ping=<CFloat> (HeartMonitor.period)
115 Default: 1000
115 Default: 1000
116 The frequency at which the Hub pings the engines for heartbeats (in ms)
116 The frequency at which the Hub pings the engines for heartbeats (in ms)
117 .TP
117 .TP
118 .B \-\-log\-level=<Enum> (Application.log_level)
118 .B \-\-log\-level=<Enum> (Application.log_level)
119 Default: 30
119 Default: 30
120 Choices: (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL')
120 Choices: (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL')
121 Set the log level by value or name.
121 Set the log level by value or name.
122 .TP
122 .TP
123 .B \-\-location=<Unicode> (IPControllerApp.location)
123 .B \-\-location=<Unicode> (IPControllerApp.location)
124 Default: u''
124 Default: u''
125 The external IP or domain name of the Controller, used for disambiguating
125 The external IP or domain name of the Controller, used for disambiguating
126 engine and client connections.
126 engine and client connections.
127 .TP
127 .TP
128 .B \-\-clean\-logs=<Bool> (BaseParallelApplication.clean_logs)
128 .B \-\-clean\-logs=<Bool> (BaseParallelApplication.clean_logs)
129 Default: False
129 Default: False
130 whether to cleanup old logfiles before starting
130 whether to cleanup old logfiles before starting
131 .TP
131 .TP
132 .B \-\-scheme=<Enum> (TaskScheduler.scheme_name)
132 .B \-\-scheme=<Enum> (TaskScheduler.scheme_name)
133 Default: 'leastload'
133 Default: 'leastload'
134 Choices: ('leastload', 'pure', 'lru', 'plainrandom', 'weighted', 'twobin')
134 Choices: ('leastload', 'pure', 'lru', 'plainrandom', 'weighted', 'twobin')
135 select the task scheduler scheme [default: Python LRU] Options are: 'pure',
135 select the task scheduler scheme [default: Python LRU] Options are: 'pure',
136 \&'lru', 'plainrandom', 'weighted', 'twobin','leastload'
136 \&'lru', 'plainrandom', 'weighted', 'twobin','leastload'
137 .TP
137 .TP
138 .B \-\-keyfile=<Unicode> (Session.keyfile)
138 .B \-\-keyfile=<Unicode> (Session.keyfile)
139 Default: ''
139 Default: ''
140 path to file containing execution key.
140 path to file containing execution key.
141 .TP
141 .TP
142 .B \-\-transport=<Unicode> (HubFactory.transport)
142 .B \-\-transport=<Unicode> (HubFactory.transport)
143 Default: 'tcp'
143 Default: 'tcp'
144 The 0MQ transport for communications. This will likely be the default of
144 The 0MQ transport for communications. This will likely be the default of
145 \&'tcp', but other values include 'ipc', 'epgm', 'inproc'.
145 \&'tcp', but other values include 'ipc', 'epgm', 'inproc'.
146 .TP
146 .TP
147 .B \-\-ssh=<Unicode> (IPControllerApp.ssh_server)
147 .B \-\-ssh=<Unicode> (IPControllerApp.ssh_server)
148 Default: u''
148 Default: u''
149 ssh url for clients to use when connecting to the Controller processes. It
149 ssh url for clients to use when connecting to the Controller processes. It
150 should be of the form: [user@]server[:port]. The Controller's listening
150 should be of the form: [user@]server[:port]. The Controller's listening
151 addresses must be accessible from the ssh server
151 addresses must be accessible from the ssh server
152 .SH SEE ALSO
152 .SH SEE ALSO
153 .BR ipython(1),
153 .BR ipython(1),
154 .BR ipcluster(1),
154 .BR ipcluster(1),
155 .BR ipengine(1)
155 .BR ipengine(1)
156 .br
156 .br
157 .SH AUTHOR
157 .SH AUTHOR
158 \fBipcontroller\fP is a tool that ships with IPython, created by
158 \fBipcontroller\fP is a tool that ships with IPython, created by
159 the IPython Development Team.
159 the IPython Development Team.
160 .PP
160 .PP
161 This manual page was written by Stephan Peijnik <debian@sp.or.at>,
161 This manual page was written by Stephan Peijnik <debian@sp.or.at>,
162 for the Debian project (but may be used by others). Modified by Fernando Perez
162 for the Debian project (but may be used by others). Modified by Fernando Perez
163 <Fernando.Perez@berkeley.edu> for inclusion in IPython, and updated by
163 <Fernando.Perez@berkeley.edu> for inclusion in IPython, and updated by
164 Min Ragan-Kelley <benjaminrk@gmail.com> for 0.11.
164 Min Ragan-Kelley <benjaminrk@gmail.com> for 0.11.
@@ -1,98 +1,98 b''
1 .TH IPLOGGER 1 "July 21, 2011" "" ""
1 .TH IPLOGGER 1 "July 21, 2011" "" ""
2 .\" Man page generated from reStructeredText.
2 .\" Man page generated from reStructeredText.
3 .SH NAME
3 .SH NAME
4 \fBiplogger \- IPython logger for parallel computing.
4 \fBiplogger \- IPython logger for parallel computing.
5 .SH DESCRIPTION
5 .SH DESCRIPTION
6 Start an IPython logger for parallel computing.
6 Start an IPython logger for parallel computing.
7 .sp
7 .sp
8 IPython controllers and engines (and your own processes) can broadcast log
8 IPython controllers and engines (and your own processes) can broadcast log
9 messages by registering a \fIzmq.log.handlers.PUBHandler\fP with the \fIlogging\fP
9 messages by registering a \fIzmq.log.handlers.PUBHandler\fP with the \fIlogging\fP
10 module. The logger can be configured using command line options or using a
10 module. The logger can be configured using command line options or using a
11 cluster directory. Cluster directories contain config, log and security files
11 cluster directory. Cluster directories contain config, log and security files
12 and are usually located in your ipython directory and named as "profile_name".
12 and are usually located in your ipython directory and named as "profile_name".
13 See the \fIprofile\fP and \fIprofile\-dir\fP options for details.
13 See the \fIprofile\fP and \fIprofile\-dir\fP options for details.
14 .SH OPTIONS
14 .SH OPTIONS
15 .sp
15 .sp
16 IPython command\-line arguments are passed as \(aq\-\-<flag>\(aq, or \(aq\-\-<name>=<value>\(aq.
16 IPython command\-line arguments are passed as \(aq\-\-<flag>\(aq, or \(aq\-\-<name>=<value>\(aq.
17 .sp
17 .sp
18 Arguments that take values are actually convenience aliases to full
18 Arguments that take values are actually convenience aliases to full
19 Configurables, whose aliases are listed on the help line. For more information
19 Configurables, whose aliases are listed on the help line. For more information
20 on full configurables, see \(aq\-\-help\-all\(aq.
20 on full configurables, see \(aq\-\-help\-all\(aq.
21 .TP
21 .TP
22 .B \-\-debug
22 .B \-\-debug
23 .
23 .
24 set log level to logging.DEBUG (maximize logging output)
24 set log level to logging.DEBUG (maximize logging output)
25 .TP
25 .TP
26 .B \-\-init
26 .B \-\-init
27 .
27 .
28 Initialize profile with default config files. This is equivalent
28 Initialize profile with default config files. This is equivalent
29 to running \fIipython profile create <profile>\fP prior to startup.
29 to running \fIipython profile create <profile>\fP prior to startup.
30 .TP
30 .TP
31 .B \-\-log\-to\-file
31 .B \-\-log\-to\-file
32 .
32 .
33 send log output to a file
33 send log output to a file
34 .TP
34 .TP
35 .B \-\-quiet
35 .B \-\-quiet
36 .
36 .
37 set log level to logging.CRITICAL (minimize logging output)
37 set log level to logging.CRITICAL (minimize logging output)
38 .TP
38 .TP
39 .B \-\-profile=<Unicode> (BaseIPythonApplication.profile)
39 .B \-\-profile=<Unicode> (BaseIPythonApplication.profile)
40 .
40 .
41 Default: u\(aqdefault\(aq
41 Default: u\(aqdefault\(aq
42 The IPython profile to use.
42 The IPython profile to use.
43 .TP
43 .TP
44 .B \-\-log\-to\-file=<Bool> (BaseParallelApplication.log_to_file)
44 .B \-\-log\-to\-file=<Bool> (BaseParallelApplication.log_to_file)
45 .
45 .
46 Default: False
46 Default: False
47 whether to log to a file
47 whether to log to a file
48 .TP
48 .TP
49 .B \-\-ipython\-dir=<Unicode> (BaseIPythonApplication.ipython_dir)
49 .B \-\-ipython\-dir=<Unicode> (BaseIPythonApplication.ipython_dir)
50 .
50 .
51 The name of the IPython directory. This directory is used for logging
51 The name of the IPython directory. This directory is used for logging
52 configuration (through profiles), history storage, etc. The default is
52 configuration (through profiles), history storage, etc. The default is
53 usually $XDG_CONFIG_HOME/ipython. This options can also be specified
53 usually $XDG_CONFIG_HOME/ipython. This options can also be specified
54 through the environment variable IPYTHON_DIR.
54 through the environment variable IPYTHONDIR.
55 .TP
55 .TP
56 .B \-\-url=<Unicode> (LogWatcher.url)
56 .B \-\-url=<Unicode> (LogWatcher.url)
57 .
57 .
58 Default: \(aq\fI\%tcp://127.0.0.1:20202\fP\(aq
58 Default: \(aq\fI\%tcp://127.0.0.1:20202\fP\(aq
59 ZMQ url on which to listen for log messages
59 ZMQ url on which to listen for log messages
60 .TP
60 .TP
61 .B \-\-topics=<List> (LogWatcher.topics)
61 .B \-\-topics=<List> (LogWatcher.topics)
62 .
62 .
63 Default: [\(aq\(aq]
63 Default: [\(aq\(aq]
64 The ZMQ topics to subscribe to. Default is to subscribe to all messages
64 The ZMQ topics to subscribe to. Default is to subscribe to all messages
65 .TP
65 .TP
66 .B \-\-log\-level=<Enum> (Application.log_level)
66 .B \-\-log\-level=<Enum> (Application.log_level)
67 .
67 .
68 Default: 30
68 Default: 30
69 Choices: (0, 10, 20, 30, 40, 50, \(aqDEBUG\(aq, \(aqINFO\(aq, \(aqWARN\(aq, \(aqERROR\(aq, \(aqCRITICAL\(aq)
69 Choices: (0, 10, 20, 30, 40, 50, \(aqDEBUG\(aq, \(aqINFO\(aq, \(aqWARN\(aq, \(aqERROR\(aq, \(aqCRITICAL\(aq)
70 Set the log level by value or name.
70 Set the log level by value or name.
71 .TP
71 .TP
72 .B \-\-log\-url=<Unicode> (BaseParallelApplication.log_url)
72 .B \-\-log\-url=<Unicode> (BaseParallelApplication.log_url)
73 .
73 .
74 Default: \(aq\(aq
74 Default: \(aq\(aq
75 The ZMQ URL of the iplogger to aggregate logging.
75 The ZMQ URL of the iplogger to aggregate logging.
76 .TP
76 .TP
77 .B \-\-clean\-logs=<Bool> (BaseParallelApplication.clean_logs)
77 .B \-\-clean\-logs=<Bool> (BaseParallelApplication.clean_logs)
78 .
78 .
79 Default: False
79 Default: False
80 whether to cleanup old logfiles before starting
80 whether to cleanup old logfiles before starting
81 .TP
81 .TP
82 .B \-\-profile\-dir=<Unicode> (ProfileDir.location)
82 .B \-\-profile\-dir=<Unicode> (ProfileDir.location)
83 .
83 .
84 Default: u\(aq\(aq
84 Default: u\(aq\(aq
85 Set the profile location directly. This overrides the logic used by the
85 Set the profile location directly. This overrides the logic used by the
86 \fIprofile\fP option.
86 \fIprofile\fP option.
87 .TP
87 .TP
88 .B \-\-work\-dir=<Unicode> (BaseParallelApplication.work_dir)
88 .B \-\-work\-dir=<Unicode> (BaseParallelApplication.work_dir)
89 .
89 .
90 Set the working dir for the process.
90 Set the working dir for the process.
91 .SH SEE ALSO
91 .SH SEE ALSO
92 .BR ipython(1),
92 .BR ipython(1),
93 .BR ipcontroller(1),
93 .BR ipcontroller(1),
94 .BR ipengine(1)
94 .BR ipengine(1)
95 .br
95 .br
96 .SH AUTHOR
96 .SH AUTHOR
97 \fBiplogger\fP is a tool that ships with IPython, created by
97 \fBiplogger\fP is a tool that ships with IPython, created by
98 the IPython Development Team.
98 the IPython Development Team.
@@ -1,241 +1,241 b''
1 .\" Hey, EMACS: -*- nroff -*-
1 .\" Hey, EMACS: -*- nroff -*-
2 .\" First parameter, NAME, should be all caps
2 .\" First parameter, NAME, should be all caps
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
4 .\" other parameters are allowed: see man(7), man(1)
4 .\" other parameters are allowed: see man(7), man(1)
5 .TH IPYTHON 1 "July 15, 2011"
5 .TH IPYTHON 1 "July 15, 2011"
6 .\" Please adjust this date whenever revising the manpage.
6 .\" Please adjust this date whenever revising the manpage.
7 .\"
7 .\"
8 .\" Some roff macros, for reference:
8 .\" Some roff macros, for reference:
9 .\" .nh disable hyphenation
9 .\" .nh disable hyphenation
10 .\" .hy enable hyphenation
10 .\" .hy enable hyphenation
11 .\" .ad l left justify
11 .\" .ad l left justify
12 .\" .ad b justify to both left and right margins
12 .\" .ad b justify to both left and right margins
13 .\" .nf disable filling
13 .\" .nf disable filling
14 .\" .fi enable filling
14 .\" .fi enable filling
15 .\" .br insert line break
15 .\" .br insert line break
16 .\" .sp <n> insert n+1 empty lines
16 .\" .sp <n> insert n+1 empty lines
17 .\" for manpage-specific macros, see man(7) and groff_man(7)
17 .\" for manpage-specific macros, see man(7) and groff_man(7)
18 .\" .SH section heading
18 .\" .SH section heading
19 .\" .SS secondary section heading
19 .\" .SS secondary section heading
20 .\"
20 .\"
21 .\"
21 .\"
22 .\" To preview this page as plain text: nroff -man ipython.1
22 .\" To preview this page as plain text: nroff -man ipython.1
23 .\"
23 .\"
24 .SH NAME
24 .SH NAME
25 ipython \- Tools for Interactive Computing in Python.
25 ipython \- Tools for Interactive Computing in Python.
26 .SH SYNOPSIS
26 .SH SYNOPSIS
27 .B ipython
27 .B ipython
28 .RI [ options ] " files" ...
28 .RI [ options ] " files" ...
29 .SH DESCRIPTION
29 .SH DESCRIPTION
30 An interactive Python shell with automatic history (input and output), dynamic
30 An interactive Python shell with automatic history (input and output), dynamic
31 object introspection, easier configuration, command completion, access to the
31 object introspection, easier configuration, command completion, access to the
32 system shell, integration with numerical and scientific computing tools, and
32 system shell, integration with numerical and scientific computing tools, and
33 more.
33 more.
34 .
34 .
35 .SH REGULAR OPTIONS
35 .SH REGULAR OPTIONS
36 All options that take values, must be of the form '\-\-name=value', but
36 All options that take values, must be of the form '\-\-name=value', but
37 flags that take no arguments are allowed a single '\-' to allow common
37 flags that take no arguments are allowed a single '\-' to allow common
38 patterns like: 'ipython \-i myscript.py'. To pass arguments to scripts,
38 patterns like: 'ipython \-i myscript.py'. To pass arguments to scripts,
39 rather than to IPython, specify them after '\-\-'.
39 rather than to IPython, specify them after '\-\-'.
40 .br
40 .br
41 .sp 1
41 .sp 1
42 All options can also be set from your ipython_config.py configuration file.
42 All options can also be set from your ipython_config.py configuration file.
43 See the provided examples for assistance. Options given on the
43 See the provided examples for assistance. Options given on the
44 commandline override the values set in ipython_config.py. To generate
44 commandline override the values set in ipython_config.py. To generate
45 the default config file, do `ipython profile create`.
45 the default config file, do `ipython profile create`.
46 .br
46 .br
47 .sp 1
47 .sp 1
48 All options with a [no] prepended can be specified in negated form
48 All options with a [no] prepended can be specified in negated form
49 (\-\-no\-option instead of \-\-option) to turn the feature off.
49 (\-\-no\-option instead of \-\-option) to turn the feature off.
50 .TP
50 .TP
51 .B \-h, \-\-help
51 .B \-h, \-\-help
52 Show summary of options.
52 Show summary of options.
53 .B \-\-no\-autoindent
53 .B \-\-no\-autoindent
54 Turn off autoindenting.
54 Turn off autoindenting.
55 .TP
55 .TP
56 .B \-\-autoedit\-syntax
56 .B \-\-autoedit\-syntax
57 Turn on auto editing of files with syntax errors.
57 Turn on auto editing of files with syntax errors.
58 .TP
58 .TP
59 .B \-\-pylab
59 .B \-\-pylab
60 Pre-load matplotlib and numpy for interactive use with
60 Pre-load matplotlib and numpy for interactive use with
61 the default matplotlib backend.
61 the default matplotlib backend.
62 .TP
62 .TP
63 .B \-\-confirm\-exit
63 .B \-\-confirm\-exit
64 Set to confirm when you try to exit IPython with an EOF (Control-D
64 Set to confirm when you try to exit IPython with an EOF (Control-D
65 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
65 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
66 you can force a direct exit without any confirmation.
66 you can force a direct exit without any confirmation.
67 .TP
67 .TP
68 .B \-\-deep\-reload
68 .B \-\-deep\-reload
69 Enable deep (recursive) reloading by default. IPython can use the
69 Enable deep (recursive) reloading by default. IPython can use the
70 deep_reload module which reloads changes in modules recursively (it
70 deep_reload module which reloads changes in modules recursively (it
71 replaces the reload() function, so you don't need to change anything to
71 replaces the reload() function, so you don't need to change anything to
72 use it). deep_reload() forces a full reload of modules whose code may
72 use it). deep_reload() forces a full reload of modules whose code may
73 have changed, which the default reload() function does not. When
73 have changed, which the default reload() function does not. When
74 deep_reload is off, IPython will use the normal reload(), but
74 deep_reload is off, IPython will use the normal reload(), but
75 deep_reload will still be available as dreload(). This feature is off
75 deep_reload will still be available as dreload(). This feature is off
76 by default [which means that you have both normal reload() and
76 by default [which means that you have both normal reload() and
77 dreload()].
77 dreload()].
78 .TP
78 .TP
79 .B \-\-no\-autoedit\-syntax
79 .B \-\-no\-autoedit\-syntax
80 Turn off auto editing of files with syntax errors.
80 Turn off auto editing of files with syntax errors.
81 .TP
81 .TP
82 .B \-\-term\-title
82 .B \-\-term\-title
83 Enable auto setting the terminal title.
83 Enable auto setting the terminal title.
84 .TP
84 .TP
85 .B \-\-no\-confirm\-exit
85 .B \-\-no\-confirm\-exit
86 Don't prompt the user when exiting.
86 Don't prompt the user when exiting.
87 .TP
87 .TP
88 .B \-\-autoindent
88 .B \-\-autoindent
89 Turn on autoindenting.
89 Turn on autoindenting.
90 .TP
90 .TP
91 .B \-\-classic
91 .B \-\-classic
92 Gives IPython a similar feel to the classic Python prompt.
92 Gives IPython a similar feel to the classic Python prompt.
93 .TP
93 .TP
94 .B \-\-no\-automagic
94 .B \-\-no\-automagic
95 Turn off the auto calling of magic commands.
95 Turn off the auto calling of magic commands.
96 .TP
96 .TP
97 .B \-\-banner
97 .B \-\-banner
98 Display a banner upon starting IPython.
98 Display a banner upon starting IPython.
99 .TP
99 .TP
100 .B \-\-automagic
100 .B \-\-automagic
101 Turn on the auto calling of magic commands. Type %%magic at the
101 Turn on the auto calling of magic commands. Type %%magic at the
102 IPython prompt for more information.
102 IPython prompt for more information.
103 .TP
103 .TP
104 .B \-\-no\-deep\-reload
104 .B \-\-no\-deep\-reload
105 Disable deep (recursive) reloading by default.
105 Disable deep (recursive) reloading by default.
106 .TP
106 .TP
107 .B \-\-no\-term\-title
107 .B \-\-no\-term\-title
108 Disable auto setting the terminal title.
108 Disable auto setting the terminal title.
109 .TP
109 .TP
110 .B \-\-nosep
110 .B \-\-nosep
111 Eliminate all spacing between prompts.
111 Eliminate all spacing between prompts.
112 .TP
112 .TP
113 .B \-\-i
113 .B \-\-i
114 also works as '\-i'
114 also works as '\-i'
115 If running code from the command line, become interactive afterwards.
115 If running code from the command line, become interactive afterwards.
116 .TP
116 .TP
117 .B \-\-debug
117 .B \-\-debug
118 set log level to logging.DEBUG (maximize logging output)
118 set log level to logging.DEBUG (maximize logging output)
119 .TP
119 .TP
120 .B \-\-pprint
120 .B \-\-pprint
121 Enable auto pretty printing of results.
121 Enable auto pretty printing of results.
122 .TP
122 .TP
123 .B \-\-quiet
123 .B \-\-quiet
124 set log level to logging.CRITICAL (minimize logging output)
124 set log level to logging.CRITICAL (minimize logging output)
125 .TP
125 .TP
126 .B \-\-pdb
126 .B \-\-pdb
127 Enable auto calling the pdb debugger after every exception.
127 Enable auto calling the pdb debugger after every exception.
128 .TP
128 .TP
129 .B \-\-color\-info
129 .B \-\-color\-info
130 IPython can display information about objects via a set of func-
130 IPython can display information about objects via a set of func-
131 tions, and optionally can use colors for this, syntax highlighting
131 tions, and optionally can use colors for this, syntax highlighting
132 source code and various other elements. However, because this
132 source code and various other elements. However, because this
133 information is passed through a pager (like 'less') and many pagers get
133 information is passed through a pager (like 'less') and many pagers get
134 confused with color codes, this option is off by default. You can test
134 confused with color codes, this option is off by default. You can test
135 it and turn it on permanently in your ipython_config.py file if it
135 it and turn it on permanently in your ipython_config.py file if it
136 works for you. Test it and turn it on permanently if it works with
136 works for you. Test it and turn it on permanently if it works with
137 your system. The magic function %%color_info allows you to toggle this
137 your system. The magic function %%color_info allows you to toggle this
138 interactively for testing.
138 interactively for testing.
139 .TP
139 .TP
140 .B \-\-init
140 .B \-\-init
141 Initialize profile with default config files
141 Initialize profile with default config files
142 .TP
142 .TP
143 .B \-\-no\-pdb
143 .B \-\-no\-pdb
144 Disable auto calling the pdb debugger after every exception.
144 Disable auto calling the pdb debugger after every exception.
145 .TP
145 .TP
146 .B \-\-quick
146 .B \-\-quick
147 Enable quick startup with no config files.
147 Enable quick startup with no config files.
148 .TP
148 .TP
149 .B \-\-no\-color\-info
149 .B \-\-no\-color\-info
150 Disable using colors for info related things.
150 Disable using colors for info related things.
151 .TP
151 .TP
152 .B \-\-no\-pprint
152 .B \-\-no\-pprint
153 Disable auto auto pretty printing of results.
153 Disable auto auto pretty printing of results.
154 .TP
154 .TP
155 .B \-\-no\-banner
155 .B \-\-no\-banner
156 Don't display a banner upon starting IPython.
156 Don't display a banner upon starting IPython.
157 .TP
157 .TP
158 .B \-\-profile=<Unicode> (BaseIPythonApplication.profile)
158 .B \-\-profile=<Unicode> (BaseIPythonApplication.profile)
159 Default: u'default'
159 Default: u'default'
160 The IPython profile to use.
160 The IPython profile to use.
161 .TP
161 .TP
162 .B \-\-c=<Unicode> (InteractiveShellApp.code_to_run)
162 .B \-\-c=<Unicode> (InteractiveShellApp.code_to_run)
163 Default: ''
163 Default: ''
164 Execute the given command string.
164 Execute the given command string.
165 .TP
165 .TP
166 .B \-\-logappend=<Unicode> (InteractiveShell.logappend)
166 .B \-\-logappend=<Unicode> (InteractiveShell.logappend)
167 Default: ''
167 Default: ''
168 Start logging to the given file in append mode.
168 Start logging to the given file in append mode.
169 .TP
169 .TP
170 .B \-\-autocall=<Enum> (InteractiveShell.autocall)
170 .B \-\-autocall=<Enum> (InteractiveShell.autocall)
171 Default: 1
171 Default: 1
172 Choices: (0, 1, 2)
172 Choices: (0, 1, 2)
173 Make IPython automatically call any callable object even if you didn't type
173 Make IPython automatically call any callable object even if you didn't type
174 explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically.
174 explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically.
175 The value can be '0' to disable the feature, '1' for 'smart' autocall, where
175 The value can be '0' to disable the feature, '1' for 'smart' autocall, where
176 it is not applied if there are no more arguments on the line, and '2' for
176 it is not applied if there are no more arguments on the line, and '2' for
177 \&'full' autocall, where all callable objects are automatically called (even
177 \&'full' autocall, where all callable objects are automatically called (even
178 if no arguments are present). The default is '1'.
178 if no arguments are present). The default is '1'.
179 .TP
179 .TP
180 .B \-\-ipython\-dir=<Unicode> (BaseIPythonApplication.ipython_dir)
180 .B \-\-ipython\-dir=<Unicode> (BaseIPythonApplication.ipython_dir)
181 Default: u'/Users/minrk/.ipython'
181 Default: u'/Users/minrk/.ipython'
182 The name of the IPython directory. This directory is used for logging
182 The name of the IPython directory. This directory is used for logging
183 configuration (through profiles), history storage, etc. The default is
183 configuration (through profiles), history storage, etc. The default is
184 usually $HOME/.ipython. This options can also be specified through the
184 usually $HOME/.ipython. This options can also be specified through the
185 environment variable IPYTHON_DIR.
185 environment variable IPYTHONDIR.
186 .TP
186 .TP
187 .B \-\-gui=<CaselessStrEnum> (TerminalIPythonApp.gui)
187 .B \-\-gui=<CaselessStrEnum> (TerminalIPythonApp.gui)
188 Default: None
188 Default: None
189 Choices: ('qt', 'wx', 'gtk')
189 Choices: ('qt', 'wx', 'gtk')
190 Enable GUI event loop integration ('qt', 'wx', 'gtk').
190 Enable GUI event loop integration ('qt', 'wx', 'gtk').
191 .TP
191 .TP
192 .B \-\-pylab=<CaselessStrEnum> (TerminalIPythonApp.pylab)
192 .B \-\-pylab=<CaselessStrEnum> (TerminalIPythonApp.pylab)
193 Default: None
193 Default: None
194 Choices: ['tk', 'qt', 'wx', 'gtk', 'osx', 'auto']
194 Choices: ['tk', 'qt', 'wx', 'gtk', 'osx', 'auto']
195 Pre-load matplotlib and numpy for interactive use, selecting a particular
195 Pre-load matplotlib and numpy for interactive use, selecting a particular
196 matplotlib backend and loop integration.
196 matplotlib backend and loop integration.
197 .TP
197 .TP
198 .B \-\-ext=<Unicode> (InteractiveShellApp.extra_extension)
198 .B \-\-ext=<Unicode> (InteractiveShellApp.extra_extension)
199 Default: ''
199 Default: ''
200 dotted module name of an IPython extension to load.
200 dotted module name of an IPython extension to load.
201 .TP
201 .TP
202 .B \-\-log\-level=<Enum> (Application.log_level)
202 .B \-\-log\-level=<Enum> (Application.log_level)
203 Default: 30
203 Default: 30
204 Choices: (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL')
204 Choices: (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL')
205 Set the log level by value or name.
205 Set the log level by value or name.
206 .TP
206 .TP
207 .B \-\-colors=<CaselessStrEnum> (InteractiveShell.colors)
207 .B \-\-colors=<CaselessStrEnum> (InteractiveShell.colors)
208 Default: 'LightBG'
208 Default: 'LightBG'
209 Choices: ('NoColor', 'LightBG', 'Linux')
209 Choices: ('NoColor', 'LightBG', 'Linux')
210 Set the color scheme (NoColor, Linux, or LightBG).
210 Set the color scheme (NoColor, Linux, or LightBG).
211 .TP
211 .TP
212 .B \-\-cache\-size=<Int> (InteractiveShell.cache_size)
212 .B \-\-cache\-size=<Int> (InteractiveShell.cache_size)
213 Default: 1000
213 Default: 1000
214 Set the size of the output cache. The default is 1000, you can change it
214 Set the size of the output cache. The default is 1000, you can change it
215 permanently in your config file. Setting it to 0 completely disables the
215 permanently in your config file. Setting it to 0 completely disables the
216 caching system, and the minimum value accepted is 20 (if you provide a value
216 caching system, and the minimum value accepted is 20 (if you provide a value
217 less than 20, it is reset to 0 and a warning is issued). This limit is
217 less than 20, it is reset to 0 and a warning is issued). This limit is
218 defined because otherwise you'll spend more time re-flushing a too small
218 defined because otherwise you'll spend more time re-flushing a too small
219 cache than working
219 cache than working
220 .TP
220 .TP
221 .B \-\-logfile=<Unicode> (InteractiveShell.logfile)
221 .B \-\-logfile=<Unicode> (InteractiveShell.logfile)
222 Default: ''
222 Default: ''
223 The name of the logfile to use.
223 The name of the logfile to use.
224 .
224 .
225 .SH EMBEDDING
225 .SH EMBEDDING
226 It is possible to start an IPython instance inside your own Python
226 It is possible to start an IPython instance inside your own Python
227 programs. In the documentation example files there are some
227 programs. In the documentation example files there are some
228 illustrations on how to do this.
228 illustrations on how to do this.
229 .br
229 .br
230 .sp 1
230 .sp 1
231 This feature allows you to evalutate dynamically the state of your
231 This feature allows you to evalutate dynamically the state of your
232 code, operate with your variables, analyze them, etc. Note however
232 code, operate with your variables, analyze them, etc. Note however
233 that any changes you make to values while in the shell do NOT
233 that any changes you make to values while in the shell do NOT
234 propagate back to the running code, so it is safe to modify your
234 propagate back to the running code, so it is safe to modify your
235 values because you won't break your code in bizarre ways by doing so.
235 values because you won't break your code in bizarre ways by doing so.
236 .SH AUTHOR
236 .SH AUTHOR
237 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
237 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
238 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
238 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
239 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
239 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
240 <jack@xiph.org>, for the Debian project (but may be used by others), and updated by
240 <jack@xiph.org>, for the Debian project (but may be used by others), and updated by
241 Min Ragan-Kelley <benjaminrk@gmail.com> for 0.11.
241 Min Ragan-Kelley <benjaminrk@gmail.com> for 0.11.
@@ -1,231 +1,231 b''
1 .. _initial config:
1 .. _initial config:
2
2
3 =============================================================
3 =============================================================
4 Outdated configuration information that might still be useful
4 Outdated configuration information that might still be useful
5 =============================================================
5 =============================================================
6
6
7 .. warning::
7 .. warning::
8
8
9 All of the information in this file is outdated. Until the new
9 All of the information in this file is outdated. Until the new
10 configuration system is better documented, this material is being kept.
10 configuration system is better documented, this material is being kept.
11
11
12 This section will help you set various things in your environment for
12 This section will help you set various things in your environment for
13 your IPython sessions to be as efficient as possible. All of IPython's
13 your IPython sessions to be as efficient as possible. All of IPython's
14 configuration information, along with several example files, is stored
14 configuration information, along with several example files, is stored
15 in a directory named by default $HOME/.config/ipython if $HOME/.config
15 in a directory named by default $HOME/.config/ipython if $HOME/.config
16 exists (Linux), or $HOME/.ipython as a secondary default. You can change this by
16 exists (Linux), or $HOME/.ipython as a secondary default. You can change this by
17 defining the environment variable IPYTHONDIR, or at runtime with the
17 defining the environment variable IPYTHONDIR, or at runtime with the
18 command line option -ipythondir.
18 command line option -ipythondir.
19
19
20 If all goes well, the first time you run IPython it should automatically create
20 If all goes well, the first time you run IPython it should automatically create
21 a user copy of the config directory for you, based on its builtin defaults. You
21 a user copy of the config directory for you, based on its builtin defaults. You
22 can look at the files it creates to learn more about configuring the
22 can look at the files it creates to learn more about configuring the
23 system. The main file you will modify to configure IPython's behavior is called
23 system. The main file you will modify to configure IPython's behavior is called
24 ipythonrc (with a .ini extension under Windows), included for reference
24 ipythonrc (with a .ini extension under Windows), included for reference
25 :ref:`here <ipythonrc>`. This file is very commented and has many variables you
25 :ref:`here <ipythonrc>`. This file is very commented and has many variables you
26 can change to suit your taste, you can find more details :ref:`here
26 can change to suit your taste, you can find more details :ref:`here
27 <customization>`. Here we discuss the basic things you will want to make sure
27 <customization>`. Here we discuss the basic things you will want to make sure
28 things are working properly from the beginning.
28 things are working properly from the beginning.
29
29
30 Color
30 Color
31 =====
31 =====
32
32
33 The default IPython configuration has most bells and whistles turned on
33 The default IPython configuration has most bells and whistles turned on
34 (they're pretty safe). But there's one that may cause problems on some
34 (they're pretty safe). But there's one that may cause problems on some
35 systems: the use of color on screen for displaying information. This is
35 systems: the use of color on screen for displaying information. This is
36 very useful, since IPython can show prompts and exception tracebacks
36 very useful, since IPython can show prompts and exception tracebacks
37 with various colors, display syntax-highlighted source code, and in
37 with various colors, display syntax-highlighted source code, and in
38 general make it easier to visually parse information.
38 general make it easier to visually parse information.
39
39
40 The following terminals seem to handle the color sequences fine:
40 The following terminals seem to handle the color sequences fine:
41
41
42 * Linux main text console, KDE Konsole, Gnome Terminal, E-term,
42 * Linux main text console, KDE Konsole, Gnome Terminal, E-term,
43 rxvt, xterm.
43 rxvt, xterm.
44 * CDE terminal (tested under Solaris). This one boldfaces light colors.
44 * CDE terminal (tested under Solaris). This one boldfaces light colors.
45 * (X)Emacs buffers. See the emacs_ section for more details on
45 * (X)Emacs buffers. See the emacs_ section for more details on
46 using IPython with (X)Emacs.
46 using IPython with (X)Emacs.
47 * A Windows (XP/2k) command prompt with pyreadline_.
47 * A Windows (XP/2k) command prompt with pyreadline_.
48 * A Windows (XP/2k) CygWin shell. Although some users have reported
48 * A Windows (XP/2k) CygWin shell. Although some users have reported
49 problems; it is not clear whether there is an issue for everyone
49 problems; it is not clear whether there is an issue for everyone
50 or only under specific configurations. If you have full color
50 or only under specific configurations. If you have full color
51 support under cygwin, please post to the IPython mailing list so
51 support under cygwin, please post to the IPython mailing list so
52 this issue can be resolved for all users.
52 this issue can be resolved for all users.
53
53
54 .. _pyreadline: https://code.launchpad.net/pyreadline
54 .. _pyreadline: https://code.launchpad.net/pyreadline
55
55
56 These have shown problems:
56 These have shown problems:
57
57
58 * Windows command prompt in WinXP/2k logged into a Linux machine via
58 * Windows command prompt in WinXP/2k logged into a Linux machine via
59 telnet or ssh.
59 telnet or ssh.
60 * Windows native command prompt in WinXP/2k, without Gary Bishop's
60 * Windows native command prompt in WinXP/2k, without Gary Bishop's
61 extensions. Once Gary's readline library is installed, the normal
61 extensions. Once Gary's readline library is installed, the normal
62 WinXP/2k command prompt works perfectly.
62 WinXP/2k command prompt works perfectly.
63
63
64 Currently the following color schemes are available:
64 Currently the following color schemes are available:
65
65
66 * NoColor: uses no color escapes at all (all escapes are empty '' ''
66 * NoColor: uses no color escapes at all (all escapes are empty '' ''
67 strings). This 'scheme' is thus fully safe to use in any terminal.
67 strings). This 'scheme' is thus fully safe to use in any terminal.
68 * Linux: works well in Linux console type environments: dark
68 * Linux: works well in Linux console type environments: dark
69 background with light fonts. It uses bright colors for
69 background with light fonts. It uses bright colors for
70 information, so it is difficult to read if you have a light
70 information, so it is difficult to read if you have a light
71 colored background.
71 colored background.
72 * LightBG: the basic colors are similar to those in the Linux scheme
72 * LightBG: the basic colors are similar to those in the Linux scheme
73 but darker. It is easy to read in terminals with light backgrounds.
73 but darker. It is easy to read in terminals with light backgrounds.
74
74
75 IPython uses colors for two main groups of things: prompts and
75 IPython uses colors for two main groups of things: prompts and
76 tracebacks which are directly printed to the terminal, and the object
76 tracebacks which are directly printed to the terminal, and the object
77 introspection system which passes large sets of data through a pager.
77 introspection system which passes large sets of data through a pager.
78
78
79 Input/Output prompts and exception tracebacks
79 Input/Output prompts and exception tracebacks
80 =============================================
80 =============================================
81
81
82 You can test whether the colored prompts and tracebacks work on your
82 You can test whether the colored prompts and tracebacks work on your
83 system interactively by typing '%colors Linux' at the prompt (use
83 system interactively by typing '%colors Linux' at the prompt (use
84 '%colors LightBG' if your terminal has a light background). If the input
84 '%colors LightBG' if your terminal has a light background). If the input
85 prompt shows garbage like::
85 prompt shows garbage like::
86
86
87 [0;32mIn [[1;32m1[0;32m]: [0;00m
87 [0;32mIn [[1;32m1[0;32m]: [0;00m
88
88
89 instead of (in color) something like::
89 instead of (in color) something like::
90
90
91 In [1]:
91 In [1]:
92
92
93 this means that your terminal doesn't properly handle color escape
93 this means that your terminal doesn't properly handle color escape
94 sequences. You can go to a 'no color' mode by typing '%colors NoColor'.
94 sequences. You can go to a 'no color' mode by typing '%colors NoColor'.
95
95
96 You can try using a different terminal emulator program (Emacs users,
96 You can try using a different terminal emulator program (Emacs users,
97 see below). To permanently set your color preferences, edit the file
97 see below). To permanently set your color preferences, edit the file
98 $IPYTHON_DIR/ipythonrc and set the colors option to the desired value.
98 $IPYTHONDIR/ipythonrc and set the colors option to the desired value.
99
99
100
100
101 Object details (types, docstrings, source code, etc.)
101 Object details (types, docstrings, source code, etc.)
102 =====================================================
102 =====================================================
103
103
104 IPython has a set of special functions for studying the objects you are working
104 IPython has a set of special functions for studying the objects you are working
105 with, discussed in detail :ref:`here <dynamic_object_info>`. But this system
105 with, discussed in detail :ref:`here <dynamic_object_info>`. But this system
106 relies on passing information which is longer than your screen through a data
106 relies on passing information which is longer than your screen through a data
107 pager, such as the common Unix less and more programs. In order to be able to
107 pager, such as the common Unix less and more programs. In order to be able to
108 see this information in color, your pager needs to be properly configured. I
108 see this information in color, your pager needs to be properly configured. I
109 strongly recommend using less instead of more, as it seems that more simply can
109 strongly recommend using less instead of more, as it seems that more simply can
110 not understand colored text correctly.
110 not understand colored text correctly.
111
111
112 In order to configure less as your default pager, do the following:
112 In order to configure less as your default pager, do the following:
113
113
114 1. Set the environment PAGER variable to less.
114 1. Set the environment PAGER variable to less.
115 2. Set the environment LESS variable to -r (plus any other options
115 2. Set the environment LESS variable to -r (plus any other options
116 you always want to pass to less by default). This tells less to
116 you always want to pass to less by default). This tells less to
117 properly interpret control sequences, which is how color
117 properly interpret control sequences, which is how color
118 information is given to your terminal.
118 information is given to your terminal.
119
119
120 For the bash shell, add to your ~/.bashrc file the lines::
120 For the bash shell, add to your ~/.bashrc file the lines::
121
121
122 export PAGER=less
122 export PAGER=less
123 export LESS=-r
123 export LESS=-r
124
124
125 For the csh or tcsh shells, add to your ~/.cshrc file the lines::
125 For the csh or tcsh shells, add to your ~/.cshrc file the lines::
126
126
127 setenv PAGER less
127 setenv PAGER less
128 setenv LESS -r
128 setenv LESS -r
129
129
130 There is similar syntax for other Unix shells, look at your system
130 There is similar syntax for other Unix shells, look at your system
131 documentation for details.
131 documentation for details.
132
132
133 If you are on a system which lacks proper data pagers (such as Windows),
133 If you are on a system which lacks proper data pagers (such as Windows),
134 IPython will use a very limited builtin pager.
134 IPython will use a very limited builtin pager.
135
135
136 .. _Prompts:
136 .. _Prompts:
137
137
138 Fine-tuning your prompt
138 Fine-tuning your prompt
139 =======================
139 =======================
140
140
141 IPython's prompts can be customized using a syntax similar to that of
141 IPython's prompts can be customized using a syntax similar to that of
142 the bash shell. Many of bash's escapes are supported, as well as a few
142 the bash shell. Many of bash's escapes are supported, as well as a few
143 additional ones. We list them below::
143 additional ones. We list them below::
144
144
145 \#
145 \#
146 the prompt/history count number. This escape is automatically
146 the prompt/history count number. This escape is automatically
147 wrapped in the coloring codes for the currently active color scheme.
147 wrapped in the coloring codes for the currently active color scheme.
148 \N
148 \N
149 the 'naked' prompt/history count number: this is just the number
149 the 'naked' prompt/history count number: this is just the number
150 itself, without any coloring applied to it. This lets you produce
150 itself, without any coloring applied to it. This lets you produce
151 numbered prompts with your own colors.
151 numbered prompts with your own colors.
152 \D
152 \D
153 the prompt/history count, with the actual digits replaced by dots.
153 the prompt/history count, with the actual digits replaced by dots.
154 Used mainly in continuation prompts (prompt_in2)
154 Used mainly in continuation prompts (prompt_in2)
155 \w
155 \w
156 the current working directory
156 the current working directory
157 \W
157 \W
158 the basename of current working directory
158 the basename of current working directory
159 \Xn
159 \Xn
160 where $n=0\ldots5.$ The current working directory, with $HOME
160 where $n=0\ldots5.$ The current working directory, with $HOME
161 replaced by ~, and filtered out to contain only $n$ path elements
161 replaced by ~, and filtered out to contain only $n$ path elements
162 \Yn
162 \Yn
163 Similar to \Xn, but with the $n+1$ element included if it is ~ (this
163 Similar to \Xn, but with the $n+1$ element included if it is ~ (this
164 is similar to the behavior of the %cn escapes in tcsh)
164 is similar to the behavior of the %cn escapes in tcsh)
165 \u
165 \u
166 the username of the current user
166 the username of the current user
167 \$
167 \$
168 if the effective UID is 0, a #, otherwise a $
168 if the effective UID is 0, a #, otherwise a $
169 \h
169 \h
170 the hostname up to the first '.'
170 the hostname up to the first '.'
171 \H
171 \H
172 the hostname
172 the hostname
173 \n
173 \n
174 a newline
174 a newline
175 \r
175 \r
176 a carriage return
176 a carriage return
177 \v
177 \v
178 IPython version string
178 IPython version string
179
179
180 In addition to these, ANSI color escapes can be insterted into the
180 In addition to these, ANSI color escapes can be insterted into the
181 prompts, as \C_ColorName. The list of valid color names is: Black, Blue,
181 prompts, as \C_ColorName. The list of valid color names is: Black, Blue,
182 Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray,
182 Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray,
183 LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White,
183 LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White,
184 Yellow.
184 Yellow.
185
185
186 Finally, IPython supports the evaluation of arbitrary expressions in
186 Finally, IPython supports the evaluation of arbitrary expressions in
187 your prompt string. The prompt strings are evaluated through the syntax
187 your prompt string. The prompt strings are evaluated through the syntax
188 of PEP 215, but basically you can use $x.y to expand the value of x.y,
188 of PEP 215, but basically you can use $x.y to expand the value of x.y,
189 and for more complicated expressions you can use braces: ${foo()+x} will
189 and for more complicated expressions you can use braces: ${foo()+x} will
190 call function foo and add to it the value of x, before putting the
190 call function foo and add to it the value of x, before putting the
191 result into your prompt. For example, using
191 result into your prompt. For example, using
192 prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: '
192 prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: '
193 will print the result of the uptime command on each prompt (assuming the
193 will print the result of the uptime command on each prompt (assuming the
194 commands module has been imported in your ipythonrc file).
194 commands module has been imported in your ipythonrc file).
195
195
196
196
197 Prompt examples
197 Prompt examples
198
198
199 The following options in an ipythonrc file will give you IPython's
199 The following options in an ipythonrc file will give you IPython's
200 default prompts::
200 default prompts::
201
201
202 prompt_in1 'In [\#]:'
202 prompt_in1 'In [\#]:'
203 prompt_in2 ' .\D.:'
203 prompt_in2 ' .\D.:'
204 prompt_out 'Out[\#]:'
204 prompt_out 'Out[\#]:'
205
205
206 which look like this::
206 which look like this::
207
207
208 In [1]: 1+2
208 In [1]: 1+2
209 Out[1]: 3
209 Out[1]: 3
210
210
211 In [2]: for i in (1,2,3):
211 In [2]: for i in (1,2,3):
212 ...: print i,
212 ...: print i,
213 ...:
213 ...:
214 1 2 3
214 1 2 3
215
215
216 These will give you a very colorful prompt with path information::
216 These will give you a very colorful prompt with path information::
217
217
218 #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>'
218 #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>'
219 prompt_in2 ' ..\D>'
219 prompt_in2 ' ..\D>'
220 prompt_out '<\#>'
220 prompt_out '<\#>'
221
221
222 which look like this::
222 which look like this::
223
223
224 fperez[~/ipython]1> 1+2
224 fperez[~/ipython]1> 1+2
225 <1> 3
225 <1> 3
226 fperez[~/ipython]2> for i in (1,2,3):
226 fperez[~/ipython]2> for i in (1,2,3):
227 ...> print i,
227 ...> print i,
228 ...>
228 ...>
229 1 2 3
229 1 2 3
230
230
231
231
@@ -1,531 +1,531 b''
1 .. _config_overview:
1 .. _config_overview:
2
2
3 ============================================
3 ============================================
4 Overview of the IPython configuration system
4 Overview of the IPython configuration system
5 ============================================
5 ============================================
6
6
7 This section describes the IPython configuration system. Starting with version
7 This section describes the IPython configuration system. Starting with version
8 0.11, IPython has a completely new configuration system that is quite
8 0.11, IPython has a completely new configuration system that is quite
9 different from the older :file:`ipythonrc` or :file:`ipy_user_conf.py`
9 different from the older :file:`ipythonrc` or :file:`ipy_user_conf.py`
10 approaches. The new configuration system was designed from scratch to address
10 approaches. The new configuration system was designed from scratch to address
11 the particular configuration needs of IPython. While there are many
11 the particular configuration needs of IPython. While there are many
12 other excellent configuration systems out there, we found that none of them
12 other excellent configuration systems out there, we found that none of them
13 met our requirements.
13 met our requirements.
14
14
15 .. warning::
15 .. warning::
16
16
17 If you are upgrading to version 0.11 of IPython, you will need to migrate
17 If you are upgrading to version 0.11 of IPython, you will need to migrate
18 your old :file:`ipythonrc` or :file:`ipy_user_conf.py` configuration files
18 your old :file:`ipythonrc` or :file:`ipy_user_conf.py` configuration files
19 to the new system. You may want to read the section on
19 to the new system. You may want to read the section on
20 :ref:`configuring IPython <configuring_ipython>`. There are also some ideas
20 :ref:`configuring IPython <configuring_ipython>`. There are also some ideas
21 `on the IPython wiki <http://wiki.ipython.org/Cookbook/Moving_config_to_IPython_0.11>`_
21 `on the IPython wiki <http://wiki.ipython.org/Cookbook/Moving_config_to_IPython_0.11>`_
22 about this.
22 about this.
23
23
24 The discussion that follows is focused on teaching users how to configure
24 The discussion that follows is focused on teaching users how to configure
25 IPython to their liking. Developers who want to know more about how they
25 IPython to their liking. Developers who want to know more about how they
26 can enable their objects to take advantage of the configuration system
26 can enable their objects to take advantage of the configuration system
27 should consult our :ref:`developer guide <developer_guide>`
27 should consult our :ref:`developer guide <developer_guide>`
28
28
29 The main concepts
29 The main concepts
30 =================
30 =================
31
31
32 There are a number of abstractions that the IPython configuration system uses.
32 There are a number of abstractions that the IPython configuration system uses.
33 Each of these abstractions is represented by a Python class.
33 Each of these abstractions is represented by a Python class.
34
34
35 Configuration object: :class:`~IPython.config.loader.Config`
35 Configuration object: :class:`~IPython.config.loader.Config`
36 A configuration object is a simple dictionary-like class that holds
36 A configuration object is a simple dictionary-like class that holds
37 configuration attributes and sub-configuration objects. These classes
37 configuration attributes and sub-configuration objects. These classes
38 support dotted attribute style access (``Foo.bar``) in addition to the
38 support dotted attribute style access (``Foo.bar``) in addition to the
39 regular dictionary style access (``Foo['bar']``). Configuration objects
39 regular dictionary style access (``Foo['bar']``). Configuration objects
40 are smart. They know how to merge themselves with other configuration
40 are smart. They know how to merge themselves with other configuration
41 objects and they automatically create sub-configuration objects.
41 objects and they automatically create sub-configuration objects.
42
42
43 Application: :class:`~IPython.config.application.Application`
43 Application: :class:`~IPython.config.application.Application`
44 An application is a process that does a specific job. The most obvious
44 An application is a process that does a specific job. The most obvious
45 application is the :command:`ipython` command line program. Each
45 application is the :command:`ipython` command line program. Each
46 application reads *one or more* configuration files and a single set of
46 application reads *one or more* configuration files and a single set of
47 command line options
47 command line options
48 and then produces a master configuration object for the application. This
48 and then produces a master configuration object for the application. This
49 configuration object is then passed to the configurable objects that the
49 configuration object is then passed to the configurable objects that the
50 application creates. These configurable objects implement the actual logic
50 application creates. These configurable objects implement the actual logic
51 of the application and know how to configure themselves given the
51 of the application and know how to configure themselves given the
52 configuration object.
52 configuration object.
53
53
54 Applications always have a `log` attribute that is a configured Logger.
54 Applications always have a `log` attribute that is a configured Logger.
55 This allows centralized logging configuration per-application.
55 This allows centralized logging configuration per-application.
56
56
57 Configurable: :class:`~IPython.config.configurable.Configurable`
57 Configurable: :class:`~IPython.config.configurable.Configurable`
58 A configurable is a regular Python class that serves as a base class for
58 A configurable is a regular Python class that serves as a base class for
59 all main classes in an application. The
59 all main classes in an application. The
60 :class:`~IPython.config.configurable.Configurable` base class is
60 :class:`~IPython.config.configurable.Configurable` base class is
61 lightweight and only does one things.
61 lightweight and only does one things.
62
62
63 This :class:`~IPython.config.configurable.Configurable` is a subclass
63 This :class:`~IPython.config.configurable.Configurable` is a subclass
64 of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure
64 of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure
65 itself. Class level traits with the metadata ``config=True`` become
65 itself. Class level traits with the metadata ``config=True`` become
66 values that can be configured from the command line and configuration
66 values that can be configured from the command line and configuration
67 files.
67 files.
68
68
69 Developers create :class:`~IPython.config.configurable.Configurable`
69 Developers create :class:`~IPython.config.configurable.Configurable`
70 subclasses that implement all of the logic in the application. Each of
70 subclasses that implement all of the logic in the application. Each of
71 these subclasses has its own configuration information that controls how
71 these subclasses has its own configuration information that controls how
72 instances are created.
72 instances are created.
73
73
74 Singletons: :class:`~IPython.config.configurable.SingletonConfigurable`
74 Singletons: :class:`~IPython.config.configurable.SingletonConfigurable`
75 Any object for which there is a single canonical instance. These are
75 Any object for which there is a single canonical instance. These are
76 just like Configurables, except they have a class method
76 just like Configurables, except they have a class method
77 :meth:`~IPython.config.configurable.SingletonConfigurable.instance`,
77 :meth:`~IPython.config.configurable.SingletonConfigurable.instance`,
78 that returns the current active instance (or creates one if it
78 that returns the current active instance (or creates one if it
79 does not exist). Examples of singletons include
79 does not exist). Examples of singletons include
80 :class:`~IPython.config.application.Application`s and
80 :class:`~IPython.config.application.Application`s and
81 :class:`~IPython.core.interactiveshell.InteractiveShell`. This lets
81 :class:`~IPython.core.interactiveshell.InteractiveShell`. This lets
82 objects easily connect to the current running Application without passing
82 objects easily connect to the current running Application without passing
83 objects around everywhere. For instance, to get the current running
83 objects around everywhere. For instance, to get the current running
84 Application instance, simply do: ``app = Application.instance()``.
84 Application instance, simply do: ``app = Application.instance()``.
85
85
86
86
87 .. note::
87 .. note::
88
88
89 Singletons are not strictly enforced - you can have many instances
89 Singletons are not strictly enforced - you can have many instances
90 of a given singleton class, but the :meth:`instance` method will always
90 of a given singleton class, but the :meth:`instance` method will always
91 return the same one.
91 return the same one.
92
92
93 Having described these main concepts, we can now state the main idea in our
93 Having described these main concepts, we can now state the main idea in our
94 configuration system: *"configuration" allows the default values of class
94 configuration system: *"configuration" allows the default values of class
95 attributes to be controlled on a class by class basis*. Thus all instances of
95 attributes to be controlled on a class by class basis*. Thus all instances of
96 a given class are configured in the same way. Furthermore, if two instances
96 a given class are configured in the same way. Furthermore, if two instances
97 need to be configured differently, they need to be instances of two different
97 need to be configured differently, they need to be instances of two different
98 classes. While this model may seem a bit restrictive, we have found that it
98 classes. While this model may seem a bit restrictive, we have found that it
99 expresses most things that need to be configured extremely well. However, it
99 expresses most things that need to be configured extremely well. However, it
100 is possible to create two instances of the same class that have different
100 is possible to create two instances of the same class that have different
101 trait values. This is done by overriding the configuration.
101 trait values. This is done by overriding the configuration.
102
102
103 Now, we show what our configuration objects and files look like.
103 Now, we show what our configuration objects and files look like.
104
104
105 Configuration objects and files
105 Configuration objects and files
106 ===============================
106 ===============================
107
107
108 A configuration file is simply a pure Python file that sets the attributes
108 A configuration file is simply a pure Python file that sets the attributes
109 of a global, pre-created configuration object. This configuration object is a
109 of a global, pre-created configuration object. This configuration object is a
110 :class:`~IPython.config.loader.Config` instance. While in a configuration
110 :class:`~IPython.config.loader.Config` instance. While in a configuration
111 file, to get a reference to this object, simply call the :func:`get_config`
111 file, to get a reference to this object, simply call the :func:`get_config`
112 function. We inject this function into the global namespace that the
112 function. We inject this function into the global namespace that the
113 configuration file is executed in.
113 configuration file is executed in.
114
114
115 Here is an example of a super simple configuration file that does nothing::
115 Here is an example of a super simple configuration file that does nothing::
116
116
117 c = get_config()
117 c = get_config()
118
118
119 Once you get a reference to the configuration object, you simply set
119 Once you get a reference to the configuration object, you simply set
120 attributes on it. All you have to know is:
120 attributes on it. All you have to know is:
121
121
122 * The name of each attribute.
122 * The name of each attribute.
123 * The type of each attribute.
123 * The type of each attribute.
124
124
125 The answers to these two questions are provided by the various
125 The answers to these two questions are provided by the various
126 :class:`~IPython.config.configurable.Configurable` subclasses that an
126 :class:`~IPython.config.configurable.Configurable` subclasses that an
127 application uses. Let's look at how this would work for a simple configurable
127 application uses. Let's look at how this would work for a simple configurable
128 subclass::
128 subclass::
129
129
130 # Sample configurable:
130 # Sample configurable:
131 from IPython.config.configurable import Configurable
131 from IPython.config.configurable import Configurable
132 from IPython.utils.traitlets import Int, Float, Unicode, Bool
132 from IPython.utils.traitlets import Int, Float, Unicode, Bool
133
133
134 class MyClass(Configurable):
134 class MyClass(Configurable):
135 name = Unicode(u'defaultname', config=True)
135 name = Unicode(u'defaultname', config=True)
136 ranking = Int(0, config=True)
136 ranking = Int(0, config=True)
137 value = Float(99.0)
137 value = Float(99.0)
138 # The rest of the class implementation would go here..
138 # The rest of the class implementation would go here..
139
139
140 In this example, we see that :class:`MyClass` has three attributes, two
140 In this example, we see that :class:`MyClass` has three attributes, two
141 of whom (``name``, ``ranking``) can be configured. All of the attributes
141 of whom (``name``, ``ranking``) can be configured. All of the attributes
142 are given types and default values. If a :class:`MyClass` is instantiated,
142 are given types and default values. If a :class:`MyClass` is instantiated,
143 but not configured, these default values will be used. But let's see how
143 but not configured, these default values will be used. But let's see how
144 to configure this class in a configuration file::
144 to configure this class in a configuration file::
145
145
146 # Sample config file
146 # Sample config file
147 c = get_config()
147 c = get_config()
148
148
149 c.MyClass.name = 'coolname'
149 c.MyClass.name = 'coolname'
150 c.MyClass.ranking = 10
150 c.MyClass.ranking = 10
151
151
152 After this configuration file is loaded, the values set in it will override
152 After this configuration file is loaded, the values set in it will override
153 the class defaults anytime a :class:`MyClass` is created. Furthermore,
153 the class defaults anytime a :class:`MyClass` is created. Furthermore,
154 these attributes will be type checked and validated anytime they are set.
154 these attributes will be type checked and validated anytime they are set.
155 This type checking is handled by the :mod:`IPython.utils.traitlets` module,
155 This type checking is handled by the :mod:`IPython.utils.traitlets` module,
156 which provides the :class:`Unicode`, :class:`Int` and :class:`Float` types.
156 which provides the :class:`Unicode`, :class:`Int` and :class:`Float` types.
157 In addition to these traitlets, the :mod:`IPython.utils.traitlets` provides
157 In addition to these traitlets, the :mod:`IPython.utils.traitlets` provides
158 traitlets for a number of other types.
158 traitlets for a number of other types.
159
159
160 .. note::
160 .. note::
161
161
162 Underneath the hood, the :class:`Configurable` base class is a subclass of
162 Underneath the hood, the :class:`Configurable` base class is a subclass of
163 :class:`IPython.utils.traitlets.HasTraits`. The
163 :class:`IPython.utils.traitlets.HasTraits`. The
164 :mod:`IPython.utils.traitlets` module is a lightweight version of
164 :mod:`IPython.utils.traitlets` module is a lightweight version of
165 :mod:`enthought.traits`. Our implementation is a pure Python subset
165 :mod:`enthought.traits`. Our implementation is a pure Python subset
166 (mostly API compatible) of :mod:`enthought.traits` that does not have any
166 (mostly API compatible) of :mod:`enthought.traits` that does not have any
167 of the automatic GUI generation capabilities. Our plan is to achieve 100%
167 of the automatic GUI generation capabilities. Our plan is to achieve 100%
168 API compatibility to enable the actual :mod:`enthought.traits` to
168 API compatibility to enable the actual :mod:`enthought.traits` to
169 eventually be used instead. Currently, we cannot use
169 eventually be used instead. Currently, we cannot use
170 :mod:`enthought.traits` as we are committed to the core of IPython being
170 :mod:`enthought.traits` as we are committed to the core of IPython being
171 pure Python.
171 pure Python.
172
172
173 It should be very clear at this point what the naming convention is for
173 It should be very clear at this point what the naming convention is for
174 configuration attributes::
174 configuration attributes::
175
175
176 c.ClassName.attribute_name = attribute_value
176 c.ClassName.attribute_name = attribute_value
177
177
178 Here, ``ClassName`` is the name of the class whose configuration attribute you
178 Here, ``ClassName`` is the name of the class whose configuration attribute you
179 want to set, ``attribute_name`` is the name of the attribute you want to set
179 want to set, ``attribute_name`` is the name of the attribute you want to set
180 and ``attribute_value`` the the value you want it to have. The ``ClassName``
180 and ``attribute_value`` the the value you want it to have. The ``ClassName``
181 attribute of ``c`` is not the actual class, but instead is another
181 attribute of ``c`` is not the actual class, but instead is another
182 :class:`~IPython.config.loader.Config` instance.
182 :class:`~IPython.config.loader.Config` instance.
183
183
184 .. note::
184 .. note::
185
185
186 The careful reader may wonder how the ``ClassName`` (``MyClass`` in
186 The careful reader may wonder how the ``ClassName`` (``MyClass`` in
187 the above example) attribute of the configuration object ``c`` gets
187 the above example) attribute of the configuration object ``c`` gets
188 created. These attributes are created on the fly by the
188 created. These attributes are created on the fly by the
189 :class:`~IPython.config.loader.Config` instance, using a simple naming
189 :class:`~IPython.config.loader.Config` instance, using a simple naming
190 convention. Any attribute of a :class:`~IPython.config.loader.Config`
190 convention. Any attribute of a :class:`~IPython.config.loader.Config`
191 instance whose name begins with an uppercase character is assumed to be a
191 instance whose name begins with an uppercase character is assumed to be a
192 sub-configuration and a new empty :class:`~IPython.config.loader.Config`
192 sub-configuration and a new empty :class:`~IPython.config.loader.Config`
193 instance is dynamically created for that attribute. This allows deeply
193 instance is dynamically created for that attribute. This allows deeply
194 hierarchical information created easily (``c.Foo.Bar.value``) on the fly.
194 hierarchical information created easily (``c.Foo.Bar.value``) on the fly.
195
195
196 Configuration files inheritance
196 Configuration files inheritance
197 ===============================
197 ===============================
198
198
199 Let's say you want to have different configuration files for various purposes.
199 Let's say you want to have different configuration files for various purposes.
200 Our configuration system makes it easy for one configuration file to inherit
200 Our configuration system makes it easy for one configuration file to inherit
201 the information in another configuration file. The :func:`load_subconfig`
201 the information in another configuration file. The :func:`load_subconfig`
202 command can be used in a configuration file for this purpose. Here is a simple
202 command can be used in a configuration file for this purpose. Here is a simple
203 example that loads all of the values from the file :file:`base_config.py`::
203 example that loads all of the values from the file :file:`base_config.py`::
204
204
205 # base_config.py
205 # base_config.py
206 c = get_config()
206 c = get_config()
207 c.MyClass.name = 'coolname'
207 c.MyClass.name = 'coolname'
208 c.MyClass.ranking = 100
208 c.MyClass.ranking = 100
209
209
210 into the configuration file :file:`main_config.py`::
210 into the configuration file :file:`main_config.py`::
211
211
212 # main_config.py
212 # main_config.py
213 c = get_config()
213 c = get_config()
214
214
215 # Load everything from base_config.py
215 # Load everything from base_config.py
216 load_subconfig('base_config.py')
216 load_subconfig('base_config.py')
217
217
218 # Now override one of the values
218 # Now override one of the values
219 c.MyClass.name = 'bettername'
219 c.MyClass.name = 'bettername'
220
220
221 In a situation like this the :func:`load_subconfig` makes sure that the
221 In a situation like this the :func:`load_subconfig` makes sure that the
222 search path for sub-configuration files is inherited from that of the parent.
222 search path for sub-configuration files is inherited from that of the parent.
223 Thus, you can typically put the two in the same directory and everything will
223 Thus, you can typically put the two in the same directory and everything will
224 just work.
224 just work.
225
225
226 You can also load configuration files by profile, for instance:
226 You can also load configuration files by profile, for instance:
227
227
228 .. sourcecode:: python
228 .. sourcecode:: python
229
229
230 load_subconfig('ipython_config.py', profile='default')
230 load_subconfig('ipython_config.py', profile='default')
231
231
232 to inherit your default configuration as a starting point.
232 to inherit your default configuration as a starting point.
233
233
234
234
235 Class based configuration inheritance
235 Class based configuration inheritance
236 =====================================
236 =====================================
237
237
238 There is another aspect of configuration where inheritance comes into play.
238 There is another aspect of configuration where inheritance comes into play.
239 Sometimes, your classes will have an inheritance hierarchy that you want
239 Sometimes, your classes will have an inheritance hierarchy that you want
240 to be reflected in the configuration system. Here is a simple example::
240 to be reflected in the configuration system. Here is a simple example::
241
241
242 from IPython.config.configurable import Configurable
242 from IPython.config.configurable import Configurable
243 from IPython.utils.traitlets import Int, Float, Unicode, Bool
243 from IPython.utils.traitlets import Int, Float, Unicode, Bool
244
244
245 class Foo(Configurable):
245 class Foo(Configurable):
246 name = Unicode(u'fooname', config=True)
246 name = Unicode(u'fooname', config=True)
247 value = Float(100.0, config=True)
247 value = Float(100.0, config=True)
248
248
249 class Bar(Foo):
249 class Bar(Foo):
250 name = Unicode(u'barname', config=True)
250 name = Unicode(u'barname', config=True)
251 othervalue = Int(0, config=True)
251 othervalue = Int(0, config=True)
252
252
253 Now, we can create a configuration file to configure instances of :class:`Foo`
253 Now, we can create a configuration file to configure instances of :class:`Foo`
254 and :class:`Bar`::
254 and :class:`Bar`::
255
255
256 # config file
256 # config file
257 c = get_config()
257 c = get_config()
258
258
259 c.Foo.name = u'bestname'
259 c.Foo.name = u'bestname'
260 c.Bar.othervalue = 10
260 c.Bar.othervalue = 10
261
261
262 This class hierarchy and configuration file accomplishes the following:
262 This class hierarchy and configuration file accomplishes the following:
263
263
264 * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be
264 * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be
265 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also
265 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also
266 picks up the configuration information for :class:`Foo`.
266 picks up the configuration information for :class:`Foo`.
267 * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be
267 * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be
268 ``100.0``, which is the value specified as the class default.
268 ``100.0``, which is the value specified as the class default.
269 * The default value for :attr:`Bar.othervalue` will be 10 as set in the
269 * The default value for :attr:`Bar.othervalue` will be 10 as set in the
270 configuration file. Because :class:`Foo` is the parent of :class:`Bar`
270 configuration file. Because :class:`Foo` is the parent of :class:`Bar`
271 it doesn't know anything about the :attr:`othervalue` attribute.
271 it doesn't know anything about the :attr:`othervalue` attribute.
272
272
273
273
274 .. _ipython_dir:
274 .. _ipython_dir:
275
275
276 Configuration file location
276 Configuration file location
277 ===========================
277 ===========================
278
278
279 So where should you put your configuration files? IPython uses "profiles" for
279 So where should you put your configuration files? IPython uses "profiles" for
280 configuration, and by default, all profiles will be stored in the so called
280 configuration, and by default, all profiles will be stored in the so called
281 "IPython directory". The location of this directory is determined by the
281 "IPython directory". The location of this directory is determined by the
282 following algorithm:
282 following algorithm:
283
283
284 * If the ``ipython_dir`` command line flag is given, its value is used.
284 * If the ``ipython_dir`` command line flag is given, its value is used.
285
285
286 * If not, the value returned by :func:`IPython.utils.path.get_ipython_dir`
286 * If not, the value returned by :func:`IPython.utils.path.get_ipython_dir`
287 is used. This function will first look at the :envvar:`IPYTHON_DIR`
287 is used. This function will first look at the :envvar:`IPYTHONDIR`
288 environment variable and then default to a platform-specific default.
288 environment variable and then default to a platform-specific default.
289
289
290 On posix systems (Linux, Unix, etc.), IPython respects the ``$XDG_CONFIG_HOME``
290 On posix systems (Linux, Unix, etc.), IPython respects the ``$XDG_CONFIG_HOME``
291 part of the `XDG Base Directory`_ specification. If ``$XDG_CONFIG_HOME`` is
291 part of the `XDG Base Directory`_ specification. If ``$XDG_CONFIG_HOME`` is
292 defined and exists ( ``XDG_CONFIG_HOME`` has a default interpretation of
292 defined and exists ( ``XDG_CONFIG_HOME`` has a default interpretation of
293 :file:`$HOME/.config`), then IPython's config directory will be located in
293 :file:`$HOME/.config`), then IPython's config directory will be located in
294 :file:`$XDG_CONFIG_HOME/ipython`. If users still have an IPython directory
294 :file:`$XDG_CONFIG_HOME/ipython`. If users still have an IPython directory
295 in :file:`$HOME/.ipython`, then that will be used. in preference to the
295 in :file:`$HOME/.ipython`, then that will be used. in preference to the
296 system default.
296 system default.
297
297
298 For most users, the default value will simply be something like
298 For most users, the default value will simply be something like
299 :file:`$HOME/.config/ipython` on Linux, or :file:`$HOME/.ipython`
299 :file:`$HOME/.config/ipython` on Linux, or :file:`$HOME/.ipython`
300 elsewhere.
300 elsewhere.
301
301
302 Once the location of the IPython directory has been determined, you need to know
302 Once the location of the IPython directory has been determined, you need to know
303 which profile you are using. For users with a single configuration, this will
303 which profile you are using. For users with a single configuration, this will
304 simply be 'default', and will be located in
304 simply be 'default', and will be located in
305 :file:`<IPYTHON_DIR>/profile_default`.
305 :file:`<IPYTHONDIR>/profile_default`.
306
306
307 The next thing you need to know is what to call your configuration file. The
307 The next thing you need to know is what to call your configuration file. The
308 basic idea is that each application has its own default configuration filename.
308 basic idea is that each application has its own default configuration filename.
309 The default named used by the :command:`ipython` command line program is
309 The default named used by the :command:`ipython` command line program is
310 :file:`ipython_config.py`, and *all* IPython applications will use this file.
310 :file:`ipython_config.py`, and *all* IPython applications will use this file.
311 Other applications, such as the parallel :command:`ipcluster` scripts or the
311 Other applications, such as the parallel :command:`ipcluster` scripts or the
312 QtConsole will load their own config files *after* :file:`ipython_config.py`. To
312 QtConsole will load their own config files *after* :file:`ipython_config.py`. To
313 load a particular configuration file instead of the default, the name can be
313 load a particular configuration file instead of the default, the name can be
314 overridden by the ``config_file`` command line flag.
314 overridden by the ``config_file`` command line flag.
315
315
316 To generate the default configuration files, do::
316 To generate the default configuration files, do::
317
317
318 $> ipython profile create
318 $> ipython profile create
319
319
320 and you will have a default :file:`ipython_config.py` in your IPython directory
320 and you will have a default :file:`ipython_config.py` in your IPython directory
321 under :file:`profile_default`. If you want the default config files for the
321 under :file:`profile_default`. If you want the default config files for the
322 :mod:`IPython.parallel` applications, add ``--parallel`` to the end of the
322 :mod:`IPython.parallel` applications, add ``--parallel`` to the end of the
323 command-line args.
323 command-line args.
324
324
325 .. _Profiles:
325 .. _Profiles:
326
326
327 Profiles
327 Profiles
328 ========
328 ========
329
329
330 A profile is a directory containing configuration and runtime files, such as
330 A profile is a directory containing configuration and runtime files, such as
331 logs, connection info for the parallel apps, and your IPython command history.
331 logs, connection info for the parallel apps, and your IPython command history.
332
332
333 The idea is that users often want to maintain a set of configuration files for
333 The idea is that users often want to maintain a set of configuration files for
334 different purposes: one for doing numerical computing with NumPy and SciPy and
334 different purposes: one for doing numerical computing with NumPy and SciPy and
335 another for doing symbolic computing with SymPy. Profiles make it easy to keep a
335 another for doing symbolic computing with SymPy. Profiles make it easy to keep a
336 separate configuration files, logs, and histories for each of these purposes.
336 separate configuration files, logs, and histories for each of these purposes.
337
337
338 Let's start by showing how a profile is used:
338 Let's start by showing how a profile is used:
339
339
340 .. code-block:: bash
340 .. code-block:: bash
341
341
342 $ ipython --profile=sympy
342 $ ipython --profile=sympy
343
343
344 This tells the :command:`ipython` command line program to get its configuration
344 This tells the :command:`ipython` command line program to get its configuration
345 from the "sympy" profile. The file names for various profiles do not change. The
345 from the "sympy" profile. The file names for various profiles do not change. The
346 only difference is that profiles are named in a special way. In the case above,
346 only difference is that profiles are named in a special way. In the case above,
347 the "sympy" profile means looking for :file:`ipython_config.py` in :file:`<IPYTHON_DIR>/profile_sympy`.
347 the "sympy" profile means looking for :file:`ipython_config.py` in :file:`<IPYTHONDIR>/profile_sympy`.
348
348
349 The general pattern is this: simply create a new profile with:
349 The general pattern is this: simply create a new profile with:
350
350
351 .. code-block:: bash
351 .. code-block:: bash
352
352
353 ipython profile create <name>
353 ipython profile create <name>
354
354
355 which adds a directory called ``profile_<name>`` to your IPython directory. Then
355 which adds a directory called ``profile_<name>`` to your IPython directory. Then
356 you can load this profile by adding ``--profile=<name>`` to your command line
356 you can load this profile by adding ``--profile=<name>`` to your command line
357 options. Profiles are supported by all IPython applications.
357 options. Profiles are supported by all IPython applications.
358
358
359 IPython ships with some sample profiles in :file:`IPython/config/profile`. If
359 IPython ships with some sample profiles in :file:`IPython/config/profile`. If
360 you create profiles with the name of one of our shipped profiles, these config
360 you create profiles with the name of one of our shipped profiles, these config
361 files will be copied over instead of starting with the automatically generated
361 files will be copied over instead of starting with the automatically generated
362 config files.
362 config files.
363
363
364 Security Files
364 Security Files
365 --------------
365 --------------
366
366
367 If you are using the notebook, qtconsole, or parallel code, IPython stores
367 If you are using the notebook, qtconsole, or parallel code, IPython stores
368 connection information in small JSON files in the active profile's security
368 connection information in small JSON files in the active profile's security
369 directory. This directory is made private, so only you can see the files inside. If
369 directory. This directory is made private, so only you can see the files inside. If
370 you need to move connection files around to other computers, this is where they will
370 you need to move connection files around to other computers, this is where they will
371 be. If you want your code to be able to open security files by name, we have a
371 be. If you want your code to be able to open security files by name, we have a
372 convenience function :func:`IPython.utils.path.get_security_file`, which will return
372 convenience function :func:`IPython.utils.path.get_security_file`, which will return
373 the absolute path to a security file from its filename and [optionally] profile
373 the absolute path to a security file from its filename and [optionally] profile
374 name.
374 name.
375
375
376 Startup Files
376 Startup Files
377 -------------
377 -------------
378
378
379 If you want some code to be run at the beginning of every IPython session with a
379 If you want some code to be run at the beginning of every IPython session with a
380 particular profile, the easiest way is to add Python (.py) or IPython (.ipy) scripts
380 particular profile, the easiest way is to add Python (.py) or IPython (.ipy) scripts
381 to your :file:`<profile>/startup` directory. Files in this directory will always be
381 to your :file:`<profile>/startup` directory. Files in this directory will always be
382 executed as soon as the IPython shell is constructed, and before any other code or
382 executed as soon as the IPython shell is constructed, and before any other code or
383 scripts you have specified. If you have multiple files in the startup directory,
383 scripts you have specified. If you have multiple files in the startup directory,
384 they will be run in lexicographical order, so you can control the ordering by adding
384 they will be run in lexicographical order, so you can control the ordering by adding
385 a '00-' prefix.
385 a '00-' prefix.
386
386
387 .. note::
387 .. note::
388
388
389 Automatic startup files are new in IPython 0.12. Use the
389 Automatic startup files are new in IPython 0.12. Use the
390 InteractiveShellApp.exec_files configurable for similar behavior in 0.11.
390 InteractiveShellApp.exec_files configurable for similar behavior in 0.11.
391
391
392
392
393 .. _commandline:
393 .. _commandline:
394
394
395 Command-line arguments
395 Command-line arguments
396 ======================
396 ======================
397
397
398 IPython exposes *all* configurable options on the command-line. The command-line
398 IPython exposes *all* configurable options on the command-line. The command-line
399 arguments are generated from the Configurable traits of the classes associated
399 arguments are generated from the Configurable traits of the classes associated
400 with a given Application. Configuring IPython from the command-line may look
400 with a given Application. Configuring IPython from the command-line may look
401 very similar to an IPython config file
401 very similar to an IPython config file
402
402
403 IPython applications use a parser called
403 IPython applications use a parser called
404 :class:`~IPython.config.loader.KeyValueLoader` to load values into a Config
404 :class:`~IPython.config.loader.KeyValueLoader` to load values into a Config
405 object. Values are assigned in much the same way as in a config file:
405 object. Values are assigned in much the same way as in a config file:
406
406
407 .. code-block:: bash
407 .. code-block:: bash
408
408
409 $> ipython --InteractiveShell.use_readline=False --BaseIPythonApplication.profile='myprofile'
409 $> ipython --InteractiveShell.use_readline=False --BaseIPythonApplication.profile='myprofile'
410
410
411 Is the same as adding:
411 Is the same as adding:
412
412
413 .. sourcecode:: python
413 .. sourcecode:: python
414
414
415 c.InteractiveShell.use_readline=False
415 c.InteractiveShell.use_readline=False
416 c.BaseIPythonApplication.profile='myprofile'
416 c.BaseIPythonApplication.profile='myprofile'
417
417
418 to your config file. Key/Value arguments *always* take a value, separated by '='
418 to your config file. Key/Value arguments *always* take a value, separated by '='
419 and no spaces.
419 and no spaces.
420
420
421 Common Arguments
421 Common Arguments
422 ****************
422 ****************
423
423
424 Since the strictness and verbosity of the KVLoader above are not ideal for everyday
424 Since the strictness and verbosity of the KVLoader above are not ideal for everyday
425 use, common arguments can be specified as flags_ or aliases_.
425 use, common arguments can be specified as flags_ or aliases_.
426
426
427 Flags and Aliases are handled by :mod:`argparse` instead, allowing for more flexible
427 Flags and Aliases are handled by :mod:`argparse` instead, allowing for more flexible
428 parsing. In general, flags and aliases are prefixed by ``--``, except for those
428 parsing. In general, flags and aliases are prefixed by ``--``, except for those
429 that are single characters, in which case they can be specified with a single ``-``, e.g.:
429 that are single characters, in which case they can be specified with a single ``-``, e.g.:
430
430
431 .. code-block:: bash
431 .. code-block:: bash
432
432
433 $> ipython -i -c "import numpy; x=numpy.linspace(0,1)" --profile testing --colors=lightbg
433 $> ipython -i -c "import numpy; x=numpy.linspace(0,1)" --profile testing --colors=lightbg
434
434
435 Aliases
435 Aliases
436 -------
436 -------
437
437
438 For convenience, applications have a mapping of commonly used traits, so you don't have
438 For convenience, applications have a mapping of commonly used traits, so you don't have
439 to specify the whole class name:
439 to specify the whole class name:
440
440
441 .. code-block:: bash
441 .. code-block:: bash
442
442
443 $> ipython --profile myprofile
443 $> ipython --profile myprofile
444 # and
444 # and
445 $> ipython --profile='myprofile'
445 $> ipython --profile='myprofile'
446 # are equivalent to
446 # are equivalent to
447 $> ipython --BaseIPythonApplication.profile='myprofile'
447 $> ipython --BaseIPythonApplication.profile='myprofile'
448
448
449 Flags
449 Flags
450 -----
450 -----
451
451
452 Applications can also be passed **flags**. Flags are options that take no
452 Applications can also be passed **flags**. Flags are options that take no
453 arguments. They are simply wrappers for
453 arguments. They are simply wrappers for
454 setting one or more configurables with predefined values, often True/False.
454 setting one or more configurables with predefined values, often True/False.
455
455
456 For instance:
456 For instance:
457
457
458 .. code-block:: bash
458 .. code-block:: bash
459
459
460 $> ipcontroller --debug
460 $> ipcontroller --debug
461 # is equivalent to
461 # is equivalent to
462 $> ipcontroller --Application.log_level=DEBUG
462 $> ipcontroller --Application.log_level=DEBUG
463 # and
463 # and
464 $> ipython --pylab
464 $> ipython --pylab
465 # is equivalent to
465 # is equivalent to
466 $> ipython --pylab=auto
466 $> ipython --pylab=auto
467 # or
467 # or
468 $> ipython --no-banner
468 $> ipython --no-banner
469 # is equivalent to
469 # is equivalent to
470 $> ipython --TerminalIPythonApp.display_banner=False
470 $> ipython --TerminalIPythonApp.display_banner=False
471
471
472 Subcommands
472 Subcommands
473 ***********
473 ***********
474
474
475
475
476 Some IPython applications have **subcommands**. Subcommands are modeled after
476 Some IPython applications have **subcommands**. Subcommands are modeled after
477 :command:`git`, and are called with the form :command:`command subcommand
477 :command:`git`, and are called with the form :command:`command subcommand
478 [...args]`. Currently, the QtConsole is a subcommand of terminal IPython:
478 [...args]`. Currently, the QtConsole is a subcommand of terminal IPython:
479
479
480 .. code-block:: bash
480 .. code-block:: bash
481
481
482 $> ipython qtconsole --profile=myprofile
482 $> ipython qtconsole --profile=myprofile
483
483
484 and :command:`ipcluster` is simply a wrapper for its various subcommands (start,
484 and :command:`ipcluster` is simply a wrapper for its various subcommands (start,
485 stop, engines).
485 stop, engines).
486
486
487 .. code-block:: bash
487 .. code-block:: bash
488
488
489 $> ipcluster start --profile=myprofile --n=4
489 $> ipcluster start --profile=myprofile --n=4
490
490
491
491
492 To see a list of the available aliases, flags, and subcommands for an IPython application, simply pass ``-h`` or ``--help``. And to see the full list of configurable options (*very* long), pass ``--help-all``.
492 To see a list of the available aliases, flags, and subcommands for an IPython application, simply pass ``-h`` or ``--help``. And to see the full list of configurable options (*very* long), pass ``--help-all``.
493
493
494
494
495 Design requirements
495 Design requirements
496 ===================
496 ===================
497
497
498 Here are the main requirements we wanted our configuration system to have:
498 Here are the main requirements we wanted our configuration system to have:
499
499
500 * Support for hierarchical configuration information.
500 * Support for hierarchical configuration information.
501
501
502 * Full integration with command line option parsers. Often, you want to read
502 * Full integration with command line option parsers. Often, you want to read
503 a configuration file, but then override some of the values with command line
503 a configuration file, but then override some of the values with command line
504 options. Our configuration system automates this process and allows each
504 options. Our configuration system automates this process and allows each
505 command line option to be linked to a particular attribute in the
505 command line option to be linked to a particular attribute in the
506 configuration hierarchy that it will override.
506 configuration hierarchy that it will override.
507
507
508 * Configuration files that are themselves valid Python code. This accomplishes
508 * Configuration files that are themselves valid Python code. This accomplishes
509 many things. First, it becomes possible to put logic in your configuration
509 many things. First, it becomes possible to put logic in your configuration
510 files that sets attributes based on your operating system, network setup,
510 files that sets attributes based on your operating system, network setup,
511 Python version, etc. Second, Python has a super simple syntax for accessing
511 Python version, etc. Second, Python has a super simple syntax for accessing
512 hierarchical data structures, namely regular attribute access
512 hierarchical data structures, namely regular attribute access
513 (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to
513 (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to
514 import configuration attributes from one configuration file to another.
514 import configuration attributes from one configuration file to another.
515 Fourth, even though Python is dynamically typed, it does have types that can
515 Fourth, even though Python is dynamically typed, it does have types that can
516 be checked at runtime. Thus, a ``1`` in a config file is the integer '1',
516 be checked at runtime. Thus, a ``1`` in a config file is the integer '1',
517 while a ``'1'`` is a string.
517 while a ``'1'`` is a string.
518
518
519 * A fully automated method for getting the configuration information to the
519 * A fully automated method for getting the configuration information to the
520 classes that need it at runtime. Writing code that walks a configuration
520 classes that need it at runtime. Writing code that walks a configuration
521 hierarchy to extract a particular attribute is painful. When you have
521 hierarchy to extract a particular attribute is painful. When you have
522 complex configuration information with hundreds of attributes, this makes
522 complex configuration information with hundreds of attributes, this makes
523 you want to cry.
523 you want to cry.
524
524
525 * Type checking and validation that doesn't require the entire configuration
525 * Type checking and validation that doesn't require the entire configuration
526 hierarchy to be specified statically before runtime. Python is a very
526 hierarchy to be specified statically before runtime. Python is a very
527 dynamic language and you don't always know everything that needs to be
527 dynamic language and you don't always know everything that needs to be
528 configured when a program starts.
528 configured when a program starts.
529
529
530
530
531 .. _`XDG Base Directory`: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
531 .. _`XDG Base Directory`: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
@@ -1,609 +1,609 b''
1 .. _qtconsole:
1 .. _qtconsole:
2
2
3 =========================
3 =========================
4 A Qt Console for IPython
4 A Qt Console for IPython
5 =========================
5 =========================
6
6
7 We now have a version of IPython, using the new two-process :ref:`ZeroMQ Kernel
7 We now have a version of IPython, using the new two-process :ref:`ZeroMQ Kernel
8 <ipythonzmq>`, running in a PyQt_ GUI. This is a very lightweight widget that
8 <ipythonzmq>`, running in a PyQt_ GUI. This is a very lightweight widget that
9 largely feels like a terminal, but provides a number of enhancements only
9 largely feels like a terminal, but provides a number of enhancements only
10 possible in a GUI, such as inline figures, proper multiline editing with syntax
10 possible in a GUI, such as inline figures, proper multiline editing with syntax
11 highlighting, graphical calltips, and much more.
11 highlighting, graphical calltips, and much more.
12
12
13 .. figure:: ../_static/qtconsole.png
13 .. figure:: ../_static/qtconsole.png
14 :width: 400px
14 :width: 400px
15 :alt: IPython Qt console with embedded plots
15 :alt: IPython Qt console with embedded plots
16 :align: center
16 :align: center
17 :target: ../_static/qtconsole.png
17 :target: ../_static/qtconsole.png
18
18
19 The Qt console for IPython, using inline matplotlib plots.
19 The Qt console for IPython, using inline matplotlib plots.
20
20
21 To get acquainted with the Qt console, type `%guiref` to see a quick
21 To get acquainted with the Qt console, type `%guiref` to see a quick
22 introduction of its main features.
22 introduction of its main features.
23
23
24 The Qt frontend has hand-coded emacs-style bindings for text navigation. This
24 The Qt frontend has hand-coded emacs-style bindings for text navigation. This
25 is not yet configurable.
25 is not yet configurable.
26
26
27 .. tip::
27 .. tip::
28
28
29 Since the Qt console tries hard to behave like a terminal, by default it
29 Since the Qt console tries hard to behave like a terminal, by default it
30 immediately executes single lines of input that are complete. If you want
30 immediately executes single lines of input that are complete. If you want
31 to force multiline input, hit :kbd:`Ctrl-Enter` at the end of the first line
31 to force multiline input, hit :kbd:`Ctrl-Enter` at the end of the first line
32 instead of :kbd:`Enter`, and it will open a new line for input. At any
32 instead of :kbd:`Enter`, and it will open a new line for input. At any
33 point in a multiline block, you can force its execution (without having to
33 point in a multiline block, you can force its execution (without having to
34 go to the bottom) with :kbd:`Shift-Enter`.
34 go to the bottom) with :kbd:`Shift-Enter`.
35
35
36 ``%loadpy``
36 ``%loadpy``
37 ===========
37 ===========
38
38
39 The new ``%loadpy`` magic takes any python script (must end in '.py'), and
39 The new ``%loadpy`` magic takes any python script (must end in '.py'), and
40 pastes its contents as your next input, so you can edit it before
40 pastes its contents as your next input, so you can edit it before
41 executing. The script may be on your machine, but you can also specify a url,
41 executing. The script may be on your machine, but you can also specify a url,
42 and it will download the script from the web. This is particularly useful for
42 and it will download the script from the web. This is particularly useful for
43 playing with examples from documentation, such as matplotlib.
43 playing with examples from documentation, such as matplotlib.
44
44
45 .. sourcecode:: ipython
45 .. sourcecode:: ipython
46
46
47 In [6]: %loadpy http://matplotlib.sourceforge.net/plot_directive/mpl_examples/mplot3d/contour3d_demo.py
47 In [6]: %loadpy http://matplotlib.sourceforge.net/plot_directive/mpl_examples/mplot3d/contour3d_demo.py
48
48
49 In [7]: from mpl_toolkits.mplot3d import axes3d
49 In [7]: from mpl_toolkits.mplot3d import axes3d
50 ...: import matplotlib.pyplot as plt
50 ...: import matplotlib.pyplot as plt
51 ...:
51 ...:
52 ...: fig = plt.figure()
52 ...: fig = plt.figure()
53 ...: ax = fig.add_subplot(111, projection='3d')
53 ...: ax = fig.add_subplot(111, projection='3d')
54 ...: X, Y, Z = axes3d.get_test_data(0.05)
54 ...: X, Y, Z = axes3d.get_test_data(0.05)
55 ...: cset = ax.contour(X, Y, Z)
55 ...: cset = ax.contour(X, Y, Z)
56 ...: ax.clabel(cset, fontsize=9, inline=1)
56 ...: ax.clabel(cset, fontsize=9, inline=1)
57 ...:
57 ...:
58 ...: plt.show()
58 ...: plt.show()
59
59
60 Pylab
60 Pylab
61 =====
61 =====
62
62
63 One of the most exciting features of the new console is embedded matplotlib
63 One of the most exciting features of the new console is embedded matplotlib
64 figures. You can use any standard matplotlib GUI backend
64 figures. You can use any standard matplotlib GUI backend
65 to draw the figures, and since there is now a two-process model, there is no
65 to draw the figures, and since there is now a two-process model, there is no
66 longer a conflict between user input and the drawing eventloop.
66 longer a conflict between user input and the drawing eventloop.
67
67
68 .. image:: figs/besselj.png
68 .. image:: figs/besselj.png
69 :width: 519px
69 :width: 519px
70
70
71 .. display:
71 .. display:
72
72
73 :func:`display`
73 :func:`display`
74 ***************
74 ***************
75
75
76 An additional function, :func:`display`, will be added to the global namespace
76 An additional function, :func:`display`, will be added to the global namespace
77 if you specify the ``--pylab`` option at the command line. The IPython display
77 if you specify the ``--pylab`` option at the command line. The IPython display
78 system provides a mechanism for specifying PNG or SVG (and more)
78 system provides a mechanism for specifying PNG or SVG (and more)
79 representations of objects for GUI frontends. By default, IPython registers
79 representations of objects for GUI frontends. By default, IPython registers
80 convenient PNG and SVG renderers for matplotlib figures, so you can embed them
80 convenient PNG and SVG renderers for matplotlib figures, so you can embed them
81 in your document by calling :func:`display` on one or more of them. This is
81 in your document by calling :func:`display` on one or more of them. This is
82 especially useful for saving_ your work.
82 especially useful for saving_ your work.
83
83
84 .. sourcecode:: ipython
84 .. sourcecode:: ipython
85
85
86 In [5]: plot(range(5)) # plots in the matplotlib window
86 In [5]: plot(range(5)) # plots in the matplotlib window
87
87
88 In [6]: display(gcf()) # embeds the current figure in the qtconsole
88 In [6]: display(gcf()) # embeds the current figure in the qtconsole
89
89
90 In [7]: display(*getfigs()) # embeds all active figures in the qtconsole
90 In [7]: display(*getfigs()) # embeds all active figures in the qtconsole
91
91
92 If you have a reference to a matplotlib figure object, you can always display
92 If you have a reference to a matplotlib figure object, you can always display
93 that specific figure:
93 that specific figure:
94
94
95 .. sourcecode:: ipython
95 .. sourcecode:: ipython
96
96
97 In [1]: f = figure()
97 In [1]: f = figure()
98
98
99 In [2]: plot(rand(100))
99 In [2]: plot(rand(100))
100 Out[2]: [<matplotlib.lines.Line2D at 0x7fc6ac03dd90>]
100 Out[2]: [<matplotlib.lines.Line2D at 0x7fc6ac03dd90>]
101
101
102 In [3]: display(f)
102 In [3]: display(f)
103
103
104 # Plot is shown here
104 # Plot is shown here
105
105
106 In [4]: title('A title')
106 In [4]: title('A title')
107 Out[4]: <matplotlib.text.Text at 0x7fc6ac023450>
107 Out[4]: <matplotlib.text.Text at 0x7fc6ac023450>
108
108
109 In [5]: display(f)
109 In [5]: display(f)
110
110
111 # Updated plot with title is shown here.
111 # Updated plot with title is shown here.
112
112
113 .. _inline:
113 .. _inline:
114
114
115 ``--pylab=inline``
115 ``--pylab=inline``
116 ******************
116 ******************
117
117
118 If you want to have all of your figures embedded in your session, instead of
118 If you want to have all of your figures embedded in your session, instead of
119 calling :func:`display`, you can specify ``--pylab=inline`` when you start the
119 calling :func:`display`, you can specify ``--pylab=inline`` when you start the
120 console, and each time you make a plot, it will show up in your document, as if
120 console, and each time you make a plot, it will show up in your document, as if
121 you had called :func:`display(fig)`.
121 you had called :func:`display(fig)`.
122
122
123 The inline backend can use either SVG or PNG figures (PNG being the default).
123 The inline backend can use either SVG or PNG figures (PNG being the default).
124 To switch between them, set the ``InlineBackend.figure_format`` configurable
124 To switch between them, set the ``InlineBackend.figure_format`` configurable
125 in a config file, or via the ``%config`` magic:
125 in a config file, or via the ``%config`` magic:
126
126
127 .. sourcecode:: ipython
127 .. sourcecode:: ipython
128
128
129 In [10]: %config InlineBackend.figure_format = 'svg'
129 In [10]: %config InlineBackend.figure_format = 'svg'
130
130
131 .. note::
131 .. note::
132
132
133 Changing the inline figure format also affects calls to :func:`display` above,
133 Changing the inline figure format also affects calls to :func:`display` above,
134 even if you are not using the inline backend for all figures.
134 even if you are not using the inline backend for all figures.
135
135
136 By default, IPython closes all figures at the completion of each execution. This means you
136 By default, IPython closes all figures at the completion of each execution. This means you
137 don't have to manually close figures, which is less convenient when figures aren't attached
137 don't have to manually close figures, which is less convenient when figures aren't attached
138 to windows with an obvious close button. It also means that the first matplotlib call in
138 to windows with an obvious close button. It also means that the first matplotlib call in
139 each cell will always create a new figure:
139 each cell will always create a new figure:
140
140
141 .. sourcecode:: ipython
141 .. sourcecode:: ipython
142
142
143 In [11]: plot(range(100))
143 In [11]: plot(range(100))
144 <single-line plot>
144 <single-line plot>
145
145
146 In [12]: plot([1,3,2])
146 In [12]: plot([1,3,2])
147 <another single-line plot>
147 <another single-line plot>
148
148
149
149
150 However, it does prevent the list of active figures surviving from one input cell to the
150 However, it does prevent the list of active figures surviving from one input cell to the
151 next, so if you want to continue working with a figure, you must hold on to a reference to
151 next, so if you want to continue working with a figure, you must hold on to a reference to
152 it:
152 it:
153
153
154 .. sourcecode:: ipython
154 .. sourcecode:: ipython
155
155
156 In [11]: fig = gcf()
156 In [11]: fig = gcf()
157 ....: fig.plot(rand(100))
157 ....: fig.plot(rand(100))
158 <plot>
158 <plot>
159 In [12]: fig.title('Random Title')
159 In [12]: fig.title('Random Title')
160 <redraw plot with title>
160 <redraw plot with title>
161
161
162 This behavior is controlled by the :attr:`InlineBackend.close_figures` configurable, and
162 This behavior is controlled by the :attr:`InlineBackend.close_figures` configurable, and
163 if you set it to False, via %config or config file, then IPython will *not* close figures,
163 if you set it to False, via %config or config file, then IPython will *not* close figures,
164 and tools like :func:`gcf`, :func:`gca`, :func:`getfigs` will behave the same as they
164 and tools like :func:`gcf`, :func:`gca`, :func:`getfigs` will behave the same as they
165 do with other backends. You will, however, have to manually close figures:
165 do with other backends. You will, however, have to manually close figures:
166
166
167 .. sourcecode:: ipython
167 .. sourcecode:: ipython
168
168
169 # close all active figures:
169 # close all active figures:
170 In [13]: [ fig.close() for fig in getfigs() ]
170 In [13]: [ fig.close() for fig in getfigs() ]
171
171
172
172
173
173
174 .. _saving:
174 .. _saving:
175
175
176 Saving and Printing
176 Saving and Printing
177 ===================
177 ===================
178
178
179 IPythonQt has the ability to save your current session, as either HTML or
179 IPythonQt has the ability to save your current session, as either HTML or
180 XHTML. If you have been using :func:`display` or inline_ pylab, your figures
180 XHTML. If you have been using :func:`display` or inline_ pylab, your figures
181 will be PNG in HTML, or inlined as SVG in XHTML. PNG images have the option to
181 will be PNG in HTML, or inlined as SVG in XHTML. PNG images have the option to
182 be either in an external folder, as in many browsers' "Webpage, Complete"
182 be either in an external folder, as in many browsers' "Webpage, Complete"
183 option, or inlined as well, for a larger, but more portable file.
183 option, or inlined as well, for a larger, but more portable file.
184
184
185 .. note::
185 .. note::
186
186
187 Export to SVG+XHTML requires that you are using SVG figures, which is *not*
187 Export to SVG+XHTML requires that you are using SVG figures, which is *not*
188 the default. To switch the inline figure format to use SVG during an active
188 the default. To switch the inline figure format to use SVG during an active
189 session, do:
189 session, do:
190
190
191 .. sourcecode:: ipython
191 .. sourcecode:: ipython
192
192
193 In [10]: %config InlineBackend.figure_format = 'svg'
193 In [10]: %config InlineBackend.figure_format = 'svg'
194
194
195 Or, you can add the same line (c.Inline... instead of %config Inline...) to
195 Or, you can add the same line (c.Inline... instead of %config Inline...) to
196 your config files.
196 your config files.
197
197
198 This will only affect figures plotted after making this call
198 This will only affect figures plotted after making this call
199
199
200
200
201 The widget also exposes the ability to print directly, via the default print
201 The widget also exposes the ability to print directly, via the default print
202 shortcut or context menu.
202 shortcut or context menu.
203
203
204
204
205 .. Note::
205 .. Note::
206
206
207 Saving is only available to richtext Qt widgets, which are used by default,
207 Saving is only available to richtext Qt widgets, which are used by default,
208 but if you pass the ``--plain`` flag, saving will not be available to you.
208 but if you pass the ``--plain`` flag, saving will not be available to you.
209
209
210
210
211 See these examples of :download:`png/html<figs/jn.html>` and
211 See these examples of :download:`png/html<figs/jn.html>` and
212 :download:`svg/xhtml <figs/jn.xhtml>` output. Note that syntax highlighting
212 :download:`svg/xhtml <figs/jn.xhtml>` output. Note that syntax highlighting
213 does not survive export. This is a known issue, and is being investigated.
213 does not survive export. This is a known issue, and is being investigated.
214
214
215
215
216 Colors and Highlighting
216 Colors and Highlighting
217 =======================
217 =======================
218
218
219 Terminal IPython has always had some coloring, but never syntax
219 Terminal IPython has always had some coloring, but never syntax
220 highlighting. There are a few simple color choices, specified by the ``colors``
220 highlighting. There are a few simple color choices, specified by the ``colors``
221 flag or ``%colors`` magic:
221 flag or ``%colors`` magic:
222
222
223 * LightBG for light backgrounds
223 * LightBG for light backgrounds
224 * Linux for dark backgrounds
224 * Linux for dark backgrounds
225 * NoColor for a simple colorless terminal
225 * NoColor for a simple colorless terminal
226
226
227 The Qt widget has full support for the ``colors`` flag used in the terminal shell.
227 The Qt widget has full support for the ``colors`` flag used in the terminal shell.
228
228
229 The Qt widget, however, has full syntax highlighting as you type, handled by
229 The Qt widget, however, has full syntax highlighting as you type, handled by
230 the `pygments`_ library. The ``style`` argument exposes access to any style by
230 the `pygments`_ library. The ``style`` argument exposes access to any style by
231 name that can be found by pygments, and there are several already
231 name that can be found by pygments, and there are several already
232 installed. The ``colors`` argument, if unspecified, will be guessed based on
232 installed. The ``colors`` argument, if unspecified, will be guessed based on
233 the chosen style. Similarly, there are default styles associated with each
233 the chosen style. Similarly, there are default styles associated with each
234 ``colors`` option.
234 ``colors`` option.
235
235
236
236
237 Screenshot of ``ipython qtconsole --colors=linux``, which uses the 'monokai'
237 Screenshot of ``ipython qtconsole --colors=linux``, which uses the 'monokai'
238 theme by default:
238 theme by default:
239
239
240 .. image:: figs/colors_dark.png
240 .. image:: figs/colors_dark.png
241 :width: 627px
241 :width: 627px
242
242
243 .. Note::
243 .. Note::
244
244
245 Calling ``ipython qtconsole -h`` will show all the style names that
245 Calling ``ipython qtconsole -h`` will show all the style names that
246 pygments can find on your system.
246 pygments can find on your system.
247
247
248 You can also pass the filename of a custom CSS stylesheet, if you want to do
248 You can also pass the filename of a custom CSS stylesheet, if you want to do
249 your own coloring, via the ``stylesheet`` argument. The default LightBG
249 your own coloring, via the ``stylesheet`` argument. The default LightBG
250 stylesheet:
250 stylesheet:
251
251
252 .. sourcecode:: css
252 .. sourcecode:: css
253
253
254 QPlainTextEdit, QTextEdit { background-color: white;
254 QPlainTextEdit, QTextEdit { background-color: white;
255 color: black ;
255 color: black ;
256 selection-background-color: #ccc}
256 selection-background-color: #ccc}
257 .error { color: red; }
257 .error { color: red; }
258 .in-prompt { color: navy; }
258 .in-prompt { color: navy; }
259 .in-prompt-number { font-weight: bold; }
259 .in-prompt-number { font-weight: bold; }
260 .out-prompt { color: darkred; }
260 .out-prompt { color: darkred; }
261 .out-prompt-number { font-weight: bold; }
261 .out-prompt-number { font-weight: bold; }
262
262
263 Fonts
263 Fonts
264 =====
264 =====
265
265
266 The QtConsole has configurable via the ConsoleWidget. To change these, set the
266 The QtConsole has configurable via the ConsoleWidget. To change these, set the
267 ``font_family`` or ``font_size`` traits of the ConsoleWidget. For instance, to
267 ``font_family`` or ``font_size`` traits of the ConsoleWidget. For instance, to
268 use 9pt Anonymous Pro::
268 use 9pt Anonymous Pro::
269
269
270 $> ipython qtconsole --ConsoleWidget.font_family="Anonymous Pro" --ConsoleWidget.font_size=9
270 $> ipython qtconsole --ConsoleWidget.font_family="Anonymous Pro" --ConsoleWidget.font_size=9
271
271
272 Process Management
272 Process Management
273 ==================
273 ==================
274
274
275 With the two-process ZMQ model, the frontend does not block input during
275 With the two-process ZMQ model, the frontend does not block input during
276 execution. This means that actions can be taken by the frontend while the
276 execution. This means that actions can be taken by the frontend while the
277 Kernel is executing, or even after it crashes. The most basic such command is
277 Kernel is executing, or even after it crashes. The most basic such command is
278 via 'Ctrl-.', which restarts the kernel. This can be done in the middle of a
278 via 'Ctrl-.', which restarts the kernel. This can be done in the middle of a
279 blocking execution. The frontend can also know, via a heartbeat mechanism, that
279 blocking execution. The frontend can also know, via a heartbeat mechanism, that
280 the kernel has died. This means that the frontend can safely restart the
280 the kernel has died. This means that the frontend can safely restart the
281 kernel.
281 kernel.
282
282
283 .. _multiple_consoles:
283 .. _multiple_consoles:
284
284
285 Multiple Consoles
285 Multiple Consoles
286 *****************
286 *****************
287
287
288 Since the Kernel listens on the network, multiple frontends can connect to it.
288 Since the Kernel listens on the network, multiple frontends can connect to it.
289 These do not have to all be qt frontends - any IPython frontend can connect and
289 These do not have to all be qt frontends - any IPython frontend can connect and
290 run code. When you start ipython qtconsole, there will be an output line,
290 run code. When you start ipython qtconsole, there will be an output line,
291 like::
291 like::
292
292
293 [IPKernelApp] To connect another client to this kernel, use:
293 [IPKernelApp] To connect another client to this kernel, use:
294 [IPKernelApp] --existing kernel-12345.json
294 [IPKernelApp] --existing kernel-12345.json
295
295
296 Other frontends can connect to your kernel, and share in the execution. This is
296 Other frontends can connect to your kernel, and share in the execution. This is
297 great for collaboration. The ``--existing`` flag means connect to a kernel
297 great for collaboration. The ``--existing`` flag means connect to a kernel
298 that already exists. Starting other consoles
298 that already exists. Starting other consoles
299 with that flag will not try to start their own kernel, but rather connect to
299 with that flag will not try to start their own kernel, but rather connect to
300 yours. :file:`kernel-12345.json` is a small JSON file with the ip, port, and
300 yours. :file:`kernel-12345.json` is a small JSON file with the ip, port, and
301 authentication information necessary to connect to your kernel. By default, this file
301 authentication information necessary to connect to your kernel. By default, this file
302 will be in your default profile's security directory. If it is somewhere else,
302 will be in your default profile's security directory. If it is somewhere else,
303 the output line will print the full path of the connection file, rather than
303 the output line will print the full path of the connection file, rather than
304 just its filename.
304 just its filename.
305
305
306 If you need to find the connection info to send, and don't know where your connection file
306 If you need to find the connection info to send, and don't know where your connection file
307 lives, there are a couple of ways to get it. If you are already running an IPython console
307 lives, there are a couple of ways to get it. If you are already running an IPython console
308 connected to the kernel, you can use the ``%connect_info`` magic to display the information
308 connected to the kernel, you can use the ``%connect_info`` magic to display the information
309 necessary to connect another frontend to the kernel.
309 necessary to connect another frontend to the kernel.
310
310
311 .. sourcecode:: ipython
311 .. sourcecode:: ipython
312
312
313 In [2]: %connect_info
313 In [2]: %connect_info
314 {
314 {
315 "stdin_port":50255,
315 "stdin_port":50255,
316 "ip":"127.0.0.1",
316 "ip":"127.0.0.1",
317 "hb_port":50256,
317 "hb_port":50256,
318 "key":"70be6f0f-1564-4218-8cda-31be40a4d6aa",
318 "key":"70be6f0f-1564-4218-8cda-31be40a4d6aa",
319 "shell_port":50253,
319 "shell_port":50253,
320 "iopub_port":50254
320 "iopub_port":50254
321 }
321 }
322
322
323 Paste the above JSON into a file, and connect with:
323 Paste the above JSON into a file, and connect with:
324 $> ipython <app> --existing <file>
324 $> ipython <app> --existing <file>
325 or, if you are local, you can connect with just:
325 or, if you are local, you can connect with just:
326 $> ipython <app> --existing kernel-12345.json
326 $> ipython <app> --existing kernel-12345.json
327 or even just:
327 or even just:
328 $> ipython <app> --existing
328 $> ipython <app> --existing
329 if this is the most recent IPython session you have started.
329 if this is the most recent IPython session you have started.
330
330
331 Otherwise, you can find a connection file by name (and optionally profile) with
331 Otherwise, you can find a connection file by name (and optionally profile) with
332 :func:`IPython.lib.kernel.find_connection_file`:
332 :func:`IPython.lib.kernel.find_connection_file`:
333
333
334 .. sourcecode:: bash
334 .. sourcecode:: bash
335
335
336 $> python -c "from IPython.lib.kernel import find_connection_file;\
336 $> python -c "from IPython.lib.kernel import find_connection_file;\
337 print find_connection_file('kernel-12345.json')"
337 print find_connection_file('kernel-12345.json')"
338 /home/you/.ipython/profile_default/security/kernel-12345.json
338 /home/you/.ipython/profile_default/security/kernel-12345.json
339
339
340 And if you are using a particular IPython profile:
340 And if you are using a particular IPython profile:
341
341
342 .. sourcecode:: bash
342 .. sourcecode:: bash
343
343
344 $> python -c "from IPython.lib.kernel import find_connection_file;\
344 $> python -c "from IPython.lib.kernel import find_connection_file;\
345 print find_connection_file('kernel-12345.json', profile='foo')"
345 print find_connection_file('kernel-12345.json', profile='foo')"
346 /home/you/.ipython/profile_foo/security/kernel-12345.json
346 /home/you/.ipython/profile_foo/security/kernel-12345.json
347
347
348 You can even launch a standalone kernel, and connect and disconnect Qt Consoles
348 You can even launch a standalone kernel, and connect and disconnect Qt Consoles
349 from various machines. This lets you keep the same running IPython session
349 from various machines. This lets you keep the same running IPython session
350 on your work machine (with matplotlib plots and everything), logging in from home,
350 on your work machine (with matplotlib plots and everything), logging in from home,
351 cafΓ©s, etc.::
351 cafΓ©s, etc.::
352
352
353 $> ipython kernel
353 $> ipython kernel
354 [IPKernelApp] To connect another client to this kernel, use:
354 [IPKernelApp] To connect another client to this kernel, use:
355 [IPKernelApp] --existing kernel-12345.json
355 [IPKernelApp] --existing kernel-12345.json
356
356
357 This is actually exactly the same as the subprocess launched by the qtconsole, so
357 This is actually exactly the same as the subprocess launched by the qtconsole, so
358 all the information about connecting to a standalone kernel is identical to that
358 all the information about connecting to a standalone kernel is identical to that
359 of connecting to the kernel attached to a running console.
359 of connecting to the kernel attached to a running console.
360
360
361 .. _kernel_security:
361 .. _kernel_security:
362
362
363 Security
363 Security
364 --------
364 --------
365
365
366 .. warning::
366 .. warning::
367
367
368 Since the ZMQ code currently has no encryption, listening on an
368 Since the ZMQ code currently has no encryption, listening on an
369 external-facing IP is dangerous. You are giving any computer that can see
369 external-facing IP is dangerous. You are giving any computer that can see
370 you on the network the ability to connect to your kernel, and view your traffic.
370 you on the network the ability to connect to your kernel, and view your traffic.
371 Read the rest of this section before listening on external ports
371 Read the rest of this section before listening on external ports
372 or running an IPython kernel on a shared machine.
372 or running an IPython kernel on a shared machine.
373
373
374 By default (for security reasons), the kernel only listens on localhost, so you
374 By default (for security reasons), the kernel only listens on localhost, so you
375 can only connect multiple frontends to the kernel from your local machine. You
375 can only connect multiple frontends to the kernel from your local machine. You
376 can specify to listen on an external interface by specifying the ``ip``
376 can specify to listen on an external interface by specifying the ``ip``
377 argument::
377 argument::
378
378
379 $> ipython qtconsole --ip=192.168.1.123
379 $> ipython qtconsole --ip=192.168.1.123
380
380
381 If you specify the ip as 0.0.0.0 or '*', that means all interfaces, so any
381 If you specify the ip as 0.0.0.0 or '*', that means all interfaces, so any
382 computer that can see yours on the network can connect to the kernel.
382 computer that can see yours on the network can connect to the kernel.
383
383
384 Messages are not encrypted, so users with access to the ports your kernel is using will be
384 Messages are not encrypted, so users with access to the ports your kernel is using will be
385 able to see any output of the kernel. They will **NOT** be able to issue shell commands as
385 able to see any output of the kernel. They will **NOT** be able to issue shell commands as
386 you due to message signatures, which are enabled by default as of IPython 0.12.
386 you due to message signatures, which are enabled by default as of IPython 0.12.
387
387
388 .. warning::
388 .. warning::
389
389
390 If you disable message signatures, then any user with access to the ports your
390 If you disable message signatures, then any user with access to the ports your
391 kernel is listening on can issue arbitrary code as you. **DO NOT** disable message
391 kernel is listening on can issue arbitrary code as you. **DO NOT** disable message
392 signatures unless you have a lot of trust in your environment.
392 signatures unless you have a lot of trust in your environment.
393
393
394 The one security feature IPython does provide is protection from unauthorized execution.
394 The one security feature IPython does provide is protection from unauthorized execution.
395 IPython's messaging system will sign messages with HMAC digests using a shared-key. The key
395 IPython's messaging system will sign messages with HMAC digests using a shared-key. The key
396 is never sent over the network, it is only used to generate a unique hash for each message,
396 is never sent over the network, it is only used to generate a unique hash for each message,
397 based on its content. When IPython receives a message, it will check that the digest
397 based on its content. When IPython receives a message, it will check that the digest
398 matches, and discard the message. You can use any file that only you have access to to
398 matches, and discard the message. You can use any file that only you have access to to
399 generate this key, but the default is just to generate a new UUID. You can generate a random
399 generate this key, but the default is just to generate a new UUID. You can generate a random
400 private key with::
400 private key with::
401
401
402 # generate 1024b of random data, and store in a file only you can read:
402 # generate 1024b of random data, and store in a file only you can read:
403 # (assumes IPYTHON_DIR is defined, otherwise use your IPython directory)
403 # (assumes IPYTHONDIR is defined, otherwise use your IPython directory)
404 $> python -c "import os; print os.urandom(128).encode('base64')" > $IPYTHON_DIR/sessionkey
404 $> python -c "import os; print os.urandom(128).encode('base64')" > $IPYTHONDIR/sessionkey
405 $> chmod 600 $IPYTHON_DIR/sessionkey
405 $> chmod 600 $IPYTHONDIR/sessionkey
406
406
407 The *contents* of this file will be stored in the JSON connection file, so that file
407 The *contents* of this file will be stored in the JSON connection file, so that file
408 contains everything you need to connect to and use a kernel.
408 contains everything you need to connect to and use a kernel.
409
409
410 To use this generated key, simply specify the ``Session.keyfile`` configurable
410 To use this generated key, simply specify the ``Session.keyfile`` configurable
411 in :file:`ipython_config.py` or at the command-line, as in::
411 in :file:`ipython_config.py` or at the command-line, as in::
412
412
413 # instruct IPython to sign messages with that key, instead of a new UUID
413 # instruct IPython to sign messages with that key, instead of a new UUID
414 $> ipython qtconsole --Session.keyfile=$IPYTHON_DIR/sessionkey
414 $> ipython qtconsole --Session.keyfile=$IPYTHONDIR/sessionkey
415
415
416 .. _ssh_tunnels:
416 .. _ssh_tunnels:
417
417
418 SSH Tunnels
418 SSH Tunnels
419 -----------
419 -----------
420
420
421 Sometimes you want to connect to machines across the internet, or just across
421 Sometimes you want to connect to machines across the internet, or just across
422 a LAN that either doesn't permit open ports or you don't trust the other
422 a LAN that either doesn't permit open ports or you don't trust the other
423 machines on the network. To do this, you can use SSH tunnels. SSH tunnels
423 machines on the network. To do this, you can use SSH tunnels. SSH tunnels
424 are a way to securely forward ports on your local machine to ports on another
424 are a way to securely forward ports on your local machine to ports on another
425 machine, to which you have SSH access.
425 machine, to which you have SSH access.
426
426
427 In simple cases, IPython's tools can forward ports over ssh by simply adding the
427 In simple cases, IPython's tools can forward ports over ssh by simply adding the
428 ``--ssh=remote`` argument to the usual ``--existing...`` set of flags for connecting
428 ``--ssh=remote`` argument to the usual ``--existing...`` set of flags for connecting
429 to a running kernel, after copying the JSON connection file (or its contents) to
429 to a running kernel, after copying the JSON connection file (or its contents) to
430 the second computer.
430 the second computer.
431
431
432 .. warning::
432 .. warning::
433
433
434 Using SSH tunnels does *not* increase localhost security. In fact, when
434 Using SSH tunnels does *not* increase localhost security. In fact, when
435 tunneling from one machine to another *both* machines have open
435 tunneling from one machine to another *both* machines have open
436 ports on localhost available for connections to the kernel.
436 ports on localhost available for connections to the kernel.
437
437
438 There are two primary models for using SSH tunnels with IPython. The first
438 There are two primary models for using SSH tunnels with IPython. The first
439 is to have the Kernel listen only on localhost, and connect to it from
439 is to have the Kernel listen only on localhost, and connect to it from
440 another machine on the same LAN.
440 another machine on the same LAN.
441
441
442 First, let's start a kernel on machine **worker**, listening only
442 First, let's start a kernel on machine **worker**, listening only
443 on loopback::
443 on loopback::
444
444
445 user@worker $> ipython kernel
445 user@worker $> ipython kernel
446 [IPKernelApp] To connect another client to this kernel, use:
446 [IPKernelApp] To connect another client to this kernel, use:
447 [IPKernelApp] --existing kernel-12345.json
447 [IPKernelApp] --existing kernel-12345.json
448
448
449 In this case, the IP that you would connect
449 In this case, the IP that you would connect
450 to would still be 127.0.0.1, but you want to specify the additional ``--ssh`` argument
450 to would still be 127.0.0.1, but you want to specify the additional ``--ssh`` argument
451 with the hostname of the kernel (in this example, it's 'worker')::
451 with the hostname of the kernel (in this example, it's 'worker')::
452
452
453 user@client $> ipython qtconsole --ssh=worker --existing /path/to/kernel-12345.json
453 user@client $> ipython qtconsole --ssh=worker --existing /path/to/kernel-12345.json
454
454
455 Which will write a new connection file with the forwarded ports, so you can reuse them::
455 Which will write a new connection file with the forwarded ports, so you can reuse them::
456
456
457 [IPythonQtConsoleApp] To connect another client via this tunnel, use:
457 [IPythonQtConsoleApp] To connect another client via this tunnel, use:
458 [IPythonQtConsoleApp] --existing kernel-12345-ssh.json
458 [IPythonQtConsoleApp] --existing kernel-12345-ssh.json
459
459
460 Note again that this opens ports on the *client* machine that point to your kernel.
460 Note again that this opens ports on the *client* machine that point to your kernel.
461
461
462 .. note::
462 .. note::
463
463
464 the ssh argument is simply passed to openssh, so it can be fully specified ``user@host:port``
464 the ssh argument is simply passed to openssh, so it can be fully specified ``user@host:port``
465 but it will also respect your aliases, etc. in :file:`.ssh/config` if you have any.
465 but it will also respect your aliases, etc. in :file:`.ssh/config` if you have any.
466
466
467 The second pattern is for connecting to a machine behind a firewall across the internet
467 The second pattern is for connecting to a machine behind a firewall across the internet
468 (or otherwise wide network). This time, we have a machine **login** that you have ssh access
468 (or otherwise wide network). This time, we have a machine **login** that you have ssh access
469 to, which can see **kernel**, but **client** is on another network. The important difference
469 to, which can see **kernel**, but **client** is on another network. The important difference
470 now is that **client** can see **login**, but *not* **worker**. So we need to forward ports from
470 now is that **client** can see **login**, but *not* **worker**. So we need to forward ports from
471 client to worker *via* login. This means that the kernel must be started listening
471 client to worker *via* login. This means that the kernel must be started listening
472 on external interfaces, so that its ports are visible to `login`::
472 on external interfaces, so that its ports are visible to `login`::
473
473
474 user@worker $> ipython kernel --ip=0.0.0.0
474 user@worker $> ipython kernel --ip=0.0.0.0
475 [IPKernelApp] To connect another client to this kernel, use:
475 [IPKernelApp] To connect another client to this kernel, use:
476 [IPKernelApp] --existing kernel-12345.json
476 [IPKernelApp] --existing kernel-12345.json
477
477
478 Which we can connect to from the client with::
478 Which we can connect to from the client with::
479
479
480 user@client $> ipython qtconsole --ssh=login --ip=192.168.1.123 --existing /path/to/kernel-12345.json
480 user@client $> ipython qtconsole --ssh=login --ip=192.168.1.123 --existing /path/to/kernel-12345.json
481
481
482 .. note::
482 .. note::
483
483
484 The IP here is the address of worker as seen from *login*, and need only be specified if
484 The IP here is the address of worker as seen from *login*, and need only be specified if
485 the kernel used the ambiguous 0.0.0.0 (all interfaces) address. If it had used
485 the kernel used the ambiguous 0.0.0.0 (all interfaces) address. If it had used
486 192.168.1.123 to start with, it would not be needed.
486 192.168.1.123 to start with, it would not be needed.
487
487
488
488
489 Manual SSH tunnels
489 Manual SSH tunnels
490 ------------------
490 ------------------
491
491
492 It's possible that IPython's ssh helper functions won't work for you, for various
492 It's possible that IPython's ssh helper functions won't work for you, for various
493 reasons. You can still connect to remote machines, as long as you set up the tunnels
493 reasons. You can still connect to remote machines, as long as you set up the tunnels
494 yourself. The basic format of forwarding a local port to a remote one is::
494 yourself. The basic format of forwarding a local port to a remote one is::
495
495
496 [client] $> ssh <server> <localport>:<remoteip>:<remoteport> -f -N
496 [client] $> ssh <server> <localport>:<remoteip>:<remoteport> -f -N
497
497
498 This will forward local connections to **localport** on client to **remoteip:remoteport**
498 This will forward local connections to **localport** on client to **remoteip:remoteport**
499 *via* **server**. Note that remoteip is interpreted relative to *server*, not the client.
499 *via* **server**. Note that remoteip is interpreted relative to *server*, not the client.
500 So if you have direct ssh access to the machine to which you want to forward connections,
500 So if you have direct ssh access to the machine to which you want to forward connections,
501 then the server *is* the remote machine, and remoteip should be server's IP as seen from the
501 then the server *is* the remote machine, and remoteip should be server's IP as seen from the
502 server itself, i.e. 127.0.0.1. Thus, to forward local port 12345 to remote port 54321 on
502 server itself, i.e. 127.0.0.1. Thus, to forward local port 12345 to remote port 54321 on
503 a machine you can see, do::
503 a machine you can see, do::
504
504
505 [client] $> ssh machine 12345:127.0.0.1:54321 -f -N
505 [client] $> ssh machine 12345:127.0.0.1:54321 -f -N
506
506
507 But if your target is actually on a LAN at 192.168.1.123, behind another machine called **login**,
507 But if your target is actually on a LAN at 192.168.1.123, behind another machine called **login**,
508 then you would do::
508 then you would do::
509
509
510 [client] $> ssh login 12345:192.168.1.16:54321 -f -N
510 [client] $> ssh login 12345:192.168.1.16:54321 -f -N
511
511
512 The ``-f -N`` on the end are flags that tell ssh to run in the background,
512 The ``-f -N`` on the end are flags that tell ssh to run in the background,
513 and don't actually run any commands beyond creating the tunnel.
513 and don't actually run any commands beyond creating the tunnel.
514
514
515 .. seealso::
515 .. seealso::
516
516
517 A short discussion of ssh tunnels: http://www.revsys.com/writings/quicktips/ssh-tunnel.html
517 A short discussion of ssh tunnels: http://www.revsys.com/writings/quicktips/ssh-tunnel.html
518
518
519
519
520
520
521 Stopping Kernels and Consoles
521 Stopping Kernels and Consoles
522 *****************************
522 *****************************
523
523
524 Since there can be many consoles per kernel, the shutdown mechanism and dialog
524 Since there can be many consoles per kernel, the shutdown mechanism and dialog
525 are probably more complicated than you are used to. Since you don't always want
525 are probably more complicated than you are used to. Since you don't always want
526 to shutdown a kernel when you close a window, you are given the option to just
526 to shutdown a kernel when you close a window, you are given the option to just
527 close the console window or also close the Kernel and *all other windows*. Note
527 close the console window or also close the Kernel and *all other windows*. Note
528 that this only refers to all other *local* windows, as remote Consoles are not
528 that this only refers to all other *local* windows, as remote Consoles are not
529 allowed to shutdown the kernel, and shutdowns do not close Remote consoles (to
529 allowed to shutdown the kernel, and shutdowns do not close Remote consoles (to
530 allow for saving, etc.).
530 allow for saving, etc.).
531
531
532 Rules:
532 Rules:
533
533
534 * Restarting the kernel automatically clears all *local* Consoles, and prompts remote
534 * Restarting the kernel automatically clears all *local* Consoles, and prompts remote
535 Consoles about the reset.
535 Consoles about the reset.
536 * Shutdown closes all *local* Consoles, and notifies remotes that
536 * Shutdown closes all *local* Consoles, and notifies remotes that
537 the Kernel has been shutdown.
537 the Kernel has been shutdown.
538 * Remote Consoles may not restart or shutdown the kernel.
538 * Remote Consoles may not restart or shutdown the kernel.
539
539
540 Qt and the QtConsole
540 Qt and the QtConsole
541 ====================
541 ====================
542
542
543 An important part of working with the QtConsole when you are writing your own
543 An important part of working with the QtConsole when you are writing your own
544 Qt code is to remember that user code (in the kernel) is *not* in the same
544 Qt code is to remember that user code (in the kernel) is *not* in the same
545 process as the frontend. This means that there is not necessarily any Qt code
545 process as the frontend. This means that there is not necessarily any Qt code
546 running in the kernel, and under most normal circumstances there isn't. If,
546 running in the kernel, and under most normal circumstances there isn't. If,
547 however, you specify ``--pylab=qt`` at the command-line, then there *will* be a
547 however, you specify ``--pylab=qt`` at the command-line, then there *will* be a
548 :class:`QCoreApplication` instance running in the kernel process along with
548 :class:`QCoreApplication` instance running in the kernel process along with
549 user-code. To get a reference to this application, do:
549 user-code. To get a reference to this application, do:
550
550
551 .. sourcecode:: python
551 .. sourcecode:: python
552
552
553 from PyQt4 import QtCore
553 from PyQt4 import QtCore
554 app = QtCore.QCoreApplication.instance()
554 app = QtCore.QCoreApplication.instance()
555 # app will be None if there is no such instance
555 # app will be None if there is no such instance
556
556
557 A common problem listed in the PyQt4 Gotchas_ is the fact that Python's garbage
557 A common problem listed in the PyQt4 Gotchas_ is the fact that Python's garbage
558 collection will destroy Qt objects (Windows, etc.) once there is no longer a
558 collection will destroy Qt objects (Windows, etc.) once there is no longer a
559 Python reference to them, so you have to hold on to them. For instance, in:
559 Python reference to them, so you have to hold on to them. For instance, in:
560
560
561 .. sourcecode:: python
561 .. sourcecode:: python
562
562
563 def make_window():
563 def make_window():
564 win = QtGui.QMainWindow()
564 win = QtGui.QMainWindow()
565
565
566 def make_and_return_window():
566 def make_and_return_window():
567 win = QtGui.QMainWindow()
567 win = QtGui.QMainWindow()
568 return win
568 return win
569
569
570 :func:`make_window` will never draw a window, because garbage collection will
570 :func:`make_window` will never draw a window, because garbage collection will
571 destroy it before it is drawn, whereas :func:`make_and_return_window` lets the
571 destroy it before it is drawn, whereas :func:`make_and_return_window` lets the
572 caller decide when the window object should be destroyed. If, as a developer,
572 caller decide when the window object should be destroyed. If, as a developer,
573 you know that you always want your objects to last as long as the process, you
573 you know that you always want your objects to last as long as the process, you
574 can attach them to the QApplication instance itself:
574 can attach them to the QApplication instance itself:
575
575
576 .. sourcecode:: python
576 .. sourcecode:: python
577
577
578 # do this just once:
578 # do this just once:
579 app = QtCore.QCoreApplication.instance()
579 app = QtCore.QCoreApplication.instance()
580 app.references = set()
580 app.references = set()
581 # then when you create Windows, add them to the set
581 # then when you create Windows, add them to the set
582 def make_window():
582 def make_window():
583 win = QtGui.QMainWindow()
583 win = QtGui.QMainWindow()
584 app.references.add(win)
584 app.references.add(win)
585
585
586 Now the QApplication itself holds a reference to ``win``, so it will never be
586 Now the QApplication itself holds a reference to ``win``, so it will never be
587 garbage collected until the application itself is destroyed.
587 garbage collected until the application itself is destroyed.
588
588
589 .. _Gotchas: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/gotchas.html#garbage-collection
589 .. _Gotchas: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/gotchas.html#garbage-collection
590
590
591 Regressions
591 Regressions
592 ===========
592 ===========
593
593
594 There are some features, where the qt console lags behind the Terminal
594 There are some features, where the qt console lags behind the Terminal
595 frontend:
595 frontend:
596
596
597 * !cmd input: Due to our use of pexpect, we cannot pass input to subprocesses
597 * !cmd input: Due to our use of pexpect, we cannot pass input to subprocesses
598 launched using the '!' escape, so you should never call a command that
598 launched using the '!' escape, so you should never call a command that
599 requires interactive input. For such cases, use the terminal IPython. This
599 requires interactive input. For such cases, use the terminal IPython. This
600 will not be fixed, as abandoning pexpect would significantly degrade the
600 will not be fixed, as abandoning pexpect would significantly degrade the
601 console experience.
601 console experience.
602
602
603 * Use of ``\b`` and ``\r`` characters in the console: these are control
603 * Use of ``\b`` and ``\r`` characters in the console: these are control
604 characters that allow the cursor to move backwards on a line, and are used to
604 characters that allow the cursor to move backwards on a line, and are used to
605 display things like in-place progress bars in a terminal. We currently do
605 display things like in-place progress bars in a terminal. We currently do
606 not support this, but it is being tracked as issue :ghissue:`629`.
606 not support this, but it is being tracked as issue :ghissue:`629`.
607
607
608 .. _PyQt: http://www.riverbankcomputing.co.uk/software/pyqt/download
608 .. _PyQt: http://www.riverbankcomputing.co.uk/software/pyqt/download
609 .. _pygments: http://pygments.org/
609 .. _pygments: http://pygments.org/
@@ -1,1005 +1,1005 b''
1 =================
1 =================
2 IPython reference
2 IPython reference
3 =================
3 =================
4
4
5 .. _command_line_options:
5 .. _command_line_options:
6
6
7 Command-line usage
7 Command-line usage
8 ==================
8 ==================
9
9
10 You start IPython with the command::
10 You start IPython with the command::
11
11
12 $ ipython [options] files
12 $ ipython [options] files
13
13
14 .. note::
14 .. note::
15
15
16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
17
17
18 If invoked with no options, it executes all the files listed in sequence
18 If invoked with no options, it executes all the files listed in sequence
19 and drops you into the interpreter while still acknowledging any options
19 and drops you into the interpreter while still acknowledging any options
20 you may have set in your ipython_config.py. This behavior is different from
20 you may have set in your ipython_config.py. This behavior is different from
21 standard Python, which when called as python -i will only execute one
21 standard Python, which when called as python -i will only execute one
22 file and ignore your configuration setup.
22 file and ignore your configuration setup.
23
23
24 Please note that some of the configuration options are not available at
24 Please note that some of the configuration options are not available at
25 the command line, simply because they are not practical here. Look into
25 the command line, simply because they are not practical here. Look into
26 your configuration files for details on those. There are separate configuration
26 your configuration files for details on those. There are separate configuration
27 files for each profile, and the files look like "ipython_config.py" or
27 files for each profile, and the files look like "ipython_config.py" or
28 "ipython_config_<frontendname>.py". Profile directories look like
28 "ipython_config_<frontendname>.py". Profile directories look like
29 "profile_profilename" and are typically installed in the IPYTHON_DIR directory.
29 "profile_profilename" and are typically installed in the IPYTHONDIR directory.
30 For Linux users, this will be $HOME/.config/ipython, and for other users it
30 For Linux users, this will be $HOME/.config/ipython, and for other users it
31 will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
31 will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
32 Settings\\YourUserName in most instances.
32 Settings\\YourUserName in most instances.
33
33
34
34
35 Eventloop integration
35 Eventloop integration
36 ---------------------
36 ---------------------
37
37
38 Previously IPython had command line options for controlling GUI event loop
38 Previously IPython had command line options for controlling GUI event loop
39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
40 version 0.11, these have been removed. Please see the new ``%gui``
40 version 0.11, these have been removed. Please see the new ``%gui``
41 magic command or :ref:`this section <gui_support>` for details on the new
41 magic command or :ref:`this section <gui_support>` for details on the new
42 interface, or specify the gui at the commandline::
42 interface, or specify the gui at the commandline::
43
43
44 $ ipython --gui=qt
44 $ ipython --gui=qt
45
45
46
46
47 Command-line Options
47 Command-line Options
48 --------------------
48 --------------------
49
49
50 To see the options IPython accepts, use ``ipython --help`` (and you probably
50 To see the options IPython accepts, use ``ipython --help`` (and you probably
51 should run the output through a pager such as ``ipython --help | less`` for
51 should run the output through a pager such as ``ipython --help | less`` for
52 more convenient reading). This shows all the options that have a single-word
52 more convenient reading). This shows all the options that have a single-word
53 alias to control them, but IPython lets you configure all of its objects from
53 alias to control them, but IPython lets you configure all of its objects from
54 the command-line by passing the full class name and a corresponding value; type
54 the command-line by passing the full class name and a corresponding value; type
55 ``ipython --help-all`` to see this full list. For example::
55 ``ipython --help-all`` to see this full list. For example::
56
56
57 ipython --pylab qt
57 ipython --pylab qt
58
58
59 is equivalent to::
59 is equivalent to::
60
60
61 ipython --TerminalIPythonApp.pylab='qt'
61 ipython --TerminalIPythonApp.pylab='qt'
62
62
63 Note that in the second form, you *must* use the equal sign, as the expression
63 Note that in the second form, you *must* use the equal sign, as the expression
64 is evaluated as an actual Python assignment. While in the above example the
64 is evaluated as an actual Python assignment. While in the above example the
65 short form is more convenient, only the most common options have a short form,
65 short form is more convenient, only the most common options have a short form,
66 while any configurable variable in IPython can be set at the command-line by
66 while any configurable variable in IPython can be set at the command-line by
67 using the long form. This long form is the same syntax used in the
67 using the long form. This long form is the same syntax used in the
68 configuration files, if you want to set these options permanently.
68 configuration files, if you want to set these options permanently.
69
69
70
70
71 Interactive use
71 Interactive use
72 ===============
72 ===============
73
73
74 IPython is meant to work as a drop-in replacement for the standard interactive
74 IPython is meant to work as a drop-in replacement for the standard interactive
75 interpreter. As such, any code which is valid python should execute normally
75 interpreter. As such, any code which is valid python should execute normally
76 under IPython (cases where this is not true should be reported as bugs). It
76 under IPython (cases where this is not true should be reported as bugs). It
77 does, however, offer many features which are not available at a standard python
77 does, however, offer many features which are not available at a standard python
78 prompt. What follows is a list of these.
78 prompt. What follows is a list of these.
79
79
80
80
81 Caution for Windows users
81 Caution for Windows users
82 -------------------------
82 -------------------------
83
83
84 Windows, unfortunately, uses the '\\' character as a path separator. This is a
84 Windows, unfortunately, uses the '\\' character as a path separator. This is a
85 terrible choice, because '\\' also represents the escape character in most
85 terrible choice, because '\\' also represents the escape character in most
86 modern programming languages, including Python. For this reason, using '/'
86 modern programming languages, including Python. For this reason, using '/'
87 character is recommended if you have problems with ``\``. However, in Windows
87 character is recommended if you have problems with ``\``. However, in Windows
88 commands '/' flags options, so you can not use it for the root directory. This
88 commands '/' flags options, so you can not use it for the root directory. This
89 means that paths beginning at the root must be typed in a contrived manner
89 means that paths beginning at the root must be typed in a contrived manner
90 like: ``%copy \opt/foo/bar.txt \tmp``
90 like: ``%copy \opt/foo/bar.txt \tmp``
91
91
92 .. _magic:
92 .. _magic:
93
93
94 Magic command system
94 Magic command system
95 --------------------
95 --------------------
96
96
97 IPython will treat any line whose first character is a % as a special
97 IPython will treat any line whose first character is a % as a special
98 call to a 'magic' function. These allow you to control the behavior of
98 call to a 'magic' function. These allow you to control the behavior of
99 IPython itself, plus a lot of system-type features. They are all
99 IPython itself, plus a lot of system-type features. They are all
100 prefixed with a % character, but parameters are given without
100 prefixed with a % character, but parameters are given without
101 parentheses or quotes.
101 parentheses or quotes.
102
102
103 Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it
103 Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it
104 exists.
104 exists.
105
105
106 If you have 'automagic' enabled (as it by default), you don't need
106 If you have 'automagic' enabled (as it by default), you don't need
107 to type in the % explicitly. IPython will scan its internal list of
107 to type in the % explicitly. IPython will scan its internal list of
108 magic functions and call one if it exists. With automagic on you can
108 magic functions and call one if it exists. With automagic on you can
109 then just type ``cd mydir`` to go to directory 'mydir'. The automagic
109 then just type ``cd mydir`` to go to directory 'mydir'. The automagic
110 system has the lowest possible precedence in name searches, so defining
110 system has the lowest possible precedence in name searches, so defining
111 an identifier with the same name as an existing magic function will
111 an identifier with the same name as an existing magic function will
112 shadow it for automagic use. You can still access the shadowed magic
112 shadow it for automagic use. You can still access the shadowed magic
113 function by explicitly using the % character at the beginning of the line.
113 function by explicitly using the % character at the beginning of the line.
114
114
115 An example (with automagic on) should clarify all this:
115 An example (with automagic on) should clarify all this:
116
116
117 .. sourcecode:: ipython
117 .. sourcecode:: ipython
118
118
119 In [1]: cd ipython # %cd is called by automagic
119 In [1]: cd ipython # %cd is called by automagic
120 /home/fperez/ipython
120 /home/fperez/ipython
121
121
122 In [2]: cd=1 # now cd is just a variable
122 In [2]: cd=1 # now cd is just a variable
123
123
124 In [3]: cd .. # and doesn't work as a function anymore
124 In [3]: cd .. # and doesn't work as a function anymore
125 File "<ipython-input-3-9fedb3aff56c>", line 1
125 File "<ipython-input-3-9fedb3aff56c>", line 1
126 cd ..
126 cd ..
127 ^
127 ^
128 SyntaxError: invalid syntax
128 SyntaxError: invalid syntax
129
129
130
130
131 In [4]: %cd .. # but %cd always works
131 In [4]: %cd .. # but %cd always works
132 /home/fperez
132 /home/fperez
133
133
134 In [5]: del cd # if you remove the cd variable, automagic works again
134 In [5]: del cd # if you remove the cd variable, automagic works again
135
135
136 In [6]: cd ipython
136 In [6]: cd ipython
137
137
138 /home/fperez/ipython
138 /home/fperez/ipython
139
139
140 You can define your own magic functions to extend the system. The
140 You can define your own magic functions to extend the system. The
141 following example defines a new magic command, %impall:
141 following example defines a new magic command, %impall:
142
142
143 .. sourcecode:: python
143 .. sourcecode:: python
144
144
145 ip = get_ipython()
145 ip = get_ipython()
146
146
147 def doimp(self, arg):
147 def doimp(self, arg):
148 ip = self.api
148 ip = self.api
149 ip.ex("import %s; reload(%s); from %s import *" % (arg,arg,arg) )
149 ip.ex("import %s; reload(%s); from %s import *" % (arg,arg,arg) )
150
150
151 ip.define_magic('impall', doimp)
151 ip.define_magic('impall', doimp)
152
152
153 Type ``%magic`` for more information, including a list of all available magic
153 Type ``%magic`` for more information, including a list of all available magic
154 functions at any time and their docstrings. You can also type
154 functions at any time and their docstrings. You can also type
155 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for information on
155 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for information on
156 the '?' system) to get information about any particular magic function you are
156 the '?' system) to get information about any particular magic function you are
157 interested in.
157 interested in.
158
158
159 The API documentation for the :mod:`IPython.core.magic` module contains the full
159 The API documentation for the :mod:`IPython.core.magic` module contains the full
160 docstrings of all currently available magic commands.
160 docstrings of all currently available magic commands.
161
161
162
162
163 Access to the standard Python help
163 Access to the standard Python help
164 ----------------------------------
164 ----------------------------------
165
165
166 Simply type ``help()`` to access Python's standard help system. You can
166 Simply type ``help()`` to access Python's standard help system. You can
167 also type ``help(object)`` for information about a given object, or
167 also type ``help(object)`` for information about a given object, or
168 ``help('keyword')`` for information on a keyword. You may need to configure your
168 ``help('keyword')`` for information on a keyword. You may need to configure your
169 PYTHONDOCS environment variable for this feature to work correctly.
169 PYTHONDOCS environment variable for this feature to work correctly.
170
170
171 .. _dynamic_object_info:
171 .. _dynamic_object_info:
172
172
173 Dynamic object information
173 Dynamic object information
174 --------------------------
174 --------------------------
175
175
176 Typing ``?word`` or ``word?`` prints detailed information about an object. If
176 Typing ``?word`` or ``word?`` prints detailed information about an object. If
177 certain strings in the object are too long (e.g. function signatures) they get
177 certain strings in the object are too long (e.g. function signatures) they get
178 snipped in the center for brevity. This system gives access variable types and
178 snipped in the center for brevity. This system gives access variable types and
179 values, docstrings, function prototypes and other useful information.
179 values, docstrings, function prototypes and other useful information.
180
180
181 If the information will not fit in the terminal, it is displayed in a pager
181 If the information will not fit in the terminal, it is displayed in a pager
182 (``less`` if available, otherwise a basic internal pager).
182 (``less`` if available, otherwise a basic internal pager).
183
183
184 Typing ``??word`` or ``word??`` gives access to the full information, including
184 Typing ``??word`` or ``word??`` gives access to the full information, including
185 the source code where possible. Long strings are not snipped.
185 the source code where possible. Long strings are not snipped.
186
186
187 The following magic functions are particularly useful for gathering
187 The following magic functions are particularly useful for gathering
188 information about your working environment. You can get more details by
188 information about your working environment. You can get more details by
189 typing ``%magic`` or querying them individually (``%function_name?``);
189 typing ``%magic`` or querying them individually (``%function_name?``);
190 this is just a summary:
190 this is just a summary:
191
191
192 * **%pdoc <object>**: Print (or run through a pager if too long) the
192 * **%pdoc <object>**: Print (or run through a pager if too long) the
193 docstring for an object. If the given object is a class, it will
193 docstring for an object. If the given object is a class, it will
194 print both the class and the constructor docstrings.
194 print both the class and the constructor docstrings.
195 * **%pdef <object>**: Print the definition header for any callable
195 * **%pdef <object>**: Print the definition header for any callable
196 object. If the object is a class, print the constructor information.
196 object. If the object is a class, print the constructor information.
197 * **%psource <object>**: Print (or run through a pager if too long)
197 * **%psource <object>**: Print (or run through a pager if too long)
198 the source code for an object.
198 the source code for an object.
199 * **%pfile <object>**: Show the entire source file where an object was
199 * **%pfile <object>**: Show the entire source file where an object was
200 defined via a pager, opening it at the line where the object
200 defined via a pager, opening it at the line where the object
201 definition begins.
201 definition begins.
202 * **%who/%whos**: These functions give information about identifiers
202 * **%who/%whos**: These functions give information about identifiers
203 you have defined interactively (not things you loaded or defined
203 you have defined interactively (not things you loaded or defined
204 in your configuration files). %who just prints a list of
204 in your configuration files). %who just prints a list of
205 identifiers and %whos prints a table with some basic details about
205 identifiers and %whos prints a table with some basic details about
206 each identifier.
206 each identifier.
207
207
208 Note that the dynamic object information functions (?/??, ``%pdoc``,
208 Note that the dynamic object information functions (?/??, ``%pdoc``,
209 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
209 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
210 directly on variables. For example, after doing ``import os``, you can use
210 directly on variables. For example, after doing ``import os``, you can use
211 ``os.path.abspath??``.
211 ``os.path.abspath??``.
212
212
213 .. _readline:
213 .. _readline:
214
214
215 Readline-based features
215 Readline-based features
216 -----------------------
216 -----------------------
217
217
218 These features require the GNU readline library, so they won't work if your
218 These features require the GNU readline library, so they won't work if your
219 Python installation lacks readline support. We will first describe the default
219 Python installation lacks readline support. We will first describe the default
220 behavior IPython uses, and then how to change it to suit your preferences.
220 behavior IPython uses, and then how to change it to suit your preferences.
221
221
222
222
223 Command line completion
223 Command line completion
224 +++++++++++++++++++++++
224 +++++++++++++++++++++++
225
225
226 At any time, hitting TAB will complete any available python commands or
226 At any time, hitting TAB will complete any available python commands or
227 variable names, and show you a list of the possible completions if
227 variable names, and show you a list of the possible completions if
228 there's no unambiguous one. It will also complete filenames in the
228 there's no unambiguous one. It will also complete filenames in the
229 current directory if no python names match what you've typed so far.
229 current directory if no python names match what you've typed so far.
230
230
231
231
232 Search command history
232 Search command history
233 ++++++++++++++++++++++
233 ++++++++++++++++++++++
234
234
235 IPython provides two ways for searching through previous input and thus
235 IPython provides two ways for searching through previous input and thus
236 reduce the need for repetitive typing:
236 reduce the need for repetitive typing:
237
237
238 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
238 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
239 (next,down) to search through only the history items that match
239 (next,down) to search through only the history items that match
240 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
240 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
241 prompt, they just behave like normal arrow keys.
241 prompt, they just behave like normal arrow keys.
242 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
242 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
243 searches your history for lines that contain what you've typed so
243 searches your history for lines that contain what you've typed so
244 far, completing as much as it can.
244 far, completing as much as it can.
245
245
246
246
247 Persistent command history across sessions
247 Persistent command history across sessions
248 ++++++++++++++++++++++++++++++++++++++++++
248 ++++++++++++++++++++++++++++++++++++++++++
249
249
250 IPython will save your input history when it leaves and reload it next
250 IPython will save your input history when it leaves and reload it next
251 time you restart it. By default, the history file is named
251 time you restart it. By default, the history file is named
252 $IPYTHON_DIR/profile_<name>/history.sqlite. This allows you to keep
252 $IPYTHONDIR/profile_<name>/history.sqlite. This allows you to keep
253 separate histories related to various tasks: commands related to
253 separate histories related to various tasks: commands related to
254 numerical work will not be clobbered by a system shell history, for
254 numerical work will not be clobbered by a system shell history, for
255 example.
255 example.
256
256
257
257
258 Autoindent
258 Autoindent
259 ++++++++++
259 ++++++++++
260
260
261 IPython can recognize lines ending in ':' and indent the next line,
261 IPython can recognize lines ending in ':' and indent the next line,
262 while also un-indenting automatically after 'raise' or 'return'.
262 while also un-indenting automatically after 'raise' or 'return'.
263
263
264 This feature uses the readline library, so it will honor your
264 This feature uses the readline library, so it will honor your
265 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
265 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
266 to). Adding the following lines to your :file:`.inputrc` file can make
266 to). Adding the following lines to your :file:`.inputrc` file can make
267 indenting/unindenting more convenient (M-i indents, M-u unindents)::
267 indenting/unindenting more convenient (M-i indents, M-u unindents)::
268
268
269 $if Python
269 $if Python
270 "\M-i": " "
270 "\M-i": " "
271 "\M-u": "\d\d\d\d"
271 "\M-u": "\d\d\d\d"
272 $endif
272 $endif
273
273
274 Note that there are 4 spaces between the quote marks after "M-i" above.
274 Note that there are 4 spaces between the quote marks after "M-i" above.
275
275
276 .. warning::
276 .. warning::
277
277
278 Setting the above indents will cause problems with unicode text entry in
278 Setting the above indents will cause problems with unicode text entry in
279 the terminal.
279 the terminal.
280
280
281 .. warning::
281 .. warning::
282
282
283 Autoindent is ON by default, but it can cause problems with the pasting of
283 Autoindent is ON by default, but it can cause problems with the pasting of
284 multi-line indented code (the pasted code gets re-indented on each line). A
284 multi-line indented code (the pasted code gets re-indented on each line). A
285 magic function %autoindent allows you to toggle it on/off at runtime. You
285 magic function %autoindent allows you to toggle it on/off at runtime. You
286 can also disable it permanently on in your :file:`ipython_config.py` file
286 can also disable it permanently on in your :file:`ipython_config.py` file
287 (set TerminalInteractiveShell.autoindent=False).
287 (set TerminalInteractiveShell.autoindent=False).
288
288
289 If you want to paste multiple lines in the terminal, it is recommended that
289 If you want to paste multiple lines in the terminal, it is recommended that
290 you use ``%paste``.
290 you use ``%paste``.
291
291
292
292
293 Customizing readline behavior
293 Customizing readline behavior
294 +++++++++++++++++++++++++++++
294 +++++++++++++++++++++++++++++
295
295
296 All these features are based on the GNU readline library, which has an
296 All these features are based on the GNU readline library, which has an
297 extremely customizable interface. Normally, readline is configured via a
297 extremely customizable interface. Normally, readline is configured via a
298 file which defines the behavior of the library; the details of the
298 file which defines the behavior of the library; the details of the
299 syntax for this can be found in the readline documentation available
299 syntax for this can be found in the readline documentation available
300 with your system or on the Internet. IPython doesn't read this file (if
300 with your system or on the Internet. IPython doesn't read this file (if
301 it exists) directly, but it does support passing to readline valid
301 it exists) directly, but it does support passing to readline valid
302 options via a simple interface. In brief, you can customize readline by
302 options via a simple interface. In brief, you can customize readline by
303 setting the following options in your configuration file (note
303 setting the following options in your configuration file (note
304 that these options can not be specified at the command line):
304 that these options can not be specified at the command line):
305
305
306 * **readline_parse_and_bind**: this holds a list of strings to be executed
306 * **readline_parse_and_bind**: this holds a list of strings to be executed
307 via a readline.parse_and_bind() command. The syntax for valid commands
307 via a readline.parse_and_bind() command. The syntax for valid commands
308 of this kind can be found by reading the documentation for the GNU
308 of this kind can be found by reading the documentation for the GNU
309 readline library, as these commands are of the kind which readline
309 readline library, as these commands are of the kind which readline
310 accepts in its configuration file.
310 accepts in its configuration file.
311 * **readline_remove_delims**: a string of characters to be removed
311 * **readline_remove_delims**: a string of characters to be removed
312 from the default word-delimiters list used by readline, so that
312 from the default word-delimiters list used by readline, so that
313 completions may be performed on strings which contain them. Do not
313 completions may be performed on strings which contain them. Do not
314 change the default value unless you know what you're doing.
314 change the default value unless you know what you're doing.
315
315
316 You will find the default values in your configuration file.
316 You will find the default values in your configuration file.
317
317
318
318
319 Session logging and restoring
319 Session logging and restoring
320 -----------------------------
320 -----------------------------
321
321
322 You can log all input from a session either by starting IPython with the
322 You can log all input from a session either by starting IPython with the
323 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
323 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
324 or by activating the logging at any moment with the magic function %logstart.
324 or by activating the logging at any moment with the magic function %logstart.
325
325
326 Log files can later be reloaded by running them as scripts and IPython
326 Log files can later be reloaded by running them as scripts and IPython
327 will attempt to 'replay' the log by executing all the lines in it, thus
327 will attempt to 'replay' the log by executing all the lines in it, thus
328 restoring the state of a previous session. This feature is not quite
328 restoring the state of a previous session. This feature is not quite
329 perfect, but can still be useful in many cases.
329 perfect, but can still be useful in many cases.
330
330
331 The log files can also be used as a way to have a permanent record of
331 The log files can also be used as a way to have a permanent record of
332 any code you wrote while experimenting. Log files are regular text files
332 any code you wrote while experimenting. Log files are regular text files
333 which you can later open in your favorite text editor to extract code or
333 which you can later open in your favorite text editor to extract code or
334 to 'clean them up' before using them to replay a session.
334 to 'clean them up' before using them to replay a session.
335
335
336 The `%logstart` function for activating logging in mid-session is used as
336 The `%logstart` function for activating logging in mid-session is used as
337 follows::
337 follows::
338
338
339 %logstart [log_name [log_mode]]
339 %logstart [log_name [log_mode]]
340
340
341 If no name is given, it defaults to a file named 'ipython_log.py' in your
341 If no name is given, it defaults to a file named 'ipython_log.py' in your
342 current working directory, in 'rotate' mode (see below).
342 current working directory, in 'rotate' mode (see below).
343
343
344 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
344 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
345 history up to that point and then continues logging.
345 history up to that point and then continues logging.
346
346
347 %logstart takes a second optional parameter: logging mode. This can be
347 %logstart takes a second optional parameter: logging mode. This can be
348 one of (note that the modes are given unquoted):
348 one of (note that the modes are given unquoted):
349
349
350 * [over:] overwrite existing log_name.
350 * [over:] overwrite existing log_name.
351 * [backup:] rename (if exists) to log_name~ and start log_name.
351 * [backup:] rename (if exists) to log_name~ and start log_name.
352 * [append:] well, that says it.
352 * [append:] well, that says it.
353 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
353 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
354
354
355 The %logoff and %logon functions allow you to temporarily stop and
355 The %logoff and %logon functions allow you to temporarily stop and
356 resume logging to a file which had previously been started with
356 resume logging to a file which had previously been started with
357 %logstart. They will fail (with an explanation) if you try to use them
357 %logstart. They will fail (with an explanation) if you try to use them
358 before logging has been started.
358 before logging has been started.
359
359
360 .. _system_shell_access:
360 .. _system_shell_access:
361
361
362 System shell access
362 System shell access
363 -------------------
363 -------------------
364
364
365 Any input line beginning with a ! character is passed verbatim (minus
365 Any input line beginning with a ! character is passed verbatim (minus
366 the !, of course) to the underlying operating system. For example,
366 the !, of course) to the underlying operating system. For example,
367 typing ``!ls`` will run 'ls' in the current directory.
367 typing ``!ls`` will run 'ls' in the current directory.
368
368
369 Manual capture of command output
369 Manual capture of command output
370 --------------------------------
370 --------------------------------
371
371
372 You can assign the result of a system command to a Python variable with the
372 You can assign the result of a system command to a Python variable with the
373 syntax ``myfiles = !ls``. This gets machine readable output from stdout
373 syntax ``myfiles = !ls``. This gets machine readable output from stdout
374 (e.g. without colours), and splits on newlines. To explicitly get this sort of
374 (e.g. without colours), and splits on newlines. To explicitly get this sort of
375 output without assigning to a variable, use two exclamation marks (``!!ls``) or
375 output without assigning to a variable, use two exclamation marks (``!!ls``) or
376 the ``%sx`` magic command.
376 the ``%sx`` magic command.
377
377
378 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
378 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
379 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
379 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
380 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
380 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
381 See :ref:`string_lists` for details.
381 See :ref:`string_lists` for details.
382
382
383 IPython also allows you to expand the value of python variables when
383 IPython also allows you to expand the value of python variables when
384 making system calls. Wrap variables or expressions in {braces}::
384 making system calls. Wrap variables or expressions in {braces}::
385
385
386 In [1]: pyvar = 'Hello world'
386 In [1]: pyvar = 'Hello world'
387 In [2]: !echo "A python variable: {pyvar}"
387 In [2]: !echo "A python variable: {pyvar}"
388 A python variable: Hello world
388 A python variable: Hello world
389 In [3]: import math
389 In [3]: import math
390 In [4]: x = 8
390 In [4]: x = 8
391 In [5]: !echo {math.factorial(x)}
391 In [5]: !echo {math.factorial(x)}
392 40320
392 40320
393
393
394 For simple cases, you can alternatively prepend $ to a variable name::
394 For simple cases, you can alternatively prepend $ to a variable name::
395
395
396 In [6]: !echo $sys.argv
396 In [6]: !echo $sys.argv
397 [/home/fperez/usr/bin/ipython]
397 [/home/fperez/usr/bin/ipython]
398 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
398 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
399 A system variable: /home/fperez
399 A system variable: /home/fperez
400
400
401 System command aliases
401 System command aliases
402 ----------------------
402 ----------------------
403
403
404 The %alias magic function allows you to define magic functions which are in fact
404 The %alias magic function allows you to define magic functions which are in fact
405 system shell commands. These aliases can have parameters.
405 system shell commands. These aliases can have parameters.
406
406
407 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
407 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
408
408
409 Then, typing ``alias_name params`` will execute the system command 'cmd
409 Then, typing ``alias_name params`` will execute the system command 'cmd
410 params' (from your underlying operating system).
410 params' (from your underlying operating system).
411
411
412 You can also define aliases with parameters using %s specifiers (one per
412 You can also define aliases with parameters using %s specifiers (one per
413 parameter). The following example defines the parts function as an
413 parameter). The following example defines the parts function as an
414 alias to the command 'echo first %s second %s' where each %s will be
414 alias to the command 'echo first %s second %s' where each %s will be
415 replaced by a positional parameter to the call to %parts::
415 replaced by a positional parameter to the call to %parts::
416
416
417 In [1]: %alias parts echo first %s second %s
417 In [1]: %alias parts echo first %s second %s
418 In [2]: parts A B
418 In [2]: parts A B
419 first A second B
419 first A second B
420 In [3]: parts A
420 In [3]: parts A
421 ERROR: Alias <parts> requires 2 arguments, 1 given.
421 ERROR: Alias <parts> requires 2 arguments, 1 given.
422
422
423 If called with no parameters, %alias prints the table of currently
423 If called with no parameters, %alias prints the table of currently
424 defined aliases.
424 defined aliases.
425
425
426 The %rehashx magic allows you to load your entire $PATH as
426 The %rehashx magic allows you to load your entire $PATH as
427 ipython aliases. See its docstring for further details.
427 ipython aliases. See its docstring for further details.
428
428
429
429
430 .. _dreload:
430 .. _dreload:
431
431
432 Recursive reload
432 Recursive reload
433 ----------------
433 ----------------
434
434
435 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
435 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
436 module: changes made to any of its dependencies will be reloaded without
436 module: changes made to any of its dependencies will be reloaded without
437 having to exit. To start using it, do::
437 having to exit. To start using it, do::
438
438
439 from IPython.lib.deepreload import reload as dreload
439 from IPython.lib.deepreload import reload as dreload
440
440
441
441
442 Verbose and colored exception traceback printouts
442 Verbose and colored exception traceback printouts
443 -------------------------------------------------
443 -------------------------------------------------
444
444
445 IPython provides the option to see very detailed exception tracebacks,
445 IPython provides the option to see very detailed exception tracebacks,
446 which can be especially useful when debugging large programs. You can
446 which can be especially useful when debugging large programs. You can
447 run any Python file with the %run function to benefit from these
447 run any Python file with the %run function to benefit from these
448 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
448 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
449 be colored (if your terminal supports it) which makes them much easier
449 be colored (if your terminal supports it) which makes them much easier
450 to parse visually.
450 to parse visually.
451
451
452 See the magic xmode and colors functions for details (just type %magic).
452 See the magic xmode and colors functions for details (just type %magic).
453
453
454 These features are basically a terminal version of Ka-Ping Yee's cgitb
454 These features are basically a terminal version of Ka-Ping Yee's cgitb
455 module, now part of the standard Python library.
455 module, now part of the standard Python library.
456
456
457
457
458 .. _input_caching:
458 .. _input_caching:
459
459
460 Input caching system
460 Input caching system
461 --------------------
461 --------------------
462
462
463 IPython offers numbered prompts (In/Out) with input and output caching
463 IPython offers numbered prompts (In/Out) with input and output caching
464 (also referred to as 'input history'). All input is saved and can be
464 (also referred to as 'input history'). All input is saved and can be
465 retrieved as variables (besides the usual arrow key recall), in
465 retrieved as variables (besides the usual arrow key recall), in
466 addition to the %rep magic command that brings a history entry
466 addition to the %rep magic command that brings a history entry
467 up for editing on the next command line.
467 up for editing on the next command line.
468
468
469 The following GLOBAL variables always exist (so don't overwrite them!):
469 The following GLOBAL variables always exist (so don't overwrite them!):
470
470
471 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
471 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
472 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
472 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
473 overwrite In with a variable of your own, you can remake the assignment to the
473 overwrite In with a variable of your own, you can remake the assignment to the
474 internal list with a simple ``In=_ih``.
474 internal list with a simple ``In=_ih``.
475
475
476 Additionally, global variables named _i<n> are dynamically created (<n>
476 Additionally, global variables named _i<n> are dynamically created (<n>
477 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
477 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
478
478
479 For example, what you typed at prompt 14 is available as _i14, _ih[14]
479 For example, what you typed at prompt 14 is available as _i14, _ih[14]
480 and In[14].
480 and In[14].
481
481
482 This allows you to easily cut and paste multi line interactive prompts
482 This allows you to easily cut and paste multi line interactive prompts
483 by printing them out: they print like a clean string, without prompt
483 by printing them out: they print like a clean string, without prompt
484 characters. You can also manipulate them like regular variables (they
484 characters. You can also manipulate them like regular variables (they
485 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
485 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
486 contents of input prompt 9.
486 contents of input prompt 9.
487
487
488 You can also re-execute multiple lines of input easily by using the
488 You can also re-execute multiple lines of input easily by using the
489 magic %rerun or %macro functions. The macro system also allows you to re-execute
489 magic %rerun or %macro functions. The macro system also allows you to re-execute
490 previous lines which include magic function calls (which require special
490 previous lines which include magic function calls (which require special
491 processing). Type %macro? for more details on the macro system.
491 processing). Type %macro? for more details on the macro system.
492
492
493 A history function %hist allows you to see any part of your input
493 A history function %hist allows you to see any part of your input
494 history by printing a range of the _i variables.
494 history by printing a range of the _i variables.
495
495
496 You can also search ('grep') through your history by typing
496 You can also search ('grep') through your history by typing
497 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
497 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
498 etc. You can bring history entries listed by '%hist -g' up for editing
498 etc. You can bring history entries listed by '%hist -g' up for editing
499 with the %recall command, or run them immediately with %rerun.
499 with the %recall command, or run them immediately with %rerun.
500
500
501 .. _output_caching:
501 .. _output_caching:
502
502
503 Output caching system
503 Output caching system
504 ---------------------
504 ---------------------
505
505
506 For output that is returned from actions, a system similar to the input
506 For output that is returned from actions, a system similar to the input
507 cache exists but using _ instead of _i. Only actions that produce a
507 cache exists but using _ instead of _i. Only actions that produce a
508 result (NOT assignments, for example) are cached. If you are familiar
508 result (NOT assignments, for example) are cached. If you are familiar
509 with Mathematica, IPython's _ variables behave exactly like
509 with Mathematica, IPython's _ variables behave exactly like
510 Mathematica's % variables.
510 Mathematica's % variables.
511
511
512 The following GLOBAL variables always exist (so don't overwrite them!):
512 The following GLOBAL variables always exist (so don't overwrite them!):
513
513
514 * [_] (a single underscore) : stores previous output, like Python's
514 * [_] (a single underscore) : stores previous output, like Python's
515 default interpreter.
515 default interpreter.
516 * [__] (two underscores): next previous.
516 * [__] (two underscores): next previous.
517 * [___] (three underscores): next-next previous.
517 * [___] (three underscores): next-next previous.
518
518
519 Additionally, global variables named _<n> are dynamically created (<n>
519 Additionally, global variables named _<n> are dynamically created (<n>
520 being the prompt counter), such that the result of output <n> is always
520 being the prompt counter), such that the result of output <n> is always
521 available as _<n> (don't use the angle brackets, just the number, e.g.
521 available as _<n> (don't use the angle brackets, just the number, e.g.
522 _21).
522 _21).
523
523
524 These variables are also stored in a global dictionary (not a
524 These variables are also stored in a global dictionary (not a
525 list, since it only has entries for lines which returned a result)
525 list, since it only has entries for lines which returned a result)
526 available under the names _oh and Out (similar to _ih and In). So the
526 available under the names _oh and Out (similar to _ih and In). So the
527 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
527 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
528 accidentally overwrite the Out variable you can recover it by typing
528 accidentally overwrite the Out variable you can recover it by typing
529 'Out=_oh' at the prompt.
529 'Out=_oh' at the prompt.
530
530
531 This system obviously can potentially put heavy memory demands on your
531 This system obviously can potentially put heavy memory demands on your
532 system, since it prevents Python's garbage collector from removing any
532 system, since it prevents Python's garbage collector from removing any
533 previously computed results. You can control how many results are kept
533 previously computed results. You can control how many results are kept
534 in memory with the option (at the command line or in your configuration
534 in memory with the option (at the command line or in your configuration
535 file) cache_size. If you set it to 0, the whole system is completely
535 file) cache_size. If you set it to 0, the whole system is completely
536 disabled and the prompts revert to the classic '>>>' of normal Python.
536 disabled and the prompts revert to the classic '>>>' of normal Python.
537
537
538
538
539 Directory history
539 Directory history
540 -----------------
540 -----------------
541
541
542 Your history of visited directories is kept in the global list _dh, and
542 Your history of visited directories is kept in the global list _dh, and
543 the magic %cd command can be used to go to any entry in that list. The
543 the magic %cd command can be used to go to any entry in that list. The
544 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
544 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
545 conveniently view the directory history.
545 conveniently view the directory history.
546
546
547
547
548 Automatic parentheses and quotes
548 Automatic parentheses and quotes
549 --------------------------------
549 --------------------------------
550
550
551 These features were adapted from Nathan Gray's LazyPython. They are
551 These features were adapted from Nathan Gray's LazyPython. They are
552 meant to allow less typing for common situations.
552 meant to allow less typing for common situations.
553
553
554
554
555 Automatic parentheses
555 Automatic parentheses
556 +++++++++++++++++++++
556 +++++++++++++++++++++
557
557
558 Callable objects (i.e. functions, methods, etc) can be invoked like this
558 Callable objects (i.e. functions, methods, etc) can be invoked like this
559 (notice the commas between the arguments)::
559 (notice the commas between the arguments)::
560
560
561 In [1]: callable_ob arg1, arg2, arg3
561 In [1]: callable_ob arg1, arg2, arg3
562 ------> callable_ob(arg1, arg2, arg3)
562 ------> callable_ob(arg1, arg2, arg3)
563
563
564 You can force automatic parentheses by using '/' as the first character
564 You can force automatic parentheses by using '/' as the first character
565 of a line. For example::
565 of a line. For example::
566
566
567 In [2]: /globals # becomes 'globals()'
567 In [2]: /globals # becomes 'globals()'
568
568
569 Note that the '/' MUST be the first character on the line! This won't work::
569 Note that the '/' MUST be the first character on the line! This won't work::
570
570
571 In [3]: print /globals # syntax error
571 In [3]: print /globals # syntax error
572
572
573 In most cases the automatic algorithm should work, so you should rarely
573 In most cases the automatic algorithm should work, so you should rarely
574 need to explicitly invoke /. One notable exception is if you are trying
574 need to explicitly invoke /. One notable exception is if you are trying
575 to call a function with a list of tuples as arguments (the parenthesis
575 to call a function with a list of tuples as arguments (the parenthesis
576 will confuse IPython)::
576 will confuse IPython)::
577
577
578 In [4]: zip (1,2,3),(4,5,6) # won't work
578 In [4]: zip (1,2,3),(4,5,6) # won't work
579
579
580 but this will work::
580 but this will work::
581
581
582 In [5]: /zip (1,2,3),(4,5,6)
582 In [5]: /zip (1,2,3),(4,5,6)
583 ------> zip ((1,2,3),(4,5,6))
583 ------> zip ((1,2,3),(4,5,6))
584 Out[5]: [(1, 4), (2, 5), (3, 6)]
584 Out[5]: [(1, 4), (2, 5), (3, 6)]
585
585
586 IPython tells you that it has altered your command line by displaying
586 IPython tells you that it has altered your command line by displaying
587 the new command line preceded by ->. e.g.::
587 the new command line preceded by ->. e.g.::
588
588
589 In [6]: callable list
589 In [6]: callable list
590 ------> callable(list)
590 ------> callable(list)
591
591
592
592
593 Automatic quoting
593 Automatic quoting
594 +++++++++++++++++
594 +++++++++++++++++
595
595
596 You can force automatic quoting of a function's arguments by using ','
596 You can force automatic quoting of a function's arguments by using ','
597 or ';' as the first character of a line. For example::
597 or ';' as the first character of a line. For example::
598
598
599 In [1]: ,my_function /home/me # becomes my_function("/home/me")
599 In [1]: ,my_function /home/me # becomes my_function("/home/me")
600
600
601 If you use ';' the whole argument is quoted as a single string, while ',' splits
601 If you use ';' the whole argument is quoted as a single string, while ',' splits
602 on whitespace::
602 on whitespace::
603
603
604 In [2]: ,my_function a b c # becomes my_function("a","b","c")
604 In [2]: ,my_function a b c # becomes my_function("a","b","c")
605
605
606 In [3]: ;my_function a b c # becomes my_function("a b c")
606 In [3]: ;my_function a b c # becomes my_function("a b c")
607
607
608 Note that the ',' or ';' MUST be the first character on the line! This
608 Note that the ',' or ';' MUST be the first character on the line! This
609 won't work::
609 won't work::
610
610
611 In [4]: x = ,my_function /home/me # syntax error
611 In [4]: x = ,my_function /home/me # syntax error
612
612
613 IPython as your default Python environment
613 IPython as your default Python environment
614 ==========================================
614 ==========================================
615
615
616 Python honors the environment variable PYTHONSTARTUP and will execute at
616 Python honors the environment variable PYTHONSTARTUP and will execute at
617 startup the file referenced by this variable. If you put the following code at
617 startup the file referenced by this variable. If you put the following code at
618 the end of that file, then IPython will be your working environment anytime you
618 the end of that file, then IPython will be your working environment anytime you
619 start Python::
619 start Python::
620
620
621 from IPython.frontend.terminal.ipapp import launch_new_instance
621 from IPython.frontend.terminal.ipapp import launch_new_instance
622 launch_new_instance()
622 launch_new_instance()
623 raise SystemExit
623 raise SystemExit
624
624
625 The ``raise SystemExit`` is needed to exit Python when
625 The ``raise SystemExit`` is needed to exit Python when
626 it finishes, otherwise you'll be back at the normal Python '>>>'
626 it finishes, otherwise you'll be back at the normal Python '>>>'
627 prompt.
627 prompt.
628
628
629 This is probably useful to developers who manage multiple Python
629 This is probably useful to developers who manage multiple Python
630 versions and don't want to have correspondingly multiple IPython
630 versions and don't want to have correspondingly multiple IPython
631 versions. Note that in this mode, there is no way to pass IPython any
631 versions. Note that in this mode, there is no way to pass IPython any
632 command-line options, as those are trapped first by Python itself.
632 command-line options, as those are trapped first by Python itself.
633
633
634 .. _Embedding:
634 .. _Embedding:
635
635
636 Embedding IPython
636 Embedding IPython
637 =================
637 =================
638
638
639 It is possible to start an IPython instance inside your own Python
639 It is possible to start an IPython instance inside your own Python
640 programs. This allows you to evaluate dynamically the state of your
640 programs. This allows you to evaluate dynamically the state of your
641 code, operate with your variables, analyze them, etc. Note however that
641 code, operate with your variables, analyze them, etc. Note however that
642 any changes you make to values while in the shell do not propagate back
642 any changes you make to values while in the shell do not propagate back
643 to the running code, so it is safe to modify your values because you
643 to the running code, so it is safe to modify your values because you
644 won't break your code in bizarre ways by doing so.
644 won't break your code in bizarre ways by doing so.
645
645
646 .. note::
646 .. note::
647
647
648 At present, trying to embed IPython from inside IPython causes problems. Run
648 At present, trying to embed IPython from inside IPython causes problems. Run
649 the code samples below outside IPython.
649 the code samples below outside IPython.
650
650
651 This feature allows you to easily have a fully functional python
651 This feature allows you to easily have a fully functional python
652 environment for doing object introspection anywhere in your code with a
652 environment for doing object introspection anywhere in your code with a
653 simple function call. In some cases a simple print statement is enough,
653 simple function call. In some cases a simple print statement is enough,
654 but if you need to do more detailed analysis of a code fragment this
654 but if you need to do more detailed analysis of a code fragment this
655 feature can be very valuable.
655 feature can be very valuable.
656
656
657 It can also be useful in scientific computing situations where it is
657 It can also be useful in scientific computing situations where it is
658 common to need to do some automatic, computationally intensive part and
658 common to need to do some automatic, computationally intensive part and
659 then stop to look at data, plots, etc.
659 then stop to look at data, plots, etc.
660 Opening an IPython instance will give you full access to your data and
660 Opening an IPython instance will give you full access to your data and
661 functions, and you can resume program execution once you are done with
661 functions, and you can resume program execution once you are done with
662 the interactive part (perhaps to stop again later, as many times as
662 the interactive part (perhaps to stop again later, as many times as
663 needed).
663 needed).
664
664
665 The following code snippet is the bare minimum you need to include in
665 The following code snippet is the bare minimum you need to include in
666 your Python programs for this to work (detailed examples follow later)::
666 your Python programs for this to work (detailed examples follow later)::
667
667
668 from IPython import embed
668 from IPython import embed
669
669
670 embed() # this call anywhere in your program will start IPython
670 embed() # this call anywhere in your program will start IPython
671
671
672 .. note::
672 .. note::
673
673
674 As of 0.13, you can embed an IPython *kernel*, for use with qtconsole,
674 As of 0.13, you can embed an IPython *kernel*, for use with qtconsole,
675 etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``.
675 etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``.
676 It should function just the same as regular embed, but you connect
676 It should function just the same as regular embed, but you connect
677 an external frontend rather than IPython starting up in the local
677 an external frontend rather than IPython starting up in the local
678 terminal.
678 terminal.
679
679
680 You can run embedded instances even in code which is itself being run at
680 You can run embedded instances even in code which is itself being run at
681 the IPython interactive prompt with '%run <filename>'. Since it's easy
681 the IPython interactive prompt with '%run <filename>'. Since it's easy
682 to get lost as to where you are (in your top-level IPython or in your
682 to get lost as to where you are (in your top-level IPython or in your
683 embedded one), it's a good idea in such cases to set the in/out prompts
683 embedded one), it's a good idea in such cases to set the in/out prompts
684 to something different for the embedded instances. The code examples
684 to something different for the embedded instances. The code examples
685 below illustrate this.
685 below illustrate this.
686
686
687 You can also have multiple IPython instances in your program and open
687 You can also have multiple IPython instances in your program and open
688 them separately, for example with different options for data
688 them separately, for example with different options for data
689 presentation. If you close and open the same instance multiple times,
689 presentation. If you close and open the same instance multiple times,
690 its prompt counters simply continue from each execution to the next.
690 its prompt counters simply continue from each execution to the next.
691
691
692 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
692 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
693 module for more details on the use of this system.
693 module for more details on the use of this system.
694
694
695 The following sample file illustrating how to use the embedding
695 The following sample file illustrating how to use the embedding
696 functionality is provided in the examples directory as example-embed.py.
696 functionality is provided in the examples directory as example-embed.py.
697 It should be fairly self-explanatory:
697 It should be fairly self-explanatory:
698
698
699 .. literalinclude:: ../../examples/core/example-embed.py
699 .. literalinclude:: ../../examples/core/example-embed.py
700 :language: python
700 :language: python
701
701
702 Once you understand how the system functions, you can use the following
702 Once you understand how the system functions, you can use the following
703 code fragments in your programs which are ready for cut and paste:
703 code fragments in your programs which are ready for cut and paste:
704
704
705 .. literalinclude:: ../../examples/core/example-embed-short.py
705 .. literalinclude:: ../../examples/core/example-embed-short.py
706 :language: python
706 :language: python
707
707
708 Using the Python debugger (pdb)
708 Using the Python debugger (pdb)
709 ===============================
709 ===============================
710
710
711 Running entire programs via pdb
711 Running entire programs via pdb
712 -------------------------------
712 -------------------------------
713
713
714 pdb, the Python debugger, is a powerful interactive debugger which
714 pdb, the Python debugger, is a powerful interactive debugger which
715 allows you to step through code, set breakpoints, watch variables,
715 allows you to step through code, set breakpoints, watch variables,
716 etc. IPython makes it very easy to start any script under the control
716 etc. IPython makes it very easy to start any script under the control
717 of pdb, regardless of whether you have wrapped it into a 'main()'
717 of pdb, regardless of whether you have wrapped it into a 'main()'
718 function or not. For this, simply type '%run -d myscript' at an
718 function or not. For this, simply type '%run -d myscript' at an
719 IPython prompt. See the %run command's documentation (via '%run?' or
719 IPython prompt. See the %run command's documentation (via '%run?' or
720 in Sec. magic_ for more details, including how to control where pdb
720 in Sec. magic_ for more details, including how to control where pdb
721 will stop execution first.
721 will stop execution first.
722
722
723 For more information on the use of the pdb debugger, read the included
723 For more information on the use of the pdb debugger, read the included
724 pdb.doc file (part of the standard Python distribution). On a stock
724 pdb.doc file (part of the standard Python distribution). On a stock
725 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
725 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
726 easiest way to read it is by using the help() function of the pdb module
726 easiest way to read it is by using the help() function of the pdb module
727 as follows (in an IPython prompt)::
727 as follows (in an IPython prompt)::
728
728
729 In [1]: import pdb
729 In [1]: import pdb
730 In [2]: pdb.help()
730 In [2]: pdb.help()
731
731
732 This will load the pdb.doc document in a file viewer for you automatically.
732 This will load the pdb.doc document in a file viewer for you automatically.
733
733
734
734
735 Automatic invocation of pdb on exceptions
735 Automatic invocation of pdb on exceptions
736 -----------------------------------------
736 -----------------------------------------
737
737
738 IPython, if started with the ``--pdb`` option (or if the option is set in
738 IPython, if started with the ``--pdb`` option (or if the option is set in
739 your config file) can call the Python pdb debugger every time your code
739 your config file) can call the Python pdb debugger every time your code
740 triggers an uncaught exception. This feature
740 triggers an uncaught exception. This feature
741 can also be toggled at any time with the %pdb magic command. This can be
741 can also be toggled at any time with the %pdb magic command. This can be
742 extremely useful in order to find the origin of subtle bugs, because pdb
742 extremely useful in order to find the origin of subtle bugs, because pdb
743 opens up at the point in your code which triggered the exception, and
743 opens up at the point in your code which triggered the exception, and
744 while your program is at this point 'dead', all the data is still
744 while your program is at this point 'dead', all the data is still
745 available and you can walk up and down the stack frame and understand
745 available and you can walk up and down the stack frame and understand
746 the origin of the problem.
746 the origin of the problem.
747
747
748 Furthermore, you can use these debugging facilities both with the
748 Furthermore, you can use these debugging facilities both with the
749 embedded IPython mode and without IPython at all. For an embedded shell
749 embedded IPython mode and without IPython at all. For an embedded shell
750 (see sec. Embedding_), simply call the constructor with
750 (see sec. Embedding_), simply call the constructor with
751 ``--pdb`` in the argument string and pdb will automatically be called if an
751 ``--pdb`` in the argument string and pdb will automatically be called if an
752 uncaught exception is triggered by your code.
752 uncaught exception is triggered by your code.
753
753
754 For stand-alone use of the feature in your programs which do not use
754 For stand-alone use of the feature in your programs which do not use
755 IPython at all, put the following lines toward the top of your 'main'
755 IPython at all, put the following lines toward the top of your 'main'
756 routine::
756 routine::
757
757
758 import sys
758 import sys
759 from IPython.core import ultratb
759 from IPython.core import ultratb
760 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
760 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
761 color_scheme='Linux', call_pdb=1)
761 color_scheme='Linux', call_pdb=1)
762
762
763 The mode keyword can be either 'Verbose' or 'Plain', giving either very
763 The mode keyword can be either 'Verbose' or 'Plain', giving either very
764 detailed or normal tracebacks respectively. The color_scheme keyword can
764 detailed or normal tracebacks respectively. The color_scheme keyword can
765 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
765 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
766 options which can be set in IPython with ``--colors`` and ``--xmode``.
766 options which can be set in IPython with ``--colors`` and ``--xmode``.
767
767
768 This will give any of your programs detailed, colored tracebacks with
768 This will give any of your programs detailed, colored tracebacks with
769 automatic invocation of pdb.
769 automatic invocation of pdb.
770
770
771
771
772 Extensions for syntax processing
772 Extensions for syntax processing
773 ================================
773 ================================
774
774
775 This isn't for the faint of heart, because the potential for breaking
775 This isn't for the faint of heart, because the potential for breaking
776 things is quite high. But it can be a very powerful and useful feature.
776 things is quite high. But it can be a very powerful and useful feature.
777 In a nutshell, you can redefine the way IPython processes the user input
777 In a nutshell, you can redefine the way IPython processes the user input
778 line to accept new, special extensions to the syntax without needing to
778 line to accept new, special extensions to the syntax without needing to
779 change any of IPython's own code.
779 change any of IPython's own code.
780
780
781 In the IPython/extensions directory you will find some examples
781 In the IPython/extensions directory you will find some examples
782 supplied, which we will briefly describe now. These can be used 'as is'
782 supplied, which we will briefly describe now. These can be used 'as is'
783 (and both provide very useful functionality), or you can use them as a
783 (and both provide very useful functionality), or you can use them as a
784 starting point for writing your own extensions.
784 starting point for writing your own extensions.
785
785
786 .. _pasting_with_prompts:
786 .. _pasting_with_prompts:
787
787
788 Pasting of code starting with Python or IPython prompts
788 Pasting of code starting with Python or IPython prompts
789 -------------------------------------------------------
789 -------------------------------------------------------
790
790
791 IPython is smart enough to filter out input prompts, be they plain Python ones
791 IPython is smart enough to filter out input prompts, be they plain Python ones
792 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and `` ...:``). You can
792 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and `` ...:``). You can
793 therefore copy and paste from existing interactive sessions without worry.
793 therefore copy and paste from existing interactive sessions without worry.
794
794
795 The following is a 'screenshot' of how things work, copying an example from the
795 The following is a 'screenshot' of how things work, copying an example from the
796 standard Python tutorial::
796 standard Python tutorial::
797
797
798 In [1]: >>> # Fibonacci series:
798 In [1]: >>> # Fibonacci series:
799
799
800 In [2]: ... # the sum of two elements defines the next
800 In [2]: ... # the sum of two elements defines the next
801
801
802 In [3]: ... a, b = 0, 1
802 In [3]: ... a, b = 0, 1
803
803
804 In [4]: >>> while b < 10:
804 In [4]: >>> while b < 10:
805 ...: ... print b
805 ...: ... print b
806 ...: ... a, b = b, a+b
806 ...: ... a, b = b, a+b
807 ...:
807 ...:
808 1
808 1
809 1
809 1
810 2
810 2
811 3
811 3
812 5
812 5
813 8
813 8
814
814
815 And pasting from IPython sessions works equally well::
815 And pasting from IPython sessions works equally well::
816
816
817 In [1]: In [5]: def f(x):
817 In [1]: In [5]: def f(x):
818 ...: ...: "A simple function"
818 ...: ...: "A simple function"
819 ...: ...: return x**2
819 ...: ...: return x**2
820 ...: ...:
820 ...: ...:
821
821
822 In [2]: f(3)
822 In [2]: f(3)
823 Out[2]: 9
823 Out[2]: 9
824
824
825 .. _gui_support:
825 .. _gui_support:
826
826
827 GUI event loop support
827 GUI event loop support
828 ======================
828 ======================
829
829
830 .. versionadded:: 0.11
830 .. versionadded:: 0.11
831 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
831 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
832
832
833 IPython has excellent support for working interactively with Graphical User
833 IPython has excellent support for working interactively with Graphical User
834 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
834 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
835 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
835 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
836 is extremely robust compared to our previous thread-based version. The
836 is extremely robust compared to our previous thread-based version. The
837 advantages of this are:
837 advantages of this are:
838
838
839 * GUIs can be enabled and disabled dynamically at runtime.
839 * GUIs can be enabled and disabled dynamically at runtime.
840 * The active GUI can be switched dynamically at runtime.
840 * The active GUI can be switched dynamically at runtime.
841 * In some cases, multiple GUIs can run simultaneously with no problems.
841 * In some cases, multiple GUIs can run simultaneously with no problems.
842 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
842 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
843 all of these things.
843 all of these things.
844
844
845 For users, enabling GUI event loop integration is simple. You simple use the
845 For users, enabling GUI event loop integration is simple. You simple use the
846 ``%gui`` magic as follows::
846 ``%gui`` magic as follows::
847
847
848 %gui [GUINAME]
848 %gui [GUINAME]
849
849
850 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
850 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
851 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
851 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
852
852
853 Thus, to use wxPython interactively and create a running :class:`wx.App`
853 Thus, to use wxPython interactively and create a running :class:`wx.App`
854 object, do::
854 object, do::
855
855
856 %gui wx
856 %gui wx
857
857
858 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
858 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
859 see :ref:`this section <matplotlib_support>`.
859 see :ref:`this section <matplotlib_support>`.
860
860
861 For developers that want to use IPython's GUI event loop integration in the
861 For developers that want to use IPython's GUI event loop integration in the
862 form of a library, these capabilities are exposed in library form in the
862 form of a library, these capabilities are exposed in library form in the
863 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
863 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
864 Interested developers should see the module docstrings for more information,
864 Interested developers should see the module docstrings for more information,
865 but there are a few points that should be mentioned here.
865 but there are a few points that should be mentioned here.
866
866
867 First, the ``PyOSInputHook`` approach only works in command line settings
867 First, the ``PyOSInputHook`` approach only works in command line settings
868 where readline is activated. The integration with various eventloops
868 where readline is activated. The integration with various eventloops
869 is handled somewhat differently (and more simply) when using the standalone
869 is handled somewhat differently (and more simply) when using the standalone
870 kernel, as in the qtconsole and notebook.
870 kernel, as in the qtconsole and notebook.
871
871
872 Second, when using the ``PyOSInputHook`` approach, a GUI application should
872 Second, when using the ``PyOSInputHook`` approach, a GUI application should
873 *not* start its event loop. Instead all of this is handled by the
873 *not* start its event loop. Instead all of this is handled by the
874 ``PyOSInputHook``. This means that applications that are meant to be used both
874 ``PyOSInputHook``. This means that applications that are meant to be used both
875 in IPython and as standalone apps need to have special code to detects how the
875 in IPython and as standalone apps need to have special code to detects how the
876 application is being run. We highly recommend using IPython's support for this.
876 application is being run. We highly recommend using IPython's support for this.
877 Since the details vary slightly between toolkits, we point you to the various
877 Since the details vary slightly between toolkits, we point you to the various
878 examples in our source directory :file:`docs/examples/lib` that demonstrate
878 examples in our source directory :file:`docs/examples/lib` that demonstrate
879 these capabilities.
879 these capabilities.
880
880
881 Third, unlike previous versions of IPython, we no longer "hijack" (replace
881 Third, unlike previous versions of IPython, we no longer "hijack" (replace
882 them with no-ops) the event loops. This is done to allow applications that
882 them with no-ops) the event loops. This is done to allow applications that
883 actually need to run the real event loops to do so. This is often needed to
883 actually need to run the real event loops to do so. This is often needed to
884 process pending events at critical points.
884 process pending events at critical points.
885
885
886 Finally, we also have a number of examples in our source directory
886 Finally, we also have a number of examples in our source directory
887 :file:`docs/examples/lib` that demonstrate these capabilities.
887 :file:`docs/examples/lib` that demonstrate these capabilities.
888
888
889 PyQt and PySide
889 PyQt and PySide
890 ---------------
890 ---------------
891
891
892 .. attempt at explanation of the complete mess that is Qt support
892 .. attempt at explanation of the complete mess that is Qt support
893
893
894 When you use ``--gui=qt`` or ``--pylab=qt``, IPython can work with either
894 When you use ``--gui=qt`` or ``--pylab=qt``, IPython can work with either
895 PyQt4 or PySide. There are three options for configuration here, because
895 PyQt4 or PySide. There are three options for configuration here, because
896 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
896 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
897 Python 2, and the more natural v2, which is the only API supported by PySide.
897 Python 2, and the more natural v2, which is the only API supported by PySide.
898 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
898 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
899 uses v2, but you can still use any interface in your code, since the
899 uses v2, but you can still use any interface in your code, since the
900 Qt frontend is in a different process.
900 Qt frontend is in a different process.
901
901
902 The default will be to import PyQt4 without configuration of the APIs, thus
902 The default will be to import PyQt4 without configuration of the APIs, thus
903 matching what most applications would expect. It will fall back of PySide if
903 matching what most applications would expect. It will fall back of PySide if
904 PyQt4 is unavailable.
904 PyQt4 is unavailable.
905
905
906 If specified, IPython will respect the environment variable ``QT_API`` used
906 If specified, IPython will respect the environment variable ``QT_API`` used
907 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
907 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
908 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
908 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
909 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
909 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
910 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
910 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
911
911
912 If you launch IPython in pylab mode with ``ipython --pylab=qt``, then IPython
912 If you launch IPython in pylab mode with ``ipython --pylab=qt``, then IPython
913 will ask matplotlib which Qt library to use (only if QT_API is *not set*), via
913 will ask matplotlib which Qt library to use (only if QT_API is *not set*), via
914 the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or older, then
914 the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or older, then
915 IPython will always use PyQt4 without setting the v2 APIs, since neither v2
915 IPython will always use PyQt4 without setting the v2 APIs, since neither v2
916 PyQt nor PySide work.
916 PyQt nor PySide work.
917
917
918 .. warning::
918 .. warning::
919
919
920 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
920 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
921 to work with IPython's qt integration, because otherwise PyQt4 will be
921 to work with IPython's qt integration, because otherwise PyQt4 will be
922 loaded in an incompatible mode.
922 loaded in an incompatible mode.
923
923
924 It also means that you must *not* have ``QT_API`` set if you want to
924 It also means that you must *not* have ``QT_API`` set if you want to
925 use ``--gui=qt`` with code that requires PyQt4 API v1.
925 use ``--gui=qt`` with code that requires PyQt4 API v1.
926
926
927
927
928 .. _matplotlib_support:
928 .. _matplotlib_support:
929
929
930 Plotting with matplotlib
930 Plotting with matplotlib
931 ========================
931 ========================
932
932
933 `Matplotlib`_ provides high quality 2D and 3D plotting for Python. Matplotlib
933 `Matplotlib`_ provides high quality 2D and 3D plotting for Python. Matplotlib
934 can produce plots on screen using a variety of GUI toolkits, including Tk,
934 can produce plots on screen using a variety of GUI toolkits, including Tk,
935 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
935 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
936 scientific computing, all with a syntax compatible with that of the popular
936 scientific computing, all with a syntax compatible with that of the popular
937 Matlab program.
937 Matlab program.
938
938
939 To start IPython with matplotlib support, use the ``--pylab`` switch. If no
939 To start IPython with matplotlib support, use the ``--pylab`` switch. If no
940 arguments are given, IPython will automatically detect your choice of
940 arguments are given, IPython will automatically detect your choice of
941 matplotlib backend. You can also request a specific backend with ``--pylab
941 matplotlib backend. You can also request a specific backend with ``--pylab
942 backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx', 'gtk', 'osx'.
942 backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx', 'gtk', 'osx'.
943 In the web notebook and Qt console, 'inline' is also a valid backend value,
943 In the web notebook and Qt console, 'inline' is also a valid backend value,
944 which produces static figures inlined inside the application window instead of
944 which produces static figures inlined inside the application window instead of
945 matplotlib's interactive figures that live in separate windows.
945 matplotlib's interactive figures that live in separate windows.
946
946
947 .. _Matplotlib: http://matplotlib.sourceforge.net
947 .. _Matplotlib: http://matplotlib.sourceforge.net
948
948
949 .. _interactive_demos:
949 .. _interactive_demos:
950
950
951 Interactive demos with IPython
951 Interactive demos with IPython
952 ==============================
952 ==============================
953
953
954 IPython ships with a basic system for running scripts interactively in
954 IPython ships with a basic system for running scripts interactively in
955 sections, useful when presenting code to audiences. A few tags embedded
955 sections, useful when presenting code to audiences. A few tags embedded
956 in comments (so that the script remains valid Python code) divide a file
956 in comments (so that the script remains valid Python code) divide a file
957 into separate blocks, and the demo can be run one block at a time, with
957 into separate blocks, and the demo can be run one block at a time, with
958 IPython printing (with syntax highlighting) the block before executing
958 IPython printing (with syntax highlighting) the block before executing
959 it, and returning to the interactive prompt after each block. The
959 it, and returning to the interactive prompt after each block. The
960 interactive namespace is updated after each block is run with the
960 interactive namespace is updated after each block is run with the
961 contents of the demo's namespace.
961 contents of the demo's namespace.
962
962
963 This allows you to show a piece of code, run it and then execute
963 This allows you to show a piece of code, run it and then execute
964 interactively commands based on the variables just created. Once you
964 interactively commands based on the variables just created. Once you
965 want to continue, you simply execute the next block of the demo. The
965 want to continue, you simply execute the next block of the demo. The
966 following listing shows the markup necessary for dividing a script into
966 following listing shows the markup necessary for dividing a script into
967 sections for execution as a demo:
967 sections for execution as a demo:
968
968
969 .. literalinclude:: ../../examples/lib/example-demo.py
969 .. literalinclude:: ../../examples/lib/example-demo.py
970 :language: python
970 :language: python
971
971
972 In order to run a file as a demo, you must first make a Demo object out
972 In order to run a file as a demo, you must first make a Demo object out
973 of it. If the file is named myscript.py, the following code will make a
973 of it. If the file is named myscript.py, the following code will make a
974 demo::
974 demo::
975
975
976 from IPython.lib.demo import Demo
976 from IPython.lib.demo import Demo
977
977
978 mydemo = Demo('myscript.py')
978 mydemo = Demo('myscript.py')
979
979
980 This creates the mydemo object, whose blocks you run one at a time by
980 This creates the mydemo object, whose blocks you run one at a time by
981 simply calling the object with no arguments. If you have autocall active
981 simply calling the object with no arguments. If you have autocall active
982 in IPython (the default), all you need to do is type::
982 in IPython (the default), all you need to do is type::
983
983
984 mydemo
984 mydemo
985
985
986 and IPython will call it, executing each block. Demo objects can be
986 and IPython will call it, executing each block. Demo objects can be
987 restarted, you can move forward or back skipping blocks, re-execute the
987 restarted, you can move forward or back skipping blocks, re-execute the
988 last block, etc. Simply use the Tab key on a demo object to see its
988 last block, etc. Simply use the Tab key on a demo object to see its
989 methods, and call '?' on them to see their docstrings for more usage
989 methods, and call '?' on them to see their docstrings for more usage
990 details. In addition, the demo module itself contains a comprehensive
990 details. In addition, the demo module itself contains a comprehensive
991 docstring, which you can access via::
991 docstring, which you can access via::
992
992
993 from IPython.lib import demo
993 from IPython.lib import demo
994
994
995 demo?
995 demo?
996
996
997 Limitations: It is important to note that these demos are limited to
997 Limitations: It is important to note that these demos are limited to
998 fairly simple uses. In particular, you cannot break up sections within
998 fairly simple uses. In particular, you cannot break up sections within
999 indented code (loops, if statements, function definitions, etc.)
999 indented code (loops, if statements, function definitions, etc.)
1000 Supporting something like this would basically require tracking the
1000 Supporting something like this would basically require tracking the
1001 internal execution state of the Python interpreter, so only top-level
1001 internal execution state of the Python interpreter, so only top-level
1002 divisions are allowed. If you want to be able to open an IPython
1002 divisions are allowed. If you want to be able to open an IPython
1003 instance at an arbitrary point in a program, you can use IPython's
1003 instance at an arbitrary point in a program, you can use IPython's
1004 embedding facilities, see :func:`IPython.embed` for details.
1004 embedding facilities, see :func:`IPython.embed` for details.
1005
1005
@@ -1,294 +1,294 b''
1 .. _ipython_as_shell:
1 .. _ipython_as_shell:
2
2
3 =========================
3 =========================
4 IPython as a system shell
4 IPython as a system shell
5 =========================
5 =========================
6
6
7 .. warning::
7 .. warning::
8
8
9 As of the 0.11 version of IPython, most of the APIs used by the shell
9 As of the 0.11 version of IPython, most of the APIs used by the shell
10 profile have been changed, so the profile currently does very little
10 profile have been changed, so the profile currently does very little
11 beyond changing the IPython prompt. To help restore the shell
11 beyond changing the IPython prompt. To help restore the shell
12 profile to past functionality described here, the old code is found in
12 profile to past functionality described here, the old code is found in
13 :file:`IPython/deathrow`, which needs to be updated to use the
13 :file:`IPython/deathrow`, which needs to be updated to use the
14 APIs in 0.11.
14 APIs in 0.11.
15
15
16 Overview
16 Overview
17 ========
17 ========
18
18
19 The 'sh' profile optimizes IPython for system shell usage. Apart from
19 The 'sh' profile optimizes IPython for system shell usage. Apart from
20 certain job control functionality that is present in unix (ctrl+z does
20 certain job control functionality that is present in unix (ctrl+z does
21 "suspend"), the sh profile should provide you with most of the
21 "suspend"), the sh profile should provide you with most of the
22 functionality you use daily in system shell, and more. Invoke IPython
22 functionality you use daily in system shell, and more. Invoke IPython
23 in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching
23 in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching
24 the "pysh" shortcut in start menu.
24 the "pysh" shortcut in start menu.
25
25
26 If you want to use the features of sh profile as your defaults (which
26 If you want to use the features of sh profile as your defaults (which
27 might be a good idea if you use other profiles a lot of the time but
27 might be a good idea if you use other profiles a lot of the time but
28 still want the convenience of sh profile), add ``import ipy_profile_sh``
28 still want the convenience of sh profile), add ``import ipy_profile_sh``
29 to your $IPYTHON_DIR/ipy_user_conf.py.
29 to your $IPYTHONDIR/ipy_user_conf.py.
30
30
31 The 'sh' profile is different from the default profile in that:
31 The 'sh' profile is different from the default profile in that:
32
32
33 * Prompt shows the current directory
33 * Prompt shows the current directory
34 * Spacing between prompts and input is more compact (no padding with
34 * Spacing between prompts and input is more compact (no padding with
35 empty lines). The startup banner is more compact as well.
35 empty lines). The startup banner is more compact as well.
36 * System commands are directly available (in alias table) without
36 * System commands are directly available (in alias table) without
37 requesting %rehashx - however, if you install new programs along
37 requesting %rehashx - however, if you install new programs along
38 your PATH, you might want to run %rehashx to update the persistent
38 your PATH, you might want to run %rehashx to update the persistent
39 alias table
39 alias table
40 * Macros are stored in raw format by default. That is, instead of
40 * Macros are stored in raw format by default. That is, instead of
41 '_ip.system("cat foo"), the macro will contain text 'cat foo')
41 '_ip.system("cat foo"), the macro will contain text 'cat foo')
42 * Autocall is in full mode
42 * Autocall is in full mode
43 * Calling "up" does "cd .."
43 * Calling "up" does "cd .."
44
44
45 The 'sh' profile is different from the now-obsolete (and unavailable)
45 The 'sh' profile is different from the now-obsolete (and unavailable)
46 'pysh' profile in that the ``$$var = command`` and ``$var = command`` syntax is
46 'pysh' profile in that the ``$$var = command`` and ``$var = command`` syntax is
47 not supported anymore. Use ``var = !command`` instead (which is available in all
47 not supported anymore. Use ``var = !command`` instead (which is available in all
48 IPython profiles).
48 IPython profiles).
49
49
50 Aliases
50 Aliases
51 =======
51 =======
52
52
53 All of your $PATH has been loaded as IPython aliases, so you should be
53 All of your $PATH has been loaded as IPython aliases, so you should be
54 able to type any normal system command and have it executed. See
54 able to type any normal system command and have it executed. See
55 %alias? and %unalias? for details on the alias facilities. See also
55 %alias? and %unalias? for details on the alias facilities. See also
56 %rehashx? for details on the mechanism used to load $PATH.
56 %rehashx? for details on the mechanism used to load $PATH.
57
57
58
58
59 Directory management
59 Directory management
60 ====================
60 ====================
61
61
62 Since each command passed by ipython to the underlying system is executed
62 Since each command passed by ipython to the underlying system is executed
63 in a subshell which exits immediately, you can NOT use !cd to navigate
63 in a subshell which exits immediately, you can NOT use !cd to navigate
64 the filesystem.
64 the filesystem.
65
65
66 IPython provides its own builtin '%cd' magic command to move in the
66 IPython provides its own builtin '%cd' magic command to move in the
67 filesystem (the % is not required with automagic on). It also maintains
67 filesystem (the % is not required with automagic on). It also maintains
68 a list of visited directories (use %dhist to see it) and allows direct
68 a list of visited directories (use %dhist to see it) and allows direct
69 switching to any of them. Type 'cd?' for more details.
69 switching to any of them. Type 'cd?' for more details.
70
70
71 %pushd, %popd and %dirs are provided for directory stack handling.
71 %pushd, %popd and %dirs are provided for directory stack handling.
72
72
73
73
74 Enabled extensions
74 Enabled extensions
75 ==================
75 ==================
76
76
77 Some extensions, listed below, are enabled as default in this profile.
77 Some extensions, listed below, are enabled as default in this profile.
78
78
79 envpersist
79 envpersist
80 ----------
80 ----------
81
81
82 %env can be used to "remember" environment variable manipulations. Examples::
82 %env can be used to "remember" environment variable manipulations. Examples::
83
83
84 %env - Show all environment variables
84 %env - Show all environment variables
85 %env VISUAL=jed - set VISUAL to jed
85 %env VISUAL=jed - set VISUAL to jed
86 %env PATH+=;/foo - append ;foo to PATH
86 %env PATH+=;/foo - append ;foo to PATH
87 %env PATH+=;/bar - also append ;bar to PATH
87 %env PATH+=;/bar - also append ;bar to PATH
88 %env PATH-=/wbin; - prepend /wbin; to PATH
88 %env PATH-=/wbin; - prepend /wbin; to PATH
89 %env -d VISUAL - forget VISUAL persistent val
89 %env -d VISUAL - forget VISUAL persistent val
90 %env -p - print all persistent env modifications
90 %env -p - print all persistent env modifications
91
91
92 ipy_which
92 ipy_which
93 ---------
93 ---------
94
94
95 %which magic command. Like 'which' in unix, but knows about ipython aliases.
95 %which magic command. Like 'which' in unix, but knows about ipython aliases.
96
96
97 Example::
97 Example::
98
98
99 [C:/ipython]|14> %which st
99 [C:/ipython]|14> %which st
100 st -> start .
100 st -> start .
101 [C:/ipython]|15> %which d
101 [C:/ipython]|15> %which d
102 d -> dir /w /og /on
102 d -> dir /w /og /on
103 [C:/ipython]|16> %which cp
103 [C:/ipython]|16> %which cp
104 cp -> cp
104 cp -> cp
105 == c:\bin\cp.exe
105 == c:\bin\cp.exe
106 c:\bin\cp.exe
106 c:\bin\cp.exe
107
107
108 ipy_app_completers
108 ipy_app_completers
109 ------------------
109 ------------------
110
110
111 Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu.
111 Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu.
112
112
113 ipy_rehashdir
113 ipy_rehashdir
114 -------------
114 -------------
115
115
116 Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir::
116 Allows you to add system command aliases for commands that are not along your path. Let's say that you just installed Putty and want to be able to invoke it without adding it to path, you can create the alias for it with rehashdir::
117
117
118 [~]|22> cd c:/opt/PuTTY/
118 [~]|22> cd c:/opt/PuTTY/
119 [c:opt/PuTTY]|23> rehashdir .
119 [c:opt/PuTTY]|23> rehashdir .
120 <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000']
120 <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000']
121
121
122 Now, you can execute any of those commams directly::
122 Now, you can execute any of those commams directly::
123
123
124 [c:opt/PuTTY]|24> cd
124 [c:opt/PuTTY]|24> cd
125 [~]|25> putty
125 [~]|25> putty
126
126
127 (the putty window opens).
127 (the putty window opens).
128
128
129 If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop::
129 If you want to store the alias so that it will always be available, do '%store putty'. If you want to %store all these aliases persistently, just do it in a for loop::
130
130
131 [~]|27> for a in _23:
131 [~]|27> for a in _23:
132 |..> %store $a
132 |..> %store $a
133 |..>
133 |..>
134 |..>
134 |..>
135 Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe')
135 Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe')
136 Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe')
136 Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe')
137 Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe')
137 Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe')
138 Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe')
138 Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe')
139 ...
139 ...
140
140
141 mglob
141 mglob
142 -----
142 -----
143
143
144 Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples::
144 Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples::
145
145
146 [c:/ipython]|9> mglob *.py
146 [c:/ipython]|9> mglob *.py
147 [c:/ipython]|10> mglob *.py rec:*.txt
147 [c:/ipython]|10> mglob *.py rec:*.txt
148 [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:.
148 [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:.
149
149
150 Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'.
150 Note that the first 2 calls will put the file list in result history (_, _9, _10), and the last one will assign it to 'workfiles'.
151
151
152
152
153 Prompt customization
153 Prompt customization
154 ====================
154 ====================
155
155
156 The sh profile uses the following prompt configurations::
156 The sh profile uses the following prompt configurations::
157
157
158 c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> '
158 c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> '
159 c.PromptManager.in2_template = r'{color.Green}|{color.LightGreen}\D{color.Green}> '
159 c.PromptManager.in2_template = r'{color.Green}|{color.LightGreen}\D{color.Green}> '
160 c.PromptManager.out_template = r'<\#> '
160 c.PromptManager.out_template = r'<\#> '
161
161
162 You can change the prompt configuration to your liking by editing
162 You can change the prompt configuration to your liking by editing
163 ipython_config.py.
163 ipython_config.py.
164
164
165 .. _string_lists:
165 .. _string_lists:
166
166
167 String lists
167 String lists
168 ============
168 ============
169
169
170 String lists (IPython.utils.text.SList) are handy way to process output
170 String lists (IPython.utils.text.SList) are handy way to process output
171 from system commands. They are produced by ``var = !cmd`` syntax.
171 from system commands. They are produced by ``var = !cmd`` syntax.
172
172
173 First, we acquire the output of 'ls -l'::
173 First, we acquire the output of 'ls -l'::
174
174
175 [Q:doc/examples]|2> lines = !ls -l
175 [Q:doc/examples]|2> lines = !ls -l
176 ==
176 ==
177 ['total 23',
177 ['total 23',
178 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
178 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
179 '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py',
179 '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py',
180 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
180 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
181 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
181 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
182 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
182 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
183 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
183 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
184 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
184 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
185
185
186 Now, let's take a look at the contents of 'lines' (the first number is
186 Now, let's take a look at the contents of 'lines' (the first number is
187 the list element number)::
187 the list element number)::
188
188
189 [Q:doc/examples]|3> lines
189 [Q:doc/examples]|3> lines
190 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
190 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
191
191
192 0: total 23
192 0: total 23
193 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
193 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
194 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py
194 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py
195 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py
195 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py
196 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
196 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
197 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
197 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
198 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
198 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
199 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
199 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
200
200
201 Now, let's filter out the 'embed' lines::
201 Now, let's filter out the 'embed' lines::
202
202
203 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
203 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
204 [Q:doc/examples]|5> l2
204 [Q:doc/examples]|5> l2
205 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
205 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
206
206
207 0: total 23
207 0: total 23
208 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
208 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
209 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
209 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
210 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
210 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
211 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
211 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
212 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
212 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
213
213
214 Now, we want strings having just file names and permissions::
214 Now, we want strings having just file names and permissions::
215
215
216 [Q:doc/examples]|6> l2.fields(8,0)
216 [Q:doc/examples]|6> l2.fields(8,0)
217 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
217 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
218
218
219 0: total
219 0: total
220 1: example-demo.py -rw-rw-rw-
220 1: example-demo.py -rw-rw-rw-
221 2: example-gnuplot.py -rwxrwxrwx
221 2: example-gnuplot.py -rwxrwxrwx
222 3: extension.py -rwxrwxrwx
222 3: extension.py -rwxrwxrwx
223 4: seteditor.py -rwxrwxrwx
223 4: seteditor.py -rwxrwxrwx
224 5: seteditor.pyc -rwxrwxrwx
224 5: seteditor.pyc -rwxrwxrwx
225
225
226 Note how the line with 'total' does not raise IndexError.
226 Note how the line with 'total' does not raise IndexError.
227
227
228 If you want to split these (yielding lists), call fields() without
228 If you want to split these (yielding lists), call fields() without
229 arguments::
229 arguments::
230
230
231 [Q:doc/examples]|7> _.fields()
231 [Q:doc/examples]|7> _.fields()
232 <7>
232 <7>
233 [['total'],
233 [['total'],
234 ['example-demo.py', '-rw-rw-rw-'],
234 ['example-demo.py', '-rw-rw-rw-'],
235 ['example-gnuplot.py', '-rwxrwxrwx'],
235 ['example-gnuplot.py', '-rwxrwxrwx'],
236 ['extension.py', '-rwxrwxrwx'],
236 ['extension.py', '-rwxrwxrwx'],
237 ['seteditor.py', '-rwxrwxrwx'],
237 ['seteditor.py', '-rwxrwxrwx'],
238 ['seteditor.pyc', '-rwxrwxrwx']]
238 ['seteditor.pyc', '-rwxrwxrwx']]
239
239
240 If you want to pass these separated with spaces to a command (typical
240 If you want to pass these separated with spaces to a command (typical
241 for lists if files), use the .s property::
241 for lists if files), use the .s property::
242
242
243
243
244 [Q:doc/examples]|13> files = l2.fields(8).s
244 [Q:doc/examples]|13> files = l2.fields(8).s
245 [Q:doc/examples]|14> files
245 [Q:doc/examples]|14> files
246 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
246 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
247 [Q:doc/examples]|15> ls $files
247 [Q:doc/examples]|15> ls $files
248 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
248 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
249
249
250 SLists are inherited from normal python lists, so every list method is
250 SLists are inherited from normal python lists, so every list method is
251 available::
251 available::
252
252
253 [Q:doc/examples]|21> lines.append('hey')
253 [Q:doc/examples]|21> lines.append('hey')
254
254
255
255
256 Real world example: remove all files outside version control
256 Real world example: remove all files outside version control
257 ------------------------------------------------------------
257 ------------------------------------------------------------
258
258
259 First, capture output of "hg status"::
259 First, capture output of "hg status"::
260
260
261 [Q:/ipython]|28> out = !hg status
261 [Q:/ipython]|28> out = !hg status
262 ==
262 ==
263 ['M IPython\\extensions\\ipy_kitcfg.py',
263 ['M IPython\\extensions\\ipy_kitcfg.py',
264 'M IPython\\extensions\\ipy_rehashdir.py',
264 'M IPython\\extensions\\ipy_rehashdir.py',
265 ...
265 ...
266 '? build\\lib\\IPython\\Debugger.py',
266 '? build\\lib\\IPython\\Debugger.py',
267 '? build\\lib\\IPython\\extensions\\InterpreterExec.py',
267 '? build\\lib\\IPython\\extensions\\InterpreterExec.py',
268 '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py',
268 '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py',
269 ...
269 ...
270
270
271 (lines starting with ? are not under version control).
271 (lines starting with ? are not under version control).
272
272
273 ::
273 ::
274
274
275 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
275 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
276 [Q:/ipython]|36> junk
276 [Q:/ipython]|36> junk
277 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
277 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
278 ...
278 ...
279 10: build\bdist.win32\winexe\temp\_ctypes.py
279 10: build\bdist.win32\winexe\temp\_ctypes.py
280 11: build\bdist.win32\winexe\temp\_hashlib.py
280 11: build\bdist.win32\winexe\temp\_hashlib.py
281 12: build\bdist.win32\winexe\temp\_socket.py
281 12: build\bdist.win32\winexe\temp\_socket.py
282
282
283 Now we can just remove these files by doing 'rm $junk.s'.
283 Now we can just remove these files by doing 'rm $junk.s'.
284
284
285 The .s, .n, .p properties
285 The .s, .n, .p properties
286 -------------------------
286 -------------------------
287
287
288 The ``.s`` property returns one string where lines are separated by
288 The ``.s`` property returns one string where lines are separated by
289 single space (for convenient passing to system commands). The ``.n``
289 single space (for convenient passing to system commands). The ``.n``
290 property return one string where the lines are separated by a newline
290 property return one string where the lines are separated by a newline
291 (i.e. the original output of the function). If the items in string
291 (i.e. the original output of the function). If the items in string
292 list are file names, ``.p`` can be used to get a list of "path" objects
292 list are file names, ``.p`` can be used to get a list of "path" objects
293 for convenient file manipulation.
293 for convenient file manipulation.
294
294
@@ -1,865 +1,865 b''
1 .. _parallel_multiengine:
1 .. _parallel_multiengine:
2
2
3 ==========================
3 ==========================
4 IPython's Direct interface
4 IPython's Direct interface
5 ==========================
5 ==========================
6
6
7 The direct, or multiengine, interface represents one possible way of working with a set of
7 The direct, or multiengine, interface represents one possible way of working with a set of
8 IPython engines. The basic idea behind the multiengine interface is that the
8 IPython engines. The basic idea behind the multiengine interface is that the
9 capabilities of each engine are directly and explicitly exposed to the user.
9 capabilities of each engine are directly and explicitly exposed to the user.
10 Thus, in the multiengine interface, each engine is given an id that is used to
10 Thus, in the multiengine interface, each engine is given an id that is used to
11 identify the engine and give it work to do. This interface is very intuitive
11 identify the engine and give it work to do. This interface is very intuitive
12 and is designed with interactive usage in mind, and is the best place for
12 and is designed with interactive usage in mind, and is the best place for
13 new users of IPython to begin.
13 new users of IPython to begin.
14
14
15 Starting the IPython controller and engines
15 Starting the IPython controller and engines
16 ===========================================
16 ===========================================
17
17
18 To follow along with this tutorial, you will need to start the IPython
18 To follow along with this tutorial, you will need to start the IPython
19 controller and four IPython engines. The simplest way of doing this is to use
19 controller and four IPython engines. The simplest way of doing this is to use
20 the :command:`ipcluster` command::
20 the :command:`ipcluster` command::
21
21
22 $ ipcluster start -n 4
22 $ ipcluster start -n 4
23
23
24 For more detailed information about starting the controller and engines, see
24 For more detailed information about starting the controller and engines, see
25 our :ref:`introduction <parallel_overview>` to using IPython for parallel computing.
25 our :ref:`introduction <parallel_overview>` to using IPython for parallel computing.
26
26
27 Creating a ``DirectView`` instance
27 Creating a ``DirectView`` instance
28 ==================================
28 ==================================
29
29
30 The first step is to import the IPython :mod:`IPython.parallel`
30 The first step is to import the IPython :mod:`IPython.parallel`
31 module and then create a :class:`.Client` instance:
31 module and then create a :class:`.Client` instance:
32
32
33 .. sourcecode:: ipython
33 .. sourcecode:: ipython
34
34
35 In [1]: from IPython.parallel import Client
35 In [1]: from IPython.parallel import Client
36
36
37 In [2]: rc = Client()
37 In [2]: rc = Client()
38
38
39 This form assumes that the default connection information (stored in
39 This form assumes that the default connection information (stored in
40 :file:`ipcontroller-client.json` found in :file:`IPYTHON_DIR/profile_default/security`) is
40 :file:`ipcontroller-client.json` found in :file:`IPYTHONDIR/profile_default/security`) is
41 accurate. If the controller was started on a remote machine, you must copy that connection
41 accurate. If the controller was started on a remote machine, you must copy that connection
42 file to the client machine, or enter its contents as arguments to the Client constructor:
42 file to the client machine, or enter its contents as arguments to the Client constructor:
43
43
44 .. sourcecode:: ipython
44 .. sourcecode:: ipython
45
45
46 # If you have copied the json connector file from the controller:
46 # If you have copied the json connector file from the controller:
47 In [2]: rc = Client('/path/to/ipcontroller-client.json')
47 In [2]: rc = Client('/path/to/ipcontroller-client.json')
48 # or to connect with a specific profile you have set up:
48 # or to connect with a specific profile you have set up:
49 In [3]: rc = Client(profile='mpi')
49 In [3]: rc = Client(profile='mpi')
50
50
51
51
52 To make sure there are engines connected to the controller, users can get a list
52 To make sure there are engines connected to the controller, users can get a list
53 of engine ids:
53 of engine ids:
54
54
55 .. sourcecode:: ipython
55 .. sourcecode:: ipython
56
56
57 In [3]: rc.ids
57 In [3]: rc.ids
58 Out[3]: [0, 1, 2, 3]
58 Out[3]: [0, 1, 2, 3]
59
59
60 Here we see that there are four engines ready to do work for us.
60 Here we see that there are four engines ready to do work for us.
61
61
62 For direct execution, we will make use of a :class:`DirectView` object, which can be
62 For direct execution, we will make use of a :class:`DirectView` object, which can be
63 constructed via list-access to the client:
63 constructed via list-access to the client:
64
64
65 .. sourcecode:: ipython
65 .. sourcecode:: ipython
66
66
67 In [4]: dview = rc[:] # use all engines
67 In [4]: dview = rc[:] # use all engines
68
68
69 .. seealso::
69 .. seealso::
70
70
71 For more information, see the in-depth explanation of :ref:`Views <parallel_details>`.
71 For more information, see the in-depth explanation of :ref:`Views <parallel_details>`.
72
72
73
73
74 Quick and easy parallelism
74 Quick and easy parallelism
75 ==========================
75 ==========================
76
76
77 In many cases, you simply want to apply a Python function to a sequence of
77 In many cases, you simply want to apply a Python function to a sequence of
78 objects, but *in parallel*. The client interface provides a simple way
78 objects, but *in parallel*. The client interface provides a simple way
79 of accomplishing this: using the DirectView's :meth:`~DirectView.map` method.
79 of accomplishing this: using the DirectView's :meth:`~DirectView.map` method.
80
80
81 Parallel map
81 Parallel map
82 ------------
82 ------------
83
83
84 Python's builtin :func:`map` functions allows a function to be applied to a
84 Python's builtin :func:`map` functions allows a function to be applied to a
85 sequence element-by-element. This type of code is typically trivial to
85 sequence element-by-element. This type of code is typically trivial to
86 parallelize. In fact, since IPython's interface is all about functions anyway,
86 parallelize. In fact, since IPython's interface is all about functions anyway,
87 you can just use the builtin :func:`map` with a :class:`RemoteFunction`, or a
87 you can just use the builtin :func:`map` with a :class:`RemoteFunction`, or a
88 DirectView's :meth:`map` method:
88 DirectView's :meth:`map` method:
89
89
90 .. sourcecode:: ipython
90 .. sourcecode:: ipython
91
91
92 In [62]: serial_result = map(lambda x:x**10, range(32))
92 In [62]: serial_result = map(lambda x:x**10, range(32))
93
93
94 In [63]: parallel_result = dview.map_sync(lambda x: x**10, range(32))
94 In [63]: parallel_result = dview.map_sync(lambda x: x**10, range(32))
95
95
96 In [67]: serial_result==parallel_result
96 In [67]: serial_result==parallel_result
97 Out[67]: True
97 Out[67]: True
98
98
99
99
100 .. note::
100 .. note::
101
101
102 The :class:`DirectView`'s version of :meth:`map` does
102 The :class:`DirectView`'s version of :meth:`map` does
103 not do dynamic load balancing. For a load balanced version, use a
103 not do dynamic load balancing. For a load balanced version, use a
104 :class:`LoadBalancedView`.
104 :class:`LoadBalancedView`.
105
105
106 .. seealso::
106 .. seealso::
107
107
108 :meth:`map` is implemented via :class:`ParallelFunction`.
108 :meth:`map` is implemented via :class:`ParallelFunction`.
109
109
110 Remote function decorators
110 Remote function decorators
111 --------------------------
111 --------------------------
112
112
113 Remote functions are just like normal functions, but when they are called,
113 Remote functions are just like normal functions, but when they are called,
114 they execute on one or more engines, rather than locally. IPython provides
114 they execute on one or more engines, rather than locally. IPython provides
115 two decorators:
115 two decorators:
116
116
117 .. sourcecode:: ipython
117 .. sourcecode:: ipython
118
118
119 In [10]: @dview.remote(block=True)
119 In [10]: @dview.remote(block=True)
120 ....: def getpid():
120 ....: def getpid():
121 ....: import os
121 ....: import os
122 ....: return os.getpid()
122 ....: return os.getpid()
123 ....:
123 ....:
124
124
125 In [11]: getpid()
125 In [11]: getpid()
126 Out[11]: [12345, 12346, 12347, 12348]
126 Out[11]: [12345, 12346, 12347, 12348]
127
127
128 The ``@parallel`` decorator creates parallel functions, that break up an element-wise
128 The ``@parallel`` decorator creates parallel functions, that break up an element-wise
129 operations and distribute them, reconstructing the result.
129 operations and distribute them, reconstructing the result.
130
130
131 .. sourcecode:: ipython
131 .. sourcecode:: ipython
132
132
133 In [12]: import numpy as np
133 In [12]: import numpy as np
134
134
135 In [13]: A = np.random.random((64,48))
135 In [13]: A = np.random.random((64,48))
136
136
137 In [14]: @dview.parallel(block=True)
137 In [14]: @dview.parallel(block=True)
138 ....: def pmul(A,B):
138 ....: def pmul(A,B):
139 ....: return A*B
139 ....: return A*B
140
140
141 In [15]: C_local = A*A
141 In [15]: C_local = A*A
142
142
143 In [16]: C_remote = pmul(A,A)
143 In [16]: C_remote = pmul(A,A)
144
144
145 In [17]: (C_local == C_remote).all()
145 In [17]: (C_local == C_remote).all()
146 Out[17]: True
146 Out[17]: True
147
147
148 Calling a ``@parallel`` function *does not* correspond to map. It is used for splitting
148 Calling a ``@parallel`` function *does not* correspond to map. It is used for splitting
149 element-wise operations that operate on a sequence or array. For ``map`` behavior,
149 element-wise operations that operate on a sequence or array. For ``map`` behavior,
150 parallel functions do have a map method.
150 parallel functions do have a map method.
151
151
152 ==================== ============================ =============================
152 ==================== ============================ =============================
153 call pfunc(seq) pfunc.map(seq)
153 call pfunc(seq) pfunc.map(seq)
154 ==================== ============================ =============================
154 ==================== ============================ =============================
155 # of tasks # of engines (1 per engine) # of engines (1 per engine)
155 # of tasks # of engines (1 per engine) # of engines (1 per engine)
156 # of remote calls # of engines (1 per engine) ``len(seq)``
156 # of remote calls # of engines (1 per engine) ``len(seq)``
157 argument to remote ``seq[i:j]`` (sub-sequence) ``seq[i]`` (single element)
157 argument to remote ``seq[i:j]`` (sub-sequence) ``seq[i]`` (single element)
158 ==================== ============================ =============================
158 ==================== ============================ =============================
159
159
160 A quick example to illustrate the difference in arguments for the two modes:
160 A quick example to illustrate the difference in arguments for the two modes:
161
161
162 .. sourcecode:: ipython
162 .. sourcecode:: ipython
163
163
164 In [16]: @dview.parallel(block=True)
164 In [16]: @dview.parallel(block=True)
165 ....: def echo(x):
165 ....: def echo(x):
166 ....: return str(x)
166 ....: return str(x)
167 ....:
167 ....:
168
168
169 In [17]: echo(range(5))
169 In [17]: echo(range(5))
170 Out[17]: ['[0, 1]', '[2]', '[3]', '[4]']
170 Out[17]: ['[0, 1]', '[2]', '[3]', '[4]']
171
171
172 In [18]: echo.map(range(5))
172 In [18]: echo.map(range(5))
173 Out[18]: ['0', '1', '2', '3', '4']
173 Out[18]: ['0', '1', '2', '3', '4']
174
174
175
175
176 .. seealso::
176 .. seealso::
177
177
178 See the :func:`~.remotefunction.parallel` and :func:`~.remotefunction.remote`
178 See the :func:`~.remotefunction.parallel` and :func:`~.remotefunction.remote`
179 decorators for options.
179 decorators for options.
180
180
181 Calling Python functions
181 Calling Python functions
182 ========================
182 ========================
183
183
184 The most basic type of operation that can be performed on the engines is to
184 The most basic type of operation that can be performed on the engines is to
185 execute Python code or call Python functions. Executing Python code can be
185 execute Python code or call Python functions. Executing Python code can be
186 done in blocking or non-blocking mode (non-blocking is default) using the
186 done in blocking or non-blocking mode (non-blocking is default) using the
187 :meth:`.View.execute` method, and calling functions can be done via the
187 :meth:`.View.execute` method, and calling functions can be done via the
188 :meth:`.View.apply` method.
188 :meth:`.View.apply` method.
189
189
190 apply
190 apply
191 -----
191 -----
192
192
193 The main method for doing remote execution (in fact, all methods that
193 The main method for doing remote execution (in fact, all methods that
194 communicate with the engines are built on top of it), is :meth:`View.apply`.
194 communicate with the engines are built on top of it), is :meth:`View.apply`.
195
195
196 We strive to provide the cleanest interface we can, so `apply` has the following
196 We strive to provide the cleanest interface we can, so `apply` has the following
197 signature:
197 signature:
198
198
199 .. sourcecode:: python
199 .. sourcecode:: python
200
200
201 view.apply(f, *args, **kwargs)
201 view.apply(f, *args, **kwargs)
202
202
203 There are various ways to call functions with IPython, and these flags are set as
203 There are various ways to call functions with IPython, and these flags are set as
204 attributes of the View. The ``DirectView`` has just two of these flags:
204 attributes of the View. The ``DirectView`` has just two of these flags:
205
205
206 dv.block : bool
206 dv.block : bool
207 whether to wait for the result, or return an :class:`AsyncResult` object
207 whether to wait for the result, or return an :class:`AsyncResult` object
208 immediately
208 immediately
209 dv.track : bool
209 dv.track : bool
210 whether to instruct pyzmq to track when zeromq is done sending the message.
210 whether to instruct pyzmq to track when zeromq is done sending the message.
211 This is primarily useful for non-copying sends of numpy arrays that you plan to
211 This is primarily useful for non-copying sends of numpy arrays that you plan to
212 edit in-place. You need to know when it becomes safe to edit the buffer
212 edit in-place. You need to know when it becomes safe to edit the buffer
213 without corrupting the message.
213 without corrupting the message.
214 dv.targets : int, list of ints
214 dv.targets : int, list of ints
215 which targets this view is associated with.
215 which targets this view is associated with.
216
216
217
217
218 Creating a view is simple: index-access on a client creates a :class:`.DirectView`.
218 Creating a view is simple: index-access on a client creates a :class:`.DirectView`.
219
219
220 .. sourcecode:: ipython
220 .. sourcecode:: ipython
221
221
222 In [4]: view = rc[1:3]
222 In [4]: view = rc[1:3]
223 Out[4]: <DirectView [1, 2]>
223 Out[4]: <DirectView [1, 2]>
224
224
225 In [5]: view.apply<tab>
225 In [5]: view.apply<tab>
226 view.apply view.apply_async view.apply_sync
226 view.apply view.apply_async view.apply_sync
227
227
228 For convenience, you can set block temporarily for a single call with the extra sync/async methods.
228 For convenience, you can set block temporarily for a single call with the extra sync/async methods.
229
229
230 Blocking execution
230 Blocking execution
231 ------------------
231 ------------------
232
232
233 In blocking mode, the :class:`.DirectView` object (called ``dview`` in
233 In blocking mode, the :class:`.DirectView` object (called ``dview`` in
234 these examples) submits the command to the controller, which places the
234 these examples) submits the command to the controller, which places the
235 command in the engines' queues for execution. The :meth:`apply` call then
235 command in the engines' queues for execution. The :meth:`apply` call then
236 blocks until the engines are done executing the command:
236 blocks until the engines are done executing the command:
237
237
238 .. sourcecode:: ipython
238 .. sourcecode:: ipython
239
239
240 In [2]: dview = rc[:] # A DirectView of all engines
240 In [2]: dview = rc[:] # A DirectView of all engines
241 In [3]: dview.block=True
241 In [3]: dview.block=True
242 In [4]: dview['a'] = 5
242 In [4]: dview['a'] = 5
243
243
244 In [5]: dview['b'] = 10
244 In [5]: dview['b'] = 10
245
245
246 In [6]: dview.apply(lambda x: a+b+x, 27)
246 In [6]: dview.apply(lambda x: a+b+x, 27)
247 Out[6]: [42, 42, 42, 42]
247 Out[6]: [42, 42, 42, 42]
248
248
249 You can also select blocking execution on a call-by-call basis with the :meth:`apply_sync`
249 You can also select blocking execution on a call-by-call basis with the :meth:`apply_sync`
250 method:
250 method:
251
251
252 In [7]: dview.block=False
252 In [7]: dview.block=False
253
253
254 In [8]: dview.apply_sync(lambda x: a+b+x, 27)
254 In [8]: dview.apply_sync(lambda x: a+b+x, 27)
255 Out[8]: [42, 42, 42, 42]
255 Out[8]: [42, 42, 42, 42]
256
256
257 Python commands can be executed as strings on specific engines by using a View's ``execute``
257 Python commands can be executed as strings on specific engines by using a View's ``execute``
258 method:
258 method:
259
259
260 .. sourcecode:: ipython
260 .. sourcecode:: ipython
261
261
262 In [6]: rc[::2].execute('c=a+b')
262 In [6]: rc[::2].execute('c=a+b')
263
263
264 In [7]: rc[1::2].execute('c=a-b')
264 In [7]: rc[1::2].execute('c=a-b')
265
265
266 In [8]: dview['c'] # shorthand for dview.pull('c', block=True)
266 In [8]: dview['c'] # shorthand for dview.pull('c', block=True)
267 Out[8]: [15, -5, 15, -5]
267 Out[8]: [15, -5, 15, -5]
268
268
269
269
270 Non-blocking execution
270 Non-blocking execution
271 ----------------------
271 ----------------------
272
272
273 In non-blocking mode, :meth:`apply` submits the command to be executed and
273 In non-blocking mode, :meth:`apply` submits the command to be executed and
274 then returns a :class:`AsyncResult` object immediately. The
274 then returns a :class:`AsyncResult` object immediately. The
275 :class:`AsyncResult` object gives you a way of getting a result at a later
275 :class:`AsyncResult` object gives you a way of getting a result at a later
276 time through its :meth:`get` method.
276 time through its :meth:`get` method.
277
277
278 .. seealso::
278 .. seealso::
279
279
280 Docs on the :ref:`AsyncResult <parallel_asyncresult>` object.
280 Docs on the :ref:`AsyncResult <parallel_asyncresult>` object.
281
281
282 This allows you to quickly submit long running commands without blocking your
282 This allows you to quickly submit long running commands without blocking your
283 local Python/IPython session:
283 local Python/IPython session:
284
284
285 .. sourcecode:: ipython
285 .. sourcecode:: ipython
286
286
287 # define our function
287 # define our function
288 In [6]: def wait(t):
288 In [6]: def wait(t):
289 ....: import time
289 ....: import time
290 ....: tic = time.time()
290 ....: tic = time.time()
291 ....: time.sleep(t)
291 ....: time.sleep(t)
292 ....: return time.time()-tic
292 ....: return time.time()-tic
293
293
294 # In non-blocking mode
294 # In non-blocking mode
295 In [7]: ar = dview.apply_async(wait, 2)
295 In [7]: ar = dview.apply_async(wait, 2)
296
296
297 # Now block for the result
297 # Now block for the result
298 In [8]: ar.get()
298 In [8]: ar.get()
299 Out[8]: [2.0006198883056641, 1.9997570514678955, 1.9996809959411621, 2.0003249645233154]
299 Out[8]: [2.0006198883056641, 1.9997570514678955, 1.9996809959411621, 2.0003249645233154]
300
300
301 # Again in non-blocking mode
301 # Again in non-blocking mode
302 In [9]: ar = dview.apply_async(wait, 10)
302 In [9]: ar = dview.apply_async(wait, 10)
303
303
304 # Poll to see if the result is ready
304 # Poll to see if the result is ready
305 In [10]: ar.ready()
305 In [10]: ar.ready()
306 Out[10]: False
306 Out[10]: False
307
307
308 # ask for the result, but wait a maximum of 1 second:
308 # ask for the result, but wait a maximum of 1 second:
309 In [45]: ar.get(1)
309 In [45]: ar.get(1)
310 ---------------------------------------------------------------------------
310 ---------------------------------------------------------------------------
311 TimeoutError Traceback (most recent call last)
311 TimeoutError Traceback (most recent call last)
312 /home/you/<ipython-input-45-7cd858bbb8e0> in <module>()
312 /home/you/<ipython-input-45-7cd858bbb8e0> in <module>()
313 ----> 1 ar.get(1)
313 ----> 1 ar.get(1)
314
314
315 /path/to/site-packages/IPython/parallel/asyncresult.pyc in get(self, timeout)
315 /path/to/site-packages/IPython/parallel/asyncresult.pyc in get(self, timeout)
316 62 raise self._exception
316 62 raise self._exception
317 63 else:
317 63 else:
318 ---> 64 raise error.TimeoutError("Result not ready.")
318 ---> 64 raise error.TimeoutError("Result not ready.")
319 65
319 65
320 66 def ready(self):
320 66 def ready(self):
321
321
322 TimeoutError: Result not ready.
322 TimeoutError: Result not ready.
323
323
324 .. Note::
324 .. Note::
325
325
326 Note the import inside the function. This is a common model, to ensure
326 Note the import inside the function. This is a common model, to ensure
327 that the appropriate modules are imported where the task is run. You can
327 that the appropriate modules are imported where the task is run. You can
328 also manually import modules into the engine(s) namespace(s) via
328 also manually import modules into the engine(s) namespace(s) via
329 :meth:`view.execute('import numpy')`.
329 :meth:`view.execute('import numpy')`.
330
330
331 Often, it is desirable to wait until a set of :class:`AsyncResult` objects
331 Often, it is desirable to wait until a set of :class:`AsyncResult` objects
332 are done. For this, there is a the method :meth:`wait`. This method takes a
332 are done. For this, there is a the method :meth:`wait`. This method takes a
333 tuple of :class:`AsyncResult` objects (or `msg_ids` or indices to the client's History),
333 tuple of :class:`AsyncResult` objects (or `msg_ids` or indices to the client's History),
334 and blocks until all of the associated results are ready:
334 and blocks until all of the associated results are ready:
335
335
336 .. sourcecode:: ipython
336 .. sourcecode:: ipython
337
337
338 In [72]: dview.block=False
338 In [72]: dview.block=False
339
339
340 # A trivial list of AsyncResults objects
340 # A trivial list of AsyncResults objects
341 In [73]: pr_list = [dview.apply_async(wait, 3) for i in range(10)]
341 In [73]: pr_list = [dview.apply_async(wait, 3) for i in range(10)]
342
342
343 # Wait until all of them are done
343 # Wait until all of them are done
344 In [74]: dview.wait(pr_list)
344 In [74]: dview.wait(pr_list)
345
345
346 # Then, their results are ready using get() or the `.r` attribute
346 # Then, their results are ready using get() or the `.r` attribute
347 In [75]: pr_list[0].get()
347 In [75]: pr_list[0].get()
348 Out[75]: [2.9982571601867676, 2.9982588291168213, 2.9987530708312988, 2.9990990161895752]
348 Out[75]: [2.9982571601867676, 2.9982588291168213, 2.9987530708312988, 2.9990990161895752]
349
349
350
350
351
351
352 The ``block`` and ``targets`` keyword arguments and attributes
352 The ``block`` and ``targets`` keyword arguments and attributes
353 --------------------------------------------------------------
353 --------------------------------------------------------------
354
354
355 Most DirectView methods (excluding :meth:`apply`) accept ``block`` and
355 Most DirectView methods (excluding :meth:`apply`) accept ``block`` and
356 ``targets`` as keyword arguments. As we have seen above, these keyword arguments control the
356 ``targets`` as keyword arguments. As we have seen above, these keyword arguments control the
357 blocking mode and which engines the command is applied to. The :class:`View` class also has
357 blocking mode and which engines the command is applied to. The :class:`View` class also has
358 :attr:`block` and :attr:`targets` attributes that control the default behavior when the keyword
358 :attr:`block` and :attr:`targets` attributes that control the default behavior when the keyword
359 arguments are not provided. Thus the following logic is used for :attr:`block` and :attr:`targets`:
359 arguments are not provided. Thus the following logic is used for :attr:`block` and :attr:`targets`:
360
360
361 * If no keyword argument is provided, the instance attributes are used.
361 * If no keyword argument is provided, the instance attributes are used.
362 * Keyword argument, if provided override the instance attributes for
362 * Keyword argument, if provided override the instance attributes for
363 the duration of a single call.
363 the duration of a single call.
364
364
365 The following examples demonstrate how to use the instance attributes:
365 The following examples demonstrate how to use the instance attributes:
366
366
367 .. sourcecode:: ipython
367 .. sourcecode:: ipython
368
368
369 In [16]: dview.targets = [0,2]
369 In [16]: dview.targets = [0,2]
370
370
371 In [17]: dview.block = False
371 In [17]: dview.block = False
372
372
373 In [18]: ar = dview.apply(lambda : 10)
373 In [18]: ar = dview.apply(lambda : 10)
374
374
375 In [19]: ar.get()
375 In [19]: ar.get()
376 Out[19]: [10, 10]
376 Out[19]: [10, 10]
377
377
378 In [16]: dview.targets = v.client.ids # all engines (4)
378 In [16]: dview.targets = v.client.ids # all engines (4)
379
379
380 In [21]: dview.block = True
380 In [21]: dview.block = True
381
381
382 In [22]: dview.apply(lambda : 42)
382 In [22]: dview.apply(lambda : 42)
383 Out[22]: [42, 42, 42, 42]
383 Out[22]: [42, 42, 42, 42]
384
384
385 The :attr:`block` and :attr:`targets` instance attributes of the
385 The :attr:`block` and :attr:`targets` instance attributes of the
386 :class:`.DirectView` also determine the behavior of the parallel magic commands.
386 :class:`.DirectView` also determine the behavior of the parallel magic commands.
387
387
388 Parallel magic commands
388 Parallel magic commands
389 -----------------------
389 -----------------------
390
390
391 We provide a few IPython magic commands (``%px``, ``%autopx`` and ``%result``)
391 We provide a few IPython magic commands (``%px``, ``%autopx`` and ``%result``)
392 that make it more pleasant to execute Python commands on the engines
392 that make it more pleasant to execute Python commands on the engines
393 interactively. These are simply shortcuts to :meth:`execute` and
393 interactively. These are simply shortcuts to :meth:`execute` and
394 :meth:`get_result` of the :class:`DirectView`. The ``%px`` magic executes a single
394 :meth:`get_result` of the :class:`DirectView`. The ``%px`` magic executes a single
395 Python command on the engines specified by the :attr:`targets` attribute of the
395 Python command on the engines specified by the :attr:`targets` attribute of the
396 :class:`DirectView` instance:
396 :class:`DirectView` instance:
397
397
398 .. sourcecode:: ipython
398 .. sourcecode:: ipython
399
399
400 # Create a DirectView for all targets
400 # Create a DirectView for all targets
401 In [22]: dv = rc[:]
401 In [22]: dv = rc[:]
402
402
403 # Make this DirectView active for parallel magic commands
403 # Make this DirectView active for parallel magic commands
404 In [23]: dv.activate()
404 In [23]: dv.activate()
405
405
406 In [24]: dv.block=True
406 In [24]: dv.block=True
407
407
408 # import numpy here and everywhere
408 # import numpy here and everywhere
409 In [25]: with dv.sync_imports():
409 In [25]: with dv.sync_imports():
410 ....: import numpy
410 ....: import numpy
411 importing numpy on engine(s)
411 importing numpy on engine(s)
412
412
413 In [27]: %px a = numpy.random.rand(2,2)
413 In [27]: %px a = numpy.random.rand(2,2)
414 Parallel execution on engines: [0, 1, 2, 3]
414 Parallel execution on engines: [0, 1, 2, 3]
415
415
416 In [28]: %px ev = numpy.linalg.eigvals(a)
416 In [28]: %px ev = numpy.linalg.eigvals(a)
417 Parallel execution on engines: [0, 1, 2, 3]
417 Parallel execution on engines: [0, 1, 2, 3]
418
418
419 In [28]: dv['ev']
419 In [28]: dv['ev']
420 Out[28]: [ array([ 1.09522024, -0.09645227]),
420 Out[28]: [ array([ 1.09522024, -0.09645227]),
421 ....: array([ 1.21435496, -0.35546712]),
421 ....: array([ 1.21435496, -0.35546712]),
422 ....: array([ 0.72180653, 0.07133042]),
422 ....: array([ 0.72180653, 0.07133042]),
423 ....: array([ 1.46384341, 1.04353244e-04])
423 ....: array([ 1.46384341, 1.04353244e-04])
424 ....: ]
424 ....: ]
425
425
426 The ``%result`` magic gets the most recent result, or takes an argument
426 The ``%result`` magic gets the most recent result, or takes an argument
427 specifying the index of the result to be requested. It is simply a shortcut to the
427 specifying the index of the result to be requested. It is simply a shortcut to the
428 :meth:`get_result` method:
428 :meth:`get_result` method:
429
429
430 .. sourcecode:: ipython
430 .. sourcecode:: ipython
431
431
432 In [29]: dv.apply_async(lambda : ev)
432 In [29]: dv.apply_async(lambda : ev)
433
433
434 In [30]: %result
434 In [30]: %result
435 Out[30]: [ [ 1.28167017 0.14197338],
435 Out[30]: [ [ 1.28167017 0.14197338],
436 ....: [-0.14093616 1.27877273],
436 ....: [-0.14093616 1.27877273],
437 ....: [-0.37023573 1.06779409],
437 ....: [-0.37023573 1.06779409],
438 ....: [ 0.83664764 -0.25602658] ]
438 ....: [ 0.83664764 -0.25602658] ]
439
439
440 The ``%autopx`` magic switches to a mode where everything you type is executed
440 The ``%autopx`` magic switches to a mode where everything you type is executed
441 on the engines given by the :attr:`targets` attribute:
441 on the engines given by the :attr:`targets` attribute:
442
442
443 .. sourcecode:: ipython
443 .. sourcecode:: ipython
444
444
445 In [30]: dv.block=False
445 In [30]: dv.block=False
446
446
447 In [31]: %autopx
447 In [31]: %autopx
448 Auto Parallel Enabled
448 Auto Parallel Enabled
449 Type %autopx to disable
449 Type %autopx to disable
450
450
451 In [32]: max_evals = []
451 In [32]: max_evals = []
452 <IPython.parallel.AsyncResult object at 0x17b8a70>
452 <IPython.parallel.AsyncResult object at 0x17b8a70>
453
453
454 In [33]: for i in range(100):
454 In [33]: for i in range(100):
455 ....: a = numpy.random.rand(10,10)
455 ....: a = numpy.random.rand(10,10)
456 ....: a = a+a.transpose()
456 ....: a = a+a.transpose()
457 ....: evals = numpy.linalg.eigvals(a)
457 ....: evals = numpy.linalg.eigvals(a)
458 ....: max_evals.append(evals[0].real)
458 ....: max_evals.append(evals[0].real)
459 ....:
459 ....:
460 ....:
460 ....:
461 <IPython.parallel.AsyncResult object at 0x17af8f0>
461 <IPython.parallel.AsyncResult object at 0x17af8f0>
462
462
463 In [34]: %autopx
463 In [34]: %autopx
464 Auto Parallel Disabled
464 Auto Parallel Disabled
465
465
466 In [35]: dv.block=True
466 In [35]: dv.block=True
467
467
468 In [36]: px ans= "Average max eigenvalue is: %f"%(sum(max_evals)/len(max_evals))
468 In [36]: px ans= "Average max eigenvalue is: %f"%(sum(max_evals)/len(max_evals))
469 Parallel execution on engines: [0, 1, 2, 3]
469 Parallel execution on engines: [0, 1, 2, 3]
470
470
471 In [37]: dv['ans']
471 In [37]: dv['ans']
472 Out[37]: [ 'Average max eigenvalue is: 10.1387247332',
472 Out[37]: [ 'Average max eigenvalue is: 10.1387247332',
473 ....: 'Average max eigenvalue is: 10.2076902286',
473 ....: 'Average max eigenvalue is: 10.2076902286',
474 ....: 'Average max eigenvalue is: 10.1891484655',
474 ....: 'Average max eigenvalue is: 10.1891484655',
475 ....: 'Average max eigenvalue is: 10.1158837784',]
475 ....: 'Average max eigenvalue is: 10.1158837784',]
476
476
477
477
478 Moving Python objects around
478 Moving Python objects around
479 ============================
479 ============================
480
480
481 In addition to calling functions and executing code on engines, you can
481 In addition to calling functions and executing code on engines, you can
482 transfer Python objects to and from your IPython session and the engines. In
482 transfer Python objects to and from your IPython session and the engines. In
483 IPython, these operations are called :meth:`push` (sending an object to the
483 IPython, these operations are called :meth:`push` (sending an object to the
484 engines) and :meth:`pull` (getting an object from the engines).
484 engines) and :meth:`pull` (getting an object from the engines).
485
485
486 Basic push and pull
486 Basic push and pull
487 -------------------
487 -------------------
488
488
489 Here are some examples of how you use :meth:`push` and :meth:`pull`:
489 Here are some examples of how you use :meth:`push` and :meth:`pull`:
490
490
491 .. sourcecode:: ipython
491 .. sourcecode:: ipython
492
492
493 In [38]: dview.push(dict(a=1.03234,b=3453))
493 In [38]: dview.push(dict(a=1.03234,b=3453))
494 Out[38]: [None,None,None,None]
494 Out[38]: [None,None,None,None]
495
495
496 In [39]: dview.pull('a')
496 In [39]: dview.pull('a')
497 Out[39]: [ 1.03234, 1.03234, 1.03234, 1.03234]
497 Out[39]: [ 1.03234, 1.03234, 1.03234, 1.03234]
498
498
499 In [40]: dview.pull('b', targets=0)
499 In [40]: dview.pull('b', targets=0)
500 Out[40]: 3453
500 Out[40]: 3453
501
501
502 In [41]: dview.pull(('a','b'))
502 In [41]: dview.pull(('a','b'))
503 Out[41]: [ [1.03234, 3453], [1.03234, 3453], [1.03234, 3453], [1.03234, 3453] ]
503 Out[41]: [ [1.03234, 3453], [1.03234, 3453], [1.03234, 3453], [1.03234, 3453] ]
504
504
505 In [43]: dview.push(dict(c='speed'))
505 In [43]: dview.push(dict(c='speed'))
506 Out[43]: [None,None,None,None]
506 Out[43]: [None,None,None,None]
507
507
508 In non-blocking mode :meth:`push` and :meth:`pull` also return
508 In non-blocking mode :meth:`push` and :meth:`pull` also return
509 :class:`AsyncResult` objects:
509 :class:`AsyncResult` objects:
510
510
511 .. sourcecode:: ipython
511 .. sourcecode:: ipython
512
512
513 In [48]: ar = dview.pull('a', block=False)
513 In [48]: ar = dview.pull('a', block=False)
514
514
515 In [49]: ar.get()
515 In [49]: ar.get()
516 Out[49]: [1.03234, 1.03234, 1.03234, 1.03234]
516 Out[49]: [1.03234, 1.03234, 1.03234, 1.03234]
517
517
518
518
519 Dictionary interface
519 Dictionary interface
520 --------------------
520 --------------------
521
521
522 Since a Python namespace is just a :class:`dict`, :class:`DirectView` objects provide
522 Since a Python namespace is just a :class:`dict`, :class:`DirectView` objects provide
523 dictionary-style access by key and methods such as :meth:`get` and
523 dictionary-style access by key and methods such as :meth:`get` and
524 :meth:`update` for convenience. This make the remote namespaces of the engines
524 :meth:`update` for convenience. This make the remote namespaces of the engines
525 appear as a local dictionary. Underneath, these methods call :meth:`apply`:
525 appear as a local dictionary. Underneath, these methods call :meth:`apply`:
526
526
527 .. sourcecode:: ipython
527 .. sourcecode:: ipython
528
528
529 In [51]: dview['a']=['foo','bar']
529 In [51]: dview['a']=['foo','bar']
530
530
531 In [52]: dview['a']
531 In [52]: dview['a']
532 Out[52]: [ ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'] ]
532 Out[52]: [ ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'] ]
533
533
534 Scatter and gather
534 Scatter and gather
535 ------------------
535 ------------------
536
536
537 Sometimes it is useful to partition a sequence and push the partitions to
537 Sometimes it is useful to partition a sequence and push the partitions to
538 different engines. In MPI language, this is know as scatter/gather and we
538 different engines. In MPI language, this is know as scatter/gather and we
539 follow that terminology. However, it is important to remember that in
539 follow that terminology. However, it is important to remember that in
540 IPython's :class:`Client` class, :meth:`scatter` is from the
540 IPython's :class:`Client` class, :meth:`scatter` is from the
541 interactive IPython session to the engines and :meth:`gather` is from the
541 interactive IPython session to the engines and :meth:`gather` is from the
542 engines back to the interactive IPython session. For scatter/gather operations
542 engines back to the interactive IPython session. For scatter/gather operations
543 between engines, MPI, pyzmq, or some other direct interconnect should be used.
543 between engines, MPI, pyzmq, or some other direct interconnect should be used.
544
544
545 .. sourcecode:: ipython
545 .. sourcecode:: ipython
546
546
547 In [58]: dview.scatter('a',range(16))
547 In [58]: dview.scatter('a',range(16))
548 Out[58]: [None,None,None,None]
548 Out[58]: [None,None,None,None]
549
549
550 In [59]: dview['a']
550 In [59]: dview['a']
551 Out[59]: [ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15] ]
551 Out[59]: [ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15] ]
552
552
553 In [60]: dview.gather('a')
553 In [60]: dview.gather('a')
554 Out[60]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
554 Out[60]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
555
555
556 Other things to look at
556 Other things to look at
557 =======================
557 =======================
558
558
559 How to do parallel list comprehensions
559 How to do parallel list comprehensions
560 --------------------------------------
560 --------------------------------------
561
561
562 In many cases list comprehensions are nicer than using the map function. While
562 In many cases list comprehensions are nicer than using the map function. While
563 we don't have fully parallel list comprehensions, it is simple to get the
563 we don't have fully parallel list comprehensions, it is simple to get the
564 basic effect using :meth:`scatter` and :meth:`gather`:
564 basic effect using :meth:`scatter` and :meth:`gather`:
565
565
566 .. sourcecode:: ipython
566 .. sourcecode:: ipython
567
567
568 In [66]: dview.scatter('x',range(64))
568 In [66]: dview.scatter('x',range(64))
569
569
570 In [67]: %px y = [i**10 for i in x]
570 In [67]: %px y = [i**10 for i in x]
571 Parallel execution on engines: [0, 1, 2, 3]
571 Parallel execution on engines: [0, 1, 2, 3]
572 Out[67]:
572 Out[67]:
573
573
574 In [68]: y = dview.gather('y')
574 In [68]: y = dview.gather('y')
575
575
576 In [69]: print y
576 In [69]: print y
577 [0, 1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824,...]
577 [0, 1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824,...]
578
578
579 Remote imports
579 Remote imports
580 --------------
580 --------------
581
581
582 Sometimes you will want to import packages both in your interactive session
582 Sometimes you will want to import packages both in your interactive session
583 and on your remote engines. This can be done with the :class:`ContextManager`
583 and on your remote engines. This can be done with the :class:`ContextManager`
584 created by a DirectView's :meth:`sync_imports` method:
584 created by a DirectView's :meth:`sync_imports` method:
585
585
586 .. sourcecode:: ipython
586 .. sourcecode:: ipython
587
587
588 In [69]: with dview.sync_imports():
588 In [69]: with dview.sync_imports():
589 ....: import numpy
589 ....: import numpy
590 importing numpy on engine(s)
590 importing numpy on engine(s)
591
591
592 Any imports made inside the block will also be performed on the view's engines.
592 Any imports made inside the block will also be performed on the view's engines.
593 sync_imports also takes a `local` boolean flag that defaults to True, which specifies
593 sync_imports also takes a `local` boolean flag that defaults to True, which specifies
594 whether the local imports should also be performed. However, support for `local=False`
594 whether the local imports should also be performed. However, support for `local=False`
595 has not been implemented, so only packages that can be imported locally will work
595 has not been implemented, so only packages that can be imported locally will work
596 this way.
596 this way.
597
597
598 You can also specify imports via the ``@require`` decorator. This is a decorator
598 You can also specify imports via the ``@require`` decorator. This is a decorator
599 designed for use in Dependencies, but can be used to handle remote imports as well.
599 designed for use in Dependencies, but can be used to handle remote imports as well.
600 Modules or module names passed to ``@require`` will be imported before the decorated
600 Modules or module names passed to ``@require`` will be imported before the decorated
601 function is called. If they cannot be imported, the decorated function will never
601 function is called. If they cannot be imported, the decorated function will never
602 execution, and will fail with an UnmetDependencyError.
602 execution, and will fail with an UnmetDependencyError.
603
603
604 .. sourcecode:: ipython
604 .. sourcecode:: ipython
605
605
606 In [69]: from IPython.parallel import require
606 In [69]: from IPython.parallel import require
607
607
608 In [70]: @require('re'):
608 In [70]: @require('re'):
609 ....: def findall(pat, x):
609 ....: def findall(pat, x):
610 ....: # re is guaranteed to be available
610 ....: # re is guaranteed to be available
611 ....: return re.findall(pat, x)
611 ....: return re.findall(pat, x)
612
612
613 # you can also pass modules themselves, that you already have locally:
613 # you can also pass modules themselves, that you already have locally:
614 In [71]: @require(time):
614 In [71]: @require(time):
615 ....: def wait(t):
615 ....: def wait(t):
616 ....: time.sleep(t)
616 ....: time.sleep(t)
617 ....: return t
617 ....: return t
618
618
619 .. _parallel_exceptions:
619 .. _parallel_exceptions:
620
620
621 Parallel exceptions
621 Parallel exceptions
622 -------------------
622 -------------------
623
623
624 In the multiengine interface, parallel commands can raise Python exceptions,
624 In the multiengine interface, parallel commands can raise Python exceptions,
625 just like serial commands. But, it is a little subtle, because a single
625 just like serial commands. But, it is a little subtle, because a single
626 parallel command can actually raise multiple exceptions (one for each engine
626 parallel command can actually raise multiple exceptions (one for each engine
627 the command was run on). To express this idea, we have a
627 the command was run on). To express this idea, we have a
628 :exc:`CompositeError` exception class that will be raised in most cases. The
628 :exc:`CompositeError` exception class that will be raised in most cases. The
629 :exc:`CompositeError` class is a special type of exception that wraps one or
629 :exc:`CompositeError` class is a special type of exception that wraps one or
630 more other types of exceptions. Here is how it works:
630 more other types of exceptions. Here is how it works:
631
631
632 .. sourcecode:: ipython
632 .. sourcecode:: ipython
633
633
634 In [76]: dview.block=True
634 In [76]: dview.block=True
635
635
636 In [77]: dview.execute('1/0')
636 In [77]: dview.execute('1/0')
637 ---------------------------------------------------------------------------
637 ---------------------------------------------------------------------------
638 CompositeError Traceback (most recent call last)
638 CompositeError Traceback (most recent call last)
639 /home/user/<ipython-input-10-5d56b303a66c> in <module>()
639 /home/user/<ipython-input-10-5d56b303a66c> in <module>()
640 ----> 1 dview.execute('1/0')
640 ----> 1 dview.execute('1/0')
641
641
642 /path/to/site-packages/IPython/parallel/client/view.pyc in execute(self, code, targets, block)
642 /path/to/site-packages/IPython/parallel/client/view.pyc in execute(self, code, targets, block)
643 591 default: self.block
643 591 default: self.block
644 592 """
644 592 """
645 --> 593 return self._really_apply(util._execute, args=(code,), block=block, targets=targets)
645 --> 593 return self._really_apply(util._execute, args=(code,), block=block, targets=targets)
646 594
646 594
647 595 def run(self, filename, targets=None, block=None):
647 595 def run(self, filename, targets=None, block=None):
648
648
649 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
649 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
650
650
651 /path/to/site-packages/IPython/parallel/client/view.pyc in sync_results(f, self, *args, **kwargs)
651 /path/to/site-packages/IPython/parallel/client/view.pyc in sync_results(f, self, *args, **kwargs)
652 55 def sync_results(f, self, *args, **kwargs):
652 55 def sync_results(f, self, *args, **kwargs):
653 56 """sync relevant results from self.client to our results attribute."""
653 56 """sync relevant results from self.client to our results attribute."""
654 ---> 57 ret = f(self, *args, **kwargs)
654 ---> 57 ret = f(self, *args, **kwargs)
655 58 delta = self.outstanding.difference(self.client.outstanding)
655 58 delta = self.outstanding.difference(self.client.outstanding)
656 59 completed = self.outstanding.intersection(delta)
656 59 completed = self.outstanding.intersection(delta)
657
657
658 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
658 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
659
659
660 /path/to/site-packages/IPython/parallel/client/view.pyc in save_ids(f, self, *args, **kwargs)
660 /path/to/site-packages/IPython/parallel/client/view.pyc in save_ids(f, self, *args, **kwargs)
661 44 n_previous = len(self.client.history)
661 44 n_previous = len(self.client.history)
662 45 try:
662 45 try:
663 ---> 46 ret = f(self, *args, **kwargs)
663 ---> 46 ret = f(self, *args, **kwargs)
664 47 finally:
664 47 finally:
665 48 nmsgs = len(self.client.history) - n_previous
665 48 nmsgs = len(self.client.history) - n_previous
666
666
667 /path/to/site-packages/IPython/parallel/client/view.pyc in _really_apply(self, f, args, kwargs, targets, block, track)
667 /path/to/site-packages/IPython/parallel/client/view.pyc in _really_apply(self, f, args, kwargs, targets, block, track)
668 529 if block:
668 529 if block:
669 530 try:
669 530 try:
670 --> 531 return ar.get()
670 --> 531 return ar.get()
671 532 except KeyboardInterrupt:
671 532 except KeyboardInterrupt:
672 533 pass
672 533 pass
673
673
674 /path/to/site-packages/IPython/parallel/client/asyncresult.pyc in get(self, timeout)
674 /path/to/site-packages/IPython/parallel/client/asyncresult.pyc in get(self, timeout)
675 101 return self._result
675 101 return self._result
676 102 else:
676 102 else:
677 --> 103 raise self._exception
677 --> 103 raise self._exception
678 104 else:
678 104 else:
679 105 raise error.TimeoutError("Result not ready.")
679 105 raise error.TimeoutError("Result not ready.")
680
680
681 CompositeError: one or more exceptions from call to method: _execute
681 CompositeError: one or more exceptions from call to method: _execute
682 [0:apply]: ZeroDivisionError: integer division or modulo by zero
682 [0:apply]: ZeroDivisionError: integer division or modulo by zero
683 [1:apply]: ZeroDivisionError: integer division or modulo by zero
683 [1:apply]: ZeroDivisionError: integer division or modulo by zero
684 [2:apply]: ZeroDivisionError: integer division or modulo by zero
684 [2:apply]: ZeroDivisionError: integer division or modulo by zero
685 [3:apply]: ZeroDivisionError: integer division or modulo by zero
685 [3:apply]: ZeroDivisionError: integer division or modulo by zero
686
686
687 Notice how the error message printed when :exc:`CompositeError` is raised has
687 Notice how the error message printed when :exc:`CompositeError` is raised has
688 information about the individual exceptions that were raised on each engine.
688 information about the individual exceptions that were raised on each engine.
689 If you want, you can even raise one of these original exceptions:
689 If you want, you can even raise one of these original exceptions:
690
690
691 .. sourcecode:: ipython
691 .. sourcecode:: ipython
692
692
693 In [80]: try:
693 In [80]: try:
694 ....: dview.execute('1/0')
694 ....: dview.execute('1/0')
695 ....: except parallel.error.CompositeError, e:
695 ....: except parallel.error.CompositeError, e:
696 ....: e.raise_exception()
696 ....: e.raise_exception()
697 ....:
697 ....:
698 ....:
698 ....:
699 ---------------------------------------------------------------------------
699 ---------------------------------------------------------------------------
700 RemoteError Traceback (most recent call last)
700 RemoteError Traceback (most recent call last)
701 /home/user/<ipython-input-17-8597e7e39858> in <module>()
701 /home/user/<ipython-input-17-8597e7e39858> in <module>()
702 2 dview.execute('1/0')
702 2 dview.execute('1/0')
703 3 except CompositeError as e:
703 3 except CompositeError as e:
704 ----> 4 e.raise_exception()
704 ----> 4 e.raise_exception()
705
705
706 /path/to/site-packages/IPython/parallel/error.pyc in raise_exception(self, excid)
706 /path/to/site-packages/IPython/parallel/error.pyc in raise_exception(self, excid)
707 266 raise IndexError("an exception with index %i does not exist"%excid)
707 266 raise IndexError("an exception with index %i does not exist"%excid)
708 267 else:
708 267 else:
709 --> 268 raise RemoteError(en, ev, etb, ei)
709 --> 268 raise RemoteError(en, ev, etb, ei)
710 269
710 269
711 270
711 270
712
712
713 RemoteError: ZeroDivisionError(integer division or modulo by zero)
713 RemoteError: ZeroDivisionError(integer division or modulo by zero)
714 Traceback (most recent call last):
714 Traceback (most recent call last):
715 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
715 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
716 exec code in working,working
716 exec code in working,working
717 File "<string>", line 1, in <module>
717 File "<string>", line 1, in <module>
718 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
718 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
719 exec code in globals()
719 exec code in globals()
720 File "<string>", line 1, in <module>
720 File "<string>", line 1, in <module>
721 ZeroDivisionError: integer division or modulo by zero
721 ZeroDivisionError: integer division or modulo by zero
722
722
723 If you are working in IPython, you can simple type ``%debug`` after one of
723 If you are working in IPython, you can simple type ``%debug`` after one of
724 these :exc:`CompositeError` exceptions is raised, and inspect the exception
724 these :exc:`CompositeError` exceptions is raised, and inspect the exception
725 instance:
725 instance:
726
726
727 .. sourcecode:: ipython
727 .. sourcecode:: ipython
728
728
729 In [81]: dview.execute('1/0')
729 In [81]: dview.execute('1/0')
730 ---------------------------------------------------------------------------
730 ---------------------------------------------------------------------------
731 CompositeError Traceback (most recent call last)
731 CompositeError Traceback (most recent call last)
732 /home/user/<ipython-input-10-5d56b303a66c> in <module>()
732 /home/user/<ipython-input-10-5d56b303a66c> in <module>()
733 ----> 1 dview.execute('1/0')
733 ----> 1 dview.execute('1/0')
734
734
735 /path/to/site-packages/IPython/parallel/client/view.pyc in execute(self, code, targets, block)
735 /path/to/site-packages/IPython/parallel/client/view.pyc in execute(self, code, targets, block)
736 591 default: self.block
736 591 default: self.block
737 592 """
737 592 """
738 --> 593 return self._really_apply(util._execute, args=(code,), block=block, targets=targets)
738 --> 593 return self._really_apply(util._execute, args=(code,), block=block, targets=targets)
739 594
739 594
740 595 def run(self, filename, targets=None, block=None):
740 595 def run(self, filename, targets=None, block=None):
741
741
742 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
742 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
743
743
744 /path/to/site-packages/IPython/parallel/client/view.pyc in sync_results(f, self, *args, **kwargs)
744 /path/to/site-packages/IPython/parallel/client/view.pyc in sync_results(f, self, *args, **kwargs)
745 55 def sync_results(f, self, *args, **kwargs):
745 55 def sync_results(f, self, *args, **kwargs):
746 56 """sync relevant results from self.client to our results attribute."""
746 56 """sync relevant results from self.client to our results attribute."""
747 ---> 57 ret = f(self, *args, **kwargs)
747 ---> 57 ret = f(self, *args, **kwargs)
748 58 delta = self.outstanding.difference(self.client.outstanding)
748 58 delta = self.outstanding.difference(self.client.outstanding)
749 59 completed = self.outstanding.intersection(delta)
749 59 completed = self.outstanding.intersection(delta)
750
750
751 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
751 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
752
752
753 /path/to/site-packages/IPython/parallel/client/view.pyc in save_ids(f, self, *args, **kwargs)
753 /path/to/site-packages/IPython/parallel/client/view.pyc in save_ids(f, self, *args, **kwargs)
754 44 n_previous = len(self.client.history)
754 44 n_previous = len(self.client.history)
755 45 try:
755 45 try:
756 ---> 46 ret = f(self, *args, **kwargs)
756 ---> 46 ret = f(self, *args, **kwargs)
757 47 finally:
757 47 finally:
758 48 nmsgs = len(self.client.history) - n_previous
758 48 nmsgs = len(self.client.history) - n_previous
759
759
760 /path/to/site-packages/IPython/parallel/client/view.pyc in _really_apply(self, f, args, kwargs, targets, block, track)
760 /path/to/site-packages/IPython/parallel/client/view.pyc in _really_apply(self, f, args, kwargs, targets, block, track)
761 529 if block:
761 529 if block:
762 530 try:
762 530 try:
763 --> 531 return ar.get()
763 --> 531 return ar.get()
764 532 except KeyboardInterrupt:
764 532 except KeyboardInterrupt:
765 533 pass
765 533 pass
766
766
767 /path/to/site-packages/IPython/parallel/client/asyncresult.pyc in get(self, timeout)
767 /path/to/site-packages/IPython/parallel/client/asyncresult.pyc in get(self, timeout)
768 101 return self._result
768 101 return self._result
769 102 else:
769 102 else:
770 --> 103 raise self._exception
770 --> 103 raise self._exception
771 104 else:
771 104 else:
772 105 raise error.TimeoutError("Result not ready.")
772 105 raise error.TimeoutError("Result not ready.")
773
773
774 CompositeError: one or more exceptions from call to method: _execute
774 CompositeError: one or more exceptions from call to method: _execute
775 [0:apply]: ZeroDivisionError: integer division or modulo by zero
775 [0:apply]: ZeroDivisionError: integer division or modulo by zero
776 [1:apply]: ZeroDivisionError: integer division or modulo by zero
776 [1:apply]: ZeroDivisionError: integer division or modulo by zero
777 [2:apply]: ZeroDivisionError: integer division or modulo by zero
777 [2:apply]: ZeroDivisionError: integer division or modulo by zero
778 [3:apply]: ZeroDivisionError: integer division or modulo by zero
778 [3:apply]: ZeroDivisionError: integer division or modulo by zero
779
779
780 In [82]: %debug
780 In [82]: %debug
781 > /path/to/site-packages/IPython/parallel/client/asyncresult.py(103)get()
781 > /path/to/site-packages/IPython/parallel/client/asyncresult.py(103)get()
782 102 else:
782 102 else:
783 --> 103 raise self._exception
783 --> 103 raise self._exception
784 104 else:
784 104 else:
785
785
786 # With the debugger running, self._exception is the exceptions instance. We can tab complete
786 # With the debugger running, self._exception is the exceptions instance. We can tab complete
787 # on it and see the extra methods that are available.
787 # on it and see the extra methods that are available.
788 ipdb> self._exception.<tab>
788 ipdb> self._exception.<tab>
789 e.__class__ e.__getitem__ e.__new__ e.__setstate__ e.args
789 e.__class__ e.__getitem__ e.__new__ e.__setstate__ e.args
790 e.__delattr__ e.__getslice__ e.__reduce__ e.__str__ e.elist
790 e.__delattr__ e.__getslice__ e.__reduce__ e.__str__ e.elist
791 e.__dict__ e.__hash__ e.__reduce_ex__ e.__weakref__ e.message
791 e.__dict__ e.__hash__ e.__reduce_ex__ e.__weakref__ e.message
792 e.__doc__ e.__init__ e.__repr__ e._get_engine_str e.print_tracebacks
792 e.__doc__ e.__init__ e.__repr__ e._get_engine_str e.print_tracebacks
793 e.__getattribute__ e.__module__ e.__setattr__ e._get_traceback e.raise_exception
793 e.__getattribute__ e.__module__ e.__setattr__ e._get_traceback e.raise_exception
794 ipdb> self._exception.print_tracebacks()
794 ipdb> self._exception.print_tracebacks()
795 [0:apply]:
795 [0:apply]:
796 Traceback (most recent call last):
796 Traceback (most recent call last):
797 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
797 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
798 exec code in working,working
798 exec code in working,working
799 File "<string>", line 1, in <module>
799 File "<string>", line 1, in <module>
800 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
800 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
801 exec code in globals()
801 exec code in globals()
802 File "<string>", line 1, in <module>
802 File "<string>", line 1, in <module>
803 ZeroDivisionError: integer division or modulo by zero
803 ZeroDivisionError: integer division or modulo by zero
804
804
805
805
806 [1:apply]:
806 [1:apply]:
807 Traceback (most recent call last):
807 Traceback (most recent call last):
808 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
808 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
809 exec code in working,working
809 exec code in working,working
810 File "<string>", line 1, in <module>
810 File "<string>", line 1, in <module>
811 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
811 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
812 exec code in globals()
812 exec code in globals()
813 File "<string>", line 1, in <module>
813 File "<string>", line 1, in <module>
814 ZeroDivisionError: integer division or modulo by zero
814 ZeroDivisionError: integer division or modulo by zero
815
815
816
816
817 [2:apply]:
817 [2:apply]:
818 Traceback (most recent call last):
818 Traceback (most recent call last):
819 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
819 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
820 exec code in working,working
820 exec code in working,working
821 File "<string>", line 1, in <module>
821 File "<string>", line 1, in <module>
822 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
822 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
823 exec code in globals()
823 exec code in globals()
824 File "<string>", line 1, in <module>
824 File "<string>", line 1, in <module>
825 ZeroDivisionError: integer division or modulo by zero
825 ZeroDivisionError: integer division or modulo by zero
826
826
827
827
828 [3:apply]:
828 [3:apply]:
829 Traceback (most recent call last):
829 Traceback (most recent call last):
830 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
830 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
831 exec code in working,working
831 exec code in working,working
832 File "<string>", line 1, in <module>
832 File "<string>", line 1, in <module>
833 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
833 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
834 exec code in globals()
834 exec code in globals()
835 File "<string>", line 1, in <module>
835 File "<string>", line 1, in <module>
836 ZeroDivisionError: integer division or modulo by zero
836 ZeroDivisionError: integer division or modulo by zero
837
837
838
838
839 All of this same error handling magic even works in non-blocking mode:
839 All of this same error handling magic even works in non-blocking mode:
840
840
841 .. sourcecode:: ipython
841 .. sourcecode:: ipython
842
842
843 In [83]: dview.block=False
843 In [83]: dview.block=False
844
844
845 In [84]: ar = dview.execute('1/0')
845 In [84]: ar = dview.execute('1/0')
846
846
847 In [85]: ar.get()
847 In [85]: ar.get()
848 ---------------------------------------------------------------------------
848 ---------------------------------------------------------------------------
849 CompositeError Traceback (most recent call last)
849 CompositeError Traceback (most recent call last)
850 /home/user/<ipython-input-21-8531eb3d26fb> in <module>()
850 /home/user/<ipython-input-21-8531eb3d26fb> in <module>()
851 ----> 1 ar.get()
851 ----> 1 ar.get()
852
852
853 /path/to/site-packages/IPython/parallel/client/asyncresult.pyc in get(self, timeout)
853 /path/to/site-packages/IPython/parallel/client/asyncresult.pyc in get(self, timeout)
854 101 return self._result
854 101 return self._result
855 102 else:
855 102 else:
856 --> 103 raise self._exception
856 --> 103 raise self._exception
857 104 else:
857 104 else:
858 105 raise error.TimeoutError("Result not ready.")
858 105 raise error.TimeoutError("Result not ready.")
859
859
860 CompositeError: one or more exceptions from call to method: _execute
860 CompositeError: one or more exceptions from call to method: _execute
861 [0:apply]: ZeroDivisionError: integer division or modulo by zero
861 [0:apply]: ZeroDivisionError: integer division or modulo by zero
862 [1:apply]: ZeroDivisionError: integer division or modulo by zero
862 [1:apply]: ZeroDivisionError: integer division or modulo by zero
863 [2:apply]: ZeroDivisionError: integer division or modulo by zero
863 [2:apply]: ZeroDivisionError: integer division or modulo by zero
864 [3:apply]: ZeroDivisionError: integer division or modulo by zero
864 [3:apply]: ZeroDivisionError: integer division or modulo by zero
865
865
General Comments 0
You need to be logged in to leave comments. Login now