##// END OF EJS Templates
IPYTHON_DIR -> IPYTHONDIR in comments and documentation
Bradley M. Froehle -
Show More
@@ -1,336 +1,336 b''
1 1 # encoding: utf-8
2 2 """
3 3 An application for IPython.
4 4
5 5 All top-level applications should use the classes in this module for
6 6 handling configuration and creating componenets.
7 7
8 8 The job of an :class:`Application` is to create the master configuration
9 9 object and then create the configurable objects, passing the config to them.
10 10
11 11 Authors:
12 12
13 13 * Brian Granger
14 14 * Fernando Perez
15 15 * Min RK
16 16
17 17 """
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Copyright (C) 2008-2011 The IPython Development Team
21 21 #
22 22 # Distributed under the terms of the BSD License. The full license is in
23 23 # the file COPYING, distributed as part of this software.
24 24 #-----------------------------------------------------------------------------
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Imports
28 28 #-----------------------------------------------------------------------------
29 29
30 30 import atexit
31 31 import glob
32 32 import logging
33 33 import os
34 34 import shutil
35 35 import sys
36 36
37 37 from IPython.config.application import Application, catch_config_error
38 38 from IPython.config.configurable import Configurable
39 39 from IPython.config.loader import Config, ConfigFileNotFound
40 40 from IPython.core import release, crashhandler
41 41 from IPython.core.profiledir import ProfileDir, ProfileDirError
42 42 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
43 43 from IPython.utils.traitlets import List, Unicode, Type, Bool, Dict
44 44 from IPython.utils import py3compat
45 45
46 46 #-----------------------------------------------------------------------------
47 47 # Classes and functions
48 48 #-----------------------------------------------------------------------------
49 49
50 50
51 51 #-----------------------------------------------------------------------------
52 52 # Base Application Class
53 53 #-----------------------------------------------------------------------------
54 54
55 55 # aliases and flags
56 56
57 57 base_aliases = {
58 58 'profile' : 'BaseIPythonApplication.profile',
59 59 'ipython-dir' : 'BaseIPythonApplication.ipython_dir',
60 60 'log-level' : 'Application.log_level',
61 61 }
62 62
63 63 base_flags = dict(
64 64 debug = ({'Application' : {'log_level' : logging.DEBUG}},
65 65 "set log level to logging.DEBUG (maximize logging output)"),
66 66 quiet = ({'Application' : {'log_level' : logging.CRITICAL}},
67 67 "set log level to logging.CRITICAL (minimize logging output)"),
68 68 init = ({'BaseIPythonApplication' : {
69 69 'copy_config_files' : True,
70 70 'auto_create' : True}
71 71 }, """Initialize profile with default config files. This is equivalent
72 72 to running `ipython profile create <profile>` prior to startup.
73 73 """)
74 74 )
75 75
76 76
77 77 class BaseIPythonApplication(Application):
78 78
79 79 name = Unicode(u'ipython')
80 80 description = Unicode(u'IPython: an enhanced interactive Python shell.')
81 81 version = Unicode(release.version)
82 82
83 83 aliases = Dict(base_aliases)
84 84 flags = Dict(base_flags)
85 85 classes = List([ProfileDir])
86 86
87 87 # Track whether the config_file has changed,
88 88 # because some logic happens only if we aren't using the default.
89 89 config_file_specified = Bool(False)
90 90
91 91 config_file_name = Unicode(u'ipython_config.py')
92 92 def _config_file_name_default(self):
93 93 return self.name.replace('-','_') + u'_config.py'
94 94 def _config_file_name_changed(self, name, old, new):
95 95 if new != old:
96 96 self.config_file_specified = True
97 97
98 98 # The directory that contains IPython's builtin profiles.
99 99 builtin_profile_dir = Unicode(
100 100 os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
101 101 )
102 102
103 103 config_file_paths = List(Unicode)
104 104 def _config_file_paths_default(self):
105 105 return [os.getcwdu()]
106 106
107 107 profile = Unicode(u'default', config=True,
108 108 help="""The IPython profile to use."""
109 109 )
110 110
111 111 def _profile_changed(self, name, old, new):
112 112 self.builtin_profile_dir = os.path.join(
113 113 get_ipython_package_dir(), u'config', u'profile', new
114 114 )
115 115
116 116 ipython_dir = Unicode(get_ipython_dir(), config=True,
117 117 help="""
118 118 The name of the IPython directory. This directory is used for logging
119 119 configuration (through profiles), history storage, etc. The default
120 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 125 overwrite = Bool(False, config=True,
126 126 help="""Whether to overwrite existing config files when copying""")
127 127 auto_create = Bool(False, config=True,
128 128 help="""Whether to create profile dir if it doesn't exist""")
129 129
130 130 config_files = List(Unicode)
131 131 def _config_files_default(self):
132 132 return [u'ipython_config.py']
133 133
134 134 copy_config_files = Bool(False, config=True,
135 135 help="""Whether to install the default config files into the profile dir.
136 136 If a new profile is being created, and IPython contains config files for that
137 137 profile, then they will be staged into the new directory. Otherwise,
138 138 default config files will be automatically generated.
139 139 """)
140 140
141 141 verbose_crash = Bool(False, config=True,
142 142 help="""Create a massive crash report when IPython enconters what may be an
143 143 internal error. The default is to append a short message to the
144 144 usual traceback""")
145 145
146 146 # The class to use as the crash handler.
147 147 crash_handler_class = Type(crashhandler.CrashHandler)
148 148
149 149 def __init__(self, **kwargs):
150 150 super(BaseIPythonApplication, self).__init__(**kwargs)
151 # ensure even default IPYTHON_DIR exists
151 # ensure even default IPYTHONDIR exists
152 152 if not os.path.exists(self.ipython_dir):
153 153 self._ipython_dir_changed('ipython_dir', self.ipython_dir, self.ipython_dir)
154 154
155 155 #-------------------------------------------------------------------------
156 156 # Various stages of Application creation
157 157 #-------------------------------------------------------------------------
158 158
159 159 def init_crash_handler(self):
160 160 """Create a crash handler, typically setting sys.excepthook to it."""
161 161 self.crash_handler = self.crash_handler_class(self)
162 162 sys.excepthook = self.excepthook
163 163 def unset_crashhandler():
164 164 sys.excepthook = sys.__excepthook__
165 165 atexit.register(unset_crashhandler)
166 166
167 167 def excepthook(self, etype, evalue, tb):
168 168 """this is sys.excepthook after init_crashhandler
169 169
170 170 set self.verbose_crash=True to use our full crashhandler, instead of
171 171 a regular traceback with a short message (crash_handler_lite)
172 172 """
173 173
174 174 if self.verbose_crash:
175 175 return self.crash_handler(etype, evalue, tb)
176 176 else:
177 177 return crashhandler.crash_handler_lite(etype, evalue, tb)
178 178
179 179 def _ipython_dir_changed(self, name, old, new):
180 180 if old in sys.path:
181 181 sys.path.remove(old)
182 182 sys.path.append(os.path.abspath(new))
183 183 if not os.path.isdir(new):
184 184 os.makedirs(new, mode=0777)
185 185 readme = os.path.join(new, 'README')
186 186 if not os.path.exists(readme):
187 187 path = os.path.join(get_ipython_package_dir(), u'config', u'profile')
188 188 shutil.copy(os.path.join(path, 'README'), readme)
189 189 self.log.debug("IPYTHON_DIR set to: %s" % new)
190 190
191 191 def load_config_file(self, suppress_errors=True):
192 192 """Load the config file.
193 193
194 194 By default, errors in loading config are handled, and a warning
195 195 printed on screen. For testing, the suppress_errors option is set
196 196 to False, so errors will make tests fail.
197 197 """
198 198 self.log.debug("Searching path %s for config files", self.config_file_paths)
199 199 base_config = 'ipython_config.py'
200 200 self.log.debug("Attempting to load config file: %s" %
201 201 base_config)
202 202 try:
203 203 Application.load_config_file(
204 204 self,
205 205 base_config,
206 206 path=self.config_file_paths
207 207 )
208 208 except ConfigFileNotFound:
209 209 # ignore errors loading parent
210 210 self.log.debug("Config file %s not found", base_config)
211 211 pass
212 212 if self.config_file_name == base_config:
213 213 # don't load secondary config
214 214 return
215 215 self.log.debug("Attempting to load config file: %s" %
216 216 self.config_file_name)
217 217 try:
218 218 Application.load_config_file(
219 219 self,
220 220 self.config_file_name,
221 221 path=self.config_file_paths
222 222 )
223 223 except ConfigFileNotFound:
224 224 # Only warn if the default config file was NOT being used.
225 225 if self.config_file_specified:
226 226 msg = self.log.warn
227 227 else:
228 228 msg = self.log.debug
229 229 msg("Config file not found, skipping: %s", self.config_file_name)
230 230 except:
231 231 # For testing purposes.
232 232 if not suppress_errors:
233 233 raise
234 234 self.log.warn("Error loading config file: %s" %
235 235 self.config_file_name, exc_info=True)
236 236
237 237 def init_profile_dir(self):
238 238 """initialize the profile dir"""
239 239 try:
240 240 # location explicitly specified:
241 241 location = self.config.ProfileDir.location
242 242 except AttributeError:
243 243 # location not specified, find by profile name
244 244 try:
245 245 p = ProfileDir.find_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
246 246 except ProfileDirError:
247 247 # not found, maybe create it (always create default profile)
248 248 if self.auto_create or self.profile=='default':
249 249 try:
250 250 p = ProfileDir.create_profile_dir_by_name(self.ipython_dir, self.profile, self.config)
251 251 except ProfileDirError:
252 252 self.log.fatal("Could not create profile: %r"%self.profile)
253 253 self.exit(1)
254 254 else:
255 255 self.log.info("Created profile dir: %r"%p.location)
256 256 else:
257 257 self.log.fatal("Profile %r not found."%self.profile)
258 258 self.exit(1)
259 259 else:
260 260 self.log.info("Using existing profile dir: %r"%p.location)
261 261 else:
262 262 # location is fully specified
263 263 try:
264 264 p = ProfileDir.find_profile_dir(location, self.config)
265 265 except ProfileDirError:
266 266 # not found, maybe create it
267 267 if self.auto_create:
268 268 try:
269 269 p = ProfileDir.create_profile_dir(location, self.config)
270 270 except ProfileDirError:
271 271 self.log.fatal("Could not create profile directory: %r"%location)
272 272 self.exit(1)
273 273 else:
274 274 self.log.info("Creating new profile dir: %r"%location)
275 275 else:
276 276 self.log.fatal("Profile directory %r not found."%location)
277 277 self.exit(1)
278 278 else:
279 279 self.log.info("Using existing profile dir: %r"%location)
280 280
281 281 self.profile_dir = p
282 282 self.config_file_paths.append(p.location)
283 283
284 284 def init_config_files(self):
285 285 """[optionally] copy default config files into profile dir."""
286 286 # copy config files
287 287 path = self.builtin_profile_dir
288 288 if self.copy_config_files:
289 289 src = self.profile
290 290
291 291 cfg = self.config_file_name
292 292 if path and os.path.exists(os.path.join(path, cfg)):
293 293 self.log.warn("Staging %r from %s into %r [overwrite=%s]"%(
294 294 cfg, src, self.profile_dir.location, self.overwrite)
295 295 )
296 296 self.profile_dir.copy_config_file(cfg, path=path, overwrite=self.overwrite)
297 297 else:
298 298 self.stage_default_config_file()
299 299 else:
300 300 # Still stage *bundled* config files, but not generated ones
301 301 # This is necessary for `ipython profile=sympy` to load the profile
302 302 # on the first go
303 303 files = glob.glob(os.path.join(path, '*.py'))
304 304 for fullpath in files:
305 305 cfg = os.path.basename(fullpath)
306 306 if self.profile_dir.copy_config_file(cfg, path=path, overwrite=False):
307 307 # file was copied
308 308 self.log.warn("Staging bundled %s from %s into %r"%(
309 309 cfg, self.profile, self.profile_dir.location)
310 310 )
311 311
312 312
313 313 def stage_default_config_file(self):
314 314 """auto generate default config file, and stage it into the profile."""
315 315 s = self.generate_config_file()
316 316 fname = os.path.join(self.profile_dir.location, self.config_file_name)
317 317 if self.overwrite or not os.path.exists(fname):
318 318 self.log.warn("Generating default config file: %r"%(fname))
319 319 with open(fname, 'w') as f:
320 320 f.write(s)
321 321
322 322 @catch_config_error
323 323 def initialize(self, argv=None):
324 324 # don't hook up crash handler before parsing command-line
325 325 self.parse_command_line(argv)
326 326 self.init_crash_handler()
327 327 if self.subapp is not None:
328 328 # stop here if subapp is taking over
329 329 return
330 330 cl_config = self.config
331 331 self.init_profile_dir()
332 332 self.init_config_files()
333 333 self.load_config_file()
334 334 # enforce cl-opts override configfile opts:
335 335 self.update_config(cl_config)
336 336
@@ -1,293 +1,293 b''
1 1 # encoding: utf-8
2 2 """
3 3 An application for managing IPython profiles.
4 4
5 5 To be invoked as the `ipython profile` subcommand.
6 6
7 7 Authors:
8 8
9 9 * Min RK
10 10
11 11 """
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Copyright (C) 2008-2011 The IPython Development Team
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #-----------------------------------------------------------------------------
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Imports
22 22 #-----------------------------------------------------------------------------
23 23
24 24 import logging
25 25 import os
26 26
27 27 from IPython.config.application import Application, boolean_flag
28 28 from IPython.core.application import (
29 29 BaseIPythonApplication, base_flags, base_aliases
30 30 )
31 31 from IPython.core.profiledir import ProfileDir
32 32 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
33 33 from IPython.utils.traitlets import Unicode, Bool, Dict
34 34
35 35 #-----------------------------------------------------------------------------
36 36 # Constants
37 37 #-----------------------------------------------------------------------------
38 38
39 39 create_help = """Create an IPython profile by name
40 40
41 41 Create an ipython profile directory by its name or
42 42 profile directory path. Profile directories contain
43 43 configuration, log and security related files and are named
44 44 using the convention 'profile_<name>'. By default they are
45 45 located in your ipython directory. Once created, you will
46 46 can edit the configuration files in the profile
47 47 directory to configure IPython. Most users will create a
48 48 profile directory by name,
49 49 `ipython profile create myprofile`, which will put the directory
50 50 in `<ipython_dir>/profile_myprofile`.
51 51 """
52 52 list_help = """List available IPython profiles
53 53
54 54 List all available profiles, by profile location, that can
55 55 be found in the current working directly or in the ipython
56 56 directory. Profile directories are named using the convention
57 57 'profile_<profile>'.
58 58 """
59 59 profile_help = """Manage IPython profiles
60 60
61 61 Profile directories contain
62 62 configuration, log and security related files and are named
63 63 using the convention 'profile_<name>'. By default they are
64 64 located in your ipython directory. You can create profiles
65 65 with `ipython profile create <name>`, or see the profiles you
66 66 already have with `ipython profile list`
67 67
68 68 To get started configuring IPython, simply do:
69 69
70 70 $> ipython profile create
71 71
72 72 and IPython will create the default profile in <ipython_dir>/profile_default,
73 73 where you can edit ipython_config.py to start configuring IPython.
74 74
75 75 """
76 76
77 77 _list_examples = "ipython profile list # list all profiles"
78 78
79 79 _create_examples = """
80 80 ipython profile create foo # create profile foo w/ default config files
81 81 ipython profile create foo --reset # restage default config files over current
82 82 ipython profile create foo --parallel # also stage parallel config files
83 83 """
84 84
85 85 _main_examples = """
86 86 ipython profile create -h # show the help string for the create subcommand
87 87 ipython profile list -h # show the help string for the list subcommand
88 88 """
89 89
90 90 #-----------------------------------------------------------------------------
91 91 # Profile Application Class (for `ipython profile` subcommand)
92 92 #-----------------------------------------------------------------------------
93 93
94 94
95 95 def list_profiles_in(path):
96 96 """list profiles in a given root directory"""
97 97 files = os.listdir(path)
98 98 profiles = []
99 99 for f in files:
100 100 full_path = os.path.join(path, f)
101 101 if os.path.isdir(full_path) and f.startswith('profile_'):
102 102 profiles.append(f.split('_',1)[-1])
103 103 return profiles
104 104
105 105
106 106 def list_bundled_profiles():
107 107 """list profiles that are bundled with IPython."""
108 108 path = os.path.join(get_ipython_package_dir(), u'config', u'profile')
109 109 files = os.listdir(path)
110 110 profiles = []
111 111 for profile in files:
112 112 full_path = os.path.join(path, profile)
113 113 if os.path.isdir(full_path) and profile != "__pycache__":
114 114 profiles.append(profile)
115 115 return profiles
116 116
117 117
118 118 class ProfileList(Application):
119 119 name = u'ipython-profile'
120 120 description = list_help
121 121 examples = _list_examples
122 122
123 123 aliases = Dict({
124 124 'ipython-dir' : 'ProfileList.ipython_dir',
125 125 'log-level' : 'Application.log_level',
126 126 })
127 127 flags = Dict(dict(
128 128 debug = ({'Application' : {'log_level' : 0}},
129 129 "Set Application.log_level to 0, maximizing log output."
130 130 )
131 131 ))
132 132
133 133 ipython_dir = Unicode(get_ipython_dir(), config=True,
134 134 help="""
135 135 The name of the IPython directory. This directory is used for logging
136 136 configuration (through profiles), history storage, etc. The default
137 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 143 def _print_profiles(self, profiles):
144 144 """print list of profiles, indented."""
145 145 for profile in profiles:
146 146 print ' %s' % profile
147 147
148 148 def list_profile_dirs(self):
149 149 profiles = list_bundled_profiles()
150 150 if profiles:
151 151 print
152 152 print "Available profiles in IPython:"
153 153 self._print_profiles(profiles)
154 154 print
155 155 print " The first request for a bundled profile will copy it"
156 156 print " into your IPython directory (%s)," % self.ipython_dir
157 157 print " where you can customize it."
158 158
159 159 profiles = list_profiles_in(self.ipython_dir)
160 160 if profiles:
161 161 print
162 162 print "Available profiles in %s:" % self.ipython_dir
163 163 self._print_profiles(profiles)
164 164
165 165 profiles = list_profiles_in(os.getcwdu())
166 166 if profiles:
167 167 print
168 168 print "Available profiles in current directory (%s):" % os.getcwdu()
169 169 self._print_profiles(profiles)
170 170
171 171 print
172 172 print "To use any of the above profiles, start IPython with:"
173 173 print " ipython --profile=<name>"
174 174 print
175 175
176 176 def start(self):
177 177 self.list_profile_dirs()
178 178
179 179
180 180 create_flags = {}
181 181 create_flags.update(base_flags)
182 182 # don't include '--init' flag, which implies running profile create in other apps
183 183 create_flags.pop('init')
184 184 create_flags['reset'] = ({'ProfileCreate': {'overwrite' : True}},
185 185 "reset config files in this profile to the defaults.")
186 186 create_flags['parallel'] = ({'ProfileCreate': {'parallel' : True}},
187 187 "Include the config files for parallel "
188 188 "computing apps (ipengine, ipcontroller, etc.)")
189 189
190 190
191 191 class ProfileCreate(BaseIPythonApplication):
192 192 name = u'ipython-profile'
193 193 description = create_help
194 194 examples = _create_examples
195 195 auto_create = Bool(True, config=False)
196 196
197 197 def _copy_config_files_default(self):
198 198 return True
199 199
200 200 parallel = Bool(False, config=True,
201 201 help="whether to include parallel computing config files")
202 202 def _parallel_changed(self, name, old, new):
203 203 parallel_files = [ 'ipcontroller_config.py',
204 204 'ipengine_config.py',
205 205 'ipcluster_config.py'
206 206 ]
207 207 if new:
208 208 for cf in parallel_files:
209 209 self.config_files.append(cf)
210 210 else:
211 211 for cf in parallel_files:
212 212 if cf in self.config_files:
213 213 self.config_files.remove(cf)
214 214
215 215 def parse_command_line(self, argv):
216 216 super(ProfileCreate, self).parse_command_line(argv)
217 217 # accept positional arg as profile name
218 218 if self.extra_args:
219 219 self.profile = self.extra_args[0]
220 220
221 221 flags = Dict(create_flags)
222 222
223 223 classes = [ProfileDir]
224 224
225 225 def init_config_files(self):
226 226 super(ProfileCreate, self).init_config_files()
227 227 # use local imports, since these classes may import from here
228 228 from IPython.frontend.terminal.ipapp import TerminalIPythonApp
229 229 apps = [TerminalIPythonApp]
230 230 try:
231 231 from IPython.frontend.qt.console.qtconsoleapp import IPythonQtConsoleApp
232 232 except Exception:
233 233 # this should be ImportError, but under weird circumstances
234 234 # this might be an AttributeError, or possibly others
235 235 # in any case, nothing should cause the profile creation to crash.
236 236 pass
237 237 else:
238 238 apps.append(IPythonQtConsoleApp)
239 239 try:
240 240 from IPython.frontend.html.notebook.notebookapp import NotebookApp
241 241 except ImportError:
242 242 pass
243 243 except Exception:
244 244 self.log.debug('Unexpected error when importing NotebookApp',
245 245 exc_info=True
246 246 )
247 247 else:
248 248 apps.append(NotebookApp)
249 249 if self.parallel:
250 250 from IPython.parallel.apps.ipcontrollerapp import IPControllerApp
251 251 from IPython.parallel.apps.ipengineapp import IPEngineApp
252 252 from IPython.parallel.apps.ipclusterapp import IPClusterStart
253 253 from IPython.parallel.apps.iploggerapp import IPLoggerApp
254 254 apps.extend([
255 255 IPControllerApp,
256 256 IPEngineApp,
257 257 IPClusterStart,
258 258 IPLoggerApp,
259 259 ])
260 260 for App in apps:
261 261 app = App()
262 262 app.config.update(self.config)
263 263 app.log = self.log
264 264 app.overwrite = self.overwrite
265 265 app.copy_config_files=True
266 266 app.profile = self.profile
267 267 app.init_profile_dir()
268 268 app.init_config_files()
269 269
270 270 def stage_default_config_file(self):
271 271 pass
272 272
273 273
274 274 class ProfileApp(Application):
275 275 name = u'ipython-profile'
276 276 description = profile_help
277 277 examples = _main_examples
278 278
279 279 subcommands = Dict(dict(
280 280 create = (ProfileCreate, "Create a new profile dir with default config files"),
281 281 list = (ProfileList, "List existing profiles")
282 282 ))
283 283
284 284 def start(self):
285 285 if self.subapp is None:
286 286 print "No subcommand specified. Must specify one of: %s"%(self.subcommands.keys())
287 287 print
288 288 self.print_description()
289 289 self.print_subcommands()
290 290 self.exit(1)
291 291 else:
292 292 return self.subapp.start()
293 293
@@ -1,535 +1,535 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Usage information for the main IPython applications.
3 3 """
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2008-2011 The IPython Development Team
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 #
8 8 # Distributed under the terms of the BSD License. The full license is in
9 9 # the file COPYING, distributed as part of this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 import sys
13 13 from IPython.core import release
14 14
15 15 cl_usage = """\
16 16 =========
17 17 IPython
18 18 =========
19 19
20 20 Tools for Interactive Computing in Python
21 21 =========================================
22 22
23 23 A Python shell with automatic history (input and output), dynamic object
24 24 introspection, easier configuration, command completion, access to the
25 25 system shell and more. IPython can also be embedded in running programs.
26 26
27 27
28 28 Usage
29 29
30 30 ipython [subcommand] [options] [files]
31 31
32 32 If invoked with no options, it executes all the files listed in sequence
33 33 and exits, use -i to enter interactive mode after running the files. Files
34 34 ending in .py will be treated as normal Python, but files ending in .ipy
35 35 can contain special IPython syntax (magic commands, shell expansions, etc.)
36 36
37 37 Almost all configuration in IPython is available via the command-line. Do
38 38 `ipython --help-all` to see all available options. For persistent
39 39 configuration, look into your `ipython_config.py` configuration file for
40 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 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,
45 IPYTHON_DIR defaults to `$HOME/.config/ipython`, and for other Unix systems
44 directory will be located in $IPYTHONDIR/profile_default. For Linux users,
45 IPYTHONDIR defaults to `$HOME/.config/ipython`, and for other Unix systems
46 46 to `$HOME/.ipython`. For Windows users, $HOME resolves to C:\\Documents
47 47 and Settings\\YourUserName in most instances.
48 48
49 49 To initialize a profile with the default configuration file, do::
50 50
51 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 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 57 environment variable with this name and setting it to the desired path.
58 58
59 59 For more information, see the manual available in HTML and PDF in your
60 60 installation, or online at http://ipython.org/documentation.html.
61 61 """
62 62
63 63 interactive_usage = """
64 64 IPython -- An enhanced Interactive Python
65 65 =========================================
66 66
67 67 IPython offers a combination of convenient shell features, special commands
68 68 and a history mechanism for both input (command history) and output (results
69 69 caching, similar to Mathematica). It is intended to be a fully compatible
70 70 replacement for the standard Python interpreter, while offering vastly
71 71 improved functionality and flexibility.
72 72
73 73 At your system command line, type 'ipython -h' to see the command line
74 74 options available. This document only describes interactive features.
75 75
76 76 MAIN FEATURES
77 77
78 78 * Access to the standard Python help. As of Python 2.1, a help system is
79 79 available with access to object docstrings and the Python manuals. Simply
80 80 type 'help' (no quotes) to access it.
81 81
82 82 * Magic commands: type %magic for information on the magic subsystem.
83 83
84 84 * System command aliases, via the %alias command or the configuration file(s).
85 85
86 86 * Dynamic object information:
87 87
88 88 Typing ?word or word? prints detailed information about an object. If
89 89 certain strings in the object are too long (docstrings, code, etc.) they get
90 90 snipped in the center for brevity.
91 91
92 92 Typing ??word or word?? gives access to the full information without
93 93 snipping long strings. Long strings are sent to the screen through the less
94 94 pager if longer than the screen, printed otherwise.
95 95
96 96 The ?/?? system gives access to the full source code for any object (if
97 97 available), shows function prototypes and other useful information.
98 98
99 99 If you just want to see an object's docstring, type '%pdoc object' (without
100 100 quotes, and without % if you have automagic on).
101 101
102 102 Both %pdoc and ?/?? give you access to documentation even on things which are
103 103 not explicitely defined. Try for example typing {}.get? or after import os,
104 104 type os.path.abspath??. The magic functions %pdef, %source and %file operate
105 105 similarly.
106 106
107 107 * Completion in the local namespace, by typing TAB at the prompt.
108 108
109 109 At any time, hitting tab will complete any available python commands or
110 110 variable names, and show you a list of the possible completions if there's
111 111 no unambiguous one. It will also complete filenames in the current directory.
112 112
113 113 This feature requires the readline and rlcomplete modules, so it won't work
114 114 if your Python lacks readline support (such as under Windows).
115 115
116 116 * Search previous command history in two ways (also requires readline):
117 117
118 118 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
119 119 search through only the history items that match what you've typed so
120 120 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
121 121 normal arrow keys.
122 122
123 123 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
124 124 your history for lines that match what you've typed so far, completing as
125 125 much as it can.
126 126
127 127 - %hist: search history by index (this does *not* require readline).
128 128
129 129 * Persistent command history across sessions.
130 130
131 131 * Logging of input with the ability to save and restore a working session.
132 132
133 133 * System escape with !. Typing !ls will run 'ls' in the current directory.
134 134
135 135 * The reload command does a 'deep' reload of a module: changes made to the
136 136 module since you imported will actually be available without having to exit.
137 137
138 138 * Verbose and colored exception traceback printouts. See the magic xmode and
139 139 xcolor functions for details (just type %magic).
140 140
141 141 * Input caching system:
142 142
143 143 IPython offers numbered prompts (In/Out) with input and output caching. All
144 144 input is saved and can be retrieved as variables (besides the usual arrow
145 145 key recall).
146 146
147 147 The following GLOBAL variables always exist (so don't overwrite them!):
148 148 _i: stores previous input.
149 149 _ii: next previous.
150 150 _iii: next-next previous.
151 151 _ih : a list of all input _ih[n] is the input from line n.
152 152
153 153 Additionally, global variables named _i<n> are dynamically created (<n>
154 154 being the prompt counter), such that _i<n> == _ih[<n>]
155 155
156 156 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
157 157
158 158 You can create macros which contain multiple input lines from this history,
159 159 for later re-execution, with the %macro function.
160 160
161 161 The history function %hist allows you to see any part of your input history
162 162 by printing a range of the _i variables. Note that inputs which contain
163 163 magic functions (%) appear in the history with a prepended comment. This is
164 164 because they aren't really valid Python code, so you can't exec them.
165 165
166 166 * Output caching system:
167 167
168 168 For output that is returned from actions, a system similar to the input
169 169 cache exists but using _ instead of _i. Only actions that produce a result
170 170 (NOT assignments, for example) are cached. If you are familiar with
171 171 Mathematica, IPython's _ variables behave exactly like Mathematica's %
172 172 variables.
173 173
174 174 The following GLOBAL variables always exist (so don't overwrite them!):
175 175 _ (one underscore): previous output.
176 176 __ (two underscores): next previous.
177 177 ___ (three underscores): next-next previous.
178 178
179 179 Global variables named _<n> are dynamically created (<n> being the prompt
180 180 counter), such that the result of output <n> is always available as _<n>.
181 181
182 182 Finally, a global dictionary named _oh exists with entries for all lines
183 183 which generated output.
184 184
185 185 * Directory history:
186 186
187 187 Your history of visited directories is kept in the global list _dh, and the
188 188 magic %cd command can be used to go to any entry in that list.
189 189
190 190 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
191 191
192 192 1. Auto-parentheses
193 193 Callable objects (i.e. functions, methods, etc) can be invoked like
194 194 this (notice the commas between the arguments):
195 195 In [1]: callable_ob arg1, arg2, arg3
196 196 and the input will be translated to this:
197 197 ------> callable_ob(arg1, arg2, arg3)
198 198 This feature is off by default (in rare cases it can produce
199 199 undesirable side-effects), but you can activate it at the command-line
200 200 by starting IPython with `--autocall 1`, set it permanently in your
201 201 configuration file, or turn on at runtime with `%autocall 1`.
202 202
203 203 You can force auto-parentheses by using '/' as the first character
204 204 of a line. For example:
205 205 In [1]: /globals # becomes 'globals()'
206 206 Note that the '/' MUST be the first character on the line! This
207 207 won't work:
208 208 In [2]: print /globals # syntax error
209 209
210 210 In most cases the automatic algorithm should work, so you should
211 211 rarely need to explicitly invoke /. One notable exception is if you
212 212 are trying to call a function with a list of tuples as arguments (the
213 213 parenthesis will confuse IPython):
214 214 In [1]: zip (1,2,3),(4,5,6) # won't work
215 215 but this will work:
216 216 In [2]: /zip (1,2,3),(4,5,6)
217 217 ------> zip ((1,2,3),(4,5,6))
218 218 Out[2]= [(1, 4), (2, 5), (3, 6)]
219 219
220 220 IPython tells you that it has altered your command line by
221 221 displaying the new command line preceded by -->. e.g.:
222 222 In [18]: callable list
223 223 -------> callable (list)
224 224
225 225 2. Auto-Quoting
226 226 You can force auto-quoting of a function's arguments by using ',' as
227 227 the first character of a line. For example:
228 228 In [1]: ,my_function /home/me # becomes my_function("/home/me")
229 229
230 230 If you use ';' instead, the whole argument is quoted as a single
231 231 string (while ',' splits on whitespace):
232 232 In [2]: ,my_function a b c # becomes my_function("a","b","c")
233 233 In [3]: ;my_function a b c # becomes my_function("a b c")
234 234
235 235 Note that the ',' MUST be the first character on the line! This
236 236 won't work:
237 237 In [4]: x = ,my_function /home/me # syntax error
238 238 """
239 239
240 240 interactive_usage_min = """\
241 241 An enhanced console for Python.
242 242 Some of its features are:
243 243 - Readline support if the readline library is present.
244 244 - Tab completion in the local namespace.
245 245 - Logging of input, see command-line options.
246 246 - System shell escape via ! , eg !ls.
247 247 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
248 248 - Keeps track of locally defined variables via %who, %whos.
249 249 - Show object information with a ? eg ?x or x? (use ?? for more info).
250 250 """
251 251
252 252 quick_reference = r"""
253 253 IPython -- An enhanced Interactive Python - Quick Reference Card
254 254 ================================================================
255 255
256 256 obj?, obj?? : Get help, or more help for object (also works as
257 257 ?obj, ??obj).
258 258 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
259 259 %magic : Information about IPython's 'magic' % functions.
260 260
261 261 Magic functions are prefixed by %, and typically take their arguments without
262 262 parentheses, quotes or even commas for convenience.
263 263
264 264 Example magic function calls:
265 265
266 266 %alias d ls -F : 'd' is now an alias for 'ls -F'
267 267 alias d ls -F : Works if 'alias' not a python name
268 268 alist = %alias : Get list of aliases to 'alist'
269 269 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
270 270 %cd?? : See help AND source for magic %cd
271 271
272 272 System commands:
273 273
274 274 !cp a.txt b/ : System command escape, calls os.system()
275 275 cp a.txt b/ : after %rehashx, most system commands work without !
276 276 cp ${f}.txt $bar : Variable expansion in magics and system commands
277 277 files = !ls /usr : Capture sytem command output
278 278 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
279 279
280 280 History:
281 281
282 282 _i, _ii, _iii : Previous, next previous, next next previous input
283 283 _i4, _ih[2:5] : Input history line 4, lines 2-4
284 284 exec _i81 : Execute input history line #81 again
285 285 %rep 81 : Edit input history line #81
286 286 _, __, ___ : previous, next previous, next next previous output
287 287 _dh : Directory history
288 288 _oh : Output history
289 289 %hist : Command history. '%hist -g foo' search history for 'foo'
290 290
291 291 Autocall:
292 292
293 293 f 1,2 : f(1,2) # Off by default, enable with %autocall magic.
294 294 /f 1,2 : f(1,2) (forced autoparen)
295 295 ,f 1 2 : f("1","2")
296 296 ;f 1 2 : f("1 2")
297 297
298 298 Remember: TAB completion works in many contexts, not just file names
299 299 or python names.
300 300
301 301 The following magic functions are currently available:
302 302
303 303 """
304 304
305 305 gui_reference = """\
306 306 ===============================
307 307 The graphical IPython console
308 308 ===============================
309 309
310 310 This console is designed to emulate the look, feel and workflow of a terminal
311 311 environment, while adding a number of enhancements that are simply not possible
312 312 in a real terminal, such as inline syntax highlighting, true multiline editing,
313 313 inline graphics and much more.
314 314
315 315 This quick reference document contains the basic information you'll need to
316 316 know to make the most efficient use of it. For the various command line
317 317 options available at startup, type ``ipython qtconsole --help`` at the command line.
318 318
319 319
320 320 Multiline editing
321 321 =================
322 322
323 323 The graphical console is capable of true multiline editing, but it also tries
324 324 to behave intuitively like a terminal when possible. If you are used to
325 325 IPython's old terminal behavior, you should find the transition painless, and
326 326 once you learn a few basic keybindings it will be a much more efficient
327 327 environment.
328 328
329 329 For single expressions or indented blocks, the console behaves almost like the
330 330 terminal IPython: single expressions are immediately evaluated, and indented
331 331 blocks are evaluated once a single blank line is entered::
332 332
333 333 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
334 334 Hello IPython!
335 335
336 336 In [2]: for i in range(10):
337 337 ...: print i,
338 338 ...:
339 339 0 1 2 3 4 5 6 7 8 9
340 340
341 341 If you want to enter more than one expression in a single input block
342 342 (something not possible in the terminal), you can use ``Control-Enter`` at the
343 343 end of your first line instead of ``Enter``. At that point the console goes
344 344 into 'cell mode' and even if your inputs are not indented, it will continue
345 345 accepting arbitrarily many lines until either you enter an extra blank line or
346 346 you hit ``Shift-Enter`` (the key binding that forces execution). When a
347 347 multiline cell is entered, IPython analyzes it and executes its code producing
348 348 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
349 349 cell is executed as if it was a script. An example should clarify this::
350 350
351 351 In [3]: x=1 # Hit C-Enter here
352 352 ...: y=2 # from now on, regular Enter is sufficient
353 353 ...: z=3
354 354 ...: x**2 # This does *not* produce an Out[] value
355 355 ...: x+y+z # Only the last expression does
356 356 ...:
357 357 Out[3]: 6
358 358
359 359 The behavior where an extra blank line forces execution is only active if you
360 360 are actually typing at the keyboard each line, and is meant to make it mimic
361 361 the IPython terminal behavior. If you paste a long chunk of input (for example
362 362 a long script copied form an editor or web browser), it can contain arbitrarily
363 363 many intermediate blank lines and they won't cause any problems. As always,
364 364 you can then make it execute by appending a blank line *at the end* or hitting
365 365 ``Shift-Enter`` anywhere within the cell.
366 366
367 367 With the up arrow key, you can retrieve previous blocks of input that contain
368 368 multiple lines. You can move inside of a multiline cell like you would in any
369 369 text editor. When you want it executed, the simplest thing to do is to hit the
370 370 force execution key, ``Shift-Enter`` (though you can also navigate to the end
371 371 and append a blank line by using ``Enter`` twice).
372 372
373 373 If you've edited a multiline cell and accidentally navigate out of it with the
374 374 up or down arrow keys, IPython will clear the cell and replace it with the
375 375 contents of the one above or below that you navigated to. If this was an
376 376 accident and you want to retrieve the cell you were editing, use the Undo
377 377 keybinding, ``Control-z``.
378 378
379 379
380 380 Key bindings
381 381 ============
382 382
383 383 The IPython console supports most of the basic Emacs line-oriented keybindings,
384 384 in addition to some of its own.
385 385
386 386 The keybinding prefixes mean:
387 387
388 388 - ``C``: Control
389 389 - ``S``: Shift
390 390 - ``M``: Meta (typically the Alt key)
391 391
392 392 The keybindings themselves are:
393 393
394 394 - ``Enter``: insert new line (may cause execution, see above).
395 395 - ``C-Enter``: *force* new line, *never* causes execution.
396 396 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
397 397 - ``Up``: step backwards through the history.
398 398 - ``Down``: step forwards through the history.
399 399 - ``S-Up``: search backwards through the history (like ``C-r`` in bash).
400 400 - ``S-Down``: search forwards through the history.
401 401 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
402 402 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
403 403 - ``C-v``: paste text from clipboard.
404 404 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
405 405 - ``C-S-z``: redo.
406 406 - ``C-o``: move to 'other' area, between pager and terminal.
407 407 - ``C-l``: clear terminal.
408 408 - ``C-a``: go to beginning of line.
409 409 - ``C-e``: go to end of line.
410 410 - ``C-u``: kill from cursor to the begining of the line.
411 411 - ``C-k``: kill from cursor to the end of the line.
412 412 - ``C-y``: yank (paste)
413 413 - ``C-p``: previous line (like up arrow)
414 414 - ``C-n``: next line (like down arrow)
415 415 - ``C-f``: forward (like right arrow)
416 416 - ``C-b``: back (like left arrow)
417 417 - ``C-d``: delete next character, or exits if input is empty
418 418 - ``M-<``: move to the beginning of the input region.
419 419 - ``M->``: move to the end of the input region.
420 420 - ``M-d``: delete next word.
421 421 - ``M-Backspace``: delete previous word.
422 422 - ``C-.``: force a kernel restart (a confirmation dialog appears).
423 423 - ``C-+``: increase font size.
424 424 - ``C--``: decrease font size.
425 425 - ``C-M-Space``: toggle full screen. (Command-Control-Space on Mac OS X)
426 426
427 427 The IPython pager
428 428 =================
429 429
430 430 IPython will show long blocks of text from many sources using a builtin pager.
431 431 You can control where this pager appears with the ``--paging`` command-line
432 432 flag:
433 433
434 434 - ``inside`` [default]: the pager is overlaid on top of the main terminal. You
435 435 must quit the pager to get back to the terminal (similar to how a pager such
436 436 as ``less`` or ``more`` works).
437 437
438 438 - ``vsplit``: the console is made double-tall, and the pager appears on the
439 439 bottom area when needed. You can view its contents while using the terminal.
440 440
441 441 - ``hsplit``: the console is made double-wide, and the pager appears on the
442 442 right area when needed. You can view its contents while using the terminal.
443 443
444 444 - ``none``: the console never pages output.
445 445
446 446 If you use the vertical or horizontal paging modes, you can navigate between
447 447 terminal and pager as follows:
448 448
449 449 - Tab key: goes from pager to terminal (but not the other way around).
450 450 - Control-o: goes from one to another always.
451 451 - Mouse: click on either.
452 452
453 453 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
454 454 focus on the pager area).
455 455
456 456 Running subprocesses
457 457 ====================
458 458
459 459 The graphical IPython console uses the ``pexpect`` module to run subprocesses
460 460 when you type ``!command``. This has a number of advantages (true asynchronous
461 461 output from subprocesses as well as very robust termination of rogue
462 462 subprocesses with ``Control-C``), as well as some limitations. The main
463 463 limitation is that you can *not* interact back with the subprocess, so anything
464 464 that invokes a pager or expects you to type input into it will block and hang
465 465 (you can kill it with ``Control-C``).
466 466
467 467 We have provided as magics ``%less`` to page files (aliased to ``%more``),
468 468 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
469 469 most common commands you'd want to call in your subshell and that would cause
470 470 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
471 471
472 472 Display
473 473 =======
474 474
475 475 The IPython console can now display objects in a variety of formats, including
476 476 HTML, PNG and SVG. This is accomplished using the display functions in
477 477 ``IPython.core.display``::
478 478
479 479 In [4]: from IPython.core.display import display, display_html
480 480
481 481 In [5]: from IPython.core.display import display_png, display_svg
482 482
483 483 Python objects can simply be passed to these functions and the appropriate
484 484 representations will be displayed in the console as long as the objects know
485 485 how to compute those representations. The easiest way of teaching objects how
486 486 to format themselves in various representations is to define special methods
487 487 such as: ``_repr_html_``, ``_repr_svg_`` and ``_repr_png_``. IPython's display formatters
488 488 can also be given custom formatter functions for various types::
489 489
490 490 In [6]: ip = get_ipython()
491 491
492 492 In [7]: html_formatter = ip.display_formatter.formatters['text/html']
493 493
494 494 In [8]: html_formatter.for_type(Foo, foo_to_html)
495 495
496 496 For further details, see ``IPython.core.formatters``.
497 497
498 498 Inline matplotlib graphics
499 499 ==========================
500 500
501 501 The IPython console is capable of displaying matplotlib figures inline, in SVG
502 502 or PNG format. If started with the ``pylab=inline``, then all figures are
503 503 rendered inline automatically (PNG by default). If started with ``--pylab``
504 504 or ``pylab=<your backend>``, then a GUI backend will be used, but IPython's
505 505 ``display()`` and ``getfigs()`` functions can be used to view plots inline::
506 506
507 507 In [9]: display(*getfigs()) # display all figures inline
508 508
509 509 In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline
510 510 """
511 511
512 512
513 513 quick_guide = """\
514 514 ? -> Introduction and overview of IPython's features.
515 515 %quickref -> Quick reference.
516 516 help -> Python's own help system.
517 517 object? -> Details about 'object', use 'object??' for extra details.
518 518 """
519 519
520 520 gui_note = """\
521 521 %guiref -> A brief reference about the graphical user interface.
522 522 """
523 523
524 524 default_banner_parts = [
525 525 'Python %s\n' % (sys.version.split('\n')[0],),
526 526 'Type "copyright", "credits" or "license" for more information.\n\n',
527 527 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
528 528 quick_guide
529 529 ]
530 530
531 531 default_gui_banner_parts = default_banner_parts + [gui_note]
532 532
533 533 default_banner = ''.join(default_banner_parts)
534 534
535 535 default_gui_banner = ''.join(default_gui_banner_parts)
@@ -1,464 +1,464 b''
1 1 # encoding: utf-8
2 2 """
3 3 Utilities for path handling.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 import os
18 18 import sys
19 19 import tempfile
20 20 import warnings
21 21 from hashlib import md5
22 22
23 23 import IPython
24 24 from IPython.utils.process import system
25 25 from IPython.utils.importstring import import_item
26 26 from IPython.utils import py3compat
27 27
28 28 #-----------------------------------------------------------------------------
29 29 # Code
30 30 #-----------------------------------------------------------------------------
31 31
32 32 fs_encoding = sys.getfilesystemencoding()
33 33
34 34 def _get_long_path_name(path):
35 35 """Dummy no-op."""
36 36 return path
37 37
38 38 def _writable_dir(path):
39 39 """Whether `path` is a directory, to which the user has write access."""
40 40 return os.path.isdir(path) and os.access(path, os.W_OK)
41 41
42 42 if sys.platform == 'win32':
43 43 def _get_long_path_name(path):
44 44 """Get a long path name (expand ~) on Windows using ctypes.
45 45
46 46 Examples
47 47 --------
48 48
49 49 >>> get_long_path_name('c:\\docume~1')
50 50 u'c:\\\\Documents and Settings'
51 51
52 52 """
53 53 try:
54 54 import ctypes
55 55 except ImportError:
56 56 raise ImportError('you need to have ctypes installed for this to work')
57 57 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
58 58 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
59 59 ctypes.c_uint ]
60 60
61 61 buf = ctypes.create_unicode_buffer(260)
62 62 rv = _GetLongPathName(path, buf, 260)
63 63 if rv == 0 or rv > 260:
64 64 return path
65 65 else:
66 66 return buf.value
67 67
68 68
69 69 def get_long_path_name(path):
70 70 """Expand a path into its long form.
71 71
72 72 On Windows this expands any ~ in the paths. On other platforms, it is
73 73 a null operation.
74 74 """
75 75 return _get_long_path_name(path)
76 76
77 77
78 78 def unquote_filename(name, win32=(sys.platform=='win32')):
79 79 """ On Windows, remove leading and trailing quotes from filenames.
80 80 """
81 81 if win32:
82 82 if name.startswith(("'", '"')) and name.endswith(("'", '"')):
83 83 name = name[1:-1]
84 84 return name
85 85
86 86
87 87 def get_py_filename(name, force_win32=None):
88 88 """Return a valid python filename in the current directory.
89 89
90 90 If the given name is not a file, it adds '.py' and searches again.
91 91 Raises IOError with an informative message if the file isn't found.
92 92
93 93 On Windows, apply Windows semantics to the filename. In particular, remove
94 94 any quoting that has been applied to it. This option can be forced for
95 95 testing purposes.
96 96 """
97 97
98 98 name = os.path.expanduser(name)
99 99 if force_win32 is None:
100 100 win32 = (sys.platform == 'win32')
101 101 else:
102 102 win32 = force_win32
103 103 name = unquote_filename(name, win32=win32)
104 104 if not os.path.isfile(name) and not name.endswith('.py'):
105 105 name += '.py'
106 106 if os.path.isfile(name):
107 107 return name
108 108 else:
109 109 raise IOError,'File `%r` not found.' % name
110 110
111 111
112 112 def filefind(filename, path_dirs=None):
113 113 """Find a file by looking through a sequence of paths.
114 114
115 115 This iterates through a sequence of paths looking for a file and returns
116 116 the full, absolute path of the first occurence of the file. If no set of
117 117 path dirs is given, the filename is tested as is, after running through
118 118 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
119 119
120 120 filefind('myfile.txt')
121 121
122 122 will find the file in the current working dir, but::
123 123
124 124 filefind('~/myfile.txt')
125 125
126 126 Will find the file in the users home directory. This function does not
127 127 automatically try any paths, such as the cwd or the user's home directory.
128 128
129 129 Parameters
130 130 ----------
131 131 filename : str
132 132 The filename to look for.
133 133 path_dirs : str, None or sequence of str
134 134 The sequence of paths to look for the file in. If None, the filename
135 135 need to be absolute or be in the cwd. If a string, the string is
136 136 put into a sequence and the searched. If a sequence, walk through
137 137 each element and join with ``filename``, calling :func:`expandvars`
138 138 and :func:`expanduser` before testing for existence.
139 139
140 140 Returns
141 141 -------
142 142 Raises :exc:`IOError` or returns absolute path to file.
143 143 """
144 144
145 145 # If paths are quoted, abspath gets confused, strip them...
146 146 filename = filename.strip('"').strip("'")
147 147 # If the input is an absolute path, just check it exists
148 148 if os.path.isabs(filename) and os.path.isfile(filename):
149 149 return filename
150 150
151 151 if path_dirs is None:
152 152 path_dirs = ("",)
153 153 elif isinstance(path_dirs, basestring):
154 154 path_dirs = (path_dirs,)
155 155
156 156 for path in path_dirs:
157 157 if path == '.': path = os.getcwdu()
158 158 testname = expand_path(os.path.join(path, filename))
159 159 if os.path.isfile(testname):
160 160 return os.path.abspath(testname)
161 161
162 162 raise IOError("File %r does not exist in any of the search paths: %r" %
163 163 (filename, path_dirs) )
164 164
165 165
166 166 class HomeDirError(Exception):
167 167 pass
168 168
169 169
170 170 def get_home_dir(require_writable=False):
171 171 """Return the 'home' directory, as a unicode string.
172 172
173 173 * First, check for frozen env in case of py2exe
174 174 * Otherwise, defer to os.path.expanduser('~')
175 175
176 176 See stdlib docs for how this is determined.
177 177 $HOME is first priority on *ALL* platforms.
178 178
179 179 Parameters
180 180 ----------
181 181
182 182 require_writable : bool [default: False]
183 183 if True:
184 184 guarantees the return value is a writable directory, otherwise
185 185 raises HomeDirError
186 186 if False:
187 187 The path is resolved, but it is not guaranteed to exist or be writable.
188 188 """
189 189
190 190 # first, check py2exe distribution root directory for _ipython.
191 191 # This overrides all. Normally does not exist.
192 192
193 193 if hasattr(sys, "frozen"): #Is frozen by py2exe
194 194 if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
195 195 root, rest = IPython.__file__.lower().split('library.zip')
196 196 else:
197 197 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
198 198 root=os.path.abspath(root).rstrip('\\')
199 199 if _writable_dir(os.path.join(root, '_ipython')):
200 200 os.environ["IPYKITROOT"] = root
201 201 return py3compat.cast_unicode(root, fs_encoding)
202 202
203 203 homedir = os.path.expanduser('~')
204 204 # Next line will make things work even when /home/ is a symlink to
205 205 # /usr/home as it is on FreeBSD, for example
206 206 homedir = os.path.realpath(homedir)
207 207
208 208 if not _writable_dir(homedir) and os.name == 'nt':
209 209 # expanduser failed, use the registry to get the 'My Documents' folder.
210 210 try:
211 211 import _winreg as wreg
212 212 key = wreg.OpenKey(
213 213 wreg.HKEY_CURRENT_USER,
214 214 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
215 215 )
216 216 homedir = wreg.QueryValueEx(key,'Personal')[0]
217 217 key.Close()
218 218 except:
219 219 pass
220 220
221 221 if (not require_writable) or _writable_dir(homedir):
222 222 return py3compat.cast_unicode(homedir, fs_encoding)
223 223 else:
224 224 raise HomeDirError('%s is not a writable dir, '
225 225 'set $HOME environment variable to override' % homedir)
226 226
227 227 def get_xdg_dir():
228 228 """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
229 229
230 230 This is only for posix (Linux,Unix,OS X, etc) systems.
231 231 """
232 232
233 233 env = os.environ
234 234
235 235 if os.name == 'posix':
236 236 # Linux, Unix, AIX, OS X
237 237 # use ~/.config if empty OR not set
238 238 xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
239 239 if xdg and _writable_dir(xdg):
240 240 return py3compat.cast_unicode(xdg, fs_encoding)
241 241
242 242 return None
243 243
244 244
245 245 def get_ipython_dir():
246 246 """Get the IPython directory for this platform and user.
247 247
248 248 This uses the logic in `get_home_dir` to find the home directory
249 249 and then adds .ipython to the end of the path.
250 250 """
251 251
252 252 env = os.environ
253 253 pjoin = os.path.join
254 254
255 255
256 256 ipdir_def = '.ipython'
257 257 xdg_def = 'ipython'
258 258
259 259 home_dir = get_home_dir()
260 260 xdg_dir = get_xdg_dir()
261 261
262 262 # import pdb; pdb.set_trace() # dbg
263 263 ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None))
264 264 if ipdir is None:
265 265 # not set explicitly, use XDG_CONFIG_HOME or HOME
266 266 home_ipdir = pjoin(home_dir, ipdir_def)
267 267 if xdg_dir:
268 268 # use XDG, as long as the user isn't already
269 269 # using $HOME/.ipython and *not* XDG/ipython
270 270
271 271 xdg_ipdir = pjoin(xdg_dir, xdg_def)
272 272
273 273 if _writable_dir(xdg_ipdir) or not _writable_dir(home_ipdir):
274 274 ipdir = xdg_ipdir
275 275
276 276 if ipdir is None:
277 277 # not using XDG
278 278 ipdir = home_ipdir
279 279
280 280 ipdir = os.path.normpath(os.path.expanduser(ipdir))
281 281
282 282 if os.path.exists(ipdir) and not _writable_dir(ipdir):
283 283 # ipdir exists, but is not writable
284 284 warnings.warn("IPython dir '%s' is not a writable location,"
285 285 " using a temp directory."%ipdir)
286 286 ipdir = tempfile.mkdtemp()
287 287 elif not os.path.exists(ipdir):
288 288 parent = ipdir.rsplit(os.path.sep, 1)[0]
289 289 if not _writable_dir(parent):
290 290 # ipdir does not exist and parent isn't writable
291 291 warnings.warn("IPython parent '%s' is not a writable location,"
292 292 " using a temp directory."%parent)
293 293 ipdir = tempfile.mkdtemp()
294 294
295 295 return py3compat.cast_unicode(ipdir, fs_encoding)
296 296
297 297
298 298 def get_ipython_package_dir():
299 299 """Get the base directory where IPython itself is installed."""
300 300 ipdir = os.path.dirname(IPython.__file__)
301 301 return py3compat.cast_unicode(ipdir, fs_encoding)
302 302
303 303
304 304 def get_ipython_module_path(module_str):
305 305 """Find the path to an IPython module in this version of IPython.
306 306
307 307 This will always find the version of the module that is in this importable
308 308 IPython package. This will always return the path to the ``.py``
309 309 version of the module.
310 310 """
311 311 if module_str == 'IPython':
312 312 return os.path.join(get_ipython_package_dir(), '__init__.py')
313 313 mod = import_item(module_str)
314 314 the_path = mod.__file__.replace('.pyc', '.py')
315 315 the_path = the_path.replace('.pyo', '.py')
316 316 return py3compat.cast_unicode(the_path, fs_encoding)
317 317
318 318 def locate_profile(profile='default'):
319 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 323 from IPython.core.profiledir import ProfileDir, ProfileDirError
324 324 try:
325 325 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
326 326 except ProfileDirError:
327 327 # IOError makes more sense when people are expecting a path
328 328 raise IOError("Couldn't find profile %r" % profile)
329 329 return pd.location
330 330
331 331 def expand_path(s):
332 332 """Expand $VARS and ~names in a string, like a shell
333 333
334 334 :Examples:
335 335
336 336 In [2]: os.environ['FOO']='test'
337 337
338 338 In [3]: expand_path('variable FOO is $FOO')
339 339 Out[3]: 'variable FOO is test'
340 340 """
341 341 # This is a pretty subtle hack. When expand user is given a UNC path
342 342 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
343 343 # the $ to get (\\server\share\%username%). I think it considered $
344 344 # alone an empty var. But, we need the $ to remains there (it indicates
345 345 # a hidden share).
346 346 if os.name=='nt':
347 347 s = s.replace('$\\', 'IPYTHON_TEMP')
348 348 s = os.path.expandvars(os.path.expanduser(s))
349 349 if os.name=='nt':
350 350 s = s.replace('IPYTHON_TEMP', '$\\')
351 351 return s
352 352
353 353
354 354 def target_outdated(target,deps):
355 355 """Determine whether a target is out of date.
356 356
357 357 target_outdated(target,deps) -> 1/0
358 358
359 359 deps: list of filenames which MUST exist.
360 360 target: single filename which may or may not exist.
361 361
362 362 If target doesn't exist or is older than any file listed in deps, return
363 363 true, otherwise return false.
364 364 """
365 365 try:
366 366 target_time = os.path.getmtime(target)
367 367 except os.error:
368 368 return 1
369 369 for dep in deps:
370 370 dep_time = os.path.getmtime(dep)
371 371 if dep_time > target_time:
372 372 #print "For target",target,"Dep failed:",dep # dbg
373 373 #print "times (dep,tar):",dep_time,target_time # dbg
374 374 return 1
375 375 return 0
376 376
377 377
378 378 def target_update(target,deps,cmd):
379 379 """Update a target with a given command given a list of dependencies.
380 380
381 381 target_update(target,deps,cmd) -> runs cmd if target is outdated.
382 382
383 383 This is just a wrapper around target_outdated() which calls the given
384 384 command if target is outdated."""
385 385
386 386 if target_outdated(target,deps):
387 387 system(cmd)
388 388
389 389 def filehash(path):
390 390 """Make an MD5 hash of a file, ignoring any differences in line
391 391 ending characters."""
392 392 with open(path, "rU") as f:
393 393 return md5(py3compat.str_to_bytes(f.read())).hexdigest()
394 394
395 395 # If the config is unmodified from the default, we'll just delete it.
396 396 # These are consistent for 0.10.x, thankfully. We're not going to worry about
397 397 # older versions.
398 398 old_config_md5 = {'ipy_user_conf.py': 'fc108bedff4b9a00f91fa0a5999140d3',
399 399 'ipythonrc': '12a68954f3403eea2eec09dc8fe5a9b5'}
400 400
401 401 def check_for_old_config(ipython_dir=None):
402 402 """Check for old config files, and present a warning if they exist.
403 403
404 404 A link to the docs of the new config is included in the message.
405 405
406 406 This should mitigate confusion with the transition to the new
407 407 config system in 0.11.
408 408 """
409 409 if ipython_dir is None:
410 410 ipython_dir = get_ipython_dir()
411 411
412 412 old_configs = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py']
413 413 warned = False
414 414 for cfg in old_configs:
415 415 f = os.path.join(ipython_dir, cfg)
416 416 if os.path.exists(f):
417 417 if filehash(f) == old_config_md5.get(cfg, ''):
418 418 os.unlink(f)
419 419 else:
420 420 warnings.warn("Found old IPython config file %r (modified by user)"%f)
421 421 warned = True
422 422
423 423 if warned:
424 424 warnings.warn("""
425 425 The IPython configuration system has changed as of 0.11, and these files will
426 426 be ignored. See http://ipython.github.com/ipython-doc/dev/config for details
427 427 of the new config system.
428 428 To start configuring IPython, do `ipython profile create`, and edit
429 429 `ipython_config.py` in <ipython_dir>/profile_default.
430 430 If you need to leave the old config files in place for an older version of
431 431 IPython and want to suppress this warning message, set
432 432 `c.InteractiveShellApp.ignore_old_config=True` in the new config.""")
433 433
434 434 def get_security_file(filename, profile='default'):
435 435 """Return the absolute path of a security file given by filename and profile
436 436
437 437 This allows users and developers to find security files without
438 438 knowledge of the IPython directory structure. The search path
439 439 will be ['.', profile.security_dir]
440 440
441 441 Parameters
442 442 ----------
443 443
444 444 filename : str
445 445 The file to be found. If it is passed as an absolute path, it will
446 446 simply be returned.
447 447 profile : str [default: 'default']
448 448 The name of the profile to search. Leaving this unspecified
449 449 The file to be found. If it is passed as an absolute path, fname will
450 450 simply be returned.
451 451
452 452 Returns
453 453 -------
454 454 Raises :exc:`IOError` if file not found or returns absolute path to file.
455 455 """
456 456 # import here, because profiledir also imports from utils.path
457 457 from IPython.core.profiledir import ProfileDir
458 458 try:
459 459 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
460 460 except Exception:
461 461 # will raise ProfileDirError if no such profile
462 462 raise IOError("Profile %r not found")
463 463 return filefind(filename, ['.', pd.security_dir])
464 464
@@ -1,48 +1,48 b''
1 1 .TH IPCLUSTER 1 "July 15, 2011" "" ""
2 2 .SH NAME
3 3 \fBipcluster \- IPython parallel computing cluster control tool
4 4 .SH SYNOPSIS
5 5 .nf
6 6 .fam C
7 7 \fBipcluster\fP {\fmpiexec,local,mpirun,pbs,ssh\fP} [\fIoptions\fP]
8 8 .fam T
9 9 .fi
10 10 .SH DESCRIPTION
11 11 ipcluster is a control tool for IPython's parallel computing functions.
12 12
13 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 15 directory from the default of ~/.ipython or ~/.config/ipython. The log and security
16 16 subdirectories of your IPython directory will be used by this script for log
17 17 files and security files.
18 18 .SH POSITIONAL ARGUMENTS
19 19
20 20 The first positional argument should be one of: {start, stop, engines},
21 21 which are the available subcommands.
22 22
23 23 For detailed help on each, type "ipcluster CMD \-\-help". Briefly:
24 24
25 25 start start an IPython cluster
26 26 stop stop a running IPython cluster
27 27 engines add a number of engines to a running cluster
28 28 .SH OPTIONS
29 29 .TP
30 30 .B
31 31 \-h, \-\-help
32 32 show help message and exit
33 33 .SH EXAMPLE
34 34 ipcluster start \-\-n=4
35 35
36 36 This command will start 4 IPython engines on the local computer.
37 37 .SH SEE ALSO
38 38 .BR ipython(1),
39 39 .BR ipcontroller(1),
40 40 .BR ipengine(1)
41 41 .br
42 42 .SH AUTHOR
43 43 \fBipcluster\fP is a tool that ships with IPython, created by
44 44 the IPython Development Team.
45 45 .PP
46 46 This manual page was written by Stephan Peijnik <debian@sp.or.at>,
47 47 for the Debian project (but may be used by others). Modified by Fernando Perez
48 48 <Fernando.Perez@berkeley.edu> for inclusion in IPython.
@@ -1,164 +1,164 b''
1 1 .TH IPCONTROLLER 1 "October 29, 2008" "" ""
2 2 .SH NAME
3 3 \fBipcontroller \- IPython parallel computing controller control tool
4 4 .SH SYNOPSIS
5 5 .nf
6 6 .fam C
7 7 \fBipengine\fP [\fIoptions\fP]
8 8 .fam T
9 9 .fi
10 10 .SH DESCRIPTION
11 11 ipcontroller is a control tool for IPython's parallel computing functions.
12 12 .SH OPTIONS
13 13 .TP
14 14 .B
15 15 \-h, \-\-help
16 16 show this help message and exit
17 17 .TP
18 18 .B
19 19 .TP
20 20 .B \-\-no\-secure
21 21 Don't authenticate messages.
22 22 .TP
23 23 .B \-\-usethreads
24 24 Use threads instead of processes for the schedulers
25 25 .TP
26 26 .B \-\-init
27 27 Initialize profile with default config files
28 28 .TP
29 29 .B \-\-log\-to\-file
30 30 send log output to a file
31 31 .TP
32 32 .B \-\-reuse
33 33 reuse existing json connection files
34 34 .TP
35 35 .B \-\-mongodb
36 36 use the MongoDB backend
37 37 .TP
38 38 .B \-\-quiet
39 39 set log level to logging.CRITICAL (minimize logging output)
40 40 .TP
41 41 .B \-\-debug
42 42 set log level to logging.DEBUG (maximize logging output)
43 43 .TP
44 44 .B \-\-sqlitedb
45 45 use the SQLiteDB backend
46 46 .TP
47 47 .B \-\-dictdb
48 48 use the in-memory DictDB backend
49 49 .TP
50 50 .B \-\-secure
51 51 Use HMAC digests for authentication of messages.
52 52 .TP
53 53 .B \-\-profile=<Unicode> (BaseIPythonApplication.profile)
54 54 Default: u'default'
55 55 The IPython profile to use.
56 56 .TP
57 57 .B \-\-hwm=<Int> (TaskScheduler.hwm)
58 58 Default: 0
59 59 .br
60 60 specify the High Water Mark (HWM) for the downstream socket in the Task
61 61 scheduler. This is the maximum number of allowed outstanding tasks on each
62 62 engine.
63 63 .TP
64 64 .B \-\-secure=<Bool> (IPControllerApp.secure)
65 65 Default: True
66 66 Whether to use HMAC digests for extra message authentication.
67 67 .TP
68 68 .B \-\-ip=<Unicode> (HubFactory.ip)
69 69 Default: '127.0.0.1'
70 70 The IP address for registration. This is generally either '127.0.0.1' for
71 71 loopback only or '*' for all interfaces. [default: '127.0.0.1']
72 72 .TP
73 73 .B \-\-log\-url=<Unicode> (BaseParallelApplication.log_url)
74 74 Default: ''
75 75 The ZMQ URL of the iplogger to aggregate logging.
76 76 .TP
77 77 .B \-\-work\-dir=<Unicode> (BaseParallelApplication.work_dir)
78 78 Default: u'/Users/minrk/dev/ip/mine/docs/man'
79 79 Set the working dir for the process.
80 80 .TP
81 81 .B \-\-port=<Int> (HubFactory.regport)
82 82 Default: 0
83 83 The port on which the Hub listens for registration.
84 84 .TP
85 85 .B \-\-profile\-dir=<Unicode> (ProfileDir.location)
86 86 Default: u''
87 87 Set the profile location directly. This overrides the logic used by the
88 88 `profile` option.
89 89 .TP
90 90 .B \-\-ident=<CBytes> (Session.session)
91 91 Default: ''
92 92 The UUID identifying this session.
93 93 .TP
94 94 .B \-\-log\-to\-file=<Bool> (BaseParallelApplication.log_to_file)
95 95 Default: False
96 96 whether to log to a file
97 97 .TP
98 98 .B \-\-ipython\-dir=<Unicode> (BaseIPythonApplication.ipython_dir)
99 99 Default: u'/Users/minrk/.ipython'
100 100 The name of the IPython directory. This directory is used for logging
101 101 configuration (through profiles), history storage, etc. The default is
102 102 usually $HOME/.ipython. This options can also be specified through the
103 environment variable IPYTHON_DIR.
103 environment variable IPYTHONDIR.
104 104 .TP
105 105 .B \-\-url=<Unicode> (HubFactory.url)
106 106 Default: ''
107 107 The 0MQ url used for registration. This sets transport, ip, and port in one
108 108 variable. For example: url='tcp://127.0.0.1:12345' or url='epgm://*:90210'
109 109 .TP
110 110 .B \-\-user=<Unicode> (Session.username)
111 111 Default: 'minrk'
112 112 Username for the Session. Default is your system username.
113 113 .TP
114 114 .B \-\-ping=<CFloat> (HeartMonitor.period)
115 115 Default: 1000
116 116 The frequency at which the Hub pings the engines for heartbeats (in ms)
117 117 .TP
118 118 .B \-\-log\-level=<Enum> (Application.log_level)
119 119 Default: 30
120 120 Choices: (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL')
121 121 Set the log level by value or name.
122 122 .TP
123 123 .B \-\-location=<Unicode> (IPControllerApp.location)
124 124 Default: u''
125 125 The external IP or domain name of the Controller, used for disambiguating
126 126 engine and client connections.
127 127 .TP
128 128 .B \-\-clean\-logs=<Bool> (BaseParallelApplication.clean_logs)
129 129 Default: False
130 130 whether to cleanup old logfiles before starting
131 131 .TP
132 132 .B \-\-scheme=<Enum> (TaskScheduler.scheme_name)
133 133 Default: 'leastload'
134 134 Choices: ('leastload', 'pure', 'lru', 'plainrandom', 'weighted', 'twobin')
135 135 select the task scheduler scheme [default: Python LRU] Options are: 'pure',
136 136 \&'lru', 'plainrandom', 'weighted', 'twobin','leastload'
137 137 .TP
138 138 .B \-\-keyfile=<Unicode> (Session.keyfile)
139 139 Default: ''
140 140 path to file containing execution key.
141 141 .TP
142 142 .B \-\-transport=<Unicode> (HubFactory.transport)
143 143 Default: 'tcp'
144 144 The 0MQ transport for communications. This will likely be the default of
145 145 \&'tcp', but other values include 'ipc', 'epgm', 'inproc'.
146 146 .TP
147 147 .B \-\-ssh=<Unicode> (IPControllerApp.ssh_server)
148 148 Default: u''
149 149 ssh url for clients to use when connecting to the Controller processes. It
150 150 should be of the form: [user@]server[:port]. The Controller's listening
151 151 addresses must be accessible from the ssh server
152 152 .SH SEE ALSO
153 153 .BR ipython(1),
154 154 .BR ipcluster(1),
155 155 .BR ipengine(1)
156 156 .br
157 157 .SH AUTHOR
158 158 \fBipcontroller\fP is a tool that ships with IPython, created by
159 159 the IPython Development Team.
160 160 .PP
161 161 This manual page was written by Stephan Peijnik <debian@sp.or.at>,
162 162 for the Debian project (but may be used by others). Modified by Fernando Perez
163 163 <Fernando.Perez@berkeley.edu> for inclusion in IPython, and updated by
164 164 Min Ragan-Kelley <benjaminrk@gmail.com> for 0.11.
@@ -1,98 +1,98 b''
1 1 .TH IPLOGGER 1 "July 21, 2011" "" ""
2 2 .\" Man page generated from reStructeredText.
3 3 .SH NAME
4 4 \fBiplogger \- IPython logger for parallel computing.
5 5 .SH DESCRIPTION
6 6 Start an IPython logger for parallel computing.
7 7 .sp
8 8 IPython controllers and engines (and your own processes) can broadcast log
9 9 messages by registering a \fIzmq.log.handlers.PUBHandler\fP with the \fIlogging\fP
10 10 module. The logger can be configured using command line options or using a
11 11 cluster directory. Cluster directories contain config, log and security files
12 12 and are usually located in your ipython directory and named as "profile_name".
13 13 See the \fIprofile\fP and \fIprofile\-dir\fP options for details.
14 14 .SH OPTIONS
15 15 .sp
16 16 IPython command\-line arguments are passed as \(aq\-\-<flag>\(aq, or \(aq\-\-<name>=<value>\(aq.
17 17 .sp
18 18 Arguments that take values are actually convenience aliases to full
19 19 Configurables, whose aliases are listed on the help line. For more information
20 20 on full configurables, see \(aq\-\-help\-all\(aq.
21 21 .TP
22 22 .B \-\-debug
23 23 .
24 24 set log level to logging.DEBUG (maximize logging output)
25 25 .TP
26 26 .B \-\-init
27 27 .
28 28 Initialize profile with default config files. This is equivalent
29 29 to running \fIipython profile create <profile>\fP prior to startup.
30 30 .TP
31 31 .B \-\-log\-to\-file
32 32 .
33 33 send log output to a file
34 34 .TP
35 35 .B \-\-quiet
36 36 .
37 37 set log level to logging.CRITICAL (minimize logging output)
38 38 .TP
39 39 .B \-\-profile=<Unicode> (BaseIPythonApplication.profile)
40 40 .
41 41 Default: u\(aqdefault\(aq
42 42 The IPython profile to use.
43 43 .TP
44 44 .B \-\-log\-to\-file=<Bool> (BaseParallelApplication.log_to_file)
45 45 .
46 46 Default: False
47 47 whether to log to a file
48 48 .TP
49 49 .B \-\-ipython\-dir=<Unicode> (BaseIPythonApplication.ipython_dir)
50 50 .
51 51 The name of the IPython directory. This directory is used for logging
52 52 configuration (through profiles), history storage, etc. The default is
53 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 55 .TP
56 56 .B \-\-url=<Unicode> (LogWatcher.url)
57 57 .
58 58 Default: \(aq\fI\%tcp://127.0.0.1:20202\fP\(aq
59 59 ZMQ url on which to listen for log messages
60 60 .TP
61 61 .B \-\-topics=<List> (LogWatcher.topics)
62 62 .
63 63 Default: [\(aq\(aq]
64 64 The ZMQ topics to subscribe to. Default is to subscribe to all messages
65 65 .TP
66 66 .B \-\-log\-level=<Enum> (Application.log_level)
67 67 .
68 68 Default: 30
69 69 Choices: (0, 10, 20, 30, 40, 50, \(aqDEBUG\(aq, \(aqINFO\(aq, \(aqWARN\(aq, \(aqERROR\(aq, \(aqCRITICAL\(aq)
70 70 Set the log level by value or name.
71 71 .TP
72 72 .B \-\-log\-url=<Unicode> (BaseParallelApplication.log_url)
73 73 .
74 74 Default: \(aq\(aq
75 75 The ZMQ URL of the iplogger to aggregate logging.
76 76 .TP
77 77 .B \-\-clean\-logs=<Bool> (BaseParallelApplication.clean_logs)
78 78 .
79 79 Default: False
80 80 whether to cleanup old logfiles before starting
81 81 .TP
82 82 .B \-\-profile\-dir=<Unicode> (ProfileDir.location)
83 83 .
84 84 Default: u\(aq\(aq
85 85 Set the profile location directly. This overrides the logic used by the
86 86 \fIprofile\fP option.
87 87 .TP
88 88 .B \-\-work\-dir=<Unicode> (BaseParallelApplication.work_dir)
89 89 .
90 90 Set the working dir for the process.
91 91 .SH SEE ALSO
92 92 .BR ipython(1),
93 93 .BR ipcontroller(1),
94 94 .BR ipengine(1)
95 95 .br
96 96 .SH AUTHOR
97 97 \fBiplogger\fP is a tool that ships with IPython, created by
98 98 the IPython Development Team.
@@ -1,241 +1,241 b''
1 1 .\" Hey, EMACS: -*- nroff -*-
2 2 .\" First parameter, NAME, should be all caps
3 3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
4 4 .\" other parameters are allowed: see man(7), man(1)
5 5 .TH IPYTHON 1 "July 15, 2011"
6 6 .\" Please adjust this date whenever revising the manpage.
7 7 .\"
8 8 .\" Some roff macros, for reference:
9 9 .\" .nh disable hyphenation
10 10 .\" .hy enable hyphenation
11 11 .\" .ad l left justify
12 12 .\" .ad b justify to both left and right margins
13 13 .\" .nf disable filling
14 14 .\" .fi enable filling
15 15 .\" .br insert line break
16 16 .\" .sp <n> insert n+1 empty lines
17 17 .\" for manpage-specific macros, see man(7) and groff_man(7)
18 18 .\" .SH section heading
19 19 .\" .SS secondary section heading
20 20 .\"
21 21 .\"
22 22 .\" To preview this page as plain text: nroff -man ipython.1
23 23 .\"
24 24 .SH NAME
25 25 ipython \- Tools for Interactive Computing in Python.
26 26 .SH SYNOPSIS
27 27 .B ipython
28 28 .RI [ options ] " files" ...
29 29 .SH DESCRIPTION
30 30 An interactive Python shell with automatic history (input and output), dynamic
31 31 object introspection, easier configuration, command completion, access to the
32 32 system shell, integration with numerical and scientific computing tools, and
33 33 more.
34 34 .
35 35 .SH REGULAR OPTIONS
36 36 All options that take values, must be of the form '\-\-name=value', but
37 37 flags that take no arguments are allowed a single '\-' to allow common
38 38 patterns like: 'ipython \-i myscript.py'. To pass arguments to scripts,
39 39 rather than to IPython, specify them after '\-\-'.
40 40 .br
41 41 .sp 1
42 42 All options can also be set from your ipython_config.py configuration file.
43 43 See the provided examples for assistance. Options given on the
44 44 commandline override the values set in ipython_config.py. To generate
45 45 the default config file, do `ipython profile create`.
46 46 .br
47 47 .sp 1
48 48 All options with a [no] prepended can be specified in negated form
49 49 (\-\-no\-option instead of \-\-option) to turn the feature off.
50 50 .TP
51 51 .B \-h, \-\-help
52 52 Show summary of options.
53 53 .B \-\-no\-autoindent
54 54 Turn off autoindenting.
55 55 .TP
56 56 .B \-\-autoedit\-syntax
57 57 Turn on auto editing of files with syntax errors.
58 58 .TP
59 59 .B \-\-pylab
60 60 Pre-load matplotlib and numpy for interactive use with
61 61 the default matplotlib backend.
62 62 .TP
63 63 .B \-\-confirm\-exit
64 64 Set to confirm when you try to exit IPython with an EOF (Control-D
65 65 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
66 66 you can force a direct exit without any confirmation.
67 67 .TP
68 68 .B \-\-deep\-reload
69 69 Enable deep (recursive) reloading by default. IPython can use the
70 70 deep_reload module which reloads changes in modules recursively (it
71 71 replaces the reload() function, so you don't need to change anything to
72 72 use it). deep_reload() forces a full reload of modules whose code may
73 73 have changed, which the default reload() function does not. When
74 74 deep_reload is off, IPython will use the normal reload(), but
75 75 deep_reload will still be available as dreload(). This feature is off
76 76 by default [which means that you have both normal reload() and
77 77 dreload()].
78 78 .TP
79 79 .B \-\-no\-autoedit\-syntax
80 80 Turn off auto editing of files with syntax errors.
81 81 .TP
82 82 .B \-\-term\-title
83 83 Enable auto setting the terminal title.
84 84 .TP
85 85 .B \-\-no\-confirm\-exit
86 86 Don't prompt the user when exiting.
87 87 .TP
88 88 .B \-\-autoindent
89 89 Turn on autoindenting.
90 90 .TP
91 91 .B \-\-classic
92 92 Gives IPython a similar feel to the classic Python prompt.
93 93 .TP
94 94 .B \-\-no\-automagic
95 95 Turn off the auto calling of magic commands.
96 96 .TP
97 97 .B \-\-banner
98 98 Display a banner upon starting IPython.
99 99 .TP
100 100 .B \-\-automagic
101 101 Turn on the auto calling of magic commands. Type %%magic at the
102 102 IPython prompt for more information.
103 103 .TP
104 104 .B \-\-no\-deep\-reload
105 105 Disable deep (recursive) reloading by default.
106 106 .TP
107 107 .B \-\-no\-term\-title
108 108 Disable auto setting the terminal title.
109 109 .TP
110 110 .B \-\-nosep
111 111 Eliminate all spacing between prompts.
112 112 .TP
113 113 .B \-\-i
114 114 also works as '\-i'
115 115 If running code from the command line, become interactive afterwards.
116 116 .TP
117 117 .B \-\-debug
118 118 set log level to logging.DEBUG (maximize logging output)
119 119 .TP
120 120 .B \-\-pprint
121 121 Enable auto pretty printing of results.
122 122 .TP
123 123 .B \-\-quiet
124 124 set log level to logging.CRITICAL (minimize logging output)
125 125 .TP
126 126 .B \-\-pdb
127 127 Enable auto calling the pdb debugger after every exception.
128 128 .TP
129 129 .B \-\-color\-info
130 130 IPython can display information about objects via a set of func-
131 131 tions, and optionally can use colors for this, syntax highlighting
132 132 source code and various other elements. However, because this
133 133 information is passed through a pager (like 'less') and many pagers get
134 134 confused with color codes, this option is off by default. You can test
135 135 it and turn it on permanently in your ipython_config.py file if it
136 136 works for you. Test it and turn it on permanently if it works with
137 137 your system. The magic function %%color_info allows you to toggle this
138 138 interactively for testing.
139 139 .TP
140 140 .B \-\-init
141 141 Initialize profile with default config files
142 142 .TP
143 143 .B \-\-no\-pdb
144 144 Disable auto calling the pdb debugger after every exception.
145 145 .TP
146 146 .B \-\-quick
147 147 Enable quick startup with no config files.
148 148 .TP
149 149 .B \-\-no\-color\-info
150 150 Disable using colors for info related things.
151 151 .TP
152 152 .B \-\-no\-pprint
153 153 Disable auto auto pretty printing of results.
154 154 .TP
155 155 .B \-\-no\-banner
156 156 Don't display a banner upon starting IPython.
157 157 .TP
158 158 .B \-\-profile=<Unicode> (BaseIPythonApplication.profile)
159 159 Default: u'default'
160 160 The IPython profile to use.
161 161 .TP
162 162 .B \-\-c=<Unicode> (InteractiveShellApp.code_to_run)
163 163 Default: ''
164 164 Execute the given command string.
165 165 .TP
166 166 .B \-\-logappend=<Unicode> (InteractiveShell.logappend)
167 167 Default: ''
168 168 Start logging to the given file in append mode.
169 169 .TP
170 170 .B \-\-autocall=<Enum> (InteractiveShell.autocall)
171 171 Default: 1
172 172 Choices: (0, 1, 2)
173 173 Make IPython automatically call any callable object even if you didn't type
174 174 explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically.
175 175 The value can be '0' to disable the feature, '1' for 'smart' autocall, where
176 176 it is not applied if there are no more arguments on the line, and '2' for
177 177 \&'full' autocall, where all callable objects are automatically called (even
178 178 if no arguments are present). The default is '1'.
179 179 .TP
180 180 .B \-\-ipython\-dir=<Unicode> (BaseIPythonApplication.ipython_dir)
181 181 Default: u'/Users/minrk/.ipython'
182 182 The name of the IPython directory. This directory is used for logging
183 183 configuration (through profiles), history storage, etc. The default is
184 184 usually $HOME/.ipython. This options can also be specified through the
185 environment variable IPYTHON_DIR.
185 environment variable IPYTHONDIR.
186 186 .TP
187 187 .B \-\-gui=<CaselessStrEnum> (TerminalIPythonApp.gui)
188 188 Default: None
189 189 Choices: ('qt', 'wx', 'gtk')
190 190 Enable GUI event loop integration ('qt', 'wx', 'gtk').
191 191 .TP
192 192 .B \-\-pylab=<CaselessStrEnum> (TerminalIPythonApp.pylab)
193 193 Default: None
194 194 Choices: ['tk', 'qt', 'wx', 'gtk', 'osx', 'auto']
195 195 Pre-load matplotlib and numpy for interactive use, selecting a particular
196 196 matplotlib backend and loop integration.
197 197 .TP
198 198 .B \-\-ext=<Unicode> (InteractiveShellApp.extra_extension)
199 199 Default: ''
200 200 dotted module name of an IPython extension to load.
201 201 .TP
202 202 .B \-\-log\-level=<Enum> (Application.log_level)
203 203 Default: 30
204 204 Choices: (0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL')
205 205 Set the log level by value or name.
206 206 .TP
207 207 .B \-\-colors=<CaselessStrEnum> (InteractiveShell.colors)
208 208 Default: 'LightBG'
209 209 Choices: ('NoColor', 'LightBG', 'Linux')
210 210 Set the color scheme (NoColor, Linux, or LightBG).
211 211 .TP
212 212 .B \-\-cache\-size=<Int> (InteractiveShell.cache_size)
213 213 Default: 1000
214 214 Set the size of the output cache. The default is 1000, you can change it
215 215 permanently in your config file. Setting it to 0 completely disables the
216 216 caching system, and the minimum value accepted is 20 (if you provide a value
217 217 less than 20, it is reset to 0 and a warning is issued). This limit is
218 218 defined because otherwise you'll spend more time re-flushing a too small
219 219 cache than working
220 220 .TP
221 221 .B \-\-logfile=<Unicode> (InteractiveShell.logfile)
222 222 Default: ''
223 223 The name of the logfile to use.
224 224 .
225 225 .SH EMBEDDING
226 226 It is possible to start an IPython instance inside your own Python
227 227 programs. In the documentation example files there are some
228 228 illustrations on how to do this.
229 229 .br
230 230 .sp 1
231 231 This feature allows you to evalutate dynamically the state of your
232 232 code, operate with your variables, analyze them, etc. Note however
233 233 that any changes you make to values while in the shell do NOT
234 234 propagate back to the running code, so it is safe to modify your
235 235 values because you won't break your code in bizarre ways by doing so.
236 236 .SH AUTHOR
237 237 IPython was written by Fernando Perez <fperez@colorado.edu>, based on earlier
238 238 code by Janko Hauser <jh@comunit.de> and Nathaniel Gray
239 239 <n8gray@caltech.edu>. This manual page was written by Jack Moffitt
240 240 <jack@xiph.org>, for the Debian project (but may be used by others), and updated by
241 241 Min Ragan-Kelley <benjaminrk@gmail.com> for 0.11.
@@ -1,231 +1,231 b''
1 1 .. _initial config:
2 2
3 3 =============================================================
4 4 Outdated configuration information that might still be useful
5 5 =============================================================
6 6
7 7 .. warning::
8 8
9 9 All of the information in this file is outdated. Until the new
10 10 configuration system is better documented, this material is being kept.
11 11
12 12 This section will help you set various things in your environment for
13 13 your IPython sessions to be as efficient as possible. All of IPython's
14 14 configuration information, along with several example files, is stored
15 15 in a directory named by default $HOME/.config/ipython if $HOME/.config
16 16 exists (Linux), or $HOME/.ipython as a secondary default. You can change this by
17 17 defining the environment variable IPYTHONDIR, or at runtime with the
18 18 command line option -ipythondir.
19 19
20 20 If all goes well, the first time you run IPython it should automatically create
21 21 a user copy of the config directory for you, based on its builtin defaults. You
22 22 can look at the files it creates to learn more about configuring the
23 23 system. The main file you will modify to configure IPython's behavior is called
24 24 ipythonrc (with a .ini extension under Windows), included for reference
25 25 :ref:`here <ipythonrc>`. This file is very commented and has many variables you
26 26 can change to suit your taste, you can find more details :ref:`here
27 27 <customization>`. Here we discuss the basic things you will want to make sure
28 28 things are working properly from the beginning.
29 29
30 30 Color
31 31 =====
32 32
33 33 The default IPython configuration has most bells and whistles turned on
34 34 (they're pretty safe). But there's one that may cause problems on some
35 35 systems: the use of color on screen for displaying information. This is
36 36 very useful, since IPython can show prompts and exception tracebacks
37 37 with various colors, display syntax-highlighted source code, and in
38 38 general make it easier to visually parse information.
39 39
40 40 The following terminals seem to handle the color sequences fine:
41 41
42 42 * Linux main text console, KDE Konsole, Gnome Terminal, E-term,
43 43 rxvt, xterm.
44 44 * CDE terminal (tested under Solaris). This one boldfaces light colors.
45 45 * (X)Emacs buffers. See the emacs_ section for more details on
46 46 using IPython with (X)Emacs.
47 47 * A Windows (XP/2k) command prompt with pyreadline_.
48 48 * A Windows (XP/2k) CygWin shell. Although some users have reported
49 49 problems; it is not clear whether there is an issue for everyone
50 50 or only under specific configurations. If you have full color
51 51 support under cygwin, please post to the IPython mailing list so
52 52 this issue can be resolved for all users.
53 53
54 54 .. _pyreadline: https://code.launchpad.net/pyreadline
55 55
56 56 These have shown problems:
57 57
58 58 * Windows command prompt in WinXP/2k logged into a Linux machine via
59 59 telnet or ssh.
60 60 * Windows native command prompt in WinXP/2k, without Gary Bishop's
61 61 extensions. Once Gary's readline library is installed, the normal
62 62 WinXP/2k command prompt works perfectly.
63 63
64 64 Currently the following color schemes are available:
65 65
66 66 * NoColor: uses no color escapes at all (all escapes are empty '' ''
67 67 strings). This 'scheme' is thus fully safe to use in any terminal.
68 68 * Linux: works well in Linux console type environments: dark
69 69 background with light fonts. It uses bright colors for
70 70 information, so it is difficult to read if you have a light
71 71 colored background.
72 72 * LightBG: the basic colors are similar to those in the Linux scheme
73 73 but darker. It is easy to read in terminals with light backgrounds.
74 74
75 75 IPython uses colors for two main groups of things: prompts and
76 76 tracebacks which are directly printed to the terminal, and the object
77 77 introspection system which passes large sets of data through a pager.
78 78
79 79 Input/Output prompts and exception tracebacks
80 80 =============================================
81 81
82 82 You can test whether the colored prompts and tracebacks work on your
83 83 system interactively by typing '%colors Linux' at the prompt (use
84 84 '%colors LightBG' if your terminal has a light background). If the input
85 85 prompt shows garbage like::
86 86
87 87 [0;32mIn [[1;32m1[0;32m]: [0;00m
88 88
89 89 instead of (in color) something like::
90 90
91 91 In [1]:
92 92
93 93 this means that your terminal doesn't properly handle color escape
94 94 sequences. You can go to a 'no color' mode by typing '%colors NoColor'.
95 95
96 96 You can try using a different terminal emulator program (Emacs users,
97 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 101 Object details (types, docstrings, source code, etc.)
102 102 =====================================================
103 103
104 104 IPython has a set of special functions for studying the objects you are working
105 105 with, discussed in detail :ref:`here <dynamic_object_info>`. But this system
106 106 relies on passing information which is longer than your screen through a data
107 107 pager, such as the common Unix less and more programs. In order to be able to
108 108 see this information in color, your pager needs to be properly configured. I
109 109 strongly recommend using less instead of more, as it seems that more simply can
110 110 not understand colored text correctly.
111 111
112 112 In order to configure less as your default pager, do the following:
113 113
114 114 1. Set the environment PAGER variable to less.
115 115 2. Set the environment LESS variable to -r (plus any other options
116 116 you always want to pass to less by default). This tells less to
117 117 properly interpret control sequences, which is how color
118 118 information is given to your terminal.
119 119
120 120 For the bash shell, add to your ~/.bashrc file the lines::
121 121
122 122 export PAGER=less
123 123 export LESS=-r
124 124
125 125 For the csh or tcsh shells, add to your ~/.cshrc file the lines::
126 126
127 127 setenv PAGER less
128 128 setenv LESS -r
129 129
130 130 There is similar syntax for other Unix shells, look at your system
131 131 documentation for details.
132 132
133 133 If you are on a system which lacks proper data pagers (such as Windows),
134 134 IPython will use a very limited builtin pager.
135 135
136 136 .. _Prompts:
137 137
138 138 Fine-tuning your prompt
139 139 =======================
140 140
141 141 IPython's prompts can be customized using a syntax similar to that of
142 142 the bash shell. Many of bash's escapes are supported, as well as a few
143 143 additional ones. We list them below::
144 144
145 145 \#
146 146 the prompt/history count number. This escape is automatically
147 147 wrapped in the coloring codes for the currently active color scheme.
148 148 \N
149 149 the 'naked' prompt/history count number: this is just the number
150 150 itself, without any coloring applied to it. This lets you produce
151 151 numbered prompts with your own colors.
152 152 \D
153 153 the prompt/history count, with the actual digits replaced by dots.
154 154 Used mainly in continuation prompts (prompt_in2)
155 155 \w
156 156 the current working directory
157 157 \W
158 158 the basename of current working directory
159 159 \Xn
160 160 where $n=0\ldots5.$ The current working directory, with $HOME
161 161 replaced by ~, and filtered out to contain only $n$ path elements
162 162 \Yn
163 163 Similar to \Xn, but with the $n+1$ element included if it is ~ (this
164 164 is similar to the behavior of the %cn escapes in tcsh)
165 165 \u
166 166 the username of the current user
167 167 \$
168 168 if the effective UID is 0, a #, otherwise a $
169 169 \h
170 170 the hostname up to the first '.'
171 171 \H
172 172 the hostname
173 173 \n
174 174 a newline
175 175 \r
176 176 a carriage return
177 177 \v
178 178 IPython version string
179 179
180 180 In addition to these, ANSI color escapes can be insterted into the
181 181 prompts, as \C_ColorName. The list of valid color names is: Black, Blue,
182 182 Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray,
183 183 LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White,
184 184 Yellow.
185 185
186 186 Finally, IPython supports the evaluation of arbitrary expressions in
187 187 your prompt string. The prompt strings are evaluated through the syntax
188 188 of PEP 215, but basically you can use $x.y to expand the value of x.y,
189 189 and for more complicated expressions you can use braces: ${foo()+x} will
190 190 call function foo and add to it the value of x, before putting the
191 191 result into your prompt. For example, using
192 192 prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: '
193 193 will print the result of the uptime command on each prompt (assuming the
194 194 commands module has been imported in your ipythonrc file).
195 195
196 196
197 197 Prompt examples
198 198
199 199 The following options in an ipythonrc file will give you IPython's
200 200 default prompts::
201 201
202 202 prompt_in1 'In [\#]:'
203 203 prompt_in2 ' .\D.:'
204 204 prompt_out 'Out[\#]:'
205 205
206 206 which look like this::
207 207
208 208 In [1]: 1+2
209 209 Out[1]: 3
210 210
211 211 In [2]: for i in (1,2,3):
212 212 ...: print i,
213 213 ...:
214 214 1 2 3
215 215
216 216 These will give you a very colorful prompt with path information::
217 217
218 218 #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>'
219 219 prompt_in2 ' ..\D>'
220 220 prompt_out '<\#>'
221 221
222 222 which look like this::
223 223
224 224 fperez[~/ipython]1> 1+2
225 225 <1> 3
226 226 fperez[~/ipython]2> for i in (1,2,3):
227 227 ...> print i,
228 228 ...>
229 229 1 2 3
230 230
231 231
@@ -1,531 +1,531 b''
1 1 .. _config_overview:
2 2
3 3 ============================================
4 4 Overview of the IPython configuration system
5 5 ============================================
6 6
7 7 This section describes the IPython configuration system. Starting with version
8 8 0.11, IPython has a completely new configuration system that is quite
9 9 different from the older :file:`ipythonrc` or :file:`ipy_user_conf.py`
10 10 approaches. The new configuration system was designed from scratch to address
11 11 the particular configuration needs of IPython. While there are many
12 12 other excellent configuration systems out there, we found that none of them
13 13 met our requirements.
14 14
15 15 .. warning::
16 16
17 17 If you are upgrading to version 0.11 of IPython, you will need to migrate
18 18 your old :file:`ipythonrc` or :file:`ipy_user_conf.py` configuration files
19 19 to the new system. You may want to read the section on
20 20 :ref:`configuring IPython <configuring_ipython>`. There are also some ideas
21 21 `on the IPython wiki <http://wiki.ipython.org/Cookbook/Moving_config_to_IPython_0.11>`_
22 22 about this.
23 23
24 24 The discussion that follows is focused on teaching users how to configure
25 25 IPython to their liking. Developers who want to know more about how they
26 26 can enable their objects to take advantage of the configuration system
27 27 should consult our :ref:`developer guide <developer_guide>`
28 28
29 29 The main concepts
30 30 =================
31 31
32 32 There are a number of abstractions that the IPython configuration system uses.
33 33 Each of these abstractions is represented by a Python class.
34 34
35 35 Configuration object: :class:`~IPython.config.loader.Config`
36 36 A configuration object is a simple dictionary-like class that holds
37 37 configuration attributes and sub-configuration objects. These classes
38 38 support dotted attribute style access (``Foo.bar``) in addition to the
39 39 regular dictionary style access (``Foo['bar']``). Configuration objects
40 40 are smart. They know how to merge themselves with other configuration
41 41 objects and they automatically create sub-configuration objects.
42 42
43 43 Application: :class:`~IPython.config.application.Application`
44 44 An application is a process that does a specific job. The most obvious
45 45 application is the :command:`ipython` command line program. Each
46 46 application reads *one or more* configuration files and a single set of
47 47 command line options
48 48 and then produces a master configuration object for the application. This
49 49 configuration object is then passed to the configurable objects that the
50 50 application creates. These configurable objects implement the actual logic
51 51 of the application and know how to configure themselves given the
52 52 configuration object.
53 53
54 54 Applications always have a `log` attribute that is a configured Logger.
55 55 This allows centralized logging configuration per-application.
56 56
57 57 Configurable: :class:`~IPython.config.configurable.Configurable`
58 58 A configurable is a regular Python class that serves as a base class for
59 59 all main classes in an application. The
60 60 :class:`~IPython.config.configurable.Configurable` base class is
61 61 lightweight and only does one things.
62 62
63 63 This :class:`~IPython.config.configurable.Configurable` is a subclass
64 64 of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure
65 65 itself. Class level traits with the metadata ``config=True`` become
66 66 values that can be configured from the command line and configuration
67 67 files.
68 68
69 69 Developers create :class:`~IPython.config.configurable.Configurable`
70 70 subclasses that implement all of the logic in the application. Each of
71 71 these subclasses has its own configuration information that controls how
72 72 instances are created.
73 73
74 74 Singletons: :class:`~IPython.config.configurable.SingletonConfigurable`
75 75 Any object for which there is a single canonical instance. These are
76 76 just like Configurables, except they have a class method
77 77 :meth:`~IPython.config.configurable.SingletonConfigurable.instance`,
78 78 that returns the current active instance (or creates one if it
79 79 does not exist). Examples of singletons include
80 80 :class:`~IPython.config.application.Application`s and
81 81 :class:`~IPython.core.interactiveshell.InteractiveShell`. This lets
82 82 objects easily connect to the current running Application without passing
83 83 objects around everywhere. For instance, to get the current running
84 84 Application instance, simply do: ``app = Application.instance()``.
85 85
86 86
87 87 .. note::
88 88
89 89 Singletons are not strictly enforced - you can have many instances
90 90 of a given singleton class, but the :meth:`instance` method will always
91 91 return the same one.
92 92
93 93 Having described these main concepts, we can now state the main idea in our
94 94 configuration system: *"configuration" allows the default values of class
95 95 attributes to be controlled on a class by class basis*. Thus all instances of
96 96 a given class are configured in the same way. Furthermore, if two instances
97 97 need to be configured differently, they need to be instances of two different
98 98 classes. While this model may seem a bit restrictive, we have found that it
99 99 expresses most things that need to be configured extremely well. However, it
100 100 is possible to create two instances of the same class that have different
101 101 trait values. This is done by overriding the configuration.
102 102
103 103 Now, we show what our configuration objects and files look like.
104 104
105 105 Configuration objects and files
106 106 ===============================
107 107
108 108 A configuration file is simply a pure Python file that sets the attributes
109 109 of a global, pre-created configuration object. This configuration object is a
110 110 :class:`~IPython.config.loader.Config` instance. While in a configuration
111 111 file, to get a reference to this object, simply call the :func:`get_config`
112 112 function. We inject this function into the global namespace that the
113 113 configuration file is executed in.
114 114
115 115 Here is an example of a super simple configuration file that does nothing::
116 116
117 117 c = get_config()
118 118
119 119 Once you get a reference to the configuration object, you simply set
120 120 attributes on it. All you have to know is:
121 121
122 122 * The name of each attribute.
123 123 * The type of each attribute.
124 124
125 125 The answers to these two questions are provided by the various
126 126 :class:`~IPython.config.configurable.Configurable` subclasses that an
127 127 application uses. Let's look at how this would work for a simple configurable
128 128 subclass::
129 129
130 130 # Sample configurable:
131 131 from IPython.config.configurable import Configurable
132 132 from IPython.utils.traitlets import Int, Float, Unicode, Bool
133 133
134 134 class MyClass(Configurable):
135 135 name = Unicode(u'defaultname', config=True)
136 136 ranking = Int(0, config=True)
137 137 value = Float(99.0)
138 138 # The rest of the class implementation would go here..
139 139
140 140 In this example, we see that :class:`MyClass` has three attributes, two
141 141 of whom (``name``, ``ranking``) can be configured. All of the attributes
142 142 are given types and default values. If a :class:`MyClass` is instantiated,
143 143 but not configured, these default values will be used. But let's see how
144 144 to configure this class in a configuration file::
145 145
146 146 # Sample config file
147 147 c = get_config()
148 148
149 149 c.MyClass.name = 'coolname'
150 150 c.MyClass.ranking = 10
151 151
152 152 After this configuration file is loaded, the values set in it will override
153 153 the class defaults anytime a :class:`MyClass` is created. Furthermore,
154 154 these attributes will be type checked and validated anytime they are set.
155 155 This type checking is handled by the :mod:`IPython.utils.traitlets` module,
156 156 which provides the :class:`Unicode`, :class:`Int` and :class:`Float` types.
157 157 In addition to these traitlets, the :mod:`IPython.utils.traitlets` provides
158 158 traitlets for a number of other types.
159 159
160 160 .. note::
161 161
162 162 Underneath the hood, the :class:`Configurable` base class is a subclass of
163 163 :class:`IPython.utils.traitlets.HasTraits`. The
164 164 :mod:`IPython.utils.traitlets` module is a lightweight version of
165 165 :mod:`enthought.traits`. Our implementation is a pure Python subset
166 166 (mostly API compatible) of :mod:`enthought.traits` that does not have any
167 167 of the automatic GUI generation capabilities. Our plan is to achieve 100%
168 168 API compatibility to enable the actual :mod:`enthought.traits` to
169 169 eventually be used instead. Currently, we cannot use
170 170 :mod:`enthought.traits` as we are committed to the core of IPython being
171 171 pure Python.
172 172
173 173 It should be very clear at this point what the naming convention is for
174 174 configuration attributes::
175 175
176 176 c.ClassName.attribute_name = attribute_value
177 177
178 178 Here, ``ClassName`` is the name of the class whose configuration attribute you
179 179 want to set, ``attribute_name`` is the name of the attribute you want to set
180 180 and ``attribute_value`` the the value you want it to have. The ``ClassName``
181 181 attribute of ``c`` is not the actual class, but instead is another
182 182 :class:`~IPython.config.loader.Config` instance.
183 183
184 184 .. note::
185 185
186 186 The careful reader may wonder how the ``ClassName`` (``MyClass`` in
187 187 the above example) attribute of the configuration object ``c`` gets
188 188 created. These attributes are created on the fly by the
189 189 :class:`~IPython.config.loader.Config` instance, using a simple naming
190 190 convention. Any attribute of a :class:`~IPython.config.loader.Config`
191 191 instance whose name begins with an uppercase character is assumed to be a
192 192 sub-configuration and a new empty :class:`~IPython.config.loader.Config`
193 193 instance is dynamically created for that attribute. This allows deeply
194 194 hierarchical information created easily (``c.Foo.Bar.value``) on the fly.
195 195
196 196 Configuration files inheritance
197 197 ===============================
198 198
199 199 Let's say you want to have different configuration files for various purposes.
200 200 Our configuration system makes it easy for one configuration file to inherit
201 201 the information in another configuration file. The :func:`load_subconfig`
202 202 command can be used in a configuration file for this purpose. Here is a simple
203 203 example that loads all of the values from the file :file:`base_config.py`::
204 204
205 205 # base_config.py
206 206 c = get_config()
207 207 c.MyClass.name = 'coolname'
208 208 c.MyClass.ranking = 100
209 209
210 210 into the configuration file :file:`main_config.py`::
211 211
212 212 # main_config.py
213 213 c = get_config()
214 214
215 215 # Load everything from base_config.py
216 216 load_subconfig('base_config.py')
217 217
218 218 # Now override one of the values
219 219 c.MyClass.name = 'bettername'
220 220
221 221 In a situation like this the :func:`load_subconfig` makes sure that the
222 222 search path for sub-configuration files is inherited from that of the parent.
223 223 Thus, you can typically put the two in the same directory and everything will
224 224 just work.
225 225
226 226 You can also load configuration files by profile, for instance:
227 227
228 228 .. sourcecode:: python
229 229
230 230 load_subconfig('ipython_config.py', profile='default')
231 231
232 232 to inherit your default configuration as a starting point.
233 233
234 234
235 235 Class based configuration inheritance
236 236 =====================================
237 237
238 238 There is another aspect of configuration where inheritance comes into play.
239 239 Sometimes, your classes will have an inheritance hierarchy that you want
240 240 to be reflected in the configuration system. Here is a simple example::
241 241
242 242 from IPython.config.configurable import Configurable
243 243 from IPython.utils.traitlets import Int, Float, Unicode, Bool
244 244
245 245 class Foo(Configurable):
246 246 name = Unicode(u'fooname', config=True)
247 247 value = Float(100.0, config=True)
248 248
249 249 class Bar(Foo):
250 250 name = Unicode(u'barname', config=True)
251 251 othervalue = Int(0, config=True)
252 252
253 253 Now, we can create a configuration file to configure instances of :class:`Foo`
254 254 and :class:`Bar`::
255 255
256 256 # config file
257 257 c = get_config()
258 258
259 259 c.Foo.name = u'bestname'
260 260 c.Bar.othervalue = 10
261 261
262 262 This class hierarchy and configuration file accomplishes the following:
263 263
264 264 * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be
265 265 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also
266 266 picks up the configuration information for :class:`Foo`.
267 267 * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be
268 268 ``100.0``, which is the value specified as the class default.
269 269 * The default value for :attr:`Bar.othervalue` will be 10 as set in the
270 270 configuration file. Because :class:`Foo` is the parent of :class:`Bar`
271 271 it doesn't know anything about the :attr:`othervalue` attribute.
272 272
273 273
274 274 .. _ipython_dir:
275 275
276 276 Configuration file location
277 277 ===========================
278 278
279 279 So where should you put your configuration files? IPython uses "profiles" for
280 280 configuration, and by default, all profiles will be stored in the so called
281 281 "IPython directory". The location of this directory is determined by the
282 282 following algorithm:
283 283
284 284 * If the ``ipython_dir`` command line flag is given, its value is used.
285 285
286 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 288 environment variable and then default to a platform-specific default.
289 289
290 290 On posix systems (Linux, Unix, etc.), IPython respects the ``$XDG_CONFIG_HOME``
291 291 part of the `XDG Base Directory`_ specification. If ``$XDG_CONFIG_HOME`` is
292 292 defined and exists ( ``XDG_CONFIG_HOME`` has a default interpretation of
293 293 :file:`$HOME/.config`), then IPython's config directory will be located in
294 294 :file:`$XDG_CONFIG_HOME/ipython`. If users still have an IPython directory
295 295 in :file:`$HOME/.ipython`, then that will be used. in preference to the
296 296 system default.
297 297
298 298 For most users, the default value will simply be something like
299 299 :file:`$HOME/.config/ipython` on Linux, or :file:`$HOME/.ipython`
300 300 elsewhere.
301 301
302 302 Once the location of the IPython directory has been determined, you need to know
303 303 which profile you are using. For users with a single configuration, this will
304 304 simply be 'default', and will be located in
305 :file:`<IPYTHON_DIR>/profile_default`.
305 :file:`<IPYTHONDIR>/profile_default`.
306 306
307 307 The next thing you need to know is what to call your configuration file. The
308 308 basic idea is that each application has its own default configuration filename.
309 309 The default named used by the :command:`ipython` command line program is
310 310 :file:`ipython_config.py`, and *all* IPython applications will use this file.
311 311 Other applications, such as the parallel :command:`ipcluster` scripts or the
312 312 QtConsole will load their own config files *after* :file:`ipython_config.py`. To
313 313 load a particular configuration file instead of the default, the name can be
314 314 overridden by the ``config_file`` command line flag.
315 315
316 316 To generate the default configuration files, do::
317 317
318 318 $> ipython profile create
319 319
320 320 and you will have a default :file:`ipython_config.py` in your IPython directory
321 321 under :file:`profile_default`. If you want the default config files for the
322 322 :mod:`IPython.parallel` applications, add ``--parallel`` to the end of the
323 323 command-line args.
324 324
325 325 .. _Profiles:
326 326
327 327 Profiles
328 328 ========
329 329
330 330 A profile is a directory containing configuration and runtime files, such as
331 331 logs, connection info for the parallel apps, and your IPython command history.
332 332
333 333 The idea is that users often want to maintain a set of configuration files for
334 334 different purposes: one for doing numerical computing with NumPy and SciPy and
335 335 another for doing symbolic computing with SymPy. Profiles make it easy to keep a
336 336 separate configuration files, logs, and histories for each of these purposes.
337 337
338 338 Let's start by showing how a profile is used:
339 339
340 340 .. code-block:: bash
341 341
342 342 $ ipython --profile=sympy
343 343
344 344 This tells the :command:`ipython` command line program to get its configuration
345 345 from the "sympy" profile. The file names for various profiles do not change. The
346 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 349 The general pattern is this: simply create a new profile with:
350 350
351 351 .. code-block:: bash
352 352
353 353 ipython profile create <name>
354 354
355 355 which adds a directory called ``profile_<name>`` to your IPython directory. Then
356 356 you can load this profile by adding ``--profile=<name>`` to your command line
357 357 options. Profiles are supported by all IPython applications.
358 358
359 359 IPython ships with some sample profiles in :file:`IPython/config/profile`. If
360 360 you create profiles with the name of one of our shipped profiles, these config
361 361 files will be copied over instead of starting with the automatically generated
362 362 config files.
363 363
364 364 Security Files
365 365 --------------
366 366
367 367 If you are using the notebook, qtconsole, or parallel code, IPython stores
368 368 connection information in small JSON files in the active profile's security
369 369 directory. This directory is made private, so only you can see the files inside. If
370 370 you need to move connection files around to other computers, this is where they will
371 371 be. If you want your code to be able to open security files by name, we have a
372 372 convenience function :func:`IPython.utils.path.get_security_file`, which will return
373 373 the absolute path to a security file from its filename and [optionally] profile
374 374 name.
375 375
376 376 Startup Files
377 377 -------------
378 378
379 379 If you want some code to be run at the beginning of every IPython session with a
380 380 particular profile, the easiest way is to add Python (.py) or IPython (.ipy) scripts
381 381 to your :file:`<profile>/startup` directory. Files in this directory will always be
382 382 executed as soon as the IPython shell is constructed, and before any other code or
383 383 scripts you have specified. If you have multiple files in the startup directory,
384 384 they will be run in lexicographical order, so you can control the ordering by adding
385 385 a '00-' prefix.
386 386
387 387 .. note::
388 388
389 389 Automatic startup files are new in IPython 0.12. Use the
390 390 InteractiveShellApp.exec_files configurable for similar behavior in 0.11.
391 391
392 392
393 393 .. _commandline:
394 394
395 395 Command-line arguments
396 396 ======================
397 397
398 398 IPython exposes *all* configurable options on the command-line. The command-line
399 399 arguments are generated from the Configurable traits of the classes associated
400 400 with a given Application. Configuring IPython from the command-line may look
401 401 very similar to an IPython config file
402 402
403 403 IPython applications use a parser called
404 404 :class:`~IPython.config.loader.KeyValueLoader` to load values into a Config
405 405 object. Values are assigned in much the same way as in a config file:
406 406
407 407 .. code-block:: bash
408 408
409 409 $> ipython --InteractiveShell.use_readline=False --BaseIPythonApplication.profile='myprofile'
410 410
411 411 Is the same as adding:
412 412
413 413 .. sourcecode:: python
414 414
415 415 c.InteractiveShell.use_readline=False
416 416 c.BaseIPythonApplication.profile='myprofile'
417 417
418 418 to your config file. Key/Value arguments *always* take a value, separated by '='
419 419 and no spaces.
420 420
421 421 Common Arguments
422 422 ****************
423 423
424 424 Since the strictness and verbosity of the KVLoader above are not ideal for everyday
425 425 use, common arguments can be specified as flags_ or aliases_.
426 426
427 427 Flags and Aliases are handled by :mod:`argparse` instead, allowing for more flexible
428 428 parsing. In general, flags and aliases are prefixed by ``--``, except for those
429 429 that are single characters, in which case they can be specified with a single ``-``, e.g.:
430 430
431 431 .. code-block:: bash
432 432
433 433 $> ipython -i -c "import numpy; x=numpy.linspace(0,1)" --profile testing --colors=lightbg
434 434
435 435 Aliases
436 436 -------
437 437
438 438 For convenience, applications have a mapping of commonly used traits, so you don't have
439 439 to specify the whole class name:
440 440
441 441 .. code-block:: bash
442 442
443 443 $> ipython --profile myprofile
444 444 # and
445 445 $> ipython --profile='myprofile'
446 446 # are equivalent to
447 447 $> ipython --BaseIPythonApplication.profile='myprofile'
448 448
449 449 Flags
450 450 -----
451 451
452 452 Applications can also be passed **flags**. Flags are options that take no
453 453 arguments. They are simply wrappers for
454 454 setting one or more configurables with predefined values, often True/False.
455 455
456 456 For instance:
457 457
458 458 .. code-block:: bash
459 459
460 460 $> ipcontroller --debug
461 461 # is equivalent to
462 462 $> ipcontroller --Application.log_level=DEBUG
463 463 # and
464 464 $> ipython --pylab
465 465 # is equivalent to
466 466 $> ipython --pylab=auto
467 467 # or
468 468 $> ipython --no-banner
469 469 # is equivalent to
470 470 $> ipython --TerminalIPythonApp.display_banner=False
471 471
472 472 Subcommands
473 473 ***********
474 474
475 475
476 476 Some IPython applications have **subcommands**. Subcommands are modeled after
477 477 :command:`git`, and are called with the form :command:`command subcommand
478 478 [...args]`. Currently, the QtConsole is a subcommand of terminal IPython:
479 479
480 480 .. code-block:: bash
481 481
482 482 $> ipython qtconsole --profile=myprofile
483 483
484 484 and :command:`ipcluster` is simply a wrapper for its various subcommands (start,
485 485 stop, engines).
486 486
487 487 .. code-block:: bash
488 488
489 489 $> ipcluster start --profile=myprofile --n=4
490 490
491 491
492 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 495 Design requirements
496 496 ===================
497 497
498 498 Here are the main requirements we wanted our configuration system to have:
499 499
500 500 * Support for hierarchical configuration information.
501 501
502 502 * Full integration with command line option parsers. Often, you want to read
503 503 a configuration file, but then override some of the values with command line
504 504 options. Our configuration system automates this process and allows each
505 505 command line option to be linked to a particular attribute in the
506 506 configuration hierarchy that it will override.
507 507
508 508 * Configuration files that are themselves valid Python code. This accomplishes
509 509 many things. First, it becomes possible to put logic in your configuration
510 510 files that sets attributes based on your operating system, network setup,
511 511 Python version, etc. Second, Python has a super simple syntax for accessing
512 512 hierarchical data structures, namely regular attribute access
513 513 (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to
514 514 import configuration attributes from one configuration file to another.
515 515 Fourth, even though Python is dynamically typed, it does have types that can
516 516 be checked at runtime. Thus, a ``1`` in a config file is the integer '1',
517 517 while a ``'1'`` is a string.
518 518
519 519 * A fully automated method for getting the configuration information to the
520 520 classes that need it at runtime. Writing code that walks a configuration
521 521 hierarchy to extract a particular attribute is painful. When you have
522 522 complex configuration information with hundreds of attributes, this makes
523 523 you want to cry.
524 524
525 525 * Type checking and validation that doesn't require the entire configuration
526 526 hierarchy to be specified statically before runtime. Python is a very
527 527 dynamic language and you don't always know everything that needs to be
528 528 configured when a program starts.
529 529
530 530
531 531 .. _`XDG Base Directory`: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
@@ -1,609 +1,609 b''
1 1 .. _qtconsole:
2 2
3 3 =========================
4 4 A Qt Console for IPython
5 5 =========================
6 6
7 7 We now have a version of IPython, using the new two-process :ref:`ZeroMQ Kernel
8 8 <ipythonzmq>`, running in a PyQt_ GUI. This is a very lightweight widget that
9 9 largely feels like a terminal, but provides a number of enhancements only
10 10 possible in a GUI, such as inline figures, proper multiline editing with syntax
11 11 highlighting, graphical calltips, and much more.
12 12
13 13 .. figure:: ../_static/qtconsole.png
14 14 :width: 400px
15 15 :alt: IPython Qt console with embedded plots
16 16 :align: center
17 17 :target: ../_static/qtconsole.png
18 18
19 19 The Qt console for IPython, using inline matplotlib plots.
20 20
21 21 To get acquainted with the Qt console, type `%guiref` to see a quick
22 22 introduction of its main features.
23 23
24 24 The Qt frontend has hand-coded emacs-style bindings for text navigation. This
25 25 is not yet configurable.
26 26
27 27 .. tip::
28 28
29 29 Since the Qt console tries hard to behave like a terminal, by default it
30 30 immediately executes single lines of input that are complete. If you want
31 31 to force multiline input, hit :kbd:`Ctrl-Enter` at the end of the first line
32 32 instead of :kbd:`Enter`, and it will open a new line for input. At any
33 33 point in a multiline block, you can force its execution (without having to
34 34 go to the bottom) with :kbd:`Shift-Enter`.
35 35
36 36 ``%loadpy``
37 37 ===========
38 38
39 39 The new ``%loadpy`` magic takes any python script (must end in '.py'), and
40 40 pastes its contents as your next input, so you can edit it before
41 41 executing. The script may be on your machine, but you can also specify a url,
42 42 and it will download the script from the web. This is particularly useful for
43 43 playing with examples from documentation, such as matplotlib.
44 44
45 45 .. sourcecode:: ipython
46 46
47 47 In [6]: %loadpy http://matplotlib.sourceforge.net/plot_directive/mpl_examples/mplot3d/contour3d_demo.py
48 48
49 49 In [7]: from mpl_toolkits.mplot3d import axes3d
50 50 ...: import matplotlib.pyplot as plt
51 51 ...:
52 52 ...: fig = plt.figure()
53 53 ...: ax = fig.add_subplot(111, projection='3d')
54 54 ...: X, Y, Z = axes3d.get_test_data(0.05)
55 55 ...: cset = ax.contour(X, Y, Z)
56 56 ...: ax.clabel(cset, fontsize=9, inline=1)
57 57 ...:
58 58 ...: plt.show()
59 59
60 60 Pylab
61 61 =====
62 62
63 63 One of the most exciting features of the new console is embedded matplotlib
64 64 figures. You can use any standard matplotlib GUI backend
65 65 to draw the figures, and since there is now a two-process model, there is no
66 66 longer a conflict between user input and the drawing eventloop.
67 67
68 68 .. image:: figs/besselj.png
69 69 :width: 519px
70 70
71 71 .. display:
72 72
73 73 :func:`display`
74 74 ***************
75 75
76 76 An additional function, :func:`display`, will be added to the global namespace
77 77 if you specify the ``--pylab`` option at the command line. The IPython display
78 78 system provides a mechanism for specifying PNG or SVG (and more)
79 79 representations of objects for GUI frontends. By default, IPython registers
80 80 convenient PNG and SVG renderers for matplotlib figures, so you can embed them
81 81 in your document by calling :func:`display` on one or more of them. This is
82 82 especially useful for saving_ your work.
83 83
84 84 .. sourcecode:: ipython
85 85
86 86 In [5]: plot(range(5)) # plots in the matplotlib window
87 87
88 88 In [6]: display(gcf()) # embeds the current figure in the qtconsole
89 89
90 90 In [7]: display(*getfigs()) # embeds all active figures in the qtconsole
91 91
92 92 If you have a reference to a matplotlib figure object, you can always display
93 93 that specific figure:
94 94
95 95 .. sourcecode:: ipython
96 96
97 97 In [1]: f = figure()
98 98
99 99 In [2]: plot(rand(100))
100 100 Out[2]: [<matplotlib.lines.Line2D at 0x7fc6ac03dd90>]
101 101
102 102 In [3]: display(f)
103 103
104 104 # Plot is shown here
105 105
106 106 In [4]: title('A title')
107 107 Out[4]: <matplotlib.text.Text at 0x7fc6ac023450>
108 108
109 109 In [5]: display(f)
110 110
111 111 # Updated plot with title is shown here.
112 112
113 113 .. _inline:
114 114
115 115 ``--pylab=inline``
116 116 ******************
117 117
118 118 If you want to have all of your figures embedded in your session, instead of
119 119 calling :func:`display`, you can specify ``--pylab=inline`` when you start the
120 120 console, and each time you make a plot, it will show up in your document, as if
121 121 you had called :func:`display(fig)`.
122 122
123 123 The inline backend can use either SVG or PNG figures (PNG being the default).
124 124 To switch between them, set the ``InlineBackend.figure_format`` configurable
125 125 in a config file, or via the ``%config`` magic:
126 126
127 127 .. sourcecode:: ipython
128 128
129 129 In [10]: %config InlineBackend.figure_format = 'svg'
130 130
131 131 .. note::
132 132
133 133 Changing the inline figure format also affects calls to :func:`display` above,
134 134 even if you are not using the inline backend for all figures.
135 135
136 136 By default, IPython closes all figures at the completion of each execution. This means you
137 137 don't have to manually close figures, which is less convenient when figures aren't attached
138 138 to windows with an obvious close button. It also means that the first matplotlib call in
139 139 each cell will always create a new figure:
140 140
141 141 .. sourcecode:: ipython
142 142
143 143 In [11]: plot(range(100))
144 144 <single-line plot>
145 145
146 146 In [12]: plot([1,3,2])
147 147 <another single-line plot>
148 148
149 149
150 150 However, it does prevent the list of active figures surviving from one input cell to the
151 151 next, so if you want to continue working with a figure, you must hold on to a reference to
152 152 it:
153 153
154 154 .. sourcecode:: ipython
155 155
156 156 In [11]: fig = gcf()
157 157 ....: fig.plot(rand(100))
158 158 <plot>
159 159 In [12]: fig.title('Random Title')
160 160 <redraw plot with title>
161 161
162 162 This behavior is controlled by the :attr:`InlineBackend.close_figures` configurable, and
163 163 if you set it to False, via %config or config file, then IPython will *not* close figures,
164 164 and tools like :func:`gcf`, :func:`gca`, :func:`getfigs` will behave the same as they
165 165 do with other backends. You will, however, have to manually close figures:
166 166
167 167 .. sourcecode:: ipython
168 168
169 169 # close all active figures:
170 170 In [13]: [ fig.close() for fig in getfigs() ]
171 171
172 172
173 173
174 174 .. _saving:
175 175
176 176 Saving and Printing
177 177 ===================
178 178
179 179 IPythonQt has the ability to save your current session, as either HTML or
180 180 XHTML. If you have been using :func:`display` or inline_ pylab, your figures
181 181 will be PNG in HTML, or inlined as SVG in XHTML. PNG images have the option to
182 182 be either in an external folder, as in many browsers' "Webpage, Complete"
183 183 option, or inlined as well, for a larger, but more portable file.
184 184
185 185 .. note::
186 186
187 187 Export to SVG+XHTML requires that you are using SVG figures, which is *not*
188 188 the default. To switch the inline figure format to use SVG during an active
189 189 session, do:
190 190
191 191 .. sourcecode:: ipython
192 192
193 193 In [10]: %config InlineBackend.figure_format = 'svg'
194 194
195 195 Or, you can add the same line (c.Inline... instead of %config Inline...) to
196 196 your config files.
197 197
198 198 This will only affect figures plotted after making this call
199 199
200 200
201 201 The widget also exposes the ability to print directly, via the default print
202 202 shortcut or context menu.
203 203
204 204
205 205 .. Note::
206 206
207 207 Saving is only available to richtext Qt widgets, which are used by default,
208 208 but if you pass the ``--plain`` flag, saving will not be available to you.
209 209
210 210
211 211 See these examples of :download:`png/html<figs/jn.html>` and
212 212 :download:`svg/xhtml <figs/jn.xhtml>` output. Note that syntax highlighting
213 213 does not survive export. This is a known issue, and is being investigated.
214 214
215 215
216 216 Colors and Highlighting
217 217 =======================
218 218
219 219 Terminal IPython has always had some coloring, but never syntax
220 220 highlighting. There are a few simple color choices, specified by the ``colors``
221 221 flag or ``%colors`` magic:
222 222
223 223 * LightBG for light backgrounds
224 224 * Linux for dark backgrounds
225 225 * NoColor for a simple colorless terminal
226 226
227 227 The Qt widget has full support for the ``colors`` flag used in the terminal shell.
228 228
229 229 The Qt widget, however, has full syntax highlighting as you type, handled by
230 230 the `pygments`_ library. The ``style`` argument exposes access to any style by
231 231 name that can be found by pygments, and there are several already
232 232 installed. The ``colors`` argument, if unspecified, will be guessed based on
233 233 the chosen style. Similarly, there are default styles associated with each
234 234 ``colors`` option.
235 235
236 236
237 237 Screenshot of ``ipython qtconsole --colors=linux``, which uses the 'monokai'
238 238 theme by default:
239 239
240 240 .. image:: figs/colors_dark.png
241 241 :width: 627px
242 242
243 243 .. Note::
244 244
245 245 Calling ``ipython qtconsole -h`` will show all the style names that
246 246 pygments can find on your system.
247 247
248 248 You can also pass the filename of a custom CSS stylesheet, if you want to do
249 249 your own coloring, via the ``stylesheet`` argument. The default LightBG
250 250 stylesheet:
251 251
252 252 .. sourcecode:: css
253 253
254 254 QPlainTextEdit, QTextEdit { background-color: white;
255 255 color: black ;
256 256 selection-background-color: #ccc}
257 257 .error { color: red; }
258 258 .in-prompt { color: navy; }
259 259 .in-prompt-number { font-weight: bold; }
260 260 .out-prompt { color: darkred; }
261 261 .out-prompt-number { font-weight: bold; }
262 262
263 263 Fonts
264 264 =====
265 265
266 266 The QtConsole has configurable via the ConsoleWidget. To change these, set the
267 267 ``font_family`` or ``font_size`` traits of the ConsoleWidget. For instance, to
268 268 use 9pt Anonymous Pro::
269 269
270 270 $> ipython qtconsole --ConsoleWidget.font_family="Anonymous Pro" --ConsoleWidget.font_size=9
271 271
272 272 Process Management
273 273 ==================
274 274
275 275 With the two-process ZMQ model, the frontend does not block input during
276 276 execution. This means that actions can be taken by the frontend while the
277 277 Kernel is executing, or even after it crashes. The most basic such command is
278 278 via 'Ctrl-.', which restarts the kernel. This can be done in the middle of a
279 279 blocking execution. The frontend can also know, via a heartbeat mechanism, that
280 280 the kernel has died. This means that the frontend can safely restart the
281 281 kernel.
282 282
283 283 .. _multiple_consoles:
284 284
285 285 Multiple Consoles
286 286 *****************
287 287
288 288 Since the Kernel listens on the network, multiple frontends can connect to it.
289 289 These do not have to all be qt frontends - any IPython frontend can connect and
290 290 run code. When you start ipython qtconsole, there will be an output line,
291 291 like::
292 292
293 293 [IPKernelApp] To connect another client to this kernel, use:
294 294 [IPKernelApp] --existing kernel-12345.json
295 295
296 296 Other frontends can connect to your kernel, and share in the execution. This is
297 297 great for collaboration. The ``--existing`` flag means connect to a kernel
298 298 that already exists. Starting other consoles
299 299 with that flag will not try to start their own kernel, but rather connect to
300 300 yours. :file:`kernel-12345.json` is a small JSON file with the ip, port, and
301 301 authentication information necessary to connect to your kernel. By default, this file
302 302 will be in your default profile's security directory. If it is somewhere else,
303 303 the output line will print the full path of the connection file, rather than
304 304 just its filename.
305 305
306 306 If you need to find the connection info to send, and don't know where your connection file
307 307 lives, there are a couple of ways to get it. If you are already running an IPython console
308 308 connected to the kernel, you can use the ``%connect_info`` magic to display the information
309 309 necessary to connect another frontend to the kernel.
310 310
311 311 .. sourcecode:: ipython
312 312
313 313 In [2]: %connect_info
314 314 {
315 315 "stdin_port":50255,
316 316 "ip":"127.0.0.1",
317 317 "hb_port":50256,
318 318 "key":"70be6f0f-1564-4218-8cda-31be40a4d6aa",
319 319 "shell_port":50253,
320 320 "iopub_port":50254
321 321 }
322 322
323 323 Paste the above JSON into a file, and connect with:
324 324 $> ipython <app> --existing <file>
325 325 or, if you are local, you can connect with just:
326 326 $> ipython <app> --existing kernel-12345.json
327 327 or even just:
328 328 $> ipython <app> --existing
329 329 if this is the most recent IPython session you have started.
330 330
331 331 Otherwise, you can find a connection file by name (and optionally profile) with
332 332 :func:`IPython.lib.kernel.find_connection_file`:
333 333
334 334 .. sourcecode:: bash
335 335
336 336 $> python -c "from IPython.lib.kernel import find_connection_file;\
337 337 print find_connection_file('kernel-12345.json')"
338 338 /home/you/.ipython/profile_default/security/kernel-12345.json
339 339
340 340 And if you are using a particular IPython profile:
341 341
342 342 .. sourcecode:: bash
343 343
344 344 $> python -c "from IPython.lib.kernel import find_connection_file;\
345 345 print find_connection_file('kernel-12345.json', profile='foo')"
346 346 /home/you/.ipython/profile_foo/security/kernel-12345.json
347 347
348 348 You can even launch a standalone kernel, and connect and disconnect Qt Consoles
349 349 from various machines. This lets you keep the same running IPython session
350 350 on your work machine (with matplotlib plots and everything), logging in from home,
351 351 cafΓ©s, etc.::
352 352
353 353 $> ipython kernel
354 354 [IPKernelApp] To connect another client to this kernel, use:
355 355 [IPKernelApp] --existing kernel-12345.json
356 356
357 357 This is actually exactly the same as the subprocess launched by the qtconsole, so
358 358 all the information about connecting to a standalone kernel is identical to that
359 359 of connecting to the kernel attached to a running console.
360 360
361 361 .. _kernel_security:
362 362
363 363 Security
364 364 --------
365 365
366 366 .. warning::
367 367
368 368 Since the ZMQ code currently has no encryption, listening on an
369 369 external-facing IP is dangerous. You are giving any computer that can see
370 370 you on the network the ability to connect to your kernel, and view your traffic.
371 371 Read the rest of this section before listening on external ports
372 372 or running an IPython kernel on a shared machine.
373 373
374 374 By default (for security reasons), the kernel only listens on localhost, so you
375 375 can only connect multiple frontends to the kernel from your local machine. You
376 376 can specify to listen on an external interface by specifying the ``ip``
377 377 argument::
378 378
379 379 $> ipython qtconsole --ip=192.168.1.123
380 380
381 381 If you specify the ip as 0.0.0.0 or '*', that means all interfaces, so any
382 382 computer that can see yours on the network can connect to the kernel.
383 383
384 384 Messages are not encrypted, so users with access to the ports your kernel is using will be
385 385 able to see any output of the kernel. They will **NOT** be able to issue shell commands as
386 386 you due to message signatures, which are enabled by default as of IPython 0.12.
387 387
388 388 .. warning::
389 389
390 390 If you disable message signatures, then any user with access to the ports your
391 391 kernel is listening on can issue arbitrary code as you. **DO NOT** disable message
392 392 signatures unless you have a lot of trust in your environment.
393 393
394 394 The one security feature IPython does provide is protection from unauthorized execution.
395 395 IPython's messaging system will sign messages with HMAC digests using a shared-key. The key
396 396 is never sent over the network, it is only used to generate a unique hash for each message,
397 397 based on its content. When IPython receives a message, it will check that the digest
398 398 matches, and discard the message. You can use any file that only you have access to to
399 399 generate this key, but the default is just to generate a new UUID. You can generate a random
400 400 private key with::
401 401
402 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)
404 $> python -c "import os; print os.urandom(128).encode('base64')" > $IPYTHON_DIR/sessionkey
405 $> chmod 600 $IPYTHON_DIR/sessionkey
403 # (assumes IPYTHONDIR is defined, otherwise use your IPython directory)
404 $> python -c "import os; print os.urandom(128).encode('base64')" > $IPYTHONDIR/sessionkey
405 $> chmod 600 $IPYTHONDIR/sessionkey
406 406
407 407 The *contents* of this file will be stored in the JSON connection file, so that file
408 408 contains everything you need to connect to and use a kernel.
409 409
410 410 To use this generated key, simply specify the ``Session.keyfile`` configurable
411 411 in :file:`ipython_config.py` or at the command-line, as in::
412 412
413 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 416 .. _ssh_tunnels:
417 417
418 418 SSH Tunnels
419 419 -----------
420 420
421 421 Sometimes you want to connect to machines across the internet, or just across
422 422 a LAN that either doesn't permit open ports or you don't trust the other
423 423 machines on the network. To do this, you can use SSH tunnels. SSH tunnels
424 424 are a way to securely forward ports on your local machine to ports on another
425 425 machine, to which you have SSH access.
426 426
427 427 In simple cases, IPython's tools can forward ports over ssh by simply adding the
428 428 ``--ssh=remote`` argument to the usual ``--existing...`` set of flags for connecting
429 429 to a running kernel, after copying the JSON connection file (or its contents) to
430 430 the second computer.
431 431
432 432 .. warning::
433 433
434 434 Using SSH tunnels does *not* increase localhost security. In fact, when
435 435 tunneling from one machine to another *both* machines have open
436 436 ports on localhost available for connections to the kernel.
437 437
438 438 There are two primary models for using SSH tunnels with IPython. The first
439 439 is to have the Kernel listen only on localhost, and connect to it from
440 440 another machine on the same LAN.
441 441
442 442 First, let's start a kernel on machine **worker**, listening only
443 443 on loopback::
444 444
445 445 user@worker $> ipython kernel
446 446 [IPKernelApp] To connect another client to this kernel, use:
447 447 [IPKernelApp] --existing kernel-12345.json
448 448
449 449 In this case, the IP that you would connect
450 450 to would still be 127.0.0.1, but you want to specify the additional ``--ssh`` argument
451 451 with the hostname of the kernel (in this example, it's 'worker')::
452 452
453 453 user@client $> ipython qtconsole --ssh=worker --existing /path/to/kernel-12345.json
454 454
455 455 Which will write a new connection file with the forwarded ports, so you can reuse them::
456 456
457 457 [IPythonQtConsoleApp] To connect another client via this tunnel, use:
458 458 [IPythonQtConsoleApp] --existing kernel-12345-ssh.json
459 459
460 460 Note again that this opens ports on the *client* machine that point to your kernel.
461 461
462 462 .. note::
463 463
464 464 the ssh argument is simply passed to openssh, so it can be fully specified ``user@host:port``
465 465 but it will also respect your aliases, etc. in :file:`.ssh/config` if you have any.
466 466
467 467 The second pattern is for connecting to a machine behind a firewall across the internet
468 468 (or otherwise wide network). This time, we have a machine **login** that you have ssh access
469 469 to, which can see **kernel**, but **client** is on another network. The important difference
470 470 now is that **client** can see **login**, but *not* **worker**. So we need to forward ports from
471 471 client to worker *via* login. This means that the kernel must be started listening
472 472 on external interfaces, so that its ports are visible to `login`::
473 473
474 474 user@worker $> ipython kernel --ip=0.0.0.0
475 475 [IPKernelApp] To connect another client to this kernel, use:
476 476 [IPKernelApp] --existing kernel-12345.json
477 477
478 478 Which we can connect to from the client with::
479 479
480 480 user@client $> ipython qtconsole --ssh=login --ip=192.168.1.123 --existing /path/to/kernel-12345.json
481 481
482 482 .. note::
483 483
484 484 The IP here is the address of worker as seen from *login*, and need only be specified if
485 485 the kernel used the ambiguous 0.0.0.0 (all interfaces) address. If it had used
486 486 192.168.1.123 to start with, it would not be needed.
487 487
488 488
489 489 Manual SSH tunnels
490 490 ------------------
491 491
492 492 It's possible that IPython's ssh helper functions won't work for you, for various
493 493 reasons. You can still connect to remote machines, as long as you set up the tunnels
494 494 yourself. The basic format of forwarding a local port to a remote one is::
495 495
496 496 [client] $> ssh <server> <localport>:<remoteip>:<remoteport> -f -N
497 497
498 498 This will forward local connections to **localport** on client to **remoteip:remoteport**
499 499 *via* **server**. Note that remoteip is interpreted relative to *server*, not the client.
500 500 So if you have direct ssh access to the machine to which you want to forward connections,
501 501 then the server *is* the remote machine, and remoteip should be server's IP as seen from the
502 502 server itself, i.e. 127.0.0.1. Thus, to forward local port 12345 to remote port 54321 on
503 503 a machine you can see, do::
504 504
505 505 [client] $> ssh machine 12345:127.0.0.1:54321 -f -N
506 506
507 507 But if your target is actually on a LAN at 192.168.1.123, behind another machine called **login**,
508 508 then you would do::
509 509
510 510 [client] $> ssh login 12345:192.168.1.16:54321 -f -N
511 511
512 512 The ``-f -N`` on the end are flags that tell ssh to run in the background,
513 513 and don't actually run any commands beyond creating the tunnel.
514 514
515 515 .. seealso::
516 516
517 517 A short discussion of ssh tunnels: http://www.revsys.com/writings/quicktips/ssh-tunnel.html
518 518
519 519
520 520
521 521 Stopping Kernels and Consoles
522 522 *****************************
523 523
524 524 Since there can be many consoles per kernel, the shutdown mechanism and dialog
525 525 are probably more complicated than you are used to. Since you don't always want
526 526 to shutdown a kernel when you close a window, you are given the option to just
527 527 close the console window or also close the Kernel and *all other windows*. Note
528 528 that this only refers to all other *local* windows, as remote Consoles are not
529 529 allowed to shutdown the kernel, and shutdowns do not close Remote consoles (to
530 530 allow for saving, etc.).
531 531
532 532 Rules:
533 533
534 534 * Restarting the kernel automatically clears all *local* Consoles, and prompts remote
535 535 Consoles about the reset.
536 536 * Shutdown closes all *local* Consoles, and notifies remotes that
537 537 the Kernel has been shutdown.
538 538 * Remote Consoles may not restart or shutdown the kernel.
539 539
540 540 Qt and the QtConsole
541 541 ====================
542 542
543 543 An important part of working with the QtConsole when you are writing your own
544 544 Qt code is to remember that user code (in the kernel) is *not* in the same
545 545 process as the frontend. This means that there is not necessarily any Qt code
546 546 running in the kernel, and under most normal circumstances there isn't. If,
547 547 however, you specify ``--pylab=qt`` at the command-line, then there *will* be a
548 548 :class:`QCoreApplication` instance running in the kernel process along with
549 549 user-code. To get a reference to this application, do:
550 550
551 551 .. sourcecode:: python
552 552
553 553 from PyQt4 import QtCore
554 554 app = QtCore.QCoreApplication.instance()
555 555 # app will be None if there is no such instance
556 556
557 557 A common problem listed in the PyQt4 Gotchas_ is the fact that Python's garbage
558 558 collection will destroy Qt objects (Windows, etc.) once there is no longer a
559 559 Python reference to them, so you have to hold on to them. For instance, in:
560 560
561 561 .. sourcecode:: python
562 562
563 563 def make_window():
564 564 win = QtGui.QMainWindow()
565 565
566 566 def make_and_return_window():
567 567 win = QtGui.QMainWindow()
568 568 return win
569 569
570 570 :func:`make_window` will never draw a window, because garbage collection will
571 571 destroy it before it is drawn, whereas :func:`make_and_return_window` lets the
572 572 caller decide when the window object should be destroyed. If, as a developer,
573 573 you know that you always want your objects to last as long as the process, you
574 574 can attach them to the QApplication instance itself:
575 575
576 576 .. sourcecode:: python
577 577
578 578 # do this just once:
579 579 app = QtCore.QCoreApplication.instance()
580 580 app.references = set()
581 581 # then when you create Windows, add them to the set
582 582 def make_window():
583 583 win = QtGui.QMainWindow()
584 584 app.references.add(win)
585 585
586 586 Now the QApplication itself holds a reference to ``win``, so it will never be
587 587 garbage collected until the application itself is destroyed.
588 588
589 589 .. _Gotchas: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/gotchas.html#garbage-collection
590 590
591 591 Regressions
592 592 ===========
593 593
594 594 There are some features, where the qt console lags behind the Terminal
595 595 frontend:
596 596
597 597 * !cmd input: Due to our use of pexpect, we cannot pass input to subprocesses
598 598 launched using the '!' escape, so you should never call a command that
599 599 requires interactive input. For such cases, use the terminal IPython. This
600 600 will not be fixed, as abandoning pexpect would significantly degrade the
601 601 console experience.
602 602
603 603 * Use of ``\b`` and ``\r`` characters in the console: these are control
604 604 characters that allow the cursor to move backwards on a line, and are used to
605 605 display things like in-place progress bars in a terminal. We currently do
606 606 not support this, but it is being tracked as issue :ghissue:`629`.
607 607
608 608 .. _PyQt: http://www.riverbankcomputing.co.uk/software/pyqt/download
609 609 .. _pygments: http://pygments.org/
@@ -1,1005 +1,1005 b''
1 1 =================
2 2 IPython reference
3 3 =================
4 4
5 5 .. _command_line_options:
6 6
7 7 Command-line usage
8 8 ==================
9 9
10 10 You start IPython with the command::
11 11
12 12 $ ipython [options] files
13 13
14 14 .. note::
15 15
16 16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
17 17
18 18 If invoked with no options, it executes all the files listed in sequence
19 19 and drops you into the interpreter while still acknowledging any options
20 20 you may have set in your ipython_config.py. This behavior is different from
21 21 standard Python, which when called as python -i will only execute one
22 22 file and ignore your configuration setup.
23 23
24 24 Please note that some of the configuration options are not available at
25 25 the command line, simply because they are not practical here. Look into
26 26 your configuration files for details on those. There are separate configuration
27 27 files for each profile, and the files look like "ipython_config.py" or
28 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 30 For Linux users, this will be $HOME/.config/ipython, and for other users it
31 31 will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
32 32 Settings\\YourUserName in most instances.
33 33
34 34
35 35 Eventloop integration
36 36 ---------------------
37 37
38 38 Previously IPython had command line options for controlling GUI event loop
39 39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
40 40 version 0.11, these have been removed. Please see the new ``%gui``
41 41 magic command or :ref:`this section <gui_support>` for details on the new
42 42 interface, or specify the gui at the commandline::
43 43
44 44 $ ipython --gui=qt
45 45
46 46
47 47 Command-line Options
48 48 --------------------
49 49
50 50 To see the options IPython accepts, use ``ipython --help`` (and you probably
51 51 should run the output through a pager such as ``ipython --help | less`` for
52 52 more convenient reading). This shows all the options that have a single-word
53 53 alias to control them, but IPython lets you configure all of its objects from
54 54 the command-line by passing the full class name and a corresponding value; type
55 55 ``ipython --help-all`` to see this full list. For example::
56 56
57 57 ipython --pylab qt
58 58
59 59 is equivalent to::
60 60
61 61 ipython --TerminalIPythonApp.pylab='qt'
62 62
63 63 Note that in the second form, you *must* use the equal sign, as the expression
64 64 is evaluated as an actual Python assignment. While in the above example the
65 65 short form is more convenient, only the most common options have a short form,
66 66 while any configurable variable in IPython can be set at the command-line by
67 67 using the long form. This long form is the same syntax used in the
68 68 configuration files, if you want to set these options permanently.
69 69
70 70
71 71 Interactive use
72 72 ===============
73 73
74 74 IPython is meant to work as a drop-in replacement for the standard interactive
75 75 interpreter. As such, any code which is valid python should execute normally
76 76 under IPython (cases where this is not true should be reported as bugs). It
77 77 does, however, offer many features which are not available at a standard python
78 78 prompt. What follows is a list of these.
79 79
80 80
81 81 Caution for Windows users
82 82 -------------------------
83 83
84 84 Windows, unfortunately, uses the '\\' character as a path separator. This is a
85 85 terrible choice, because '\\' also represents the escape character in most
86 86 modern programming languages, including Python. For this reason, using '/'
87 87 character is recommended if you have problems with ``\``. However, in Windows
88 88 commands '/' flags options, so you can not use it for the root directory. This
89 89 means that paths beginning at the root must be typed in a contrived manner
90 90 like: ``%copy \opt/foo/bar.txt \tmp``
91 91
92 92 .. _magic:
93 93
94 94 Magic command system
95 95 --------------------
96 96
97 97 IPython will treat any line whose first character is a % as a special
98 98 call to a 'magic' function. These allow you to control the behavior of
99 99 IPython itself, plus a lot of system-type features. They are all
100 100 prefixed with a % character, but parameters are given without
101 101 parentheses or quotes.
102 102
103 103 Example: typing ``%cd mydir`` changes your working directory to 'mydir', if it
104 104 exists.
105 105
106 106 If you have 'automagic' enabled (as it by default), you don't need
107 107 to type in the % explicitly. IPython will scan its internal list of
108 108 magic functions and call one if it exists. With automagic on you can
109 109 then just type ``cd mydir`` to go to directory 'mydir'. The automagic
110 110 system has the lowest possible precedence in name searches, so defining
111 111 an identifier with the same name as an existing magic function will
112 112 shadow it for automagic use. You can still access the shadowed magic
113 113 function by explicitly using the % character at the beginning of the line.
114 114
115 115 An example (with automagic on) should clarify all this:
116 116
117 117 .. sourcecode:: ipython
118 118
119 119 In [1]: cd ipython # %cd is called by automagic
120 120 /home/fperez/ipython
121 121
122 122 In [2]: cd=1 # now cd is just a variable
123 123
124 124 In [3]: cd .. # and doesn't work as a function anymore
125 125 File "<ipython-input-3-9fedb3aff56c>", line 1
126 126 cd ..
127 127 ^
128 128 SyntaxError: invalid syntax
129 129
130 130
131 131 In [4]: %cd .. # but %cd always works
132 132 /home/fperez
133 133
134 134 In [5]: del cd # if you remove the cd variable, automagic works again
135 135
136 136 In [6]: cd ipython
137 137
138 138 /home/fperez/ipython
139 139
140 140 You can define your own magic functions to extend the system. The
141 141 following example defines a new magic command, %impall:
142 142
143 143 .. sourcecode:: python
144 144
145 145 ip = get_ipython()
146 146
147 147 def doimp(self, arg):
148 148 ip = self.api
149 149 ip.ex("import %s; reload(%s); from %s import *" % (arg,arg,arg) )
150 150
151 151 ip.define_magic('impall', doimp)
152 152
153 153 Type ``%magic`` for more information, including a list of all available magic
154 154 functions at any time and their docstrings. You can also type
155 155 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for information on
156 156 the '?' system) to get information about any particular magic function you are
157 157 interested in.
158 158
159 159 The API documentation for the :mod:`IPython.core.magic` module contains the full
160 160 docstrings of all currently available magic commands.
161 161
162 162
163 163 Access to the standard Python help
164 164 ----------------------------------
165 165
166 166 Simply type ``help()`` to access Python's standard help system. You can
167 167 also type ``help(object)`` for information about a given object, or
168 168 ``help('keyword')`` for information on a keyword. You may need to configure your
169 169 PYTHONDOCS environment variable for this feature to work correctly.
170 170
171 171 .. _dynamic_object_info:
172 172
173 173 Dynamic object information
174 174 --------------------------
175 175
176 176 Typing ``?word`` or ``word?`` prints detailed information about an object. If
177 177 certain strings in the object are too long (e.g. function signatures) they get
178 178 snipped in the center for brevity. This system gives access variable types and
179 179 values, docstrings, function prototypes and other useful information.
180 180
181 181 If the information will not fit in the terminal, it is displayed in a pager
182 182 (``less`` if available, otherwise a basic internal pager).
183 183
184 184 Typing ``??word`` or ``word??`` gives access to the full information, including
185 185 the source code where possible. Long strings are not snipped.
186 186
187 187 The following magic functions are particularly useful for gathering
188 188 information about your working environment. You can get more details by
189 189 typing ``%magic`` or querying them individually (``%function_name?``);
190 190 this is just a summary:
191 191
192 192 * **%pdoc <object>**: Print (or run through a pager if too long) the
193 193 docstring for an object. If the given object is a class, it will
194 194 print both the class and the constructor docstrings.
195 195 * **%pdef <object>**: Print the definition header for any callable
196 196 object. If the object is a class, print the constructor information.
197 197 * **%psource <object>**: Print (or run through a pager if too long)
198 198 the source code for an object.
199 199 * **%pfile <object>**: Show the entire source file where an object was
200 200 defined via a pager, opening it at the line where the object
201 201 definition begins.
202 202 * **%who/%whos**: These functions give information about identifiers
203 203 you have defined interactively (not things you loaded or defined
204 204 in your configuration files). %who just prints a list of
205 205 identifiers and %whos prints a table with some basic details about
206 206 each identifier.
207 207
208 208 Note that the dynamic object information functions (?/??, ``%pdoc``,
209 209 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
210 210 directly on variables. For example, after doing ``import os``, you can use
211 211 ``os.path.abspath??``.
212 212
213 213 .. _readline:
214 214
215 215 Readline-based features
216 216 -----------------------
217 217
218 218 These features require the GNU readline library, so they won't work if your
219 219 Python installation lacks readline support. We will first describe the default
220 220 behavior IPython uses, and then how to change it to suit your preferences.
221 221
222 222
223 223 Command line completion
224 224 +++++++++++++++++++++++
225 225
226 226 At any time, hitting TAB will complete any available python commands or
227 227 variable names, and show you a list of the possible completions if
228 228 there's no unambiguous one. It will also complete filenames in the
229 229 current directory if no python names match what you've typed so far.
230 230
231 231
232 232 Search command history
233 233 ++++++++++++++++++++++
234 234
235 235 IPython provides two ways for searching through previous input and thus
236 236 reduce the need for repetitive typing:
237 237
238 238 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
239 239 (next,down) to search through only the history items that match
240 240 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
241 241 prompt, they just behave like normal arrow keys.
242 242 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
243 243 searches your history for lines that contain what you've typed so
244 244 far, completing as much as it can.
245 245
246 246
247 247 Persistent command history across sessions
248 248 ++++++++++++++++++++++++++++++++++++++++++
249 249
250 250 IPython will save your input history when it leaves and reload it next
251 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 253 separate histories related to various tasks: commands related to
254 254 numerical work will not be clobbered by a system shell history, for
255 255 example.
256 256
257 257
258 258 Autoindent
259 259 ++++++++++
260 260
261 261 IPython can recognize lines ending in ':' and indent the next line,
262 262 while also un-indenting automatically after 'raise' or 'return'.
263 263
264 264 This feature uses the readline library, so it will honor your
265 265 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
266 266 to). Adding the following lines to your :file:`.inputrc` file can make
267 267 indenting/unindenting more convenient (M-i indents, M-u unindents)::
268 268
269 269 $if Python
270 270 "\M-i": " "
271 271 "\M-u": "\d\d\d\d"
272 272 $endif
273 273
274 274 Note that there are 4 spaces between the quote marks after "M-i" above.
275 275
276 276 .. warning::
277 277
278 278 Setting the above indents will cause problems with unicode text entry in
279 279 the terminal.
280 280
281 281 .. warning::
282 282
283 283 Autoindent is ON by default, but it can cause problems with the pasting of
284 284 multi-line indented code (the pasted code gets re-indented on each line). A
285 285 magic function %autoindent allows you to toggle it on/off at runtime. You
286 286 can also disable it permanently on in your :file:`ipython_config.py` file
287 287 (set TerminalInteractiveShell.autoindent=False).
288 288
289 289 If you want to paste multiple lines in the terminal, it is recommended that
290 290 you use ``%paste``.
291 291
292 292
293 293 Customizing readline behavior
294 294 +++++++++++++++++++++++++++++
295 295
296 296 All these features are based on the GNU readline library, which has an
297 297 extremely customizable interface. Normally, readline is configured via a
298 298 file which defines the behavior of the library; the details of the
299 299 syntax for this can be found in the readline documentation available
300 300 with your system or on the Internet. IPython doesn't read this file (if
301 301 it exists) directly, but it does support passing to readline valid
302 302 options via a simple interface. In brief, you can customize readline by
303 303 setting the following options in your configuration file (note
304 304 that these options can not be specified at the command line):
305 305
306 306 * **readline_parse_and_bind**: this holds a list of strings to be executed
307 307 via a readline.parse_and_bind() command. The syntax for valid commands
308 308 of this kind can be found by reading the documentation for the GNU
309 309 readline library, as these commands are of the kind which readline
310 310 accepts in its configuration file.
311 311 * **readline_remove_delims**: a string of characters to be removed
312 312 from the default word-delimiters list used by readline, so that
313 313 completions may be performed on strings which contain them. Do not
314 314 change the default value unless you know what you're doing.
315 315
316 316 You will find the default values in your configuration file.
317 317
318 318
319 319 Session logging and restoring
320 320 -----------------------------
321 321
322 322 You can log all input from a session either by starting IPython with the
323 323 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
324 324 or by activating the logging at any moment with the magic function %logstart.
325 325
326 326 Log files can later be reloaded by running them as scripts and IPython
327 327 will attempt to 'replay' the log by executing all the lines in it, thus
328 328 restoring the state of a previous session. This feature is not quite
329 329 perfect, but can still be useful in many cases.
330 330
331 331 The log files can also be used as a way to have a permanent record of
332 332 any code you wrote while experimenting. Log files are regular text files
333 333 which you can later open in your favorite text editor to extract code or
334 334 to 'clean them up' before using them to replay a session.
335 335
336 336 The `%logstart` function for activating logging in mid-session is used as
337 337 follows::
338 338
339 339 %logstart [log_name [log_mode]]
340 340
341 341 If no name is given, it defaults to a file named 'ipython_log.py' in your
342 342 current working directory, in 'rotate' mode (see below).
343 343
344 344 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
345 345 history up to that point and then continues logging.
346 346
347 347 %logstart takes a second optional parameter: logging mode. This can be
348 348 one of (note that the modes are given unquoted):
349 349
350 350 * [over:] overwrite existing log_name.
351 351 * [backup:] rename (if exists) to log_name~ and start log_name.
352 352 * [append:] well, that says it.
353 353 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
354 354
355 355 The %logoff and %logon functions allow you to temporarily stop and
356 356 resume logging to a file which had previously been started with
357 357 %logstart. They will fail (with an explanation) if you try to use them
358 358 before logging has been started.
359 359
360 360 .. _system_shell_access:
361 361
362 362 System shell access
363 363 -------------------
364 364
365 365 Any input line beginning with a ! character is passed verbatim (minus
366 366 the !, of course) to the underlying operating system. For example,
367 367 typing ``!ls`` will run 'ls' in the current directory.
368 368
369 369 Manual capture of command output
370 370 --------------------------------
371 371
372 372 You can assign the result of a system command to a Python variable with the
373 373 syntax ``myfiles = !ls``. This gets machine readable output from stdout
374 374 (e.g. without colours), and splits on newlines. To explicitly get this sort of
375 375 output without assigning to a variable, use two exclamation marks (``!!ls``) or
376 376 the ``%sx`` magic command.
377 377
378 378 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
379 379 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
380 380 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
381 381 See :ref:`string_lists` for details.
382 382
383 383 IPython also allows you to expand the value of python variables when
384 384 making system calls. Wrap variables or expressions in {braces}::
385 385
386 386 In [1]: pyvar = 'Hello world'
387 387 In [2]: !echo "A python variable: {pyvar}"
388 388 A python variable: Hello world
389 389 In [3]: import math
390 390 In [4]: x = 8
391 391 In [5]: !echo {math.factorial(x)}
392 392 40320
393 393
394 394 For simple cases, you can alternatively prepend $ to a variable name::
395 395
396 396 In [6]: !echo $sys.argv
397 397 [/home/fperez/usr/bin/ipython]
398 398 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
399 399 A system variable: /home/fperez
400 400
401 401 System command aliases
402 402 ----------------------
403 403
404 404 The %alias magic function allows you to define magic functions which are in fact
405 405 system shell commands. These aliases can have parameters.
406 406
407 407 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
408 408
409 409 Then, typing ``alias_name params`` will execute the system command 'cmd
410 410 params' (from your underlying operating system).
411 411
412 412 You can also define aliases with parameters using %s specifiers (one per
413 413 parameter). The following example defines the parts function as an
414 414 alias to the command 'echo first %s second %s' where each %s will be
415 415 replaced by a positional parameter to the call to %parts::
416 416
417 417 In [1]: %alias parts echo first %s second %s
418 418 In [2]: parts A B
419 419 first A second B
420 420 In [3]: parts A
421 421 ERROR: Alias <parts> requires 2 arguments, 1 given.
422 422
423 423 If called with no parameters, %alias prints the table of currently
424 424 defined aliases.
425 425
426 426 The %rehashx magic allows you to load your entire $PATH as
427 427 ipython aliases. See its docstring for further details.
428 428
429 429
430 430 .. _dreload:
431 431
432 432 Recursive reload
433 433 ----------------
434 434
435 435 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
436 436 module: changes made to any of its dependencies will be reloaded without
437 437 having to exit. To start using it, do::
438 438
439 439 from IPython.lib.deepreload import reload as dreload
440 440
441 441
442 442 Verbose and colored exception traceback printouts
443 443 -------------------------------------------------
444 444
445 445 IPython provides the option to see very detailed exception tracebacks,
446 446 which can be especially useful when debugging large programs. You can
447 447 run any Python file with the %run function to benefit from these
448 448 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
449 449 be colored (if your terminal supports it) which makes them much easier
450 450 to parse visually.
451 451
452 452 See the magic xmode and colors functions for details (just type %magic).
453 453
454 454 These features are basically a terminal version of Ka-Ping Yee's cgitb
455 455 module, now part of the standard Python library.
456 456
457 457
458 458 .. _input_caching:
459 459
460 460 Input caching system
461 461 --------------------
462 462
463 463 IPython offers numbered prompts (In/Out) with input and output caching
464 464 (also referred to as 'input history'). All input is saved and can be
465 465 retrieved as variables (besides the usual arrow key recall), in
466 466 addition to the %rep magic command that brings a history entry
467 467 up for editing on the next command line.
468 468
469 469 The following GLOBAL variables always exist (so don't overwrite them!):
470 470
471 471 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
472 472 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
473 473 overwrite In with a variable of your own, you can remake the assignment to the
474 474 internal list with a simple ``In=_ih``.
475 475
476 476 Additionally, global variables named _i<n> are dynamically created (<n>
477 477 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
478 478
479 479 For example, what you typed at prompt 14 is available as _i14, _ih[14]
480 480 and In[14].
481 481
482 482 This allows you to easily cut and paste multi line interactive prompts
483 483 by printing them out: they print like a clean string, without prompt
484 484 characters. You can also manipulate them like regular variables (they
485 485 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
486 486 contents of input prompt 9.
487 487
488 488 You can also re-execute multiple lines of input easily by using the
489 489 magic %rerun or %macro functions. The macro system also allows you to re-execute
490 490 previous lines which include magic function calls (which require special
491 491 processing). Type %macro? for more details on the macro system.
492 492
493 493 A history function %hist allows you to see any part of your input
494 494 history by printing a range of the _i variables.
495 495
496 496 You can also search ('grep') through your history by typing
497 497 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
498 498 etc. You can bring history entries listed by '%hist -g' up for editing
499 499 with the %recall command, or run them immediately with %rerun.
500 500
501 501 .. _output_caching:
502 502
503 503 Output caching system
504 504 ---------------------
505 505
506 506 For output that is returned from actions, a system similar to the input
507 507 cache exists but using _ instead of _i. Only actions that produce a
508 508 result (NOT assignments, for example) are cached. If you are familiar
509 509 with Mathematica, IPython's _ variables behave exactly like
510 510 Mathematica's % variables.
511 511
512 512 The following GLOBAL variables always exist (so don't overwrite them!):
513 513
514 514 * [_] (a single underscore) : stores previous output, like Python's
515 515 default interpreter.
516 516 * [__] (two underscores): next previous.
517 517 * [___] (three underscores): next-next previous.
518 518
519 519 Additionally, global variables named _<n> are dynamically created (<n>
520 520 being the prompt counter), such that the result of output <n> is always
521 521 available as _<n> (don't use the angle brackets, just the number, e.g.
522 522 _21).
523 523
524 524 These variables are also stored in a global dictionary (not a
525 525 list, since it only has entries for lines which returned a result)
526 526 available under the names _oh and Out (similar to _ih and In). So the
527 527 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
528 528 accidentally overwrite the Out variable you can recover it by typing
529 529 'Out=_oh' at the prompt.
530 530
531 531 This system obviously can potentially put heavy memory demands on your
532 532 system, since it prevents Python's garbage collector from removing any
533 533 previously computed results. You can control how many results are kept
534 534 in memory with the option (at the command line or in your configuration
535 535 file) cache_size. If you set it to 0, the whole system is completely
536 536 disabled and the prompts revert to the classic '>>>' of normal Python.
537 537
538 538
539 539 Directory history
540 540 -----------------
541 541
542 542 Your history of visited directories is kept in the global list _dh, and
543 543 the magic %cd command can be used to go to any entry in that list. The
544 544 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
545 545 conveniently view the directory history.
546 546
547 547
548 548 Automatic parentheses and quotes
549 549 --------------------------------
550 550
551 551 These features were adapted from Nathan Gray's LazyPython. They are
552 552 meant to allow less typing for common situations.
553 553
554 554
555 555 Automatic parentheses
556 556 +++++++++++++++++++++
557 557
558 558 Callable objects (i.e. functions, methods, etc) can be invoked like this
559 559 (notice the commas between the arguments)::
560 560
561 561 In [1]: callable_ob arg1, arg2, arg3
562 562 ------> callable_ob(arg1, arg2, arg3)
563 563
564 564 You can force automatic parentheses by using '/' as the first character
565 565 of a line. For example::
566 566
567 567 In [2]: /globals # becomes 'globals()'
568 568
569 569 Note that the '/' MUST be the first character on the line! This won't work::
570 570
571 571 In [3]: print /globals # syntax error
572 572
573 573 In most cases the automatic algorithm should work, so you should rarely
574 574 need to explicitly invoke /. One notable exception is if you are trying
575 575 to call a function with a list of tuples as arguments (the parenthesis
576 576 will confuse IPython)::
577 577
578 578 In [4]: zip (1,2,3),(4,5,6) # won't work
579 579
580 580 but this will work::
581 581
582 582 In [5]: /zip (1,2,3),(4,5,6)
583 583 ------> zip ((1,2,3),(4,5,6))
584 584 Out[5]: [(1, 4), (2, 5), (3, 6)]
585 585
586 586 IPython tells you that it has altered your command line by displaying
587 587 the new command line preceded by ->. e.g.::
588 588
589 589 In [6]: callable list
590 590 ------> callable(list)
591 591
592 592
593 593 Automatic quoting
594 594 +++++++++++++++++
595 595
596 596 You can force automatic quoting of a function's arguments by using ','
597 597 or ';' as the first character of a line. For example::
598 598
599 599 In [1]: ,my_function /home/me # becomes my_function("/home/me")
600 600
601 601 If you use ';' the whole argument is quoted as a single string, while ',' splits
602 602 on whitespace::
603 603
604 604 In [2]: ,my_function a b c # becomes my_function("a","b","c")
605 605
606 606 In [3]: ;my_function a b c # becomes my_function("a b c")
607 607
608 608 Note that the ',' or ';' MUST be the first character on the line! This
609 609 won't work::
610 610
611 611 In [4]: x = ,my_function /home/me # syntax error
612 612
613 613 IPython as your default Python environment
614 614 ==========================================
615 615
616 616 Python honors the environment variable PYTHONSTARTUP and will execute at
617 617 startup the file referenced by this variable. If you put the following code at
618 618 the end of that file, then IPython will be your working environment anytime you
619 619 start Python::
620 620
621 621 from IPython.frontend.terminal.ipapp import launch_new_instance
622 622 launch_new_instance()
623 623 raise SystemExit
624 624
625 625 The ``raise SystemExit`` is needed to exit Python when
626 626 it finishes, otherwise you'll be back at the normal Python '>>>'
627 627 prompt.
628 628
629 629 This is probably useful to developers who manage multiple Python
630 630 versions and don't want to have correspondingly multiple IPython
631 631 versions. Note that in this mode, there is no way to pass IPython any
632 632 command-line options, as those are trapped first by Python itself.
633 633
634 634 .. _Embedding:
635 635
636 636 Embedding IPython
637 637 =================
638 638
639 639 It is possible to start an IPython instance inside your own Python
640 640 programs. This allows you to evaluate dynamically the state of your
641 641 code, operate with your variables, analyze them, etc. Note however that
642 642 any changes you make to values while in the shell do not propagate back
643 643 to the running code, so it is safe to modify your values because you
644 644 won't break your code in bizarre ways by doing so.
645 645
646 646 .. note::
647 647
648 648 At present, trying to embed IPython from inside IPython causes problems. Run
649 649 the code samples below outside IPython.
650 650
651 651 This feature allows you to easily have a fully functional python
652 652 environment for doing object introspection anywhere in your code with a
653 653 simple function call. In some cases a simple print statement is enough,
654 654 but if you need to do more detailed analysis of a code fragment this
655 655 feature can be very valuable.
656 656
657 657 It can also be useful in scientific computing situations where it is
658 658 common to need to do some automatic, computationally intensive part and
659 659 then stop to look at data, plots, etc.
660 660 Opening an IPython instance will give you full access to your data and
661 661 functions, and you can resume program execution once you are done with
662 662 the interactive part (perhaps to stop again later, as many times as
663 663 needed).
664 664
665 665 The following code snippet is the bare minimum you need to include in
666 666 your Python programs for this to work (detailed examples follow later)::
667 667
668 668 from IPython import embed
669 669
670 670 embed() # this call anywhere in your program will start IPython
671 671
672 672 .. note::
673 673
674 674 As of 0.13, you can embed an IPython *kernel*, for use with qtconsole,
675 675 etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``.
676 676 It should function just the same as regular embed, but you connect
677 677 an external frontend rather than IPython starting up in the local
678 678 terminal.
679 679
680 680 You can run embedded instances even in code which is itself being run at
681 681 the IPython interactive prompt with '%run <filename>'. Since it's easy
682 682 to get lost as to where you are (in your top-level IPython or in your
683 683 embedded one), it's a good idea in such cases to set the in/out prompts
684 684 to something different for the embedded instances. The code examples
685 685 below illustrate this.
686 686
687 687 You can also have multiple IPython instances in your program and open
688 688 them separately, for example with different options for data
689 689 presentation. If you close and open the same instance multiple times,
690 690 its prompt counters simply continue from each execution to the next.
691 691
692 692 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
693 693 module for more details on the use of this system.
694 694
695 695 The following sample file illustrating how to use the embedding
696 696 functionality is provided in the examples directory as example-embed.py.
697 697 It should be fairly self-explanatory:
698 698
699 699 .. literalinclude:: ../../examples/core/example-embed.py
700 700 :language: python
701 701
702 702 Once you understand how the system functions, you can use the following
703 703 code fragments in your programs which are ready for cut and paste:
704 704
705 705 .. literalinclude:: ../../examples/core/example-embed-short.py
706 706 :language: python
707 707
708 708 Using the Python debugger (pdb)
709 709 ===============================
710 710
711 711 Running entire programs via pdb
712 712 -------------------------------
713 713
714 714 pdb, the Python debugger, is a powerful interactive debugger which
715 715 allows you to step through code, set breakpoints, watch variables,
716 716 etc. IPython makes it very easy to start any script under the control
717 717 of pdb, regardless of whether you have wrapped it into a 'main()'
718 718 function or not. For this, simply type '%run -d myscript' at an
719 719 IPython prompt. See the %run command's documentation (via '%run?' or
720 720 in Sec. magic_ for more details, including how to control where pdb
721 721 will stop execution first.
722 722
723 723 For more information on the use of the pdb debugger, read the included
724 724 pdb.doc file (part of the standard Python distribution). On a stock
725 725 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
726 726 easiest way to read it is by using the help() function of the pdb module
727 727 as follows (in an IPython prompt)::
728 728
729 729 In [1]: import pdb
730 730 In [2]: pdb.help()
731 731
732 732 This will load the pdb.doc document in a file viewer for you automatically.
733 733
734 734
735 735 Automatic invocation of pdb on exceptions
736 736 -----------------------------------------
737 737
738 738 IPython, if started with the ``--pdb`` option (or if the option is set in
739 739 your config file) can call the Python pdb debugger every time your code
740 740 triggers an uncaught exception. This feature
741 741 can also be toggled at any time with the %pdb magic command. This can be
742 742 extremely useful in order to find the origin of subtle bugs, because pdb
743 743 opens up at the point in your code which triggered the exception, and
744 744 while your program is at this point 'dead', all the data is still
745 745 available and you can walk up and down the stack frame and understand
746 746 the origin of the problem.
747 747
748 748 Furthermore, you can use these debugging facilities both with the
749 749 embedded IPython mode and without IPython at all. For an embedded shell
750 750 (see sec. Embedding_), simply call the constructor with
751 751 ``--pdb`` in the argument string and pdb will automatically be called if an
752 752 uncaught exception is triggered by your code.
753 753
754 754 For stand-alone use of the feature in your programs which do not use
755 755 IPython at all, put the following lines toward the top of your 'main'
756 756 routine::
757 757
758 758 import sys
759 759 from IPython.core import ultratb
760 760 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
761 761 color_scheme='Linux', call_pdb=1)
762 762
763 763 The mode keyword can be either 'Verbose' or 'Plain', giving either very
764 764 detailed or normal tracebacks respectively. The color_scheme keyword can
765 765 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
766 766 options which can be set in IPython with ``--colors`` and ``--xmode``.
767 767
768 768 This will give any of your programs detailed, colored tracebacks with
769 769 automatic invocation of pdb.
770 770
771 771
772 772 Extensions for syntax processing
773 773 ================================
774 774
775 775 This isn't for the faint of heart, because the potential for breaking
776 776 things is quite high. But it can be a very powerful and useful feature.
777 777 In a nutshell, you can redefine the way IPython processes the user input
778 778 line to accept new, special extensions to the syntax without needing to
779 779 change any of IPython's own code.
780 780
781 781 In the IPython/extensions directory you will find some examples
782 782 supplied, which we will briefly describe now. These can be used 'as is'
783 783 (and both provide very useful functionality), or you can use them as a
784 784 starting point for writing your own extensions.
785 785
786 786 .. _pasting_with_prompts:
787 787
788 788 Pasting of code starting with Python or IPython prompts
789 789 -------------------------------------------------------
790 790
791 791 IPython is smart enough to filter out input prompts, be they plain Python ones
792 792 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and `` ...:``). You can
793 793 therefore copy and paste from existing interactive sessions without worry.
794 794
795 795 The following is a 'screenshot' of how things work, copying an example from the
796 796 standard Python tutorial::
797 797
798 798 In [1]: >>> # Fibonacci series:
799 799
800 800 In [2]: ... # the sum of two elements defines the next
801 801
802 802 In [3]: ... a, b = 0, 1
803 803
804 804 In [4]: >>> while b < 10:
805 805 ...: ... print b
806 806 ...: ... a, b = b, a+b
807 807 ...:
808 808 1
809 809 1
810 810 2
811 811 3
812 812 5
813 813 8
814 814
815 815 And pasting from IPython sessions works equally well::
816 816
817 817 In [1]: In [5]: def f(x):
818 818 ...: ...: "A simple function"
819 819 ...: ...: return x**2
820 820 ...: ...:
821 821
822 822 In [2]: f(3)
823 823 Out[2]: 9
824 824
825 825 .. _gui_support:
826 826
827 827 GUI event loop support
828 828 ======================
829 829
830 830 .. versionadded:: 0.11
831 831 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
832 832
833 833 IPython has excellent support for working interactively with Graphical User
834 834 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
835 835 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
836 836 is extremely robust compared to our previous thread-based version. The
837 837 advantages of this are:
838 838
839 839 * GUIs can be enabled and disabled dynamically at runtime.
840 840 * The active GUI can be switched dynamically at runtime.
841 841 * In some cases, multiple GUIs can run simultaneously with no problems.
842 842 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
843 843 all of these things.
844 844
845 845 For users, enabling GUI event loop integration is simple. You simple use the
846 846 ``%gui`` magic as follows::
847 847
848 848 %gui [GUINAME]
849 849
850 850 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
851 851 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
852 852
853 853 Thus, to use wxPython interactively and create a running :class:`wx.App`
854 854 object, do::
855 855
856 856 %gui wx
857 857
858 858 For information on IPython's Matplotlib integration (and the ``pylab`` mode)
859 859 see :ref:`this section <matplotlib_support>`.
860 860
861 861 For developers that want to use IPython's GUI event loop integration in the
862 862 form of a library, these capabilities are exposed in library form in the
863 863 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
864 864 Interested developers should see the module docstrings for more information,
865 865 but there are a few points that should be mentioned here.
866 866
867 867 First, the ``PyOSInputHook`` approach only works in command line settings
868 868 where readline is activated. The integration with various eventloops
869 869 is handled somewhat differently (and more simply) when using the standalone
870 870 kernel, as in the qtconsole and notebook.
871 871
872 872 Second, when using the ``PyOSInputHook`` approach, a GUI application should
873 873 *not* start its event loop. Instead all of this is handled by the
874 874 ``PyOSInputHook``. This means that applications that are meant to be used both
875 875 in IPython and as standalone apps need to have special code to detects how the
876 876 application is being run. We highly recommend using IPython's support for this.
877 877 Since the details vary slightly between toolkits, we point you to the various
878 878 examples in our source directory :file:`docs/examples/lib` that demonstrate
879 879 these capabilities.
880 880
881 881 Third, unlike previous versions of IPython, we no longer "hijack" (replace
882 882 them with no-ops) the event loops. This is done to allow applications that
883 883 actually need to run the real event loops to do so. This is often needed to
884 884 process pending events at critical points.
885 885
886 886 Finally, we also have a number of examples in our source directory
887 887 :file:`docs/examples/lib` that demonstrate these capabilities.
888 888
889 889 PyQt and PySide
890 890 ---------------
891 891
892 892 .. attempt at explanation of the complete mess that is Qt support
893 893
894 894 When you use ``--gui=qt`` or ``--pylab=qt``, IPython can work with either
895 895 PyQt4 or PySide. There are three options for configuration here, because
896 896 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
897 897 Python 2, and the more natural v2, which is the only API supported by PySide.
898 898 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
899 899 uses v2, but you can still use any interface in your code, since the
900 900 Qt frontend is in a different process.
901 901
902 902 The default will be to import PyQt4 without configuration of the APIs, thus
903 903 matching what most applications would expect. It will fall back of PySide if
904 904 PyQt4 is unavailable.
905 905
906 906 If specified, IPython will respect the environment variable ``QT_API`` used
907 907 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
908 908 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
909 909 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
910 910 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
911 911
912 912 If you launch IPython in pylab mode with ``ipython --pylab=qt``, then IPython
913 913 will ask matplotlib which Qt library to use (only if QT_API is *not set*), via
914 914 the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or older, then
915 915 IPython will always use PyQt4 without setting the v2 APIs, since neither v2
916 916 PyQt nor PySide work.
917 917
918 918 .. warning::
919 919
920 920 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
921 921 to work with IPython's qt integration, because otherwise PyQt4 will be
922 922 loaded in an incompatible mode.
923 923
924 924 It also means that you must *not* have ``QT_API`` set if you want to
925 925 use ``--gui=qt`` with code that requires PyQt4 API v1.
926 926
927 927
928 928 .. _matplotlib_support:
929 929
930 930 Plotting with matplotlib
931 931 ========================
932 932
933 933 `Matplotlib`_ provides high quality 2D and 3D plotting for Python. Matplotlib
934 934 can produce plots on screen using a variety of GUI toolkits, including Tk,
935 935 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
936 936 scientific computing, all with a syntax compatible with that of the popular
937 937 Matlab program.
938 938
939 939 To start IPython with matplotlib support, use the ``--pylab`` switch. If no
940 940 arguments are given, IPython will automatically detect your choice of
941 941 matplotlib backend. You can also request a specific backend with ``--pylab
942 942 backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx', 'gtk', 'osx'.
943 943 In the web notebook and Qt console, 'inline' is also a valid backend value,
944 944 which produces static figures inlined inside the application window instead of
945 945 matplotlib's interactive figures that live in separate windows.
946 946
947 947 .. _Matplotlib: http://matplotlib.sourceforge.net
948 948
949 949 .. _interactive_demos:
950 950
951 951 Interactive demos with IPython
952 952 ==============================
953 953
954 954 IPython ships with a basic system for running scripts interactively in
955 955 sections, useful when presenting code to audiences. A few tags embedded
956 956 in comments (so that the script remains valid Python code) divide a file
957 957 into separate blocks, and the demo can be run one block at a time, with
958 958 IPython printing (with syntax highlighting) the block before executing
959 959 it, and returning to the interactive prompt after each block. The
960 960 interactive namespace is updated after each block is run with the
961 961 contents of the demo's namespace.
962 962
963 963 This allows you to show a piece of code, run it and then execute
964 964 interactively commands based on the variables just created. Once you
965 965 want to continue, you simply execute the next block of the demo. The
966 966 following listing shows the markup necessary for dividing a script into
967 967 sections for execution as a demo:
968 968
969 969 .. literalinclude:: ../../examples/lib/example-demo.py
970 970 :language: python
971 971
972 972 In order to run a file as a demo, you must first make a Demo object out
973 973 of it. If the file is named myscript.py, the following code will make a
974 974 demo::
975 975
976 976 from IPython.lib.demo import Demo
977 977
978 978 mydemo = Demo('myscript.py')
979 979
980 980 This creates the mydemo object, whose blocks you run one at a time by
981 981 simply calling the object with no arguments. If you have autocall active
982 982 in IPython (the default), all you need to do is type::
983 983
984 984 mydemo
985 985
986 986 and IPython will call it, executing each block. Demo objects can be
987 987 restarted, you can move forward or back skipping blocks, re-execute the
988 988 last block, etc. Simply use the Tab key on a demo object to see its
989 989 methods, and call '?' on them to see their docstrings for more usage
990 990 details. In addition, the demo module itself contains a comprehensive
991 991 docstring, which you can access via::
992 992
993 993 from IPython.lib import demo
994 994
995 995 demo?
996 996
997 997 Limitations: It is important to note that these demos are limited to
998 998 fairly simple uses. In particular, you cannot break up sections within
999 999 indented code (loops, if statements, function definitions, etc.)
1000 1000 Supporting something like this would basically require tracking the
1001 1001 internal execution state of the Python interpreter, so only top-level
1002 1002 divisions are allowed. If you want to be able to open an IPython
1003 1003 instance at an arbitrary point in a program, you can use IPython's
1004 1004 embedding facilities, see :func:`IPython.embed` for details.
1005 1005
@@ -1,294 +1,294 b''
1 1 .. _ipython_as_shell:
2 2
3 3 =========================
4 4 IPython as a system shell
5 5 =========================
6 6
7 7 .. warning::
8 8
9 9 As of the 0.11 version of IPython, most of the APIs used by the shell
10 10 profile have been changed, so the profile currently does very little
11 11 beyond changing the IPython prompt. To help restore the shell
12 12 profile to past functionality described here, the old code is found in
13 13 :file:`IPython/deathrow`, which needs to be updated to use the
14 14 APIs in 0.11.
15 15
16 16 Overview
17 17 ========
18 18
19 19 The 'sh' profile optimizes IPython for system shell usage. Apart from
20 20 certain job control functionality that is present in unix (ctrl+z does
21 21 "suspend"), the sh profile should provide you with most of the
22 22 functionality you use daily in system shell, and more. Invoke IPython
23 23 in 'sh' profile by doing 'ipython -p sh', or (in win32) by launching
24 24 the "pysh" shortcut in start menu.
25 25
26 26 If you want to use the features of sh profile as your defaults (which
27 27 might be a good idea if you use other profiles a lot of the time but
28 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 31 The 'sh' profile is different from the default profile in that:
32 32
33 33 * Prompt shows the current directory
34 34 * Spacing between prompts and input is more compact (no padding with
35 35 empty lines). The startup banner is more compact as well.
36 36 * System commands are directly available (in alias table) without
37 37 requesting %rehashx - however, if you install new programs along
38 38 your PATH, you might want to run %rehashx to update the persistent
39 39 alias table
40 40 * Macros are stored in raw format by default. That is, instead of
41 41 '_ip.system("cat foo"), the macro will contain text 'cat foo')
42 42 * Autocall is in full mode
43 43 * Calling "up" does "cd .."
44 44
45 45 The 'sh' profile is different from the now-obsolete (and unavailable)
46 46 'pysh' profile in that the ``$$var = command`` and ``$var = command`` syntax is
47 47 not supported anymore. Use ``var = !command`` instead (which is available in all
48 48 IPython profiles).
49 49
50 50 Aliases
51 51 =======
52 52
53 53 All of your $PATH has been loaded as IPython aliases, so you should be
54 54 able to type any normal system command and have it executed. See
55 55 %alias? and %unalias? for details on the alias facilities. See also
56 56 %rehashx? for details on the mechanism used to load $PATH.
57 57
58 58
59 59 Directory management
60 60 ====================
61 61
62 62 Since each command passed by ipython to the underlying system is executed
63 63 in a subshell which exits immediately, you can NOT use !cd to navigate
64 64 the filesystem.
65 65
66 66 IPython provides its own builtin '%cd' magic command to move in the
67 67 filesystem (the % is not required with automagic on). It also maintains
68 68 a list of visited directories (use %dhist to see it) and allows direct
69 69 switching to any of them. Type 'cd?' for more details.
70 70
71 71 %pushd, %popd and %dirs are provided for directory stack handling.
72 72
73 73
74 74 Enabled extensions
75 75 ==================
76 76
77 77 Some extensions, listed below, are enabled as default in this profile.
78 78
79 79 envpersist
80 80 ----------
81 81
82 82 %env can be used to "remember" environment variable manipulations. Examples::
83 83
84 84 %env - Show all environment variables
85 85 %env VISUAL=jed - set VISUAL to jed
86 86 %env PATH+=;/foo - append ;foo to PATH
87 87 %env PATH+=;/bar - also append ;bar to PATH
88 88 %env PATH-=/wbin; - prepend /wbin; to PATH
89 89 %env -d VISUAL - forget VISUAL persistent val
90 90 %env -p - print all persistent env modifications
91 91
92 92 ipy_which
93 93 ---------
94 94
95 95 %which magic command. Like 'which' in unix, but knows about ipython aliases.
96 96
97 97 Example::
98 98
99 99 [C:/ipython]|14> %which st
100 100 st -> start .
101 101 [C:/ipython]|15> %which d
102 102 d -> dir /w /og /on
103 103 [C:/ipython]|16> %which cp
104 104 cp -> cp
105 105 == c:\bin\cp.exe
106 106 c:\bin\cp.exe
107 107
108 108 ipy_app_completers
109 109 ------------------
110 110
111 111 Custom tab completers for some apps like svn, hg, bzr, apt-get. Try 'apt-get install <TAB>' in debian/ubuntu.
112 112
113 113 ipy_rehashdir
114 114 -------------
115 115
116 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 118 [~]|22> cd c:/opt/PuTTY/
119 119 [c:opt/PuTTY]|23> rehashdir .
120 120 <23> ['pageant', 'plink', 'pscp', 'psftp', 'putty', 'puttygen', 'unins000']
121 121
122 122 Now, you can execute any of those commams directly::
123 123
124 124 [c:opt/PuTTY]|24> cd
125 125 [~]|25> putty
126 126
127 127 (the putty window opens).
128 128
129 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 131 [~]|27> for a in _23:
132 132 |..> %store $a
133 133 |..>
134 134 |..>
135 135 Alias stored: pageant (0, 'c:\\opt\\PuTTY\\pageant.exe')
136 136 Alias stored: plink (0, 'c:\\opt\\PuTTY\\plink.exe')
137 137 Alias stored: pscp (0, 'c:\\opt\\PuTTY\\pscp.exe')
138 138 Alias stored: psftp (0, 'c:\\opt\\PuTTY\\psftp.exe')
139 139 ...
140 140
141 141 mglob
142 142 -----
143 143
144 144 Provide the magic function %mglob, which makes it easier (than the 'find' command) to collect (possibly recursive) file lists. Examples::
145 145
146 146 [c:/ipython]|9> mglob *.py
147 147 [c:/ipython]|10> mglob *.py rec:*.txt
148 148 [c:/ipython]|19> workfiles = %mglob !.svn/ !.hg/ !*_Data/ !*.bak rec:.
149 149
150 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 153 Prompt customization
154 154 ====================
155 155
156 156 The sh profile uses the following prompt configurations::
157 157
158 158 c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> '
159 159 c.PromptManager.in2_template = r'{color.Green}|{color.LightGreen}\D{color.Green}> '
160 160 c.PromptManager.out_template = r'<\#> '
161 161
162 162 You can change the prompt configuration to your liking by editing
163 163 ipython_config.py.
164 164
165 165 .. _string_lists:
166 166
167 167 String lists
168 168 ============
169 169
170 170 String lists (IPython.utils.text.SList) are handy way to process output
171 171 from system commands. They are produced by ``var = !cmd`` syntax.
172 172
173 173 First, we acquire the output of 'ls -l'::
174 174
175 175 [Q:doc/examples]|2> lines = !ls -l
176 176 ==
177 177 ['total 23',
178 178 '-rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py',
179 179 '-rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py',
180 180 '-rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py',
181 181 '-rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py',
182 182 '-rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py',
183 183 '-rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py',
184 184 '-rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc']
185 185
186 186 Now, let's take a look at the contents of 'lines' (the first number is
187 187 the list element number)::
188 188
189 189 [Q:doc/examples]|3> lines
190 190 <3> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
191 191
192 192 0: total 23
193 193 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
194 194 2: -rw-rw-rw- 1 ville None 1927 Sep 30 2006 example-embed-short.py
195 195 3: -rwxrwxrwx 1 ville None 4606 Sep 1 17:15 example-embed.py
196 196 4: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
197 197 5: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
198 198 6: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
199 199 7: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
200 200
201 201 Now, let's filter out the 'embed' lines::
202 202
203 203 [Q:doc/examples]|4> l2 = lines.grep('embed',prune=1)
204 204 [Q:doc/examples]|5> l2
205 205 <5> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
206 206
207 207 0: total 23
208 208 1: -rw-rw-rw- 1 ville None 1163 Sep 30 2006 example-demo.py
209 209 2: -rwxrwxrwx 1 ville None 1017 Sep 30 2006 example-gnuplot.py
210 210 3: -rwxrwxrwx 1 ville None 339 Jun 11 18:01 extension.py
211 211 4: -rwxrwxrwx 1 ville None 113 Dec 20 2006 seteditor.py
212 212 5: -rwxrwxrwx 1 ville None 245 Dec 12 2006 seteditor.pyc
213 213
214 214 Now, we want strings having just file names and permissions::
215 215
216 216 [Q:doc/examples]|6> l2.fields(8,0)
217 217 <6> SList (.p, .n, .l, .s, .grep(), .fields() available). Value:
218 218
219 219 0: total
220 220 1: example-demo.py -rw-rw-rw-
221 221 2: example-gnuplot.py -rwxrwxrwx
222 222 3: extension.py -rwxrwxrwx
223 223 4: seteditor.py -rwxrwxrwx
224 224 5: seteditor.pyc -rwxrwxrwx
225 225
226 226 Note how the line with 'total' does not raise IndexError.
227 227
228 228 If you want to split these (yielding lists), call fields() without
229 229 arguments::
230 230
231 231 [Q:doc/examples]|7> _.fields()
232 232 <7>
233 233 [['total'],
234 234 ['example-demo.py', '-rw-rw-rw-'],
235 235 ['example-gnuplot.py', '-rwxrwxrwx'],
236 236 ['extension.py', '-rwxrwxrwx'],
237 237 ['seteditor.py', '-rwxrwxrwx'],
238 238 ['seteditor.pyc', '-rwxrwxrwx']]
239 239
240 240 If you want to pass these separated with spaces to a command (typical
241 241 for lists if files), use the .s property::
242 242
243 243
244 244 [Q:doc/examples]|13> files = l2.fields(8).s
245 245 [Q:doc/examples]|14> files
246 246 <14> 'example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc'
247 247 [Q:doc/examples]|15> ls $files
248 248 example-demo.py example-gnuplot.py extension.py seteditor.py seteditor.pyc
249 249
250 250 SLists are inherited from normal python lists, so every list method is
251 251 available::
252 252
253 253 [Q:doc/examples]|21> lines.append('hey')
254 254
255 255
256 256 Real world example: remove all files outside version control
257 257 ------------------------------------------------------------
258 258
259 259 First, capture output of "hg status"::
260 260
261 261 [Q:/ipython]|28> out = !hg status
262 262 ==
263 263 ['M IPython\\extensions\\ipy_kitcfg.py',
264 264 'M IPython\\extensions\\ipy_rehashdir.py',
265 265 ...
266 266 '? build\\lib\\IPython\\Debugger.py',
267 267 '? build\\lib\\IPython\\extensions\\InterpreterExec.py',
268 268 '? build\\lib\\IPython\\extensions\\InterpreterPasteInput.py',
269 269 ...
270 270
271 271 (lines starting with ? are not under version control).
272 272
273 273 ::
274 274
275 275 [Q:/ipython]|35> junk = out.grep(r'^\?').fields(1)
276 276 [Q:/ipython]|36> junk
277 277 <36> SList (.p, .n, .l, .s, .grep(), .fields() availab
278 278 ...
279 279 10: build\bdist.win32\winexe\temp\_ctypes.py
280 280 11: build\bdist.win32\winexe\temp\_hashlib.py
281 281 12: build\bdist.win32\winexe\temp\_socket.py
282 282
283 283 Now we can just remove these files by doing 'rm $junk.s'.
284 284
285 285 The .s, .n, .p properties
286 286 -------------------------
287 287
288 288 The ``.s`` property returns one string where lines are separated by
289 289 single space (for convenient passing to system commands). The ``.n``
290 290 property return one string where the lines are separated by a newline
291 291 (i.e. the original output of the function). If the items in string
292 292 list are file names, ``.p`` can be used to get a list of "path" objects
293 293 for convenient file manipulation.
294 294
@@ -1,865 +1,865 b''
1 1 .. _parallel_multiengine:
2 2
3 3 ==========================
4 4 IPython's Direct interface
5 5 ==========================
6 6
7 7 The direct, or multiengine, interface represents one possible way of working with a set of
8 8 IPython engines. The basic idea behind the multiengine interface is that the
9 9 capabilities of each engine are directly and explicitly exposed to the user.
10 10 Thus, in the multiengine interface, each engine is given an id that is used to
11 11 identify the engine and give it work to do. This interface is very intuitive
12 12 and is designed with interactive usage in mind, and is the best place for
13 13 new users of IPython to begin.
14 14
15 15 Starting the IPython controller and engines
16 16 ===========================================
17 17
18 18 To follow along with this tutorial, you will need to start the IPython
19 19 controller and four IPython engines. The simplest way of doing this is to use
20 20 the :command:`ipcluster` command::
21 21
22 22 $ ipcluster start -n 4
23 23
24 24 For more detailed information about starting the controller and engines, see
25 25 our :ref:`introduction <parallel_overview>` to using IPython for parallel computing.
26 26
27 27 Creating a ``DirectView`` instance
28 28 ==================================
29 29
30 30 The first step is to import the IPython :mod:`IPython.parallel`
31 31 module and then create a :class:`.Client` instance:
32 32
33 33 .. sourcecode:: ipython
34 34
35 35 In [1]: from IPython.parallel import Client
36 36
37 37 In [2]: rc = Client()
38 38
39 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 41 accurate. If the controller was started on a remote machine, you must copy that connection
42 42 file to the client machine, or enter its contents as arguments to the Client constructor:
43 43
44 44 .. sourcecode:: ipython
45 45
46 46 # If you have copied the json connector file from the controller:
47 47 In [2]: rc = Client('/path/to/ipcontroller-client.json')
48 48 # or to connect with a specific profile you have set up:
49 49 In [3]: rc = Client(profile='mpi')
50 50
51 51
52 52 To make sure there are engines connected to the controller, users can get a list
53 53 of engine ids:
54 54
55 55 .. sourcecode:: ipython
56 56
57 57 In [3]: rc.ids
58 58 Out[3]: [0, 1, 2, 3]
59 59
60 60 Here we see that there are four engines ready to do work for us.
61 61
62 62 For direct execution, we will make use of a :class:`DirectView` object, which can be
63 63 constructed via list-access to the client:
64 64
65 65 .. sourcecode:: ipython
66 66
67 67 In [4]: dview = rc[:] # use all engines
68 68
69 69 .. seealso::
70 70
71 71 For more information, see the in-depth explanation of :ref:`Views <parallel_details>`.
72 72
73 73
74 74 Quick and easy parallelism
75 75 ==========================
76 76
77 77 In many cases, you simply want to apply a Python function to a sequence of
78 78 objects, but *in parallel*. The client interface provides a simple way
79 79 of accomplishing this: using the DirectView's :meth:`~DirectView.map` method.
80 80
81 81 Parallel map
82 82 ------------
83 83
84 84 Python's builtin :func:`map` functions allows a function to be applied to a
85 85 sequence element-by-element. This type of code is typically trivial to
86 86 parallelize. In fact, since IPython's interface is all about functions anyway,
87 87 you can just use the builtin :func:`map` with a :class:`RemoteFunction`, or a
88 88 DirectView's :meth:`map` method:
89 89
90 90 .. sourcecode:: ipython
91 91
92 92 In [62]: serial_result = map(lambda x:x**10, range(32))
93 93
94 94 In [63]: parallel_result = dview.map_sync(lambda x: x**10, range(32))
95 95
96 96 In [67]: serial_result==parallel_result
97 97 Out[67]: True
98 98
99 99
100 100 .. note::
101 101
102 102 The :class:`DirectView`'s version of :meth:`map` does
103 103 not do dynamic load balancing. For a load balanced version, use a
104 104 :class:`LoadBalancedView`.
105 105
106 106 .. seealso::
107 107
108 108 :meth:`map` is implemented via :class:`ParallelFunction`.
109 109
110 110 Remote function decorators
111 111 --------------------------
112 112
113 113 Remote functions are just like normal functions, but when they are called,
114 114 they execute on one or more engines, rather than locally. IPython provides
115 115 two decorators:
116 116
117 117 .. sourcecode:: ipython
118 118
119 119 In [10]: @dview.remote(block=True)
120 120 ....: def getpid():
121 121 ....: import os
122 122 ....: return os.getpid()
123 123 ....:
124 124
125 125 In [11]: getpid()
126 126 Out[11]: [12345, 12346, 12347, 12348]
127 127
128 128 The ``@parallel`` decorator creates parallel functions, that break up an element-wise
129 129 operations and distribute them, reconstructing the result.
130 130
131 131 .. sourcecode:: ipython
132 132
133 133 In [12]: import numpy as np
134 134
135 135 In [13]: A = np.random.random((64,48))
136 136
137 137 In [14]: @dview.parallel(block=True)
138 138 ....: def pmul(A,B):
139 139 ....: return A*B
140 140
141 141 In [15]: C_local = A*A
142 142
143 143 In [16]: C_remote = pmul(A,A)
144 144
145 145 In [17]: (C_local == C_remote).all()
146 146 Out[17]: True
147 147
148 148 Calling a ``@parallel`` function *does not* correspond to map. It is used for splitting
149 149 element-wise operations that operate on a sequence or array. For ``map`` behavior,
150 150 parallel functions do have a map method.
151 151
152 152 ==================== ============================ =============================
153 153 call pfunc(seq) pfunc.map(seq)
154 154 ==================== ============================ =============================
155 155 # of tasks # of engines (1 per engine) # of engines (1 per engine)
156 156 # of remote calls # of engines (1 per engine) ``len(seq)``
157 157 argument to remote ``seq[i:j]`` (sub-sequence) ``seq[i]`` (single element)
158 158 ==================== ============================ =============================
159 159
160 160 A quick example to illustrate the difference in arguments for the two modes:
161 161
162 162 .. sourcecode:: ipython
163 163
164 164 In [16]: @dview.parallel(block=True)
165 165 ....: def echo(x):
166 166 ....: return str(x)
167 167 ....:
168 168
169 169 In [17]: echo(range(5))
170 170 Out[17]: ['[0, 1]', '[2]', '[3]', '[4]']
171 171
172 172 In [18]: echo.map(range(5))
173 173 Out[18]: ['0', '1', '2', '3', '4']
174 174
175 175
176 176 .. seealso::
177 177
178 178 See the :func:`~.remotefunction.parallel` and :func:`~.remotefunction.remote`
179 179 decorators for options.
180 180
181 181 Calling Python functions
182 182 ========================
183 183
184 184 The most basic type of operation that can be performed on the engines is to
185 185 execute Python code or call Python functions. Executing Python code can be
186 186 done in blocking or non-blocking mode (non-blocking is default) using the
187 187 :meth:`.View.execute` method, and calling functions can be done via the
188 188 :meth:`.View.apply` method.
189 189
190 190 apply
191 191 -----
192 192
193 193 The main method for doing remote execution (in fact, all methods that
194 194 communicate with the engines are built on top of it), is :meth:`View.apply`.
195 195
196 196 We strive to provide the cleanest interface we can, so `apply` has the following
197 197 signature:
198 198
199 199 .. sourcecode:: python
200 200
201 201 view.apply(f, *args, **kwargs)
202 202
203 203 There are various ways to call functions with IPython, and these flags are set as
204 204 attributes of the View. The ``DirectView`` has just two of these flags:
205 205
206 206 dv.block : bool
207 207 whether to wait for the result, or return an :class:`AsyncResult` object
208 208 immediately
209 209 dv.track : bool
210 210 whether to instruct pyzmq to track when zeromq is done sending the message.
211 211 This is primarily useful for non-copying sends of numpy arrays that you plan to
212 212 edit in-place. You need to know when it becomes safe to edit the buffer
213 213 without corrupting the message.
214 214 dv.targets : int, list of ints
215 215 which targets this view is associated with.
216 216
217 217
218 218 Creating a view is simple: index-access on a client creates a :class:`.DirectView`.
219 219
220 220 .. sourcecode:: ipython
221 221
222 222 In [4]: view = rc[1:3]
223 223 Out[4]: <DirectView [1, 2]>
224 224
225 225 In [5]: view.apply<tab>
226 226 view.apply view.apply_async view.apply_sync
227 227
228 228 For convenience, you can set block temporarily for a single call with the extra sync/async methods.
229 229
230 230 Blocking execution
231 231 ------------------
232 232
233 233 In blocking mode, the :class:`.DirectView` object (called ``dview`` in
234 234 these examples) submits the command to the controller, which places the
235 235 command in the engines' queues for execution. The :meth:`apply` call then
236 236 blocks until the engines are done executing the command:
237 237
238 238 .. sourcecode:: ipython
239 239
240 240 In [2]: dview = rc[:] # A DirectView of all engines
241 241 In [3]: dview.block=True
242 242 In [4]: dview['a'] = 5
243 243
244 244 In [5]: dview['b'] = 10
245 245
246 246 In [6]: dview.apply(lambda x: a+b+x, 27)
247 247 Out[6]: [42, 42, 42, 42]
248 248
249 249 You can also select blocking execution on a call-by-call basis with the :meth:`apply_sync`
250 250 method:
251 251
252 252 In [7]: dview.block=False
253 253
254 254 In [8]: dview.apply_sync(lambda x: a+b+x, 27)
255 255 Out[8]: [42, 42, 42, 42]
256 256
257 257 Python commands can be executed as strings on specific engines by using a View's ``execute``
258 258 method:
259 259
260 260 .. sourcecode:: ipython
261 261
262 262 In [6]: rc[::2].execute('c=a+b')
263 263
264 264 In [7]: rc[1::2].execute('c=a-b')
265 265
266 266 In [8]: dview['c'] # shorthand for dview.pull('c', block=True)
267 267 Out[8]: [15, -5, 15, -5]
268 268
269 269
270 270 Non-blocking execution
271 271 ----------------------
272 272
273 273 In non-blocking mode, :meth:`apply` submits the command to be executed and
274 274 then returns a :class:`AsyncResult` object immediately. The
275 275 :class:`AsyncResult` object gives you a way of getting a result at a later
276 276 time through its :meth:`get` method.
277 277
278 278 .. seealso::
279 279
280 280 Docs on the :ref:`AsyncResult <parallel_asyncresult>` object.
281 281
282 282 This allows you to quickly submit long running commands without blocking your
283 283 local Python/IPython session:
284 284
285 285 .. sourcecode:: ipython
286 286
287 287 # define our function
288 288 In [6]: def wait(t):
289 289 ....: import time
290 290 ....: tic = time.time()
291 291 ....: time.sleep(t)
292 292 ....: return time.time()-tic
293 293
294 294 # In non-blocking mode
295 295 In [7]: ar = dview.apply_async(wait, 2)
296 296
297 297 # Now block for the result
298 298 In [8]: ar.get()
299 299 Out[8]: [2.0006198883056641, 1.9997570514678955, 1.9996809959411621, 2.0003249645233154]
300 300
301 301 # Again in non-blocking mode
302 302 In [9]: ar = dview.apply_async(wait, 10)
303 303
304 304 # Poll to see if the result is ready
305 305 In [10]: ar.ready()
306 306 Out[10]: False
307 307
308 308 # ask for the result, but wait a maximum of 1 second:
309 309 In [45]: ar.get(1)
310 310 ---------------------------------------------------------------------------
311 311 TimeoutError Traceback (most recent call last)
312 312 /home/you/<ipython-input-45-7cd858bbb8e0> in <module>()
313 313 ----> 1 ar.get(1)
314 314
315 315 /path/to/site-packages/IPython/parallel/asyncresult.pyc in get(self, timeout)
316 316 62 raise self._exception
317 317 63 else:
318 318 ---> 64 raise error.TimeoutError("Result not ready.")
319 319 65
320 320 66 def ready(self):
321 321
322 322 TimeoutError: Result not ready.
323 323
324 324 .. Note::
325 325
326 326 Note the import inside the function. This is a common model, to ensure
327 327 that the appropriate modules are imported where the task is run. You can
328 328 also manually import modules into the engine(s) namespace(s) via
329 329 :meth:`view.execute('import numpy')`.
330 330
331 331 Often, it is desirable to wait until a set of :class:`AsyncResult` objects
332 332 are done. For this, there is a the method :meth:`wait`. This method takes a
333 333 tuple of :class:`AsyncResult` objects (or `msg_ids` or indices to the client's History),
334 334 and blocks until all of the associated results are ready:
335 335
336 336 .. sourcecode:: ipython
337 337
338 338 In [72]: dview.block=False
339 339
340 340 # A trivial list of AsyncResults objects
341 341 In [73]: pr_list = [dview.apply_async(wait, 3) for i in range(10)]
342 342
343 343 # Wait until all of them are done
344 344 In [74]: dview.wait(pr_list)
345 345
346 346 # Then, their results are ready using get() or the `.r` attribute
347 347 In [75]: pr_list[0].get()
348 348 Out[75]: [2.9982571601867676, 2.9982588291168213, 2.9987530708312988, 2.9990990161895752]
349 349
350 350
351 351
352 352 The ``block`` and ``targets`` keyword arguments and attributes
353 353 --------------------------------------------------------------
354 354
355 355 Most DirectView methods (excluding :meth:`apply`) accept ``block`` and
356 356 ``targets`` as keyword arguments. As we have seen above, these keyword arguments control the
357 357 blocking mode and which engines the command is applied to. The :class:`View` class also has
358 358 :attr:`block` and :attr:`targets` attributes that control the default behavior when the keyword
359 359 arguments are not provided. Thus the following logic is used for :attr:`block` and :attr:`targets`:
360 360
361 361 * If no keyword argument is provided, the instance attributes are used.
362 362 * Keyword argument, if provided override the instance attributes for
363 363 the duration of a single call.
364 364
365 365 The following examples demonstrate how to use the instance attributes:
366 366
367 367 .. sourcecode:: ipython
368 368
369 369 In [16]: dview.targets = [0,2]
370 370
371 371 In [17]: dview.block = False
372 372
373 373 In [18]: ar = dview.apply(lambda : 10)
374 374
375 375 In [19]: ar.get()
376 376 Out[19]: [10, 10]
377 377
378 378 In [16]: dview.targets = v.client.ids # all engines (4)
379 379
380 380 In [21]: dview.block = True
381 381
382 382 In [22]: dview.apply(lambda : 42)
383 383 Out[22]: [42, 42, 42, 42]
384 384
385 385 The :attr:`block` and :attr:`targets` instance attributes of the
386 386 :class:`.DirectView` also determine the behavior of the parallel magic commands.
387 387
388 388 Parallel magic commands
389 389 -----------------------
390 390
391 391 We provide a few IPython magic commands (``%px``, ``%autopx`` and ``%result``)
392 392 that make it more pleasant to execute Python commands on the engines
393 393 interactively. These are simply shortcuts to :meth:`execute` and
394 394 :meth:`get_result` of the :class:`DirectView`. The ``%px`` magic executes a single
395 395 Python command on the engines specified by the :attr:`targets` attribute of the
396 396 :class:`DirectView` instance:
397 397
398 398 .. sourcecode:: ipython
399 399
400 400 # Create a DirectView for all targets
401 401 In [22]: dv = rc[:]
402 402
403 403 # Make this DirectView active for parallel magic commands
404 404 In [23]: dv.activate()
405 405
406 406 In [24]: dv.block=True
407 407
408 408 # import numpy here and everywhere
409 409 In [25]: with dv.sync_imports():
410 410 ....: import numpy
411 411 importing numpy on engine(s)
412 412
413 413 In [27]: %px a = numpy.random.rand(2,2)
414 414 Parallel execution on engines: [0, 1, 2, 3]
415 415
416 416 In [28]: %px ev = numpy.linalg.eigvals(a)
417 417 Parallel execution on engines: [0, 1, 2, 3]
418 418
419 419 In [28]: dv['ev']
420 420 Out[28]: [ array([ 1.09522024, -0.09645227]),
421 421 ....: array([ 1.21435496, -0.35546712]),
422 422 ....: array([ 0.72180653, 0.07133042]),
423 423 ....: array([ 1.46384341, 1.04353244e-04])
424 424 ....: ]
425 425
426 426 The ``%result`` magic gets the most recent result, or takes an argument
427 427 specifying the index of the result to be requested. It is simply a shortcut to the
428 428 :meth:`get_result` method:
429 429
430 430 .. sourcecode:: ipython
431 431
432 432 In [29]: dv.apply_async(lambda : ev)
433 433
434 434 In [30]: %result
435 435 Out[30]: [ [ 1.28167017 0.14197338],
436 436 ....: [-0.14093616 1.27877273],
437 437 ....: [-0.37023573 1.06779409],
438 438 ....: [ 0.83664764 -0.25602658] ]
439 439
440 440 The ``%autopx`` magic switches to a mode where everything you type is executed
441 441 on the engines given by the :attr:`targets` attribute:
442 442
443 443 .. sourcecode:: ipython
444 444
445 445 In [30]: dv.block=False
446 446
447 447 In [31]: %autopx
448 448 Auto Parallel Enabled
449 449 Type %autopx to disable
450 450
451 451 In [32]: max_evals = []
452 452 <IPython.parallel.AsyncResult object at 0x17b8a70>
453 453
454 454 In [33]: for i in range(100):
455 455 ....: a = numpy.random.rand(10,10)
456 456 ....: a = a+a.transpose()
457 457 ....: evals = numpy.linalg.eigvals(a)
458 458 ....: max_evals.append(evals[0].real)
459 459 ....:
460 460 ....:
461 461 <IPython.parallel.AsyncResult object at 0x17af8f0>
462 462
463 463 In [34]: %autopx
464 464 Auto Parallel Disabled
465 465
466 466 In [35]: dv.block=True
467 467
468 468 In [36]: px ans= "Average max eigenvalue is: %f"%(sum(max_evals)/len(max_evals))
469 469 Parallel execution on engines: [0, 1, 2, 3]
470 470
471 471 In [37]: dv['ans']
472 472 Out[37]: [ 'Average max eigenvalue is: 10.1387247332',
473 473 ....: 'Average max eigenvalue is: 10.2076902286',
474 474 ....: 'Average max eigenvalue is: 10.1891484655',
475 475 ....: 'Average max eigenvalue is: 10.1158837784',]
476 476
477 477
478 478 Moving Python objects around
479 479 ============================
480 480
481 481 In addition to calling functions and executing code on engines, you can
482 482 transfer Python objects to and from your IPython session and the engines. In
483 483 IPython, these operations are called :meth:`push` (sending an object to the
484 484 engines) and :meth:`pull` (getting an object from the engines).
485 485
486 486 Basic push and pull
487 487 -------------------
488 488
489 489 Here are some examples of how you use :meth:`push` and :meth:`pull`:
490 490
491 491 .. sourcecode:: ipython
492 492
493 493 In [38]: dview.push(dict(a=1.03234,b=3453))
494 494 Out[38]: [None,None,None,None]
495 495
496 496 In [39]: dview.pull('a')
497 497 Out[39]: [ 1.03234, 1.03234, 1.03234, 1.03234]
498 498
499 499 In [40]: dview.pull('b', targets=0)
500 500 Out[40]: 3453
501 501
502 502 In [41]: dview.pull(('a','b'))
503 503 Out[41]: [ [1.03234, 3453], [1.03234, 3453], [1.03234, 3453], [1.03234, 3453] ]
504 504
505 505 In [43]: dview.push(dict(c='speed'))
506 506 Out[43]: [None,None,None,None]
507 507
508 508 In non-blocking mode :meth:`push` and :meth:`pull` also return
509 509 :class:`AsyncResult` objects:
510 510
511 511 .. sourcecode:: ipython
512 512
513 513 In [48]: ar = dview.pull('a', block=False)
514 514
515 515 In [49]: ar.get()
516 516 Out[49]: [1.03234, 1.03234, 1.03234, 1.03234]
517 517
518 518
519 519 Dictionary interface
520 520 --------------------
521 521
522 522 Since a Python namespace is just a :class:`dict`, :class:`DirectView` objects provide
523 523 dictionary-style access by key and methods such as :meth:`get` and
524 524 :meth:`update` for convenience. This make the remote namespaces of the engines
525 525 appear as a local dictionary. Underneath, these methods call :meth:`apply`:
526 526
527 527 .. sourcecode:: ipython
528 528
529 529 In [51]: dview['a']=['foo','bar']
530 530
531 531 In [52]: dview['a']
532 532 Out[52]: [ ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'], ['foo', 'bar'] ]
533 533
534 534 Scatter and gather
535 535 ------------------
536 536
537 537 Sometimes it is useful to partition a sequence and push the partitions to
538 538 different engines. In MPI language, this is know as scatter/gather and we
539 539 follow that terminology. However, it is important to remember that in
540 540 IPython's :class:`Client` class, :meth:`scatter` is from the
541 541 interactive IPython session to the engines and :meth:`gather` is from the
542 542 engines back to the interactive IPython session. For scatter/gather operations
543 543 between engines, MPI, pyzmq, or some other direct interconnect should be used.
544 544
545 545 .. sourcecode:: ipython
546 546
547 547 In [58]: dview.scatter('a',range(16))
548 548 Out[58]: [None,None,None,None]
549 549
550 550 In [59]: dview['a']
551 551 Out[59]: [ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15] ]
552 552
553 553 In [60]: dview.gather('a')
554 554 Out[60]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
555 555
556 556 Other things to look at
557 557 =======================
558 558
559 559 How to do parallel list comprehensions
560 560 --------------------------------------
561 561
562 562 In many cases list comprehensions are nicer than using the map function. While
563 563 we don't have fully parallel list comprehensions, it is simple to get the
564 564 basic effect using :meth:`scatter` and :meth:`gather`:
565 565
566 566 .. sourcecode:: ipython
567 567
568 568 In [66]: dview.scatter('x',range(64))
569 569
570 570 In [67]: %px y = [i**10 for i in x]
571 571 Parallel execution on engines: [0, 1, 2, 3]
572 572 Out[67]:
573 573
574 574 In [68]: y = dview.gather('y')
575 575
576 576 In [69]: print y
577 577 [0, 1, 1024, 59049, 1048576, 9765625, 60466176, 282475249, 1073741824,...]
578 578
579 579 Remote imports
580 580 --------------
581 581
582 582 Sometimes you will want to import packages both in your interactive session
583 583 and on your remote engines. This can be done with the :class:`ContextManager`
584 584 created by a DirectView's :meth:`sync_imports` method:
585 585
586 586 .. sourcecode:: ipython
587 587
588 588 In [69]: with dview.sync_imports():
589 589 ....: import numpy
590 590 importing numpy on engine(s)
591 591
592 592 Any imports made inside the block will also be performed on the view's engines.
593 593 sync_imports also takes a `local` boolean flag that defaults to True, which specifies
594 594 whether the local imports should also be performed. However, support for `local=False`
595 595 has not been implemented, so only packages that can be imported locally will work
596 596 this way.
597 597
598 598 You can also specify imports via the ``@require`` decorator. This is a decorator
599 599 designed for use in Dependencies, but can be used to handle remote imports as well.
600 600 Modules or module names passed to ``@require`` will be imported before the decorated
601 601 function is called. If they cannot be imported, the decorated function will never
602 602 execution, and will fail with an UnmetDependencyError.
603 603
604 604 .. sourcecode:: ipython
605 605
606 606 In [69]: from IPython.parallel import require
607 607
608 608 In [70]: @require('re'):
609 609 ....: def findall(pat, x):
610 610 ....: # re is guaranteed to be available
611 611 ....: return re.findall(pat, x)
612 612
613 613 # you can also pass modules themselves, that you already have locally:
614 614 In [71]: @require(time):
615 615 ....: def wait(t):
616 616 ....: time.sleep(t)
617 617 ....: return t
618 618
619 619 .. _parallel_exceptions:
620 620
621 621 Parallel exceptions
622 622 -------------------
623 623
624 624 In the multiengine interface, parallel commands can raise Python exceptions,
625 625 just like serial commands. But, it is a little subtle, because a single
626 626 parallel command can actually raise multiple exceptions (one for each engine
627 627 the command was run on). To express this idea, we have a
628 628 :exc:`CompositeError` exception class that will be raised in most cases. The
629 629 :exc:`CompositeError` class is a special type of exception that wraps one or
630 630 more other types of exceptions. Here is how it works:
631 631
632 632 .. sourcecode:: ipython
633 633
634 634 In [76]: dview.block=True
635 635
636 636 In [77]: dview.execute('1/0')
637 637 ---------------------------------------------------------------------------
638 638 CompositeError Traceback (most recent call last)
639 639 /home/user/<ipython-input-10-5d56b303a66c> in <module>()
640 640 ----> 1 dview.execute('1/0')
641 641
642 642 /path/to/site-packages/IPython/parallel/client/view.pyc in execute(self, code, targets, block)
643 643 591 default: self.block
644 644 592 """
645 645 --> 593 return self._really_apply(util._execute, args=(code,), block=block, targets=targets)
646 646 594
647 647 595 def run(self, filename, targets=None, block=None):
648 648
649 649 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
650 650
651 651 /path/to/site-packages/IPython/parallel/client/view.pyc in sync_results(f, self, *args, **kwargs)
652 652 55 def sync_results(f, self, *args, **kwargs):
653 653 56 """sync relevant results from self.client to our results attribute."""
654 654 ---> 57 ret = f(self, *args, **kwargs)
655 655 58 delta = self.outstanding.difference(self.client.outstanding)
656 656 59 completed = self.outstanding.intersection(delta)
657 657
658 658 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
659 659
660 660 /path/to/site-packages/IPython/parallel/client/view.pyc in save_ids(f, self, *args, **kwargs)
661 661 44 n_previous = len(self.client.history)
662 662 45 try:
663 663 ---> 46 ret = f(self, *args, **kwargs)
664 664 47 finally:
665 665 48 nmsgs = len(self.client.history) - n_previous
666 666
667 667 /path/to/site-packages/IPython/parallel/client/view.pyc in _really_apply(self, f, args, kwargs, targets, block, track)
668 668 529 if block:
669 669 530 try:
670 670 --> 531 return ar.get()
671 671 532 except KeyboardInterrupt:
672 672 533 pass
673 673
674 674 /path/to/site-packages/IPython/parallel/client/asyncresult.pyc in get(self, timeout)
675 675 101 return self._result
676 676 102 else:
677 677 --> 103 raise self._exception
678 678 104 else:
679 679 105 raise error.TimeoutError("Result not ready.")
680 680
681 681 CompositeError: one or more exceptions from call to method: _execute
682 682 [0:apply]: ZeroDivisionError: integer division or modulo by zero
683 683 [1:apply]: ZeroDivisionError: integer division or modulo by zero
684 684 [2:apply]: ZeroDivisionError: integer division or modulo by zero
685 685 [3:apply]: ZeroDivisionError: integer division or modulo by zero
686 686
687 687 Notice how the error message printed when :exc:`CompositeError` is raised has
688 688 information about the individual exceptions that were raised on each engine.
689 689 If you want, you can even raise one of these original exceptions:
690 690
691 691 .. sourcecode:: ipython
692 692
693 693 In [80]: try:
694 694 ....: dview.execute('1/0')
695 695 ....: except parallel.error.CompositeError, e:
696 696 ....: e.raise_exception()
697 697 ....:
698 698 ....:
699 699 ---------------------------------------------------------------------------
700 700 RemoteError Traceback (most recent call last)
701 701 /home/user/<ipython-input-17-8597e7e39858> in <module>()
702 702 2 dview.execute('1/0')
703 703 3 except CompositeError as e:
704 704 ----> 4 e.raise_exception()
705 705
706 706 /path/to/site-packages/IPython/parallel/error.pyc in raise_exception(self, excid)
707 707 266 raise IndexError("an exception with index %i does not exist"%excid)
708 708 267 else:
709 709 --> 268 raise RemoteError(en, ev, etb, ei)
710 710 269
711 711 270
712 712
713 713 RemoteError: ZeroDivisionError(integer division or modulo by zero)
714 714 Traceback (most recent call last):
715 715 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
716 716 exec code in working,working
717 717 File "<string>", line 1, in <module>
718 718 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
719 719 exec code in globals()
720 720 File "<string>", line 1, in <module>
721 721 ZeroDivisionError: integer division or modulo by zero
722 722
723 723 If you are working in IPython, you can simple type ``%debug`` after one of
724 724 these :exc:`CompositeError` exceptions is raised, and inspect the exception
725 725 instance:
726 726
727 727 .. sourcecode:: ipython
728 728
729 729 In [81]: dview.execute('1/0')
730 730 ---------------------------------------------------------------------------
731 731 CompositeError Traceback (most recent call last)
732 732 /home/user/<ipython-input-10-5d56b303a66c> in <module>()
733 733 ----> 1 dview.execute('1/0')
734 734
735 735 /path/to/site-packages/IPython/parallel/client/view.pyc in execute(self, code, targets, block)
736 736 591 default: self.block
737 737 592 """
738 738 --> 593 return self._really_apply(util._execute, args=(code,), block=block, targets=targets)
739 739 594
740 740 595 def run(self, filename, targets=None, block=None):
741 741
742 742 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
743 743
744 744 /path/to/site-packages/IPython/parallel/client/view.pyc in sync_results(f, self, *args, **kwargs)
745 745 55 def sync_results(f, self, *args, **kwargs):
746 746 56 """sync relevant results from self.client to our results attribute."""
747 747 ---> 57 ret = f(self, *args, **kwargs)
748 748 58 delta = self.outstanding.difference(self.client.outstanding)
749 749 59 completed = self.outstanding.intersection(delta)
750 750
751 751 /home/user/<string> in _really_apply(self, f, args, kwargs, targets, block, track)
752 752
753 753 /path/to/site-packages/IPython/parallel/client/view.pyc in save_ids(f, self, *args, **kwargs)
754 754 44 n_previous = len(self.client.history)
755 755 45 try:
756 756 ---> 46 ret = f(self, *args, **kwargs)
757 757 47 finally:
758 758 48 nmsgs = len(self.client.history) - n_previous
759 759
760 760 /path/to/site-packages/IPython/parallel/client/view.pyc in _really_apply(self, f, args, kwargs, targets, block, track)
761 761 529 if block:
762 762 530 try:
763 763 --> 531 return ar.get()
764 764 532 except KeyboardInterrupt:
765 765 533 pass
766 766
767 767 /path/to/site-packages/IPython/parallel/client/asyncresult.pyc in get(self, timeout)
768 768 101 return self._result
769 769 102 else:
770 770 --> 103 raise self._exception
771 771 104 else:
772 772 105 raise error.TimeoutError("Result not ready.")
773 773
774 774 CompositeError: one or more exceptions from call to method: _execute
775 775 [0:apply]: ZeroDivisionError: integer division or modulo by zero
776 776 [1:apply]: ZeroDivisionError: integer division or modulo by zero
777 777 [2:apply]: ZeroDivisionError: integer division or modulo by zero
778 778 [3:apply]: ZeroDivisionError: integer division or modulo by zero
779 779
780 780 In [82]: %debug
781 781 > /path/to/site-packages/IPython/parallel/client/asyncresult.py(103)get()
782 782 102 else:
783 783 --> 103 raise self._exception
784 784 104 else:
785 785
786 786 # With the debugger running, self._exception is the exceptions instance. We can tab complete
787 787 # on it and see the extra methods that are available.
788 788 ipdb> self._exception.<tab>
789 789 e.__class__ e.__getitem__ e.__new__ e.__setstate__ e.args
790 790 e.__delattr__ e.__getslice__ e.__reduce__ e.__str__ e.elist
791 791 e.__dict__ e.__hash__ e.__reduce_ex__ e.__weakref__ e.message
792 792 e.__doc__ e.__init__ e.__repr__ e._get_engine_str e.print_tracebacks
793 793 e.__getattribute__ e.__module__ e.__setattr__ e._get_traceback e.raise_exception
794 794 ipdb> self._exception.print_tracebacks()
795 795 [0:apply]:
796 796 Traceback (most recent call last):
797 797 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
798 798 exec code in working,working
799 799 File "<string>", line 1, in <module>
800 800 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
801 801 exec code in globals()
802 802 File "<string>", line 1, in <module>
803 803 ZeroDivisionError: integer division or modulo by zero
804 804
805 805
806 806 [1:apply]:
807 807 Traceback (most recent call last):
808 808 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
809 809 exec code in working,working
810 810 File "<string>", line 1, in <module>
811 811 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
812 812 exec code in globals()
813 813 File "<string>", line 1, in <module>
814 814 ZeroDivisionError: integer division or modulo by zero
815 815
816 816
817 817 [2:apply]:
818 818 Traceback (most recent call last):
819 819 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
820 820 exec code in working,working
821 821 File "<string>", line 1, in <module>
822 822 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
823 823 exec code in globals()
824 824 File "<string>", line 1, in <module>
825 825 ZeroDivisionError: integer division or modulo by zero
826 826
827 827
828 828 [3:apply]:
829 829 Traceback (most recent call last):
830 830 File "/path/to/site-packages/IPython/parallel/engine/streamkernel.py", line 330, in apply_request
831 831 exec code in working,working
832 832 File "<string>", line 1, in <module>
833 833 File "/path/to/site-packages/IPython/parallel/util.py", line 354, in _execute
834 834 exec code in globals()
835 835 File "<string>", line 1, in <module>
836 836 ZeroDivisionError: integer division or modulo by zero
837 837
838 838
839 839 All of this same error handling magic even works in non-blocking mode:
840 840
841 841 .. sourcecode:: ipython
842 842
843 843 In [83]: dview.block=False
844 844
845 845 In [84]: ar = dview.execute('1/0')
846 846
847 847 In [85]: ar.get()
848 848 ---------------------------------------------------------------------------
849 849 CompositeError Traceback (most recent call last)
850 850 /home/user/<ipython-input-21-8531eb3d26fb> in <module>()
851 851 ----> 1 ar.get()
852 852
853 853 /path/to/site-packages/IPython/parallel/client/asyncresult.pyc in get(self, timeout)
854 854 101 return self._result
855 855 102 else:
856 856 --> 103 raise self._exception
857 857 104 else:
858 858 105 raise error.TimeoutError("Result not ready.")
859 859
860 860 CompositeError: one or more exceptions from call to method: _execute
861 861 [0:apply]: ZeroDivisionError: integer division or modulo by zero
862 862 [1:apply]: ZeroDivisionError: integer division or modulo by zero
863 863 [2:apply]: ZeroDivisionError: integer division or modulo by zero
864 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