##// END OF EJS Templates
Merge pull request #4457 from takluyver/ipython-dir-default...
Paul Ivanov -
r13488:dbb715d2 merge
parent child Browse files
Show More
@@ -0,0 +1,5 b''
1 * Previous versions of IPython on Linux would use the XDG config directory,
2 creating :file:`~/.config/ipython` by default. We have decided to go
3 back to :file:`~/.ipython` for consistency among systems. IPython will
4 issue a warning if it finds the XDG location, and will move it to the new
5 location if there isn't already a directory there.
@@ -1,571 +1,570 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Usage information for the main IPython applications.
2 """Usage information for the main IPython applications.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008-2011 The IPython Development Team
5 # Copyright (C) 2008-2011 The IPython Development Team
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 import sys
12 import sys
13 from IPython.core import release
13 from IPython.core import release
14
14
15 cl_usage = """\
15 cl_usage = """\
16 =========
16 =========
17 IPython
17 IPython
18 =========
18 =========
19
19
20 Tools for Interactive Computing in Python
20 Tools for Interactive Computing in Python
21 =========================================
21 =========================================
22
22
23 A Python shell with automatic history (input and output), dynamic object
23 A Python shell with automatic history (input and output), dynamic object
24 introspection, easier configuration, command completion, access to the
24 introspection, easier configuration, command completion, access to the
25 system shell and more. IPython can also be embedded in running programs.
25 system shell and more. IPython can also be embedded in running programs.
26
26
27
27
28 Usage
28 Usage
29
29
30 ipython [subcommand] [options] [-c cmd | -m mod | file] [--] [arg] ...
30 ipython [subcommand] [options] [-c cmd | -m mod | file] [--] [arg] ...
31
31
32 If invoked with no options, it executes the file and exits, passing the
32 If invoked with no options, it executes the file and exits, passing the
33 remaining arguments to the script, just as if you had specified the same
33 remaining arguments to the script, just as if you had specified the same
34 command with python. You may need to specify `--` before args to be passed
34 command with python. You may need to specify `--` before args to be passed
35 to the script, to prevent IPython from attempting to parse them. If you
35 to the script, to prevent IPython from attempting to parse them. If you
36 specify the option `-i` before the filename, it will enter an interactive
36 specify the option `-i` before the filename, it will enter an interactive
37 IPython session after running the script, rather than exiting. Files ending
37 IPython session after running the script, rather than exiting. Files ending
38 in .py will be treated as normal Python, but files ending in .ipy can
38 in .py will be treated as normal Python, but files ending in .ipy can
39 contain special IPython syntax (magic commands, shell expansions, etc.).
39 contain special IPython syntax (magic commands, shell expansions, etc.).
40
40
41 Almost all configuration in IPython is available via the command-line. Do
41 Almost all configuration in IPython is available via the command-line. Do
42 `ipython --help-all` to see all available options. For persistent
42 `ipython --help-all` to see all available options. For persistent
43 configuration, look into your `ipython_config.py` configuration file for
43 configuration, look into your `ipython_config.py` configuration file for
44 details.
44 details.
45
45
46 This file is typically installed in the `IPYTHONDIR` directory, and there
46 This file is typically installed in the `IPYTHONDIR` directory, and there
47 is a separate configuration directory for each profile. The default profile
47 is a separate configuration directory for each profile. The default profile
48 directory will be located in $IPYTHONDIR/profile_default. For Linux users,
48 directory will be located in $IPYTHONDIR/profile_default. IPYTHONDIR
49 IPYTHONDIR defaults to `$HOME/.config/ipython`, and for other Unix systems
49 defaults to to `$HOME/.ipython`. For Windows users, $HOME resolves to
50 to `$HOME/.ipython`. For Windows users, $HOME resolves to C:\\Documents
50 C:\\Documents and Settings\\YourUserName in most instances.
51 and Settings\\YourUserName in most instances.
52
51
53 To initialize a profile with the default configuration file, do::
52 To initialize a profile with the default configuration file, do::
54
53
55 $> ipython profile create
54 $> ipython profile create
56
55
57 and start editing `IPYTHONDIR/profile_default/ipython_config.py`
56 and start editing `IPYTHONDIR/profile_default/ipython_config.py`
58
57
59 In IPython's documentation, we will refer to this directory as
58 In IPython's documentation, we will refer to this directory as
60 `IPYTHONDIR`, you can change its default location by creating an
59 `IPYTHONDIR`, you can change its default location by creating an
61 environment variable with this name and setting it to the desired path.
60 environment variable with this name and setting it to the desired path.
62
61
63 For more information, see the manual available in HTML and PDF in your
62 For more information, see the manual available in HTML and PDF in your
64 installation, or online at http://ipython.org/documentation.html.
63 installation, or online at http://ipython.org/documentation.html.
65 """
64 """
66
65
67 interactive_usage = """
66 interactive_usage = """
68 IPython -- An enhanced Interactive Python
67 IPython -- An enhanced Interactive Python
69 =========================================
68 =========================================
70
69
71 IPython offers a combination of convenient shell features, special commands
70 IPython offers a combination of convenient shell features, special commands
72 and a history mechanism for both input (command history) and output (results
71 and a history mechanism for both input (command history) and output (results
73 caching, similar to Mathematica). It is intended to be a fully compatible
72 caching, similar to Mathematica). It is intended to be a fully compatible
74 replacement for the standard Python interpreter, while offering vastly
73 replacement for the standard Python interpreter, while offering vastly
75 improved functionality and flexibility.
74 improved functionality and flexibility.
76
75
77 At your system command line, type 'ipython -h' to see the command line
76 At your system command line, type 'ipython -h' to see the command line
78 options available. This document only describes interactive features.
77 options available. This document only describes interactive features.
79
78
80 MAIN FEATURES
79 MAIN FEATURES
81 -------------
80 -------------
82
81
83 * Access to the standard Python help. As of Python 2.1, a help system is
82 * Access to the standard Python help. As of Python 2.1, a help system is
84 available with access to object docstrings and the Python manuals. Simply
83 available with access to object docstrings and the Python manuals. Simply
85 type 'help' (no quotes) to access it.
84 type 'help' (no quotes) to access it.
86
85
87 * Magic commands: type %magic for information on the magic subsystem.
86 * Magic commands: type %magic for information on the magic subsystem.
88
87
89 * System command aliases, via the %alias command or the configuration file(s).
88 * System command aliases, via the %alias command or the configuration file(s).
90
89
91 * Dynamic object information:
90 * Dynamic object information:
92
91
93 Typing ?word or word? prints detailed information about an object. If
92 Typing ?word or word? prints detailed information about an object. If
94 certain strings in the object are too long (docstrings, code, etc.) they get
93 certain strings in the object are too long (docstrings, code, etc.) they get
95 snipped in the center for brevity.
94 snipped in the center for brevity.
96
95
97 Typing ??word or word?? gives access to the full information without
96 Typing ??word or word?? gives access to the full information without
98 snipping long strings. Long strings are sent to the screen through the less
97 snipping long strings. Long strings are sent to the screen through the less
99 pager if longer than the screen, printed otherwise.
98 pager if longer than the screen, printed otherwise.
100
99
101 The ?/?? system gives access to the full source code for any object (if
100 The ?/?? system gives access to the full source code for any object (if
102 available), shows function prototypes and other useful information.
101 available), shows function prototypes and other useful information.
103
102
104 If you just want to see an object's docstring, type '%pdoc object' (without
103 If you just want to see an object's docstring, type '%pdoc object' (without
105 quotes, and without % if you have automagic on).
104 quotes, and without % if you have automagic on).
106
105
107 Both %pdoc and ?/?? give you access to documentation even on things which are
106 Both %pdoc and ?/?? give you access to documentation even on things which are
108 not explicitely defined. Try for example typing {}.get? or after import os,
107 not explicitely defined. Try for example typing {}.get? or after import os,
109 type os.path.abspath??. The magic functions %pdef, %source and %file operate
108 type os.path.abspath??. The magic functions %pdef, %source and %file operate
110 similarly.
109 similarly.
111
110
112 * Completion in the local namespace, by typing TAB at the prompt.
111 * Completion in the local namespace, by typing TAB at the prompt.
113
112
114 At any time, hitting tab will complete any available python commands or
113 At any time, hitting tab will complete any available python commands or
115 variable names, and show you a list of the possible completions if there's
114 variable names, and show you a list of the possible completions if there's
116 no unambiguous one. It will also complete filenames in the current directory.
115 no unambiguous one. It will also complete filenames in the current directory.
117
116
118 This feature requires the readline and rlcomplete modules, so it won't work
117 This feature requires the readline and rlcomplete modules, so it won't work
119 if your Python lacks readline support (such as under Windows).
118 if your Python lacks readline support (such as under Windows).
120
119
121 * Search previous command history in two ways (also requires readline):
120 * Search previous command history in two ways (also requires readline):
122
121
123 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
122 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
124 search through only the history items that match what you've typed so
123 search through only the history items that match what you've typed so
125 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
124 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
126 normal arrow keys.
125 normal arrow keys.
127
126
128 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
127 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
129 your history for lines that match what you've typed so far, completing as
128 your history for lines that match what you've typed so far, completing as
130 much as it can.
129 much as it can.
131
130
132 - %hist: search history by index (this does *not* require readline).
131 - %hist: search history by index (this does *not* require readline).
133
132
134 * Persistent command history across sessions.
133 * Persistent command history across sessions.
135
134
136 * Logging of input with the ability to save and restore a working session.
135 * Logging of input with the ability to save and restore a working session.
137
136
138 * System escape with !. Typing !ls will run 'ls' in the current directory.
137 * System escape with !. Typing !ls will run 'ls' in the current directory.
139
138
140 * The reload command does a 'deep' reload of a module: changes made to the
139 * The reload command does a 'deep' reload of a module: changes made to the
141 module since you imported will actually be available without having to exit.
140 module since you imported will actually be available without having to exit.
142
141
143 * Verbose and colored exception traceback printouts. See the magic xmode and
142 * Verbose and colored exception traceback printouts. See the magic xmode and
144 xcolor functions for details (just type %magic).
143 xcolor functions for details (just type %magic).
145
144
146 * Input caching system:
145 * Input caching system:
147
146
148 IPython offers numbered prompts (In/Out) with input and output caching. All
147 IPython offers numbered prompts (In/Out) with input and output caching. All
149 input is saved and can be retrieved as variables (besides the usual arrow
148 input is saved and can be retrieved as variables (besides the usual arrow
150 key recall).
149 key recall).
151
150
152 The following GLOBAL variables always exist (so don't overwrite them!):
151 The following GLOBAL variables always exist (so don't overwrite them!):
153 _i: stores previous input.
152 _i: stores previous input.
154 _ii: next previous.
153 _ii: next previous.
155 _iii: next-next previous.
154 _iii: next-next previous.
156 _ih : a list of all input _ih[n] is the input from line n.
155 _ih : a list of all input _ih[n] is the input from line n.
157
156
158 Additionally, global variables named _i<n> are dynamically created (<n>
157 Additionally, global variables named _i<n> are dynamically created (<n>
159 being the prompt counter), such that _i<n> == _ih[<n>]
158 being the prompt counter), such that _i<n> == _ih[<n>]
160
159
161 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
160 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
162
161
163 You can create macros which contain multiple input lines from this history,
162 You can create macros which contain multiple input lines from this history,
164 for later re-execution, with the %macro function.
163 for later re-execution, with the %macro function.
165
164
166 The history function %hist allows you to see any part of your input history
165 The history function %hist allows you to see any part of your input history
167 by printing a range of the _i variables. Note that inputs which contain
166 by printing a range of the _i variables. Note that inputs which contain
168 magic functions (%) appear in the history with a prepended comment. This is
167 magic functions (%) appear in the history with a prepended comment. This is
169 because they aren't really valid Python code, so you can't exec them.
168 because they aren't really valid Python code, so you can't exec them.
170
169
171 * Output caching system:
170 * Output caching system:
172
171
173 For output that is returned from actions, a system similar to the input
172 For output that is returned from actions, a system similar to the input
174 cache exists but using _ instead of _i. Only actions that produce a result
173 cache exists but using _ instead of _i. Only actions that produce a result
175 (NOT assignments, for example) are cached. If you are familiar with
174 (NOT assignments, for example) are cached. If you are familiar with
176 Mathematica, IPython's _ variables behave exactly like Mathematica's %
175 Mathematica, IPython's _ variables behave exactly like Mathematica's %
177 variables.
176 variables.
178
177
179 The following GLOBAL variables always exist (so don't overwrite them!):
178 The following GLOBAL variables always exist (so don't overwrite them!):
180 _ (one underscore): previous output.
179 _ (one underscore): previous output.
181 __ (two underscores): next previous.
180 __ (two underscores): next previous.
182 ___ (three underscores): next-next previous.
181 ___ (three underscores): next-next previous.
183
182
184 Global variables named _<n> are dynamically created (<n> being the prompt
183 Global variables named _<n> are dynamically created (<n> being the prompt
185 counter), such that the result of output <n> is always available as _<n>.
184 counter), such that the result of output <n> is always available as _<n>.
186
185
187 Finally, a global dictionary named _oh exists with entries for all lines
186 Finally, a global dictionary named _oh exists with entries for all lines
188 which generated output.
187 which generated output.
189
188
190 * Directory history:
189 * Directory history:
191
190
192 Your history of visited directories is kept in the global list _dh, and the
191 Your history of visited directories is kept in the global list _dh, and the
193 magic %cd command can be used to go to any entry in that list.
192 magic %cd command can be used to go to any entry in that list.
194
193
195 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
194 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
196
195
197 1. Auto-parentheses
196 1. Auto-parentheses
198
197
199 Callable objects (i.e. functions, methods, etc) can be invoked like
198 Callable objects (i.e. functions, methods, etc) can be invoked like
200 this (notice the commas between the arguments)::
199 this (notice the commas between the arguments)::
201
200
202 In [1]: callable_ob arg1, arg2, arg3
201 In [1]: callable_ob arg1, arg2, arg3
203
202
204 and the input will be translated to this::
203 and the input will be translated to this::
205
204
206 callable_ob(arg1, arg2, arg3)
205 callable_ob(arg1, arg2, arg3)
207
206
208 This feature is off by default (in rare cases it can produce
207 This feature is off by default (in rare cases it can produce
209 undesirable side-effects), but you can activate it at the command-line
208 undesirable side-effects), but you can activate it at the command-line
210 by starting IPython with `--autocall 1`, set it permanently in your
209 by starting IPython with `--autocall 1`, set it permanently in your
211 configuration file, or turn on at runtime with `%autocall 1`.
210 configuration file, or turn on at runtime with `%autocall 1`.
212
211
213 You can force auto-parentheses by using '/' as the first character
212 You can force auto-parentheses by using '/' as the first character
214 of a line. For example::
213 of a line. For example::
215
214
216 In [1]: /globals # becomes 'globals()'
215 In [1]: /globals # becomes 'globals()'
217
216
218 Note that the '/' MUST be the first character on the line! This
217 Note that the '/' MUST be the first character on the line! This
219 won't work::
218 won't work::
220
219
221 In [2]: print /globals # syntax error
220 In [2]: print /globals # syntax error
222
221
223 In most cases the automatic algorithm should work, so you should
222 In most cases the automatic algorithm should work, so you should
224 rarely need to explicitly invoke /. One notable exception is if you
223 rarely need to explicitly invoke /. One notable exception is if you
225 are trying to call a function with a list of tuples as arguments (the
224 are trying to call a function with a list of tuples as arguments (the
226 parenthesis will confuse IPython)::
225 parenthesis will confuse IPython)::
227
226
228 In [1]: zip (1,2,3),(4,5,6) # won't work
227 In [1]: zip (1,2,3),(4,5,6) # won't work
229
228
230 but this will work::
229 but this will work::
231
230
232 In [2]: /zip (1,2,3),(4,5,6)
231 In [2]: /zip (1,2,3),(4,5,6)
233 ------> zip ((1,2,3),(4,5,6))
232 ------> zip ((1,2,3),(4,5,6))
234 Out[2]= [(1, 4), (2, 5), (3, 6)]
233 Out[2]= [(1, 4), (2, 5), (3, 6)]
235
234
236 IPython tells you that it has altered your command line by
235 IPython tells you that it has altered your command line by
237 displaying the new command line preceded by -->. e.g.::
236 displaying the new command line preceded by -->. e.g.::
238
237
239 In [18]: callable list
238 In [18]: callable list
240 -------> callable (list)
239 -------> callable (list)
241
240
242 2. Auto-Quoting
241 2. Auto-Quoting
243
242
244 You can force auto-quoting of a function's arguments by using ',' as
243 You can force auto-quoting of a function's arguments by using ',' as
245 the first character of a line. For example::
244 the first character of a line. For example::
246
245
247 In [1]: ,my_function /home/me # becomes my_function("/home/me")
246 In [1]: ,my_function /home/me # becomes my_function("/home/me")
248
247
249 If you use ';' instead, the whole argument is quoted as a single
248 If you use ';' instead, the whole argument is quoted as a single
250 string (while ',' splits on whitespace)::
249 string (while ',' splits on whitespace)::
251
250
252 In [2]: ,my_function a b c # becomes my_function("a","b","c")
251 In [2]: ,my_function a b c # becomes my_function("a","b","c")
253 In [3]: ;my_function a b c # becomes my_function("a b c")
252 In [3]: ;my_function a b c # becomes my_function("a b c")
254
253
255 Note that the ',' MUST be the first character on the line! This
254 Note that the ',' MUST be the first character on the line! This
256 won't work::
255 won't work::
257
256
258 In [4]: x = ,my_function /home/me # syntax error
257 In [4]: x = ,my_function /home/me # syntax error
259 """
258 """
260
259
261 interactive_usage_min = """\
260 interactive_usage_min = """\
262 An enhanced console for Python.
261 An enhanced console for Python.
263 Some of its features are:
262 Some of its features are:
264 - Readline support if the readline library is present.
263 - Readline support if the readline library is present.
265 - Tab completion in the local namespace.
264 - Tab completion in the local namespace.
266 - Logging of input, see command-line options.
265 - Logging of input, see command-line options.
267 - System shell escape via ! , eg !ls.
266 - System shell escape via ! , eg !ls.
268 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
267 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
269 - Keeps track of locally defined variables via %who, %whos.
268 - Keeps track of locally defined variables via %who, %whos.
270 - Show object information with a ? eg ?x or x? (use ?? for more info).
269 - Show object information with a ? eg ?x or x? (use ?? for more info).
271 """
270 """
272
271
273 quick_reference = r"""
272 quick_reference = r"""
274 IPython -- An enhanced Interactive Python - Quick Reference Card
273 IPython -- An enhanced Interactive Python - Quick Reference Card
275 ================================================================
274 ================================================================
276
275
277 obj?, obj?? : Get help, or more help for object (also works as
276 obj?, obj?? : Get help, or more help for object (also works as
278 ?obj, ??obj).
277 ?obj, ??obj).
279 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
278 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
280 %magic : Information about IPython's 'magic' % functions.
279 %magic : Information about IPython's 'magic' % functions.
281
280
282 Magic functions are prefixed by % or %%, and typically take their arguments
281 Magic functions are prefixed by % or %%, and typically take their arguments
283 without parentheses, quotes or even commas for convenience. Line magics take a
282 without parentheses, quotes or even commas for convenience. Line magics take a
284 single % and cell magics are prefixed with two %%.
283 single % and cell magics are prefixed with two %%.
285
284
286 Example magic function calls:
285 Example magic function calls:
287
286
288 %alias d ls -F : 'd' is now an alias for 'ls -F'
287 %alias d ls -F : 'd' is now an alias for 'ls -F'
289 alias d ls -F : Works if 'alias' not a python name
288 alias d ls -F : Works if 'alias' not a python name
290 alist = %alias : Get list of aliases to 'alist'
289 alist = %alias : Get list of aliases to 'alist'
291 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
290 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
292 %cd?? : See help AND source for magic %cd
291 %cd?? : See help AND source for magic %cd
293 %timeit x=10 : time the 'x=10' statement with high precision.
292 %timeit x=10 : time the 'x=10' statement with high precision.
294 %%timeit x=2**100
293 %%timeit x=2**100
295 x**100 : time 'x*100' with a setup of 'x=2**100'; setup code is not
294 x**100 : time 'x*100' with a setup of 'x=2**100'; setup code is not
296 counted. This is an example of a cell magic.
295 counted. This is an example of a cell magic.
297
296
298 System commands:
297 System commands:
299
298
300 !cp a.txt b/ : System command escape, calls os.system()
299 !cp a.txt b/ : System command escape, calls os.system()
301 cp a.txt b/ : after %rehashx, most system commands work without !
300 cp a.txt b/ : after %rehashx, most system commands work without !
302 cp ${f}.txt $bar : Variable expansion in magics and system commands
301 cp ${f}.txt $bar : Variable expansion in magics and system commands
303 files = !ls /usr : Capture sytem command output
302 files = !ls /usr : Capture sytem command output
304 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
303 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
305
304
306 History:
305 History:
307
306
308 _i, _ii, _iii : Previous, next previous, next next previous input
307 _i, _ii, _iii : Previous, next previous, next next previous input
309 _i4, _ih[2:5] : Input history line 4, lines 2-4
308 _i4, _ih[2:5] : Input history line 4, lines 2-4
310 exec _i81 : Execute input history line #81 again
309 exec _i81 : Execute input history line #81 again
311 %rep 81 : Edit input history line #81
310 %rep 81 : Edit input history line #81
312 _, __, ___ : previous, next previous, next next previous output
311 _, __, ___ : previous, next previous, next next previous output
313 _dh : Directory history
312 _dh : Directory history
314 _oh : Output history
313 _oh : Output history
315 %hist : Command history. '%hist -g foo' search history for 'foo'
314 %hist : Command history. '%hist -g foo' search history for 'foo'
316
315
317 Autocall:
316 Autocall:
318
317
319 f 1,2 : f(1,2) # Off by default, enable with %autocall magic.
318 f 1,2 : f(1,2) # Off by default, enable with %autocall magic.
320 /f 1,2 : f(1,2) (forced autoparen)
319 /f 1,2 : f(1,2) (forced autoparen)
321 ,f 1 2 : f("1","2")
320 ,f 1 2 : f("1","2")
322 ;f 1 2 : f("1 2")
321 ;f 1 2 : f("1 2")
323
322
324 Remember: TAB completion works in many contexts, not just file names
323 Remember: TAB completion works in many contexts, not just file names
325 or python names.
324 or python names.
326
325
327 The following magic functions are currently available:
326 The following magic functions are currently available:
328
327
329 """
328 """
330
329
331 gui_reference = """\
330 gui_reference = """\
332 ===============================
331 ===============================
333 The graphical IPython console
332 The graphical IPython console
334 ===============================
333 ===============================
335
334
336 This console is designed to emulate the look, feel and workflow of a terminal
335 This console is designed to emulate the look, feel and workflow of a terminal
337 environment, while adding a number of enhancements that are simply not possible
336 environment, while adding a number of enhancements that are simply not possible
338 in a real terminal, such as inline syntax highlighting, true multiline editing,
337 in a real terminal, such as inline syntax highlighting, true multiline editing,
339 inline graphics and much more.
338 inline graphics and much more.
340
339
341 This quick reference document contains the basic information you'll need to
340 This quick reference document contains the basic information you'll need to
342 know to make the most efficient use of it. For the various command line
341 know to make the most efficient use of it. For the various command line
343 options available at startup, type ``ipython qtconsole --help`` at the command line.
342 options available at startup, type ``ipython qtconsole --help`` at the command line.
344
343
345
344
346 Multiline editing
345 Multiline editing
347 =================
346 =================
348
347
349 The graphical console is capable of true multiline editing, but it also tries
348 The graphical console is capable of true multiline editing, but it also tries
350 to behave intuitively like a terminal when possible. If you are used to
349 to behave intuitively like a terminal when possible. If you are used to
351 IPython's old terminal behavior, you should find the transition painless, and
350 IPython's old terminal behavior, you should find the transition painless, and
352 once you learn a few basic keybindings it will be a much more efficient
351 once you learn a few basic keybindings it will be a much more efficient
353 environment.
352 environment.
354
353
355 For single expressions or indented blocks, the console behaves almost like the
354 For single expressions or indented blocks, the console behaves almost like the
356 terminal IPython: single expressions are immediately evaluated, and indented
355 terminal IPython: single expressions are immediately evaluated, and indented
357 blocks are evaluated once a single blank line is entered::
356 blocks are evaluated once a single blank line is entered::
358
357
359 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
358 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
360 Hello IPython!
359 Hello IPython!
361
360
362 In [2]: for i in range(10):
361 In [2]: for i in range(10):
363 ...: print i,
362 ...: print i,
364 ...:
363 ...:
365 0 1 2 3 4 5 6 7 8 9
364 0 1 2 3 4 5 6 7 8 9
366
365
367 If you want to enter more than one expression in a single input block
366 If you want to enter more than one expression in a single input block
368 (something not possible in the terminal), you can use ``Control-Enter`` at the
367 (something not possible in the terminal), you can use ``Control-Enter`` at the
369 end of your first line instead of ``Enter``. At that point the console goes
368 end of your first line instead of ``Enter``. At that point the console goes
370 into 'cell mode' and even if your inputs are not indented, it will continue
369 into 'cell mode' and even if your inputs are not indented, it will continue
371 accepting arbitrarily many lines until either you enter an extra blank line or
370 accepting arbitrarily many lines until either you enter an extra blank line or
372 you hit ``Shift-Enter`` (the key binding that forces execution). When a
371 you hit ``Shift-Enter`` (the key binding that forces execution). When a
373 multiline cell is entered, IPython analyzes it and executes its code producing
372 multiline cell is entered, IPython analyzes it and executes its code producing
374 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
373 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
375 cell is executed as if it was a script. An example should clarify this::
374 cell is executed as if it was a script. An example should clarify this::
376
375
377 In [3]: x=1 # Hit C-Enter here
376 In [3]: x=1 # Hit C-Enter here
378 ...: y=2 # from now on, regular Enter is sufficient
377 ...: y=2 # from now on, regular Enter is sufficient
379 ...: z=3
378 ...: z=3
380 ...: x**2 # This does *not* produce an Out[] value
379 ...: x**2 # This does *not* produce an Out[] value
381 ...: x+y+z # Only the last expression does
380 ...: x+y+z # Only the last expression does
382 ...:
381 ...:
383 Out[3]: 6
382 Out[3]: 6
384
383
385 The behavior where an extra blank line forces execution is only active if you
384 The behavior where an extra blank line forces execution is only active if you
386 are actually typing at the keyboard each line, and is meant to make it mimic
385 are actually typing at the keyboard each line, and is meant to make it mimic
387 the IPython terminal behavior. If you paste a long chunk of input (for example
386 the IPython terminal behavior. If you paste a long chunk of input (for example
388 a long script copied form an editor or web browser), it can contain arbitrarily
387 a long script copied form an editor or web browser), it can contain arbitrarily
389 many intermediate blank lines and they won't cause any problems. As always,
388 many intermediate blank lines and they won't cause any problems. As always,
390 you can then make it execute by appending a blank line *at the end* or hitting
389 you can then make it execute by appending a blank line *at the end* or hitting
391 ``Shift-Enter`` anywhere within the cell.
390 ``Shift-Enter`` anywhere within the cell.
392
391
393 With the up arrow key, you can retrieve previous blocks of input that contain
392 With the up arrow key, you can retrieve previous blocks of input that contain
394 multiple lines. You can move inside of a multiline cell like you would in any
393 multiple lines. You can move inside of a multiline cell like you would in any
395 text editor. When you want it executed, the simplest thing to do is to hit the
394 text editor. When you want it executed, the simplest thing to do is to hit the
396 force execution key, ``Shift-Enter`` (though you can also navigate to the end
395 force execution key, ``Shift-Enter`` (though you can also navigate to the end
397 and append a blank line by using ``Enter`` twice).
396 and append a blank line by using ``Enter`` twice).
398
397
399 If you've edited a multiline cell and accidentally navigate out of it with the
398 If you've edited a multiline cell and accidentally navigate out of it with the
400 up or down arrow keys, IPython will clear the cell and replace it with the
399 up or down arrow keys, IPython will clear the cell and replace it with the
401 contents of the one above or below that you navigated to. If this was an
400 contents of the one above or below that you navigated to. If this was an
402 accident and you want to retrieve the cell you were editing, use the Undo
401 accident and you want to retrieve the cell you were editing, use the Undo
403 keybinding, ``Control-z``.
402 keybinding, ``Control-z``.
404
403
405
404
406 Key bindings
405 Key bindings
407 ============
406 ============
408
407
409 The IPython console supports most of the basic Emacs line-oriented keybindings,
408 The IPython console supports most of the basic Emacs line-oriented keybindings,
410 in addition to some of its own.
409 in addition to some of its own.
411
410
412 The keybinding prefixes mean:
411 The keybinding prefixes mean:
413
412
414 - ``C``: Control
413 - ``C``: Control
415 - ``S``: Shift
414 - ``S``: Shift
416 - ``M``: Meta (typically the Alt key)
415 - ``M``: Meta (typically the Alt key)
417
416
418 The keybindings themselves are:
417 The keybindings themselves are:
419
418
420 - ``Enter``: insert new line (may cause execution, see above).
419 - ``Enter``: insert new line (may cause execution, see above).
421 - ``C-Enter``: *force* new line, *never* causes execution.
420 - ``C-Enter``: *force* new line, *never* causes execution.
422 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
421 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
423 - ``Up``: step backwards through the history.
422 - ``Up``: step backwards through the history.
424 - ``Down``: step forwards through the history.
423 - ``Down``: step forwards through the history.
425 - ``S-Up``: search backwards through the history (like ``C-r`` in bash).
424 - ``S-Up``: search backwards through the history (like ``C-r`` in bash).
426 - ``S-Down``: search forwards through the history.
425 - ``S-Down``: search forwards through the history.
427 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
426 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
428 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
427 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
429 - ``C-v``: paste text from clipboard.
428 - ``C-v``: paste text from clipboard.
430 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
429 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
431 - ``C-S-z``: redo.
430 - ``C-S-z``: redo.
432 - ``C-o``: move to 'other' area, between pager and terminal.
431 - ``C-o``: move to 'other' area, between pager and terminal.
433 - ``C-l``: clear terminal.
432 - ``C-l``: clear terminal.
434 - ``C-a``: go to beginning of line.
433 - ``C-a``: go to beginning of line.
435 - ``C-e``: go to end of line.
434 - ``C-e``: go to end of line.
436 - ``C-u``: kill from cursor to the begining of the line.
435 - ``C-u``: kill from cursor to the begining of the line.
437 - ``C-k``: kill from cursor to the end of the line.
436 - ``C-k``: kill from cursor to the end of the line.
438 - ``C-y``: yank (paste)
437 - ``C-y``: yank (paste)
439 - ``C-p``: previous line (like up arrow)
438 - ``C-p``: previous line (like up arrow)
440 - ``C-n``: next line (like down arrow)
439 - ``C-n``: next line (like down arrow)
441 - ``C-f``: forward (like right arrow)
440 - ``C-f``: forward (like right arrow)
442 - ``C-b``: back (like left arrow)
441 - ``C-b``: back (like left arrow)
443 - ``C-d``: delete next character, or exits if input is empty
442 - ``C-d``: delete next character, or exits if input is empty
444 - ``M-<``: move to the beginning of the input region.
443 - ``M-<``: move to the beginning of the input region.
445 - ``M->``: move to the end of the input region.
444 - ``M->``: move to the end of the input region.
446 - ``M-d``: delete next word.
445 - ``M-d``: delete next word.
447 - ``M-Backspace``: delete previous word.
446 - ``M-Backspace``: delete previous word.
448 - ``C-.``: force a kernel restart (a confirmation dialog appears).
447 - ``C-.``: force a kernel restart (a confirmation dialog appears).
449 - ``C-+``: increase font size.
448 - ``C-+``: increase font size.
450 - ``C--``: decrease font size.
449 - ``C--``: decrease font size.
451 - ``C-M-Space``: toggle full screen. (Command-Control-Space on Mac OS X)
450 - ``C-M-Space``: toggle full screen. (Command-Control-Space on Mac OS X)
452
451
453 The IPython pager
452 The IPython pager
454 =================
453 =================
455
454
456 IPython will show long blocks of text from many sources using a builtin pager.
455 IPython will show long blocks of text from many sources using a builtin pager.
457 You can control where this pager appears with the ``--paging`` command-line
456 You can control where this pager appears with the ``--paging`` command-line
458 flag:
457 flag:
459
458
460 - ``inside`` [default]: the pager is overlaid on top of the main terminal. You
459 - ``inside`` [default]: the pager is overlaid on top of the main terminal. You
461 must quit the pager to get back to the terminal (similar to how a pager such
460 must quit the pager to get back to the terminal (similar to how a pager such
462 as ``less`` or ``more`` works).
461 as ``less`` or ``more`` works).
463
462
464 - ``vsplit``: the console is made double-tall, and the pager appears on the
463 - ``vsplit``: the console is made double-tall, and the pager appears on the
465 bottom area when needed. You can view its contents while using the terminal.
464 bottom area when needed. You can view its contents while using the terminal.
466
465
467 - ``hsplit``: the console is made double-wide, and the pager appears on the
466 - ``hsplit``: the console is made double-wide, and the pager appears on the
468 right area when needed. You can view its contents while using the terminal.
467 right area when needed. You can view its contents while using the terminal.
469
468
470 - ``none``: the console never pages output.
469 - ``none``: the console never pages output.
471
470
472 If you use the vertical or horizontal paging modes, you can navigate between
471 If you use the vertical or horizontal paging modes, you can navigate between
473 terminal and pager as follows:
472 terminal and pager as follows:
474
473
475 - Tab key: goes from pager to terminal (but not the other way around).
474 - Tab key: goes from pager to terminal (but not the other way around).
476 - Control-o: goes from one to another always.
475 - Control-o: goes from one to another always.
477 - Mouse: click on either.
476 - Mouse: click on either.
478
477
479 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
478 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
480 focus on the pager area).
479 focus on the pager area).
481
480
482 Running subprocesses
481 Running subprocesses
483 ====================
482 ====================
484
483
485 The graphical IPython console uses the ``pexpect`` module to run subprocesses
484 The graphical IPython console uses the ``pexpect`` module to run subprocesses
486 when you type ``!command``. This has a number of advantages (true asynchronous
485 when you type ``!command``. This has a number of advantages (true asynchronous
487 output from subprocesses as well as very robust termination of rogue
486 output from subprocesses as well as very robust termination of rogue
488 subprocesses with ``Control-C``), as well as some limitations. The main
487 subprocesses with ``Control-C``), as well as some limitations. The main
489 limitation is that you can *not* interact back with the subprocess, so anything
488 limitation is that you can *not* interact back with the subprocess, so anything
490 that invokes a pager or expects you to type input into it will block and hang
489 that invokes a pager or expects you to type input into it will block and hang
491 (you can kill it with ``Control-C``).
490 (you can kill it with ``Control-C``).
492
491
493 We have provided as magics ``%less`` to page files (aliased to ``%more``),
492 We have provided as magics ``%less`` to page files (aliased to ``%more``),
494 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
493 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
495 most common commands you'd want to call in your subshell and that would cause
494 most common commands you'd want to call in your subshell and that would cause
496 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
495 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
497
496
498 Display
497 Display
499 =======
498 =======
500
499
501 The IPython console can now display objects in a variety of formats, including
500 The IPython console can now display objects in a variety of formats, including
502 HTML, PNG and SVG. This is accomplished using the display functions in
501 HTML, PNG and SVG. This is accomplished using the display functions in
503 ``IPython.core.display``::
502 ``IPython.core.display``::
504
503
505 In [4]: from IPython.core.display import display, display_html
504 In [4]: from IPython.core.display import display, display_html
506
505
507 In [5]: from IPython.core.display import display_png, display_svg
506 In [5]: from IPython.core.display import display_png, display_svg
508
507
509 Python objects can simply be passed to these functions and the appropriate
508 Python objects can simply be passed to these functions and the appropriate
510 representations will be displayed in the console as long as the objects know
509 representations will be displayed in the console as long as the objects know
511 how to compute those representations. The easiest way of teaching objects how
510 how to compute those representations. The easiest way of teaching objects how
512 to format themselves in various representations is to define special methods
511 to format themselves in various representations is to define special methods
513 such as: ``_repr_html_``, ``_repr_svg_`` and ``_repr_png_``. IPython's display formatters
512 such as: ``_repr_html_``, ``_repr_svg_`` and ``_repr_png_``. IPython's display formatters
514 can also be given custom formatter functions for various types::
513 can also be given custom formatter functions for various types::
515
514
516 In [6]: ip = get_ipython()
515 In [6]: ip = get_ipython()
517
516
518 In [7]: html_formatter = ip.display_formatter.formatters['text/html']
517 In [7]: html_formatter = ip.display_formatter.formatters['text/html']
519
518
520 In [8]: html_formatter.for_type(Foo, foo_to_html)
519 In [8]: html_formatter.for_type(Foo, foo_to_html)
521
520
522 For further details, see ``IPython.core.formatters``.
521 For further details, see ``IPython.core.formatters``.
523
522
524 Inline matplotlib graphics
523 Inline matplotlib graphics
525 ==========================
524 ==========================
526
525
527 The IPython console is capable of displaying matplotlib figures inline, in SVG
526 The IPython console is capable of displaying matplotlib figures inline, in SVG
528 or PNG format. If started with the ``matplotlib=inline``, then all figures are
527 or PNG format. If started with the ``matplotlib=inline``, then all figures are
529 rendered inline automatically (PNG by default). If started with ``--matplotlib``
528 rendered inline automatically (PNG by default). If started with ``--matplotlib``
530 or ``matplotlib=<your backend>``, then a GUI backend will be used, but IPython's
529 or ``matplotlib=<your backend>``, then a GUI backend will be used, but IPython's
531 ``display()`` and ``getfigs()`` functions can be used to view plots inline::
530 ``display()`` and ``getfigs()`` functions can be used to view plots inline::
532
531
533 In [9]: display(*getfigs()) # display all figures inline
532 In [9]: display(*getfigs()) # display all figures inline
534
533
535 In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline
534 In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline
536 """
535 """
537
536
538
537
539 quick_guide = """\
538 quick_guide = """\
540 ? -> Introduction and overview of IPython's features.
539 ? -> Introduction and overview of IPython's features.
541 %quickref -> Quick reference.
540 %quickref -> Quick reference.
542 help -> Python's own help system.
541 help -> Python's own help system.
543 object? -> Details about 'object', use 'object??' for extra details.
542 object? -> Details about 'object', use 'object??' for extra details.
544 """
543 """
545
544
546 gui_note = """\
545 gui_note = """\
547 %guiref -> A brief reference about the graphical user interface.
546 %guiref -> A brief reference about the graphical user interface.
548 """
547 """
549
548
550 default_banner_parts = [
549 default_banner_parts = [
551 'Python %s\n' % (sys.version.split('\n')[0],),
550 'Python %s\n' % (sys.version.split('\n')[0],),
552 'Type "copyright", "credits" or "license" for more information.\n\n',
551 'Type "copyright", "credits" or "license" for more information.\n\n',
553 'IPython {version} -- An enhanced Interactive Python.\n'.format(
552 'IPython {version} -- An enhanced Interactive Python.\n'.format(
554 version=release.version,
553 version=release.version,
555 ),
554 ),
556 quick_guide
555 quick_guide
557 ]
556 ]
558
557
559 default_gui_banner_parts = default_banner_parts + [gui_note]
558 default_gui_banner_parts = default_banner_parts + [gui_note]
560
559
561 default_banner = ''.join(default_banner_parts)
560 default_banner = ''.join(default_banner_parts)
562
561
563 default_gui_banner = ''.join(default_gui_banner_parts)
562 default_gui_banner = ''.join(default_gui_banner_parts)
564
563
565 # page GUI Reference, for use as a magic:
564 # page GUI Reference, for use as a magic:
566
565
567 def page_guiref(arg_s=None):
566 def page_guiref(arg_s=None):
568 """Show a basic reference about the GUI Console."""
567 """Show a basic reference about the GUI Console."""
569 from IPython.core import page
568 from IPython.core import page
570 page.page(gui_reference, auto_html=True)
569 page.page(gui_reference, auto_html=True)
571
570
@@ -1,574 +1,574 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for path handling.
3 Utilities for path handling.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import os
17 import os
18 import sys
18 import sys
19 import errno
19 import errno
20 import shutil
20 import shutil
21 import random
21 import random
22 import tempfile
22 import tempfile
23 import warnings
23 import warnings
24 from hashlib import md5
24 from hashlib import md5
25 import glob
25 import glob
26
26
27 import IPython
27 import IPython
28 from IPython.testing.skipdoctest import skip_doctest
28 from IPython.testing.skipdoctest import skip_doctest
29 from IPython.utils.process import system
29 from IPython.utils.process import system
30 from IPython.utils.importstring import import_item
30 from IPython.utils.importstring import import_item
31 from IPython.utils import py3compat
31 from IPython.utils import py3compat
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33 # Code
33 # Code
34 #-----------------------------------------------------------------------------
34 #-----------------------------------------------------------------------------
35
35
36 fs_encoding = sys.getfilesystemencoding()
36 fs_encoding = sys.getfilesystemencoding()
37
37
38 def _get_long_path_name(path):
38 def _get_long_path_name(path):
39 """Dummy no-op."""
39 """Dummy no-op."""
40 return path
40 return path
41
41
42 def _writable_dir(path):
42 def _writable_dir(path):
43 """Whether `path` is a directory, to which the user has write access."""
43 """Whether `path` is a directory, to which the user has write access."""
44 return os.path.isdir(path) and os.access(path, os.W_OK)
44 return os.path.isdir(path) and os.access(path, os.W_OK)
45
45
46 if sys.platform == 'win32':
46 if sys.platform == 'win32':
47 @skip_doctest
47 @skip_doctest
48 def _get_long_path_name(path):
48 def _get_long_path_name(path):
49 """Get a long path name (expand ~) on Windows using ctypes.
49 """Get a long path name (expand ~) on Windows using ctypes.
50
50
51 Examples
51 Examples
52 --------
52 --------
53
53
54 >>> get_long_path_name('c:\\docume~1')
54 >>> get_long_path_name('c:\\docume~1')
55 u'c:\\\\Documents and Settings'
55 u'c:\\\\Documents and Settings'
56
56
57 """
57 """
58 try:
58 try:
59 import ctypes
59 import ctypes
60 except ImportError:
60 except ImportError:
61 raise ImportError('you need to have ctypes installed for this to work')
61 raise ImportError('you need to have ctypes installed for this to work')
62 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
62 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
63 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
63 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
64 ctypes.c_uint ]
64 ctypes.c_uint ]
65
65
66 buf = ctypes.create_unicode_buffer(260)
66 buf = ctypes.create_unicode_buffer(260)
67 rv = _GetLongPathName(path, buf, 260)
67 rv = _GetLongPathName(path, buf, 260)
68 if rv == 0 or rv > 260:
68 if rv == 0 or rv > 260:
69 return path
69 return path
70 else:
70 else:
71 return buf.value
71 return buf.value
72
72
73
73
74 def get_long_path_name(path):
74 def get_long_path_name(path):
75 """Expand a path into its long form.
75 """Expand a path into its long form.
76
76
77 On Windows this expands any ~ in the paths. On other platforms, it is
77 On Windows this expands any ~ in the paths. On other platforms, it is
78 a null operation.
78 a null operation.
79 """
79 """
80 return _get_long_path_name(path)
80 return _get_long_path_name(path)
81
81
82
82
83 def unquote_filename(name, win32=(sys.platform=='win32')):
83 def unquote_filename(name, win32=(sys.platform=='win32')):
84 """ On Windows, remove leading and trailing quotes from filenames.
84 """ On Windows, remove leading and trailing quotes from filenames.
85 """
85 """
86 if win32:
86 if win32:
87 if name.startswith(("'", '"')) and name.endswith(("'", '"')):
87 if name.startswith(("'", '"')) and name.endswith(("'", '"')):
88 name = name[1:-1]
88 name = name[1:-1]
89 return name
89 return name
90
90
91 def compress_user(path):
91 def compress_user(path):
92 """Reverse of :func:`os.path.expanduser`
92 """Reverse of :func:`os.path.expanduser`
93 """
93 """
94 home = os.path.expanduser('~')
94 home = os.path.expanduser('~')
95 if path.startswith(home):
95 if path.startswith(home):
96 path = "~" + path[len(home):]
96 path = "~" + path[len(home):]
97 return path
97 return path
98
98
99 def get_py_filename(name, force_win32=None):
99 def get_py_filename(name, force_win32=None):
100 """Return a valid python filename in the current directory.
100 """Return a valid python filename in the current directory.
101
101
102 If the given name is not a file, it adds '.py' and searches again.
102 If the given name is not a file, it adds '.py' and searches again.
103 Raises IOError with an informative message if the file isn't found.
103 Raises IOError with an informative message if the file isn't found.
104
104
105 On Windows, apply Windows semantics to the filename. In particular, remove
105 On Windows, apply Windows semantics to the filename. In particular, remove
106 any quoting that has been applied to it. This option can be forced for
106 any quoting that has been applied to it. This option can be forced for
107 testing purposes.
107 testing purposes.
108 """
108 """
109
109
110 name = os.path.expanduser(name)
110 name = os.path.expanduser(name)
111 if force_win32 is None:
111 if force_win32 is None:
112 win32 = (sys.platform == 'win32')
112 win32 = (sys.platform == 'win32')
113 else:
113 else:
114 win32 = force_win32
114 win32 = force_win32
115 name = unquote_filename(name, win32=win32)
115 name = unquote_filename(name, win32=win32)
116 if not os.path.isfile(name) and not name.endswith('.py'):
116 if not os.path.isfile(name) and not name.endswith('.py'):
117 name += '.py'
117 name += '.py'
118 if os.path.isfile(name):
118 if os.path.isfile(name):
119 return name
119 return name
120 else:
120 else:
121 raise IOError('File `%r` not found.' % name)
121 raise IOError('File `%r` not found.' % name)
122
122
123
123
124 def filefind(filename, path_dirs=None):
124 def filefind(filename, path_dirs=None):
125 """Find a file by looking through a sequence of paths.
125 """Find a file by looking through a sequence of paths.
126
126
127 This iterates through a sequence of paths looking for a file and returns
127 This iterates through a sequence of paths looking for a file and returns
128 the full, absolute path of the first occurence of the file. If no set of
128 the full, absolute path of the first occurence of the file. If no set of
129 path dirs is given, the filename is tested as is, after running through
129 path dirs is given, the filename is tested as is, after running through
130 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
130 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
131
131
132 filefind('myfile.txt')
132 filefind('myfile.txt')
133
133
134 will find the file in the current working dir, but::
134 will find the file in the current working dir, but::
135
135
136 filefind('~/myfile.txt')
136 filefind('~/myfile.txt')
137
137
138 Will find the file in the users home directory. This function does not
138 Will find the file in the users home directory. This function does not
139 automatically try any paths, such as the cwd or the user's home directory.
139 automatically try any paths, such as the cwd or the user's home directory.
140
140
141 Parameters
141 Parameters
142 ----------
142 ----------
143 filename : str
143 filename : str
144 The filename to look for.
144 The filename to look for.
145 path_dirs : str, None or sequence of str
145 path_dirs : str, None or sequence of str
146 The sequence of paths to look for the file in. If None, the filename
146 The sequence of paths to look for the file in. If None, the filename
147 need to be absolute or be in the cwd. If a string, the string is
147 need to be absolute or be in the cwd. If a string, the string is
148 put into a sequence and the searched. If a sequence, walk through
148 put into a sequence and the searched. If a sequence, walk through
149 each element and join with ``filename``, calling :func:`expandvars`
149 each element and join with ``filename``, calling :func:`expandvars`
150 and :func:`expanduser` before testing for existence.
150 and :func:`expanduser` before testing for existence.
151
151
152 Returns
152 Returns
153 -------
153 -------
154 Raises :exc:`IOError` or returns absolute path to file.
154 Raises :exc:`IOError` or returns absolute path to file.
155 """
155 """
156
156
157 # If paths are quoted, abspath gets confused, strip them...
157 # If paths are quoted, abspath gets confused, strip them...
158 filename = filename.strip('"').strip("'")
158 filename = filename.strip('"').strip("'")
159 # If the input is an absolute path, just check it exists
159 # If the input is an absolute path, just check it exists
160 if os.path.isabs(filename) and os.path.isfile(filename):
160 if os.path.isabs(filename) and os.path.isfile(filename):
161 return filename
161 return filename
162
162
163 if path_dirs is None:
163 if path_dirs is None:
164 path_dirs = ("",)
164 path_dirs = ("",)
165 elif isinstance(path_dirs, py3compat.string_types):
165 elif isinstance(path_dirs, py3compat.string_types):
166 path_dirs = (path_dirs,)
166 path_dirs = (path_dirs,)
167
167
168 for path in path_dirs:
168 for path in path_dirs:
169 if path == '.': path = py3compat.getcwd()
169 if path == '.': path = py3compat.getcwd()
170 testname = expand_path(os.path.join(path, filename))
170 testname = expand_path(os.path.join(path, filename))
171 if os.path.isfile(testname):
171 if os.path.isfile(testname):
172 return os.path.abspath(testname)
172 return os.path.abspath(testname)
173
173
174 raise IOError("File %r does not exist in any of the search paths: %r" %
174 raise IOError("File %r does not exist in any of the search paths: %r" %
175 (filename, path_dirs) )
175 (filename, path_dirs) )
176
176
177
177
178 class HomeDirError(Exception):
178 class HomeDirError(Exception):
179 pass
179 pass
180
180
181
181
182 def get_home_dir(require_writable=False):
182 def get_home_dir(require_writable=False):
183 """Return the 'home' directory, as a unicode string.
183 """Return the 'home' directory, as a unicode string.
184
184
185 Uses os.path.expanduser('~'), and checks for writability.
185 Uses os.path.expanduser('~'), and checks for writability.
186
186
187 See stdlib docs for how this is determined.
187 See stdlib docs for how this is determined.
188 $HOME is first priority on *ALL* platforms.
188 $HOME is first priority on *ALL* platforms.
189
189
190 Parameters
190 Parameters
191 ----------
191 ----------
192
192
193 require_writable : bool [default: False]
193 require_writable : bool [default: False]
194 if True:
194 if True:
195 guarantees the return value is a writable directory, otherwise
195 guarantees the return value is a writable directory, otherwise
196 raises HomeDirError
196 raises HomeDirError
197 if False:
197 if False:
198 The path is resolved, but it is not guaranteed to exist or be writable.
198 The path is resolved, but it is not guaranteed to exist or be writable.
199 """
199 """
200
200
201 homedir = os.path.expanduser('~')
201 homedir = os.path.expanduser('~')
202 # Next line will make things work even when /home/ is a symlink to
202 # Next line will make things work even when /home/ is a symlink to
203 # /usr/home as it is on FreeBSD, for example
203 # /usr/home as it is on FreeBSD, for example
204 homedir = os.path.realpath(homedir)
204 homedir = os.path.realpath(homedir)
205
205
206 if not _writable_dir(homedir) and os.name == 'nt':
206 if not _writable_dir(homedir) and os.name == 'nt':
207 # expanduser failed, use the registry to get the 'My Documents' folder.
207 # expanduser failed, use the registry to get the 'My Documents' folder.
208 try:
208 try:
209 try:
209 try:
210 import winreg as wreg # Py 3
210 import winreg as wreg # Py 3
211 except ImportError:
211 except ImportError:
212 import _winreg as wreg # Py 2
212 import _winreg as wreg # Py 2
213 key = wreg.OpenKey(
213 key = wreg.OpenKey(
214 wreg.HKEY_CURRENT_USER,
214 wreg.HKEY_CURRENT_USER,
215 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
215 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
216 )
216 )
217 homedir = wreg.QueryValueEx(key,'Personal')[0]
217 homedir = wreg.QueryValueEx(key,'Personal')[0]
218 key.Close()
218 key.Close()
219 except:
219 except:
220 pass
220 pass
221
221
222 if (not require_writable) or _writable_dir(homedir):
222 if (not require_writable) or _writable_dir(homedir):
223 return py3compat.cast_unicode(homedir, fs_encoding)
223 return py3compat.cast_unicode(homedir, fs_encoding)
224 else:
224 else:
225 raise HomeDirError('%s is not a writable dir, '
225 raise HomeDirError('%s is not a writable dir, '
226 'set $HOME environment variable to override' % homedir)
226 'set $HOME environment variable to override' % homedir)
227
227
228 def get_xdg_dir():
228 def get_xdg_dir():
229 """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
229 """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
230
230
231 This is only for non-OS X posix (Linux,Unix,etc.) systems.
231 This is only for non-OS X posix (Linux,Unix,etc.) systems.
232 """
232 """
233
233
234 env = os.environ
234 env = os.environ
235
235
236 if os.name == 'posix' and sys.platform != 'darwin':
236 if os.name == 'posix' and sys.platform != 'darwin':
237 # Linux, Unix, AIX, etc.
237 # Linux, Unix, AIX, etc.
238 # use ~/.config if empty OR not set
238 # use ~/.config if empty OR not set
239 xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
239 xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
240 if xdg and _writable_dir(xdg):
240 if xdg and _writable_dir(xdg):
241 return py3compat.cast_unicode(xdg, fs_encoding)
241 return py3compat.cast_unicode(xdg, fs_encoding)
242
242
243 return None
243 return None
244
244
245
245
246 def get_xdg_cache_dir():
246 def get_xdg_cache_dir():
247 """Return the XDG_CACHE_HOME, if it is defined and exists, else None.
247 """Return the XDG_CACHE_HOME, if it is defined and exists, else None.
248
248
249 This is only for non-OS X posix (Linux,Unix,etc.) systems.
249 This is only for non-OS X posix (Linux,Unix,etc.) systems.
250 """
250 """
251
251
252 env = os.environ
252 env = os.environ
253
253
254 if os.name == 'posix' and sys.platform != 'darwin':
254 if os.name == 'posix' and sys.platform != 'darwin':
255 # Linux, Unix, AIX, etc.
255 # Linux, Unix, AIX, etc.
256 # use ~/.cache if empty OR not set
256 # use ~/.cache if empty OR not set
257 xdg = env.get("XDG_CACHE_HOME", None) or os.path.join(get_home_dir(), '.cache')
257 xdg = env.get("XDG_CACHE_HOME", None) or os.path.join(get_home_dir(), '.cache')
258 if xdg and _writable_dir(xdg):
258 if xdg and _writable_dir(xdg):
259 return py3compat.cast_unicode(xdg, fs_encoding)
259 return py3compat.cast_unicode(xdg, fs_encoding)
260
260
261 return None
261 return None
262
262
263
263
264 def get_ipython_dir():
264 def get_ipython_dir():
265 """Get the IPython directory for this platform and user.
265 """Get the IPython directory for this platform and user.
266
266
267 This uses the logic in `get_home_dir` to find the home directory
267 This uses the logic in `get_home_dir` to find the home directory
268 and then adds .ipython to the end of the path.
268 and then adds .ipython to the end of the path.
269 """
269 """
270
270
271 env = os.environ
271 env = os.environ
272 pjoin = os.path.join
272 pjoin = os.path.join
273
273
274
274
275 ipdir_def = '.ipython'
275 ipdir_def = '.ipython'
276 xdg_def = 'ipython'
277
276
278 home_dir = get_home_dir()
277 home_dir = get_home_dir()
279 xdg_dir = get_xdg_dir()
278 xdg_dir = get_xdg_dir()
280
279
281 # import pdb; pdb.set_trace() # dbg
280 # import pdb; pdb.set_trace() # dbg
282 if 'IPYTHON_DIR' in env:
281 if 'IPYTHON_DIR' in env:
283 warnings.warn('The environment variable IPYTHON_DIR is deprecated. '
282 warnings.warn('The environment variable IPYTHON_DIR is deprecated. '
284 'Please use IPYTHONDIR instead.')
283 'Please use IPYTHONDIR instead.')
285 ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None))
284 ipdir = env.get('IPYTHONDIR', env.get('IPYTHON_DIR', None))
286 if ipdir is None:
285 if ipdir is None:
287 # not set explicitly, use XDG_CONFIG_HOME or HOME
286 # not set explicitly, use ~/.ipython
288 home_ipdir = pjoin(home_dir, ipdir_def)
287 ipdir = pjoin(home_dir, ipdir_def)
289 if xdg_dir:
288 if xdg_dir:
290 # use XDG, as long as the user isn't already
289 # Several IPython versions (up to 1.x) defaulted to .config/ipython
291 # using $HOME/.ipython and *not* XDG/ipython
290 # on Linux. We have decided to go back to using .ipython everywhere
292
291 xdg_ipdir = pjoin(xdg_dir, 'ipython')
293 xdg_ipdir = pjoin(xdg_dir, xdg_def)
292
294
293 if _writable_dir(xdg_ipdir):
295 if _writable_dir(xdg_ipdir) or not _writable_dir(home_ipdir):
294 cu = compress_user
296 ipdir = xdg_ipdir
295 if os.path.exists(ipdir):
297
296 warnings.warn(('Ignoring {0} in favour of {1}. Remove {0} '
298 if ipdir is None:
297 'to get rid of this message').format(cu(xdg_ipdir), cu(ipdir)))
299 # not using XDG
298 else:
300 ipdir = home_ipdir
299 warnings.warn('Moving {0} to {1}'.format(cu(xdg_ipdir), cu(ipdir)))
300 os.rename(xdg_ipdir, ipdir)
301
301
302 ipdir = os.path.normpath(os.path.expanduser(ipdir))
302 ipdir = os.path.normpath(os.path.expanduser(ipdir))
303
303
304 if os.path.exists(ipdir) and not _writable_dir(ipdir):
304 if os.path.exists(ipdir) and not _writable_dir(ipdir):
305 # ipdir exists, but is not writable
305 # ipdir exists, but is not writable
306 warnings.warn("IPython dir '%s' is not a writable location,"
306 warnings.warn("IPython dir '%s' is not a writable location,"
307 " using a temp directory."%ipdir)
307 " using a temp directory."%ipdir)
308 ipdir = tempfile.mkdtemp()
308 ipdir = tempfile.mkdtemp()
309 elif not os.path.exists(ipdir):
309 elif not os.path.exists(ipdir):
310 parent = os.path.dirname(ipdir)
310 parent = os.path.dirname(ipdir)
311 if not _writable_dir(parent):
311 if not _writable_dir(parent):
312 # ipdir does not exist and parent isn't writable
312 # ipdir does not exist and parent isn't writable
313 warnings.warn("IPython parent '%s' is not a writable location,"
313 warnings.warn("IPython parent '%s' is not a writable location,"
314 " using a temp directory."%parent)
314 " using a temp directory."%parent)
315 ipdir = tempfile.mkdtemp()
315 ipdir = tempfile.mkdtemp()
316
316
317 return py3compat.cast_unicode(ipdir, fs_encoding)
317 return py3compat.cast_unicode(ipdir, fs_encoding)
318
318
319
319
320 def get_ipython_cache_dir():
320 def get_ipython_cache_dir():
321 """Get the cache directory it is created if it does not exist."""
321 """Get the cache directory it is created if it does not exist."""
322 xdgdir = get_xdg_cache_dir()
322 xdgdir = get_xdg_cache_dir()
323 if xdgdir is None:
323 if xdgdir is None:
324 return get_ipython_dir()
324 return get_ipython_dir()
325 ipdir = os.path.join(xdgdir, "ipython")
325 ipdir = os.path.join(xdgdir, "ipython")
326 if not os.path.exists(ipdir) and _writable_dir(xdgdir):
326 if not os.path.exists(ipdir) and _writable_dir(xdgdir):
327 os.makedirs(ipdir)
327 os.makedirs(ipdir)
328 elif not _writable_dir(xdgdir):
328 elif not _writable_dir(xdgdir):
329 return get_ipython_dir()
329 return get_ipython_dir()
330
330
331 return py3compat.cast_unicode(ipdir, fs_encoding)
331 return py3compat.cast_unicode(ipdir, fs_encoding)
332
332
333
333
334 def get_ipython_package_dir():
334 def get_ipython_package_dir():
335 """Get the base directory where IPython itself is installed."""
335 """Get the base directory where IPython itself is installed."""
336 ipdir = os.path.dirname(IPython.__file__)
336 ipdir = os.path.dirname(IPython.__file__)
337 return py3compat.cast_unicode(ipdir, fs_encoding)
337 return py3compat.cast_unicode(ipdir, fs_encoding)
338
338
339
339
340 def get_ipython_module_path(module_str):
340 def get_ipython_module_path(module_str):
341 """Find the path to an IPython module in this version of IPython.
341 """Find the path to an IPython module in this version of IPython.
342
342
343 This will always find the version of the module that is in this importable
343 This will always find the version of the module that is in this importable
344 IPython package. This will always return the path to the ``.py``
344 IPython package. This will always return the path to the ``.py``
345 version of the module.
345 version of the module.
346 """
346 """
347 if module_str == 'IPython':
347 if module_str == 'IPython':
348 return os.path.join(get_ipython_package_dir(), '__init__.py')
348 return os.path.join(get_ipython_package_dir(), '__init__.py')
349 mod = import_item(module_str)
349 mod = import_item(module_str)
350 the_path = mod.__file__.replace('.pyc', '.py')
350 the_path = mod.__file__.replace('.pyc', '.py')
351 the_path = the_path.replace('.pyo', '.py')
351 the_path = the_path.replace('.pyo', '.py')
352 return py3compat.cast_unicode(the_path, fs_encoding)
352 return py3compat.cast_unicode(the_path, fs_encoding)
353
353
354 def locate_profile(profile='default'):
354 def locate_profile(profile='default'):
355 """Find the path to the folder associated with a given profile.
355 """Find the path to the folder associated with a given profile.
356
356
357 I.e. find $IPYTHONDIR/profile_whatever.
357 I.e. find $IPYTHONDIR/profile_whatever.
358 """
358 """
359 from IPython.core.profiledir import ProfileDir, ProfileDirError
359 from IPython.core.profiledir import ProfileDir, ProfileDirError
360 try:
360 try:
361 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
361 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
362 except ProfileDirError:
362 except ProfileDirError:
363 # IOError makes more sense when people are expecting a path
363 # IOError makes more sense when people are expecting a path
364 raise IOError("Couldn't find profile %r" % profile)
364 raise IOError("Couldn't find profile %r" % profile)
365 return pd.location
365 return pd.location
366
366
367 def expand_path(s):
367 def expand_path(s):
368 """Expand $VARS and ~names in a string, like a shell
368 """Expand $VARS and ~names in a string, like a shell
369
369
370 :Examples:
370 :Examples:
371
371
372 In [2]: os.environ['FOO']='test'
372 In [2]: os.environ['FOO']='test'
373
373
374 In [3]: expand_path('variable FOO is $FOO')
374 In [3]: expand_path('variable FOO is $FOO')
375 Out[3]: 'variable FOO is test'
375 Out[3]: 'variable FOO is test'
376 """
376 """
377 # This is a pretty subtle hack. When expand user is given a UNC path
377 # This is a pretty subtle hack. When expand user is given a UNC path
378 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
378 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
379 # the $ to get (\\server\share\%username%). I think it considered $
379 # the $ to get (\\server\share\%username%). I think it considered $
380 # alone an empty var. But, we need the $ to remains there (it indicates
380 # alone an empty var. But, we need the $ to remains there (it indicates
381 # a hidden share).
381 # a hidden share).
382 if os.name=='nt':
382 if os.name=='nt':
383 s = s.replace('$\\', 'IPYTHON_TEMP')
383 s = s.replace('$\\', 'IPYTHON_TEMP')
384 s = os.path.expandvars(os.path.expanduser(s))
384 s = os.path.expandvars(os.path.expanduser(s))
385 if os.name=='nt':
385 if os.name=='nt':
386 s = s.replace('IPYTHON_TEMP', '$\\')
386 s = s.replace('IPYTHON_TEMP', '$\\')
387 return s
387 return s
388
388
389
389
390 def unescape_glob(string):
390 def unescape_glob(string):
391 """Unescape glob pattern in `string`."""
391 """Unescape glob pattern in `string`."""
392 def unescape(s):
392 def unescape(s):
393 for pattern in '*[]!?':
393 for pattern in '*[]!?':
394 s = s.replace(r'\{0}'.format(pattern), pattern)
394 s = s.replace(r'\{0}'.format(pattern), pattern)
395 return s
395 return s
396 return '\\'.join(map(unescape, string.split('\\\\')))
396 return '\\'.join(map(unescape, string.split('\\\\')))
397
397
398
398
399 def shellglob(args):
399 def shellglob(args):
400 """
400 """
401 Do glob expansion for each element in `args` and return a flattened list.
401 Do glob expansion for each element in `args` and return a flattened list.
402
402
403 Unmatched glob pattern will remain as-is in the returned list.
403 Unmatched glob pattern will remain as-is in the returned list.
404
404
405 """
405 """
406 expanded = []
406 expanded = []
407 # Do not unescape backslash in Windows as it is interpreted as
407 # Do not unescape backslash in Windows as it is interpreted as
408 # path separator:
408 # path separator:
409 unescape = unescape_glob if sys.platform != 'win32' else lambda x: x
409 unescape = unescape_glob if sys.platform != 'win32' else lambda x: x
410 for a in args:
410 for a in args:
411 expanded.extend(glob.glob(a) or [unescape(a)])
411 expanded.extend(glob.glob(a) or [unescape(a)])
412 return expanded
412 return expanded
413
413
414
414
415 def target_outdated(target,deps):
415 def target_outdated(target,deps):
416 """Determine whether a target is out of date.
416 """Determine whether a target is out of date.
417
417
418 target_outdated(target,deps) -> 1/0
418 target_outdated(target,deps) -> 1/0
419
419
420 deps: list of filenames which MUST exist.
420 deps: list of filenames which MUST exist.
421 target: single filename which may or may not exist.
421 target: single filename which may or may not exist.
422
422
423 If target doesn't exist or is older than any file listed in deps, return
423 If target doesn't exist or is older than any file listed in deps, return
424 true, otherwise return false.
424 true, otherwise return false.
425 """
425 """
426 try:
426 try:
427 target_time = os.path.getmtime(target)
427 target_time = os.path.getmtime(target)
428 except os.error:
428 except os.error:
429 return 1
429 return 1
430 for dep in deps:
430 for dep in deps:
431 dep_time = os.path.getmtime(dep)
431 dep_time = os.path.getmtime(dep)
432 if dep_time > target_time:
432 if dep_time > target_time:
433 #print "For target",target,"Dep failed:",dep # dbg
433 #print "For target",target,"Dep failed:",dep # dbg
434 #print "times (dep,tar):",dep_time,target_time # dbg
434 #print "times (dep,tar):",dep_time,target_time # dbg
435 return 1
435 return 1
436 return 0
436 return 0
437
437
438
438
439 def target_update(target,deps,cmd):
439 def target_update(target,deps,cmd):
440 """Update a target with a given command given a list of dependencies.
440 """Update a target with a given command given a list of dependencies.
441
441
442 target_update(target,deps,cmd) -> runs cmd if target is outdated.
442 target_update(target,deps,cmd) -> runs cmd if target is outdated.
443
443
444 This is just a wrapper around target_outdated() which calls the given
444 This is just a wrapper around target_outdated() which calls the given
445 command if target is outdated."""
445 command if target is outdated."""
446
446
447 if target_outdated(target,deps):
447 if target_outdated(target,deps):
448 system(cmd)
448 system(cmd)
449
449
450 def filehash(path):
450 def filehash(path):
451 """Make an MD5 hash of a file, ignoring any differences in line
451 """Make an MD5 hash of a file, ignoring any differences in line
452 ending characters."""
452 ending characters."""
453 with open(path, "rU") as f:
453 with open(path, "rU") as f:
454 return md5(py3compat.str_to_bytes(f.read())).hexdigest()
454 return md5(py3compat.str_to_bytes(f.read())).hexdigest()
455
455
456 # If the config is unmodified from the default, we'll just delete it.
456 # If the config is unmodified from the default, we'll just delete it.
457 # These are consistent for 0.10.x, thankfully. We're not going to worry about
457 # These are consistent for 0.10.x, thankfully. We're not going to worry about
458 # older versions.
458 # older versions.
459 old_config_md5 = {'ipy_user_conf.py': 'fc108bedff4b9a00f91fa0a5999140d3',
459 old_config_md5 = {'ipy_user_conf.py': 'fc108bedff4b9a00f91fa0a5999140d3',
460 'ipythonrc': '12a68954f3403eea2eec09dc8fe5a9b5'}
460 'ipythonrc': '12a68954f3403eea2eec09dc8fe5a9b5'}
461
461
462 def check_for_old_config(ipython_dir=None):
462 def check_for_old_config(ipython_dir=None):
463 """Check for old config files, and present a warning if they exist.
463 """Check for old config files, and present a warning if they exist.
464
464
465 A link to the docs of the new config is included in the message.
465 A link to the docs of the new config is included in the message.
466
466
467 This should mitigate confusion with the transition to the new
467 This should mitigate confusion with the transition to the new
468 config system in 0.11.
468 config system in 0.11.
469 """
469 """
470 if ipython_dir is None:
470 if ipython_dir is None:
471 ipython_dir = get_ipython_dir()
471 ipython_dir = get_ipython_dir()
472
472
473 old_configs = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py']
473 old_configs = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py']
474 warned = False
474 warned = False
475 for cfg in old_configs:
475 for cfg in old_configs:
476 f = os.path.join(ipython_dir, cfg)
476 f = os.path.join(ipython_dir, cfg)
477 if os.path.exists(f):
477 if os.path.exists(f):
478 if filehash(f) == old_config_md5.get(cfg, ''):
478 if filehash(f) == old_config_md5.get(cfg, ''):
479 os.unlink(f)
479 os.unlink(f)
480 else:
480 else:
481 warnings.warn("Found old IPython config file %r (modified by user)"%f)
481 warnings.warn("Found old IPython config file %r (modified by user)"%f)
482 warned = True
482 warned = True
483
483
484 if warned:
484 if warned:
485 warnings.warn("""
485 warnings.warn("""
486 The IPython configuration system has changed as of 0.11, and these files will
486 The IPython configuration system has changed as of 0.11, and these files will
487 be ignored. See http://ipython.github.com/ipython-doc/dev/config for details
487 be ignored. See http://ipython.github.com/ipython-doc/dev/config for details
488 of the new config system.
488 of the new config system.
489 To start configuring IPython, do `ipython profile create`, and edit
489 To start configuring IPython, do `ipython profile create`, and edit
490 `ipython_config.py` in <ipython_dir>/profile_default.
490 `ipython_config.py` in <ipython_dir>/profile_default.
491 If you need to leave the old config files in place for an older version of
491 If you need to leave the old config files in place for an older version of
492 IPython and want to suppress this warning message, set
492 IPython and want to suppress this warning message, set
493 `c.InteractiveShellApp.ignore_old_config=True` in the new config.""")
493 `c.InteractiveShellApp.ignore_old_config=True` in the new config.""")
494
494
495 def get_security_file(filename, profile='default'):
495 def get_security_file(filename, profile='default'):
496 """Return the absolute path of a security file given by filename and profile
496 """Return the absolute path of a security file given by filename and profile
497
497
498 This allows users and developers to find security files without
498 This allows users and developers to find security files without
499 knowledge of the IPython directory structure. The search path
499 knowledge of the IPython directory structure. The search path
500 will be ['.', profile.security_dir]
500 will be ['.', profile.security_dir]
501
501
502 Parameters
502 Parameters
503 ----------
503 ----------
504
504
505 filename : str
505 filename : str
506 The file to be found. If it is passed as an absolute path, it will
506 The file to be found. If it is passed as an absolute path, it will
507 simply be returned.
507 simply be returned.
508 profile : str [default: 'default']
508 profile : str [default: 'default']
509 The name of the profile to search. Leaving this unspecified
509 The name of the profile to search. Leaving this unspecified
510 The file to be found. If it is passed as an absolute path, fname will
510 The file to be found. If it is passed as an absolute path, fname will
511 simply be returned.
511 simply be returned.
512
512
513 Returns
513 Returns
514 -------
514 -------
515 Raises :exc:`IOError` if file not found or returns absolute path to file.
515 Raises :exc:`IOError` if file not found or returns absolute path to file.
516 """
516 """
517 # import here, because profiledir also imports from utils.path
517 # import here, because profiledir also imports from utils.path
518 from IPython.core.profiledir import ProfileDir
518 from IPython.core.profiledir import ProfileDir
519 try:
519 try:
520 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
520 pd = ProfileDir.find_profile_dir_by_name(get_ipython_dir(), profile)
521 except Exception:
521 except Exception:
522 # will raise ProfileDirError if no such profile
522 # will raise ProfileDirError if no such profile
523 raise IOError("Profile %r not found")
523 raise IOError("Profile %r not found")
524 return filefind(filename, ['.', pd.security_dir])
524 return filefind(filename, ['.', pd.security_dir])
525
525
526
526
527 ENOLINK = 1998
527 ENOLINK = 1998
528
528
529 def link(src, dst):
529 def link(src, dst):
530 """Hard links ``src`` to ``dst``, returning 0 or errno.
530 """Hard links ``src`` to ``dst``, returning 0 or errno.
531
531
532 Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
532 Note that the special errno ``ENOLINK`` will be returned if ``os.link`` isn't
533 supported by the operating system.
533 supported by the operating system.
534 """
534 """
535
535
536 if not hasattr(os, "link"):
536 if not hasattr(os, "link"):
537 return ENOLINK
537 return ENOLINK
538 link_errno = 0
538 link_errno = 0
539 try:
539 try:
540 os.link(src, dst)
540 os.link(src, dst)
541 except OSError as e:
541 except OSError as e:
542 link_errno = e.errno
542 link_errno = e.errno
543 return link_errno
543 return link_errno
544
544
545
545
546 def link_or_copy(src, dst):
546 def link_or_copy(src, dst):
547 """Attempts to hardlink ``src`` to ``dst``, copying if the link fails.
547 """Attempts to hardlink ``src`` to ``dst``, copying if the link fails.
548
548
549 Attempts to maintain the semantics of ``shutil.copy``.
549 Attempts to maintain the semantics of ``shutil.copy``.
550
550
551 Because ``os.link`` does not overwrite files, a unique temporary file
551 Because ``os.link`` does not overwrite files, a unique temporary file
552 will be used if the target already exists, then that file will be moved
552 will be used if the target already exists, then that file will be moved
553 into place.
553 into place.
554 """
554 """
555
555
556 if os.path.isdir(dst):
556 if os.path.isdir(dst):
557 dst = os.path.join(dst, os.path.basename(src))
557 dst = os.path.join(dst, os.path.basename(src))
558
558
559 link_errno = link(src, dst)
559 link_errno = link(src, dst)
560 if link_errno == errno.EEXIST:
560 if link_errno == errno.EEXIST:
561 new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), )
561 new_dst = dst + "-temp-%04X" %(random.randint(1, 16**4), )
562 try:
562 try:
563 link_or_copy(src, new_dst)
563 link_or_copy(src, new_dst)
564 except:
564 except:
565 try:
565 try:
566 os.remove(new_dst)
566 os.remove(new_dst)
567 except OSError:
567 except OSError:
568 pass
568 pass
569 raise
569 raise
570 os.rename(new_dst, dst)
570 os.rename(new_dst, dst)
571 elif link_errno != 0:
571 elif link_errno != 0:
572 # Either link isn't supported, or the filesystem doesn't support
572 # Either link isn't supported, or the filesystem doesn't support
573 # linking, or 'src' and 'dst' are on different filesystems.
573 # linking, or 'src' and 'dst' are on different filesystems.
574 shutil.copy(src, dst)
574 shutil.copy(src, dst)
@@ -1,643 +1,676 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for IPython.utils.path.py"""
2 """Tests for IPython.utils.path.py"""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008-2011 The IPython Development Team
5 # Copyright (C) 2008-2011 The IPython Development Team
6 #
6 #
7 # Distributed under the terms of the BSD License. The full license is in
7 # Distributed under the terms of the BSD License. The full license is in
8 # the file COPYING, distributed as part of this software.
8 # the file COPYING, distributed as part of this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 from __future__ import with_statement
15 from __future__ import with_statement
16
16
17 import errno
17 import os
18 import os
18 import shutil
19 import shutil
19 import sys
20 import sys
20 import tempfile
21 import tempfile
22 import warnings
21 from contextlib import contextmanager
23 from contextlib import contextmanager
22
24
23 from os.path import join, abspath, split
25 from os.path import join, abspath, split
24
26
25 import nose.tools as nt
27 import nose.tools as nt
26
28
27 from nose import with_setup
29 from nose import with_setup
28
30
29 import IPython
31 import IPython
30 from IPython.testing import decorators as dec
32 from IPython.testing import decorators as dec
31 from IPython.testing.decorators import (skip_if_not_win32, skip_win32,
33 from IPython.testing.decorators import (skip_if_not_win32, skip_win32,
32 onlyif_unicode_paths,)
34 onlyif_unicode_paths,)
33 from IPython.testing.tools import make_tempfile, AssertPrints
35 from IPython.testing.tools import make_tempfile, AssertPrints
34 from IPython.utils import path
36 from IPython.utils import path
35 from IPython.utils import py3compat
37 from IPython.utils import py3compat
36 from IPython.utils.tempdir import TemporaryDirectory
38 from IPython.utils.tempdir import TemporaryDirectory
37
39
38 # Platform-dependent imports
40 # Platform-dependent imports
39 try:
41 try:
40 import winreg as wreg # Py 3
42 import winreg as wreg # Py 3
41 except ImportError:
43 except ImportError:
42 try:
44 try:
43 import _winreg as wreg # Py 2
45 import _winreg as wreg # Py 2
44 except ImportError:
46 except ImportError:
45 #Fake _winreg module on none windows platforms
47 #Fake _winreg module on none windows platforms
46 import types
48 import types
47 wr_name = "winreg" if py3compat.PY3 else "_winreg"
49 wr_name = "winreg" if py3compat.PY3 else "_winreg"
48 sys.modules[wr_name] = types.ModuleType(wr_name)
50 sys.modules[wr_name] = types.ModuleType(wr_name)
49 try:
51 try:
50 import winreg as wreg
52 import winreg as wreg
51 except ImportError:
53 except ImportError:
52 import _winreg as wreg
54 import _winreg as wreg
53 #Add entries that needs to be stubbed by the testing code
55 #Add entries that needs to be stubbed by the testing code
54 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
56 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
55
57
56 try:
58 try:
57 reload
59 reload
58 except NameError: # Python 3
60 except NameError: # Python 3
59 from imp import reload
61 from imp import reload
60
62
61 #-----------------------------------------------------------------------------
63 #-----------------------------------------------------------------------------
62 # Globals
64 # Globals
63 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
64 env = os.environ
66 env = os.environ
65 TEST_FILE_PATH = split(abspath(__file__))[0]
67 TEST_FILE_PATH = split(abspath(__file__))[0]
66 TMP_TEST_DIR = tempfile.mkdtemp()
68 TMP_TEST_DIR = tempfile.mkdtemp()
67 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
69 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
68 XDG_TEST_DIR = join(HOME_TEST_DIR, "xdg_test_dir")
70 XDG_TEST_DIR = join(HOME_TEST_DIR, "xdg_test_dir")
69 XDG_CACHE_DIR = join(HOME_TEST_DIR, "xdg_cache_dir")
71 XDG_CACHE_DIR = join(HOME_TEST_DIR, "xdg_cache_dir")
70 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
72 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
71 #
73 #
72 # Setup/teardown functions/decorators
74 # Setup/teardown functions/decorators
73 #
75 #
74
76
75 def setup():
77 def setup():
76 """Setup testenvironment for the module:
78 """Setup testenvironment for the module:
77
79
78 - Adds dummy home dir tree
80 - Adds dummy home dir tree
79 """
81 """
80 # Do not mask exceptions here. In particular, catching WindowsError is a
82 # Do not mask exceptions here. In particular, catching WindowsError is a
81 # problem because that exception is only defined on Windows...
83 # problem because that exception is only defined on Windows...
82 os.makedirs(IP_TEST_DIR)
84 os.makedirs(IP_TEST_DIR)
83 os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython'))
85 os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython'))
84 os.makedirs(os.path.join(XDG_CACHE_DIR, 'ipython'))
86 os.makedirs(os.path.join(XDG_CACHE_DIR, 'ipython'))
85
87
86
88
87 def teardown():
89 def teardown():
88 """Teardown testenvironment for the module:
90 """Teardown testenvironment for the module:
89
91
90 - Remove dummy home dir tree
92 - Remove dummy home dir tree
91 """
93 """
92 # Note: we remove the parent test dir, which is the root of all test
94 # Note: we remove the parent test dir, which is the root of all test
93 # subdirs we may have created. Use shutil instead of os.removedirs, so
95 # subdirs we may have created. Use shutil instead of os.removedirs, so
94 # that non-empty directories are all recursively removed.
96 # that non-empty directories are all recursively removed.
95 shutil.rmtree(TMP_TEST_DIR)
97 shutil.rmtree(TMP_TEST_DIR)
96
98
97
99
98 def setup_environment():
100 def setup_environment():
99 """Setup testenvironment for some functions that are tested
101 """Setup testenvironment for some functions that are tested
100 in this module. In particular this functions stores attributes
102 in this module. In particular this functions stores attributes
101 and other things that we need to stub in some test functions.
103 and other things that we need to stub in some test functions.
102 This needs to be done on a function level and not module level because
104 This needs to be done on a function level and not module level because
103 each testfunction needs a pristine environment.
105 each testfunction needs a pristine environment.
104 """
106 """
105 global oldstuff, platformstuff
107 global oldstuff, platformstuff
106 oldstuff = (env.copy(), os.name, sys.platform, path.get_home_dir, IPython.__file__, os.getcwd())
108 oldstuff = (env.copy(), os.name, sys.platform, path.get_home_dir, IPython.__file__, os.getcwd())
107
109
108 if os.name == 'nt':
110 if os.name == 'nt':
109 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
111 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
110
112
111
113
112 def teardown_environment():
114 def teardown_environment():
113 """Restore things that were remembered by the setup_environment function
115 """Restore things that were remembered by the setup_environment function
114 """
116 """
115 (oldenv, os.name, sys.platform, path.get_home_dir, IPython.__file__, old_wd) = oldstuff
117 (oldenv, os.name, sys.platform, path.get_home_dir, IPython.__file__, old_wd) = oldstuff
116 os.chdir(old_wd)
118 os.chdir(old_wd)
117 reload(path)
119 reload(path)
118
120
119 for key in list(env):
121 for key in list(env):
120 if key not in oldenv:
122 if key not in oldenv:
121 del env[key]
123 del env[key]
122 env.update(oldenv)
124 env.update(oldenv)
123 if hasattr(sys, 'frozen'):
125 if hasattr(sys, 'frozen'):
124 del sys.frozen
126 del sys.frozen
125 if os.name == 'nt':
127 if os.name == 'nt':
126 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
128 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
127
129
128 # Build decorator that uses the setup_environment/setup_environment
130 # Build decorator that uses the setup_environment/setup_environment
129 with_environment = with_setup(setup_environment, teardown_environment)
131 with_environment = with_setup(setup_environment, teardown_environment)
130
132
133 @contextmanager
134 def patch_get_home_dir(dirpath):
135 orig_get_home_dir = path.get_home_dir
136 path.get_home_dir = lambda : dirpath
137 try:
138 yield
139 finally:
140 path.get_home_dir = orig_get_home_dir
141
131 @skip_if_not_win32
142 @skip_if_not_win32
132 @with_environment
143 @with_environment
133 def test_get_home_dir_1():
144 def test_get_home_dir_1():
134 """Testcase for py2exe logic, un-compressed lib
145 """Testcase for py2exe logic, un-compressed lib
135 """
146 """
136 unfrozen = path.get_home_dir()
147 unfrozen = path.get_home_dir()
137 sys.frozen = True
148 sys.frozen = True
138
149
139 #fake filename for IPython.__init__
150 #fake filename for IPython.__init__
140 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
151 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
141
152
142 home_dir = path.get_home_dir()
153 home_dir = path.get_home_dir()
143 nt.assert_equal(home_dir, unfrozen)
154 nt.assert_equal(home_dir, unfrozen)
144
155
145
156
146 @skip_if_not_win32
157 @skip_if_not_win32
147 @with_environment
158 @with_environment
148 def test_get_home_dir_2():
159 def test_get_home_dir_2():
149 """Testcase for py2exe logic, compressed lib
160 """Testcase for py2exe logic, compressed lib
150 """
161 """
151 unfrozen = path.get_home_dir()
162 unfrozen = path.get_home_dir()
152 sys.frozen = True
163 sys.frozen = True
153 #fake filename for IPython.__init__
164 #fake filename for IPython.__init__
154 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
165 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
155
166
156 home_dir = path.get_home_dir(True)
167 home_dir = path.get_home_dir(True)
157 nt.assert_equal(home_dir, unfrozen)
168 nt.assert_equal(home_dir, unfrozen)
158
169
159
170
160 @with_environment
171 @with_environment
161 def test_get_home_dir_3():
172 def test_get_home_dir_3():
162 """get_home_dir() uses $HOME if set"""
173 """get_home_dir() uses $HOME if set"""
163 env["HOME"] = HOME_TEST_DIR
174 env["HOME"] = HOME_TEST_DIR
164 home_dir = path.get_home_dir(True)
175 home_dir = path.get_home_dir(True)
165 # get_home_dir expands symlinks
176 # get_home_dir expands symlinks
166 nt.assert_equal(home_dir, os.path.realpath(env["HOME"]))
177 nt.assert_equal(home_dir, os.path.realpath(env["HOME"]))
167
178
168
179
169 @with_environment
180 @with_environment
170 def test_get_home_dir_4():
181 def test_get_home_dir_4():
171 """get_home_dir() still works if $HOME is not set"""
182 """get_home_dir() still works if $HOME is not set"""
172
183
173 if 'HOME' in env: del env['HOME']
184 if 'HOME' in env: del env['HOME']
174 # this should still succeed, but we don't care what the answer is
185 # this should still succeed, but we don't care what the answer is
175 home = path.get_home_dir(False)
186 home = path.get_home_dir(False)
176
187
177 @with_environment
188 @with_environment
178 def test_get_home_dir_5():
189 def test_get_home_dir_5():
179 """raise HomeDirError if $HOME is specified, but not a writable dir"""
190 """raise HomeDirError if $HOME is specified, but not a writable dir"""
180 env['HOME'] = abspath(HOME_TEST_DIR+'garbage')
191 env['HOME'] = abspath(HOME_TEST_DIR+'garbage')
181 # set os.name = posix, to prevent My Documents fallback on Windows
192 # set os.name = posix, to prevent My Documents fallback on Windows
182 os.name = 'posix'
193 os.name = 'posix'
183 nt.assert_raises(path.HomeDirError, path.get_home_dir, True)
194 nt.assert_raises(path.HomeDirError, path.get_home_dir, True)
184
195
185
196
186 # Should we stub wreg fully so we can run the test on all platforms?
197 # Should we stub wreg fully so we can run the test on all platforms?
187 @skip_if_not_win32
198 @skip_if_not_win32
188 @with_environment
199 @with_environment
189 def test_get_home_dir_8():
200 def test_get_home_dir_8():
190 """Using registry hack for 'My Documents', os=='nt'
201 """Using registry hack for 'My Documents', os=='nt'
191
202
192 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
203 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
193 """
204 """
194 os.name = 'nt'
205 os.name = 'nt'
195 # Remove from stub environment all keys that may be set
206 # Remove from stub environment all keys that may be set
196 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
207 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
197 env.pop(key, None)
208 env.pop(key, None)
198
209
199 #Stub windows registry functions
210 #Stub windows registry functions
200 def OpenKey(x, y):
211 def OpenKey(x, y):
201 class key:
212 class key:
202 def Close(self):
213 def Close(self):
203 pass
214 pass
204 return key()
215 return key()
205 def QueryValueEx(x, y):
216 def QueryValueEx(x, y):
206 return [abspath(HOME_TEST_DIR)]
217 return [abspath(HOME_TEST_DIR)]
207
218
208 wreg.OpenKey = OpenKey
219 wreg.OpenKey = OpenKey
209 wreg.QueryValueEx = QueryValueEx
220 wreg.QueryValueEx = QueryValueEx
210
221
211 home_dir = path.get_home_dir()
222 home_dir = path.get_home_dir()
212 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
223 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
213
224
214
225
215 @with_environment
226 @with_environment
216 def test_get_ipython_dir_1():
227 def test_get_ipython_dir_1():
217 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
228 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
218 env_ipdir = os.path.join("someplace", ".ipython")
229 env_ipdir = os.path.join("someplace", ".ipython")
219 path._writable_dir = lambda path: True
230 path._writable_dir = lambda path: True
220 env['IPYTHONDIR'] = env_ipdir
231 env['IPYTHONDIR'] = env_ipdir
221 ipdir = path.get_ipython_dir()
232 ipdir = path.get_ipython_dir()
222 nt.assert_equal(ipdir, env_ipdir)
233 nt.assert_equal(ipdir, env_ipdir)
223
234
224
235
225 @with_environment
236 @with_environment
226 def test_get_ipython_dir_2():
237 def test_get_ipython_dir_2():
227 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
238 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
228 path.get_home_dir = lambda : "someplace"
239 with patch_get_home_dir('someplace'):
229 path.get_xdg_dir = lambda : None
240 path.get_xdg_dir = lambda : None
230 path._writable_dir = lambda path: True
241 path._writable_dir = lambda path: True
231 os.name = "posix"
242 os.name = "posix"
232 env.pop('IPYTHON_DIR', None)
243 env.pop('IPYTHON_DIR', None)
233 env.pop('IPYTHONDIR', None)
244 env.pop('IPYTHONDIR', None)
234 env.pop('XDG_CONFIG_HOME', None)
245 env.pop('XDG_CONFIG_HOME', None)
235 ipdir = path.get_ipython_dir()
246 ipdir = path.get_ipython_dir()
236 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
247 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
237
248
238 @with_environment
249 @with_environment
239 def test_get_ipython_dir_3():
250 def test_get_ipython_dir_3():
240 """test_get_ipython_dir_3, use XDG if defined, and .ipython doesn't exist."""
251 """test_get_ipython_dir_3, move XDG if defined, and .ipython doesn't exist."""
241 path.get_home_dir = lambda : "someplace"
252 tmphome = TemporaryDirectory()
242 path._writable_dir = lambda path: True
253 try:
243 os.name = "posix"
254 with patch_get_home_dir(tmphome.name):
244 env.pop('IPYTHON_DIR', None)
255 os.name = "posix"
245 env.pop('IPYTHONDIR', None)
256 env.pop('IPYTHON_DIR', None)
246 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
257 env.pop('IPYTHONDIR', None)
247 ipdir = path.get_ipython_dir()
258 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
248 if sys.platform == "darwin":
259
249 expected = os.path.join("someplace", ".ipython")
260 with warnings.catch_warnings(record=True) as w:
250 else:
261 ipdir = path.get_ipython_dir()
251 expected = os.path.join(XDG_TEST_DIR, "ipython")
262
252 nt.assert_equal(ipdir, expected)
263 nt.assert_equal(ipdir, os.path.join(tmphome.name, ".ipython"))
264 if sys.platform != 'darwin':
265 nt.assert_equal(len(w), 1)
266 nt.assert_in('Moving', str(w[0]))
267 finally:
268 tmphome.cleanup()
253
269
254 @with_environment
270 @with_environment
255 def test_get_ipython_dir_4():
271 def test_get_ipython_dir_4():
256 """test_get_ipython_dir_4, use XDG if both exist."""
272 """test_get_ipython_dir_4, warn if XDG and home both exist."""
257 path.get_home_dir = lambda : HOME_TEST_DIR
273 with patch_get_home_dir(HOME_TEST_DIR):
258 os.name = "posix"
274 os.name = "posix"
259 env.pop('IPYTHON_DIR', None)
275 env.pop('IPYTHON_DIR', None)
260 env.pop('IPYTHONDIR', None)
276 env.pop('IPYTHONDIR', None)
261 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
277 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
262 ipdir = path.get_ipython_dir()
278 try:
263 if sys.platform == "darwin":
279 os.mkdir(os.path.join(XDG_TEST_DIR, 'ipython'))
264 expected = os.path.join(HOME_TEST_DIR, ".ipython")
280 except OSError as e:
265 else:
281 if e.errno != errno.EEXIST:
266 expected = os.path.join(XDG_TEST_DIR, "ipython")
282 raise
267 nt.assert_equal(ipdir, expected)
283
284 with warnings.catch_warnings(record=True) as w:
285 ipdir = path.get_ipython_dir()
286
287 nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, ".ipython"))
288 if sys.platform != 'darwin':
289 nt.assert_equal(len(w), 1)
290 nt.assert_in('Ignoring', str(w[0]))
268
291
269 @with_environment
292 @with_environment
270 def test_get_ipython_dir_5():
293 def test_get_ipython_dir_5():
271 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
294 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
272 path.get_home_dir = lambda : HOME_TEST_DIR
295 with patch_get_home_dir(HOME_TEST_DIR):
273 os.name = "posix"
296 os.name = "posix"
274 env.pop('IPYTHON_DIR', None)
297 env.pop('IPYTHON_DIR', None)
275 env.pop('IPYTHONDIR', None)
298 env.pop('IPYTHONDIR', None)
276 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
299 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
277 os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython'))
300 try:
278 ipdir = path.get_ipython_dir()
301 os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython'))
279 nt.assert_equal(ipdir, IP_TEST_DIR)
302 except OSError as e:
303 if e.errno != errno.ENOENT:
304 raise
305 ipdir = path.get_ipython_dir()
306 nt.assert_equal(ipdir, IP_TEST_DIR)
280
307
281 @with_environment
308 @with_environment
282 def test_get_ipython_dir_6():
309 def test_get_ipython_dir_6():
283 """test_get_ipython_dir_6, use XDG if defined and neither exist."""
310 """test_get_ipython_dir_6, use home over XDG if defined and neither exist."""
284 xdg = os.path.join(HOME_TEST_DIR, 'somexdg')
311 xdg = os.path.join(HOME_TEST_DIR, 'somexdg')
285 os.mkdir(xdg)
312 os.mkdir(xdg)
286 shutil.rmtree(os.path.join(HOME_TEST_DIR, '.ipython'))
313 shutil.rmtree(os.path.join(HOME_TEST_DIR, '.ipython'))
287 path.get_home_dir = lambda : HOME_TEST_DIR
314 with patch_get_home_dir(HOME_TEST_DIR):
288 path.get_xdg_dir = lambda : xdg
315 orig_get_xdg_dir = path.get_xdg_dir
289 os.name = "posix"
316 path.get_xdg_dir = lambda : xdg
290 env.pop('IPYTHON_DIR', None)
317 try:
291 env.pop('IPYTHONDIR', None)
318 os.name = "posix"
292 env.pop('XDG_CONFIG_HOME', None)
319 env.pop('IPYTHON_DIR', None)
293 xdg_ipdir = os.path.join(xdg, "ipython")
320 env.pop('IPYTHONDIR', None)
294 ipdir = path.get_ipython_dir()
321 env.pop('XDG_CONFIG_HOME', None)
295 nt.assert_equal(ipdir, xdg_ipdir)
322 with warnings.catch_warnings(record=True) as w:
323 ipdir = path.get_ipython_dir()
324
325 nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, '.ipython'))
326 nt.assert_equal(len(w), 0)
327 finally:
328 path.get_xdg_dir = orig_get_xdg_dir
296
329
297 @with_environment
330 @with_environment
298 def test_get_ipython_dir_7():
331 def test_get_ipython_dir_7():
299 """test_get_ipython_dir_7, test home directory expansion on IPYTHONDIR"""
332 """test_get_ipython_dir_7, test home directory expansion on IPYTHONDIR"""
300 path._writable_dir = lambda path: True
333 path._writable_dir = lambda path: True
301 home_dir = os.path.normpath(os.path.expanduser('~'))
334 home_dir = os.path.normpath(os.path.expanduser('~'))
302 env['IPYTHONDIR'] = os.path.join('~', 'somewhere')
335 env['IPYTHONDIR'] = os.path.join('~', 'somewhere')
303 ipdir = path.get_ipython_dir()
336 ipdir = path.get_ipython_dir()
304 nt.assert_equal(ipdir, os.path.join(home_dir, 'somewhere'))
337 nt.assert_equal(ipdir, os.path.join(home_dir, 'somewhere'))
305
338
306 @skip_win32
339 @skip_win32
307 @with_environment
340 @with_environment
308 def test_get_ipython_dir_8():
341 def test_get_ipython_dir_8():
309 """test_get_ipython_dir_8, test / home directory"""
342 """test_get_ipython_dir_8, test / home directory"""
310 old = path._writable_dir, path.get_xdg_dir
343 old = path._writable_dir, path.get_xdg_dir
311 try:
344 try:
312 path._writable_dir = lambda path: bool(path)
345 path._writable_dir = lambda path: bool(path)
313 path.get_xdg_dir = lambda: None
346 path.get_xdg_dir = lambda: None
314 env.pop('IPYTHON_DIR', None)
347 env.pop('IPYTHON_DIR', None)
315 env.pop('IPYTHONDIR', None)
348 env.pop('IPYTHONDIR', None)
316 env['HOME'] = '/'
349 env['HOME'] = '/'
317 nt.assert_equal(path.get_ipython_dir(), '/.ipython')
350 nt.assert_equal(path.get_ipython_dir(), '/.ipython')
318 finally:
351 finally:
319 path._writable_dir, path.get_xdg_dir = old
352 path._writable_dir, path.get_xdg_dir = old
320
353
321 @with_environment
354 @with_environment
322 def test_get_xdg_dir_0():
355 def test_get_xdg_dir_0():
323 """test_get_xdg_dir_0, check xdg_dir"""
356 """test_get_xdg_dir_0, check xdg_dir"""
324 reload(path)
357 reload(path)
325 path._writable_dir = lambda path: True
358 path._writable_dir = lambda path: True
326 path.get_home_dir = lambda : 'somewhere'
359 path.get_home_dir = lambda : 'somewhere'
327 os.name = "posix"
360 os.name = "posix"
328 sys.platform = "linux2"
361 sys.platform = "linux2"
329 env.pop('IPYTHON_DIR', None)
362 env.pop('IPYTHON_DIR', None)
330 env.pop('IPYTHONDIR', None)
363 env.pop('IPYTHONDIR', None)
331 env.pop('XDG_CONFIG_HOME', None)
364 env.pop('XDG_CONFIG_HOME', None)
332
365
333 nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config'))
366 nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config'))
334
367
335
368
336 @with_environment
369 @with_environment
337 def test_get_xdg_dir_1():
370 def test_get_xdg_dir_1():
338 """test_get_xdg_dir_1, check nonexistant xdg_dir"""
371 """test_get_xdg_dir_1, check nonexistant xdg_dir"""
339 reload(path)
372 reload(path)
340 path.get_home_dir = lambda : HOME_TEST_DIR
373 path.get_home_dir = lambda : HOME_TEST_DIR
341 os.name = "posix"
374 os.name = "posix"
342 sys.platform = "linux2"
375 sys.platform = "linux2"
343 env.pop('IPYTHON_DIR', None)
376 env.pop('IPYTHON_DIR', None)
344 env.pop('IPYTHONDIR', None)
377 env.pop('IPYTHONDIR', None)
345 env.pop('XDG_CONFIG_HOME', None)
378 env.pop('XDG_CONFIG_HOME', None)
346 nt.assert_equal(path.get_xdg_dir(), None)
379 nt.assert_equal(path.get_xdg_dir(), None)
347
380
348 @with_environment
381 @with_environment
349 def test_get_xdg_dir_2():
382 def test_get_xdg_dir_2():
350 """test_get_xdg_dir_2, check xdg_dir default to ~/.config"""
383 """test_get_xdg_dir_2, check xdg_dir default to ~/.config"""
351 reload(path)
384 reload(path)
352 path.get_home_dir = lambda : HOME_TEST_DIR
385 path.get_home_dir = lambda : HOME_TEST_DIR
353 os.name = "posix"
386 os.name = "posix"
354 sys.platform = "linux2"
387 sys.platform = "linux2"
355 env.pop('IPYTHON_DIR', None)
388 env.pop('IPYTHON_DIR', None)
356 env.pop('IPYTHONDIR', None)
389 env.pop('IPYTHONDIR', None)
357 env.pop('XDG_CONFIG_HOME', None)
390 env.pop('XDG_CONFIG_HOME', None)
358 cfgdir=os.path.join(path.get_home_dir(), '.config')
391 cfgdir=os.path.join(path.get_home_dir(), '.config')
359 if not os.path.exists(cfgdir):
392 if not os.path.exists(cfgdir):
360 os.makedirs(cfgdir)
393 os.makedirs(cfgdir)
361
394
362 nt.assert_equal(path.get_xdg_dir(), cfgdir)
395 nt.assert_equal(path.get_xdg_dir(), cfgdir)
363
396
364 @with_environment
397 @with_environment
365 def test_get_xdg_dir_3():
398 def test_get_xdg_dir_3():
366 """test_get_xdg_dir_3, check xdg_dir not used on OS X"""
399 """test_get_xdg_dir_3, check xdg_dir not used on OS X"""
367 reload(path)
400 reload(path)
368 path.get_home_dir = lambda : HOME_TEST_DIR
401 path.get_home_dir = lambda : HOME_TEST_DIR
369 os.name = "posix"
402 os.name = "posix"
370 sys.platform = "darwin"
403 sys.platform = "darwin"
371 env.pop('IPYTHON_DIR', None)
404 env.pop('IPYTHON_DIR', None)
372 env.pop('IPYTHONDIR', None)
405 env.pop('IPYTHONDIR', None)
373 env.pop('XDG_CONFIG_HOME', None)
406 env.pop('XDG_CONFIG_HOME', None)
374 cfgdir=os.path.join(path.get_home_dir(), '.config')
407 cfgdir=os.path.join(path.get_home_dir(), '.config')
375 if not os.path.exists(cfgdir):
408 if not os.path.exists(cfgdir):
376 os.makedirs(cfgdir)
409 os.makedirs(cfgdir)
377
410
378 nt.assert_equal(path.get_xdg_dir(), None)
411 nt.assert_equal(path.get_xdg_dir(), None)
379
412
380 def test_filefind():
413 def test_filefind():
381 """Various tests for filefind"""
414 """Various tests for filefind"""
382 f = tempfile.NamedTemporaryFile()
415 f = tempfile.NamedTemporaryFile()
383 # print 'fname:',f.name
416 # print 'fname:',f.name
384 alt_dirs = path.get_ipython_dir()
417 alt_dirs = path.get_ipython_dir()
385 t = path.filefind(f.name, alt_dirs)
418 t = path.filefind(f.name, alt_dirs)
386 # print 'found:',t
419 # print 'found:',t
387
420
388 @with_environment
421 @with_environment
389 def test_get_ipython_cache_dir():
422 def test_get_ipython_cache_dir():
390 os.environ["HOME"] = HOME_TEST_DIR
423 os.environ["HOME"] = HOME_TEST_DIR
391 if os.name == 'posix' and sys.platform != 'darwin':
424 if os.name == 'posix' and sys.platform != 'darwin':
392 # test default
425 # test default
393 os.makedirs(os.path.join(HOME_TEST_DIR, ".cache"))
426 os.makedirs(os.path.join(HOME_TEST_DIR, ".cache"))
394 os.environ.pop("XDG_CACHE_HOME", None)
427 os.environ.pop("XDG_CACHE_HOME", None)
395 ipdir = path.get_ipython_cache_dir()
428 ipdir = path.get_ipython_cache_dir()
396 nt.assert_equal(os.path.join(HOME_TEST_DIR, ".cache", "ipython"),
429 nt.assert_equal(os.path.join(HOME_TEST_DIR, ".cache", "ipython"),
397 ipdir)
430 ipdir)
398 nt.assert_true(os.path.isdir(ipdir))
431 nt.assert_true(os.path.isdir(ipdir))
399
432
400 # test env override
433 # test env override
401 os.environ["XDG_CACHE_HOME"] = XDG_CACHE_DIR
434 os.environ["XDG_CACHE_HOME"] = XDG_CACHE_DIR
402 ipdir = path.get_ipython_cache_dir()
435 ipdir = path.get_ipython_cache_dir()
403 nt.assert_true(os.path.isdir(ipdir))
436 nt.assert_true(os.path.isdir(ipdir))
404 nt.assert_equal(ipdir, os.path.join(XDG_CACHE_DIR, "ipython"))
437 nt.assert_equal(ipdir, os.path.join(XDG_CACHE_DIR, "ipython"))
405 else:
438 else:
406 nt.assert_equal(path.get_ipython_cache_dir(),
439 nt.assert_equal(path.get_ipython_cache_dir(),
407 path.get_ipython_dir())
440 path.get_ipython_dir())
408
441
409 def test_get_ipython_package_dir():
442 def test_get_ipython_package_dir():
410 ipdir = path.get_ipython_package_dir()
443 ipdir = path.get_ipython_package_dir()
411 nt.assert_true(os.path.isdir(ipdir))
444 nt.assert_true(os.path.isdir(ipdir))
412
445
413
446
414 def test_get_ipython_module_path():
447 def test_get_ipython_module_path():
415 ipapp_path = path.get_ipython_module_path('IPython.terminal.ipapp')
448 ipapp_path = path.get_ipython_module_path('IPython.terminal.ipapp')
416 nt.assert_true(os.path.isfile(ipapp_path))
449 nt.assert_true(os.path.isfile(ipapp_path))
417
450
418
451
419 @dec.skip_if_not_win32
452 @dec.skip_if_not_win32
420 def test_get_long_path_name_win32():
453 def test_get_long_path_name_win32():
421 with TemporaryDirectory() as tmpdir:
454 with TemporaryDirectory() as tmpdir:
422
455
423 # Make a long path.
456 # Make a long path.
424 long_path = os.path.join(tmpdir, u'this is my long path name')
457 long_path = os.path.join(tmpdir, u'this is my long path name')
425 os.makedirs(long_path)
458 os.makedirs(long_path)
426
459
427 # Test to see if the short path evaluates correctly.
460 # Test to see if the short path evaluates correctly.
428 short_path = os.path.join(tmpdir, u'THISIS~1')
461 short_path = os.path.join(tmpdir, u'THISIS~1')
429 evaluated_path = path.get_long_path_name(short_path)
462 evaluated_path = path.get_long_path_name(short_path)
430 nt.assert_equal(evaluated_path.lower(), long_path.lower())
463 nt.assert_equal(evaluated_path.lower(), long_path.lower())
431
464
432
465
433 @dec.skip_win32
466 @dec.skip_win32
434 def test_get_long_path_name():
467 def test_get_long_path_name():
435 p = path.get_long_path_name('/usr/local')
468 p = path.get_long_path_name('/usr/local')
436 nt.assert_equal(p,'/usr/local')
469 nt.assert_equal(p,'/usr/local')
437
470
438 @dec.skip_win32 # can't create not-user-writable dir on win
471 @dec.skip_win32 # can't create not-user-writable dir on win
439 @with_environment
472 @with_environment
440 def test_not_writable_ipdir():
473 def test_not_writable_ipdir():
441 tmpdir = tempfile.mkdtemp()
474 tmpdir = tempfile.mkdtemp()
442 os.name = "posix"
475 os.name = "posix"
443 env.pop('IPYTHON_DIR', None)
476 env.pop('IPYTHON_DIR', None)
444 env.pop('IPYTHONDIR', None)
477 env.pop('IPYTHONDIR', None)
445 env.pop('XDG_CONFIG_HOME', None)
478 env.pop('XDG_CONFIG_HOME', None)
446 env['HOME'] = tmpdir
479 env['HOME'] = tmpdir
447 ipdir = os.path.join(tmpdir, '.ipython')
480 ipdir = os.path.join(tmpdir, '.ipython')
448 os.mkdir(ipdir)
481 os.mkdir(ipdir)
449 os.chmod(ipdir, 600)
482 os.chmod(ipdir, 600)
450 with AssertPrints('is not a writable location', channel='stderr'):
483 with AssertPrints('is not a writable location', channel='stderr'):
451 ipdir = path.get_ipython_dir()
484 ipdir = path.get_ipython_dir()
452 env.pop('IPYTHON_DIR', None)
485 env.pop('IPYTHON_DIR', None)
453
486
454 def test_unquote_filename():
487 def test_unquote_filename():
455 for win32 in (True, False):
488 for win32 in (True, False):
456 nt.assert_equal(path.unquote_filename('foo.py', win32=win32), 'foo.py')
489 nt.assert_equal(path.unquote_filename('foo.py', win32=win32), 'foo.py')
457 nt.assert_equal(path.unquote_filename('foo bar.py', win32=win32), 'foo bar.py')
490 nt.assert_equal(path.unquote_filename('foo bar.py', win32=win32), 'foo bar.py')
458 nt.assert_equal(path.unquote_filename('"foo.py"', win32=True), 'foo.py')
491 nt.assert_equal(path.unquote_filename('"foo.py"', win32=True), 'foo.py')
459 nt.assert_equal(path.unquote_filename('"foo bar.py"', win32=True), 'foo bar.py')
492 nt.assert_equal(path.unquote_filename('"foo bar.py"', win32=True), 'foo bar.py')
460 nt.assert_equal(path.unquote_filename("'foo.py'", win32=True), 'foo.py')
493 nt.assert_equal(path.unquote_filename("'foo.py'", win32=True), 'foo.py')
461 nt.assert_equal(path.unquote_filename("'foo bar.py'", win32=True), 'foo bar.py')
494 nt.assert_equal(path.unquote_filename("'foo bar.py'", win32=True), 'foo bar.py')
462 nt.assert_equal(path.unquote_filename('"foo.py"', win32=False), '"foo.py"')
495 nt.assert_equal(path.unquote_filename('"foo.py"', win32=False), '"foo.py"')
463 nt.assert_equal(path.unquote_filename('"foo bar.py"', win32=False), '"foo bar.py"')
496 nt.assert_equal(path.unquote_filename('"foo bar.py"', win32=False), '"foo bar.py"')
464 nt.assert_equal(path.unquote_filename("'foo.py'", win32=False), "'foo.py'")
497 nt.assert_equal(path.unquote_filename("'foo.py'", win32=False), "'foo.py'")
465 nt.assert_equal(path.unquote_filename("'foo bar.py'", win32=False), "'foo bar.py'")
498 nt.assert_equal(path.unquote_filename("'foo bar.py'", win32=False), "'foo bar.py'")
466
499
467 @with_environment
500 @with_environment
468 def test_get_py_filename():
501 def test_get_py_filename():
469 os.chdir(TMP_TEST_DIR)
502 os.chdir(TMP_TEST_DIR)
470 for win32 in (True, False):
503 for win32 in (True, False):
471 with make_tempfile('foo.py'):
504 with make_tempfile('foo.py'):
472 nt.assert_equal(path.get_py_filename('foo.py', force_win32=win32), 'foo.py')
505 nt.assert_equal(path.get_py_filename('foo.py', force_win32=win32), 'foo.py')
473 nt.assert_equal(path.get_py_filename('foo', force_win32=win32), 'foo.py')
506 nt.assert_equal(path.get_py_filename('foo', force_win32=win32), 'foo.py')
474 with make_tempfile('foo'):
507 with make_tempfile('foo'):
475 nt.assert_equal(path.get_py_filename('foo', force_win32=win32), 'foo')
508 nt.assert_equal(path.get_py_filename('foo', force_win32=win32), 'foo')
476 nt.assert_raises(IOError, path.get_py_filename, 'foo.py', force_win32=win32)
509 nt.assert_raises(IOError, path.get_py_filename, 'foo.py', force_win32=win32)
477 nt.assert_raises(IOError, path.get_py_filename, 'foo', force_win32=win32)
510 nt.assert_raises(IOError, path.get_py_filename, 'foo', force_win32=win32)
478 nt.assert_raises(IOError, path.get_py_filename, 'foo.py', force_win32=win32)
511 nt.assert_raises(IOError, path.get_py_filename, 'foo.py', force_win32=win32)
479 true_fn = 'foo with spaces.py'
512 true_fn = 'foo with spaces.py'
480 with make_tempfile(true_fn):
513 with make_tempfile(true_fn):
481 nt.assert_equal(path.get_py_filename('foo with spaces', force_win32=win32), true_fn)
514 nt.assert_equal(path.get_py_filename('foo with spaces', force_win32=win32), true_fn)
482 nt.assert_equal(path.get_py_filename('foo with spaces.py', force_win32=win32), true_fn)
515 nt.assert_equal(path.get_py_filename('foo with spaces.py', force_win32=win32), true_fn)
483 if win32:
516 if win32:
484 nt.assert_equal(path.get_py_filename('"foo with spaces.py"', force_win32=True), true_fn)
517 nt.assert_equal(path.get_py_filename('"foo with spaces.py"', force_win32=True), true_fn)
485 nt.assert_equal(path.get_py_filename("'foo with spaces.py'", force_win32=True), true_fn)
518 nt.assert_equal(path.get_py_filename("'foo with spaces.py'", force_win32=True), true_fn)
486 else:
519 else:
487 nt.assert_raises(IOError, path.get_py_filename, '"foo with spaces.py"', force_win32=False)
520 nt.assert_raises(IOError, path.get_py_filename, '"foo with spaces.py"', force_win32=False)
488 nt.assert_raises(IOError, path.get_py_filename, "'foo with spaces.py'", force_win32=False)
521 nt.assert_raises(IOError, path.get_py_filename, "'foo with spaces.py'", force_win32=False)
489
522
490 @onlyif_unicode_paths
523 @onlyif_unicode_paths
491 def test_unicode_in_filename():
524 def test_unicode_in_filename():
492 """When a file doesn't exist, the exception raised should be safe to call
525 """When a file doesn't exist, the exception raised should be safe to call
493 str() on - i.e. in Python 2 it must only have ASCII characters.
526 str() on - i.e. in Python 2 it must only have ASCII characters.
494
527
495 https://github.com/ipython/ipython/issues/875
528 https://github.com/ipython/ipython/issues/875
496 """
529 """
497 try:
530 try:
498 # these calls should not throw unicode encode exceptions
531 # these calls should not throw unicode encode exceptions
499 path.get_py_filename(u'fooéè.py', force_win32=False)
532 path.get_py_filename(u'fooéè.py', force_win32=False)
500 except IOError as ex:
533 except IOError as ex:
501 str(ex)
534 str(ex)
502
535
503
536
504 class TestShellGlob(object):
537 class TestShellGlob(object):
505
538
506 @classmethod
539 @classmethod
507 def setUpClass(cls):
540 def setUpClass(cls):
508 cls.filenames_start_with_a = ['a0', 'a1', 'a2']
541 cls.filenames_start_with_a = ['a0', 'a1', 'a2']
509 cls.filenames_end_with_b = ['0b', '1b', '2b']
542 cls.filenames_end_with_b = ['0b', '1b', '2b']
510 cls.filenames = cls.filenames_start_with_a + cls.filenames_end_with_b
543 cls.filenames = cls.filenames_start_with_a + cls.filenames_end_with_b
511 cls.tempdir = TemporaryDirectory()
544 cls.tempdir = TemporaryDirectory()
512 td = cls.tempdir.name
545 td = cls.tempdir.name
513
546
514 with cls.in_tempdir():
547 with cls.in_tempdir():
515 # Create empty files
548 # Create empty files
516 for fname in cls.filenames:
549 for fname in cls.filenames:
517 open(os.path.join(td, fname), 'w').close()
550 open(os.path.join(td, fname), 'w').close()
518
551
519 @classmethod
552 @classmethod
520 def tearDownClass(cls):
553 def tearDownClass(cls):
521 cls.tempdir.cleanup()
554 cls.tempdir.cleanup()
522
555
523 @classmethod
556 @classmethod
524 @contextmanager
557 @contextmanager
525 def in_tempdir(cls):
558 def in_tempdir(cls):
526 save = py3compat.getcwd()
559 save = py3compat.getcwd()
527 try:
560 try:
528 os.chdir(cls.tempdir.name)
561 os.chdir(cls.tempdir.name)
529 yield
562 yield
530 finally:
563 finally:
531 os.chdir(save)
564 os.chdir(save)
532
565
533 def check_match(self, patterns, matches):
566 def check_match(self, patterns, matches):
534 with self.in_tempdir():
567 with self.in_tempdir():
535 # glob returns unordered list. that's why sorted is required.
568 # glob returns unordered list. that's why sorted is required.
536 nt.assert_equals(sorted(path.shellglob(patterns)),
569 nt.assert_equals(sorted(path.shellglob(patterns)),
537 sorted(matches))
570 sorted(matches))
538
571
539 def common_cases(self):
572 def common_cases(self):
540 return [
573 return [
541 (['*'], self.filenames),
574 (['*'], self.filenames),
542 (['a*'], self.filenames_start_with_a),
575 (['a*'], self.filenames_start_with_a),
543 (['*c'], ['*c']),
576 (['*c'], ['*c']),
544 (['*', 'a*', '*b', '*c'], self.filenames
577 (['*', 'a*', '*b', '*c'], self.filenames
545 + self.filenames_start_with_a
578 + self.filenames_start_with_a
546 + self.filenames_end_with_b
579 + self.filenames_end_with_b
547 + ['*c']),
580 + ['*c']),
548 (['a[012]'], self.filenames_start_with_a),
581 (['a[012]'], self.filenames_start_with_a),
549 ]
582 ]
550
583
551 @skip_win32
584 @skip_win32
552 def test_match_posix(self):
585 def test_match_posix(self):
553 for (patterns, matches) in self.common_cases() + [
586 for (patterns, matches) in self.common_cases() + [
554 ([r'\*'], ['*']),
587 ([r'\*'], ['*']),
555 ([r'a\*', 'a*'], ['a*'] + self.filenames_start_with_a),
588 ([r'a\*', 'a*'], ['a*'] + self.filenames_start_with_a),
556 ([r'a\[012]'], ['a[012]']),
589 ([r'a\[012]'], ['a[012]']),
557 ]:
590 ]:
558 yield (self.check_match, patterns, matches)
591 yield (self.check_match, patterns, matches)
559
592
560 @skip_if_not_win32
593 @skip_if_not_win32
561 def test_match_windows(self):
594 def test_match_windows(self):
562 for (patterns, matches) in self.common_cases() + [
595 for (patterns, matches) in self.common_cases() + [
563 # In windows, backslash is interpreted as path
596 # In windows, backslash is interpreted as path
564 # separator. Therefore, you can't escape glob
597 # separator. Therefore, you can't escape glob
565 # using it.
598 # using it.
566 ([r'a\*', 'a*'], [r'a\*'] + self.filenames_start_with_a),
599 ([r'a\*', 'a*'], [r'a\*'] + self.filenames_start_with_a),
567 ([r'a\[012]'], [r'a\[012]']),
600 ([r'a\[012]'], [r'a\[012]']),
568 ]:
601 ]:
569 yield (self.check_match, patterns, matches)
602 yield (self.check_match, patterns, matches)
570
603
571
604
572 def test_unescape_glob():
605 def test_unescape_glob():
573 nt.assert_equals(path.unescape_glob(r'\*\[\!\]\?'), '*[!]?')
606 nt.assert_equals(path.unescape_glob(r'\*\[\!\]\?'), '*[!]?')
574 nt.assert_equals(path.unescape_glob(r'\\*'), r'\*')
607 nt.assert_equals(path.unescape_glob(r'\\*'), r'\*')
575 nt.assert_equals(path.unescape_glob(r'\\\*'), r'\*')
608 nt.assert_equals(path.unescape_glob(r'\\\*'), r'\*')
576 nt.assert_equals(path.unescape_glob(r'\\a'), r'\a')
609 nt.assert_equals(path.unescape_glob(r'\\a'), r'\a')
577 nt.assert_equals(path.unescape_glob(r'\a'), r'\a')
610 nt.assert_equals(path.unescape_glob(r'\a'), r'\a')
578
611
579
612
580 class TestLinkOrCopy(object):
613 class TestLinkOrCopy(object):
581 def setUp(self):
614 def setUp(self):
582 self.tempdir = TemporaryDirectory()
615 self.tempdir = TemporaryDirectory()
583 self.src = self.dst("src")
616 self.src = self.dst("src")
584 with open(self.src, "w") as f:
617 with open(self.src, "w") as f:
585 f.write("Hello, world!")
618 f.write("Hello, world!")
586
619
587 def tearDown(self):
620 def tearDown(self):
588 self.tempdir.cleanup()
621 self.tempdir.cleanup()
589
622
590 def dst(self, *args):
623 def dst(self, *args):
591 return os.path.join(self.tempdir.name, *args)
624 return os.path.join(self.tempdir.name, *args)
592
625
593 def assert_inode_not_equal(self, a, b):
626 def assert_inode_not_equal(self, a, b):
594 nt.assert_not_equals(os.stat(a).st_ino, os.stat(b).st_ino,
627 nt.assert_not_equals(os.stat(a).st_ino, os.stat(b).st_ino,
595 "%r and %r do reference the same indoes" %(a, b))
628 "%r and %r do reference the same indoes" %(a, b))
596
629
597 def assert_inode_equal(self, a, b):
630 def assert_inode_equal(self, a, b):
598 nt.assert_equals(os.stat(a).st_ino, os.stat(b).st_ino,
631 nt.assert_equals(os.stat(a).st_ino, os.stat(b).st_ino,
599 "%r and %r do not reference the same indoes" %(a, b))
632 "%r and %r do not reference the same indoes" %(a, b))
600
633
601 def assert_content_equal(self, a, b):
634 def assert_content_equal(self, a, b):
602 with open(a) as a_f:
635 with open(a) as a_f:
603 with open(b) as b_f:
636 with open(b) as b_f:
604 nt.assert_equals(a_f.read(), b_f.read())
637 nt.assert_equals(a_f.read(), b_f.read())
605
638
606 @skip_win32
639 @skip_win32
607 def test_link_successful(self):
640 def test_link_successful(self):
608 dst = self.dst("target")
641 dst = self.dst("target")
609 path.link_or_copy(self.src, dst)
642 path.link_or_copy(self.src, dst)
610 self.assert_inode_equal(self.src, dst)
643 self.assert_inode_equal(self.src, dst)
611
644
612 @skip_win32
645 @skip_win32
613 def test_link_into_dir(self):
646 def test_link_into_dir(self):
614 dst = self.dst("some_dir")
647 dst = self.dst("some_dir")
615 os.mkdir(dst)
648 os.mkdir(dst)
616 path.link_or_copy(self.src, dst)
649 path.link_or_copy(self.src, dst)
617 expected_dst = self.dst("some_dir", os.path.basename(self.src))
650 expected_dst = self.dst("some_dir", os.path.basename(self.src))
618 self.assert_inode_equal(self.src, expected_dst)
651 self.assert_inode_equal(self.src, expected_dst)
619
652
620 @skip_win32
653 @skip_win32
621 def test_target_exists(self):
654 def test_target_exists(self):
622 dst = self.dst("target")
655 dst = self.dst("target")
623 open(dst, "w").close()
656 open(dst, "w").close()
624 path.link_or_copy(self.src, dst)
657 path.link_or_copy(self.src, dst)
625 self.assert_inode_equal(self.src, dst)
658 self.assert_inode_equal(self.src, dst)
626
659
627 @skip_win32
660 @skip_win32
628 def test_no_link(self):
661 def test_no_link(self):
629 real_link = os.link
662 real_link = os.link
630 try:
663 try:
631 del os.link
664 del os.link
632 dst = self.dst("target")
665 dst = self.dst("target")
633 path.link_or_copy(self.src, dst)
666 path.link_or_copy(self.src, dst)
634 self.assert_content_equal(self.src, dst)
667 self.assert_content_equal(self.src, dst)
635 self.assert_inode_not_equal(self.src, dst)
668 self.assert_inode_not_equal(self.src, dst)
636 finally:
669 finally:
637 os.link = real_link
670 os.link = real_link
638
671
639 @skip_if_not_win32
672 @skip_if_not_win32
640 def test_windows(self):
673 def test_windows(self):
641 dst = self.dst("target")
674 dst = self.dst("target")
642 path.link_or_copy(self.src, dst)
675 path.link_or_copy(self.src, dst)
643 self.assert_content_equal(self.src, dst)
676 self.assert_content_equal(self.src, dst)
@@ -1,61 +1,60 b''
1 .\" Hey, EMACS: -*- nroff -*-
1 .\" Hey, EMACS: -*- nroff -*-
2 .\" First parameter, NAME, should be all caps
2 .\" First parameter, NAME, should be all caps
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
3 .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection
4 .\" other parameters are allowed: see man(7), man(1)
4 .\" other parameters are allowed: see man(7), man(1)
5 .TH IPYTHON 1 "July 15, 2011"
5 .TH IPYTHON 1 "July 15, 2011"
6 .\" Please adjust this date whenever revising the manpage.
6 .\" Please adjust this date whenever revising the manpage.
7 .\"
7 .\"
8 .\" Some roff macros, for reference:
8 .\" Some roff macros, for reference:
9 .\" .nh disable hyphenation
9 .\" .nh disable hyphenation
10 .\" .hy enable hyphenation
10 .\" .hy enable hyphenation
11 .\" .ad l left justify
11 .\" .ad l left justify
12 .\" .ad b justify to both left and right margins
12 .\" .ad b justify to both left and right margins
13 .\" .nf disable filling
13 .\" .nf disable filling
14 .\" .fi enable filling
14 .\" .fi enable filling
15 .\" .br insert line break
15 .\" .br insert line break
16 .\" .sp <n> insert n+1 empty lines
16 .\" .sp <n> insert n+1 empty lines
17 .\" for manpage-specific macros, see man(7) and groff_man(7)
17 .\" for manpage-specific macros, see man(7) and groff_man(7)
18 .\" .SH section heading
18 .\" .SH section heading
19 .\" .SS secondary section heading
19 .\" .SS secondary section heading
20 .\"
20 .\"
21 .\"
21 .\"
22 .\" To preview this page as plain text: nroff -man ipython.1
22 .\" To preview this page as plain text: nroff -man ipython.1
23 .\"
23 .\"
24 .SH NAME
24 .SH NAME
25 ipython \- Tools for Interactive Computing in Python.
25 ipython \- Tools for Interactive Computing in Python.
26 .SH SYNOPSIS
26 .SH SYNOPSIS
27 .B ipython
27 .B ipython
28 .RI [ options ] " files" ...
28 .RI [ options ] " files" ...
29
29
30 .B ipython subcommand
30 .B ipython subcommand
31 .RI [ options ] ...
31 .RI [ options ] ...
32
32
33 .SH DESCRIPTION
33 .SH DESCRIPTION
34 An interactive Python shell with automatic history (input and output), dynamic
34 An interactive Python shell with automatic history (input and output), dynamic
35 object introspection, easier configuration, command completion, access to the
35 object introspection, easier configuration, command completion, access to the
36 system shell, integration with numerical and scientific computing tools,
36 system shell, integration with numerical and scientific computing tools,
37 web notebook, Qt console, and more.
37 web notebook, Qt console, and more.
38
38
39 For more information on how to use IPython, see 'ipython \-\-help',
39 For more information on how to use IPython, see 'ipython \-\-help',
40 or 'ipython \-\-help\-all' for all available command\(hyline options.
40 or 'ipython \-\-help\-all' for all available command\(hyline options.
41
41
42 .SH "ENVIRONMENT VARIABLES"
42 .SH "ENVIRONMENT VARIABLES"
43 .sp
43 .sp
44 .PP
44 .PP
45 \fIIPYTHONDIR\fR
45 \fIIPYTHONDIR\fR
46 .RS 4
46 .RS 4
47 This is the location where IPython stores all its configuration files. The default
47 This is the location where IPython stores all its configuration files. The default
48 on most platforms is $HOME/.ipython, but on Linux IPython respects the XDG config
48 is $HOME/.ipython if IPYTHONDIR is not defined.
49 specification, which will put IPYTHONDIR in $HOME/.config/ipython by default.
50
49
51 You can see the computed value of IPYTHONDIR with `ipython locate`.
50 You can see the computed value of IPYTHONDIR with `ipython locate`.
52
51
53 .SH FILES
52 .SH FILES
54
53
55 IPython uses various configuration files stored in profiles within IPYTHONDIR.
54 IPython uses various configuration files stored in profiles within IPYTHONDIR.
56 To generate the default configuration files and start configuring IPython,
55 To generate the default configuration files and start configuring IPython,
57 do 'ipython profile create', and edit '*_config.py' files located in
56 do 'ipython profile create', and edit '*_config.py' files located in
58 IPYTHONDIR/profile_default.
57 IPYTHONDIR/profile_default.
59
58
60 .SH AUTHORS
59 .SH AUTHORS
61 IPython is written by the IPython Development Team <https://github.com/ipython/ipython>.
60 IPython is written by the IPython Development Team <https://github.com/ipython/ipython>.
@@ -1,231 +1,230 b''
1 .. _initial config:
1 .. _initial config:
2
2
3 =============================================================
3 =============================================================
4 Outdated configuration information that might still be useful
4 Outdated configuration information that might still be useful
5 =============================================================
5 =============================================================
6
6
7 .. warning::
7 .. warning::
8
8
9 All of the information in this file is outdated. Until the new
9 All of the information in this file is outdated. Until the new
10 configuration system is better documented, this material is being kept.
10 configuration system is better documented, this material is being kept.
11
11
12 This section will help you set various things in your environment for
12 This section will help you set various things in your environment for
13 your IPython sessions to be as efficient as possible. All of IPython's
13 your IPython sessions to be as efficient as possible. All of IPython's
14 configuration information, along with several example files, is stored
14 configuration information, along with several example files, is stored
15 in a directory named by default $HOME/.config/ipython if $HOME/.config
15 in a directory named by default $HOME/.ipython. You can change this by
16 exists (Linux), or $HOME/.ipython as a secondary default. You can change this by
17 defining the environment variable IPYTHONDIR, or at runtime with the
16 defining the environment variable IPYTHONDIR, or at runtime with the
18 command line option -ipythondir.
17 command line option -ipythondir.
19
18
20 If all goes well, the first time you run IPython it should automatically create
19 If all goes well, the first time you run IPython it should automatically create
21 a user copy of the config directory for you, based on its builtin defaults. You
20 a user copy of the config directory for you, based on its builtin defaults. You
22 can look at the files it creates to learn more about configuring the
21 can look at the files it creates to learn more about configuring the
23 system. The main file you will modify to configure IPython's behavior is called
22 system. The main file you will modify to configure IPython's behavior is called
24 ipythonrc (with a .ini extension under Windows), included for reference
23 ipythonrc (with a .ini extension under Windows), included for reference
25 :ref:`here <ipythonrc>`. This file is very commented and has many variables you
24 :ref:`here <ipythonrc>`. This file is very commented and has many variables you
26 can change to suit your taste, you can find more details :ref:`here
25 can change to suit your taste, you can find more details :ref:`here
27 <customization>`. Here we discuss the basic things you will want to make sure
26 <customization>`. Here we discuss the basic things you will want to make sure
28 things are working properly from the beginning.
27 things are working properly from the beginning.
29
28
30 Color
29 Color
31 =====
30 =====
32
31
33 The default IPython configuration has most bells and whistles turned on
32 The default IPython configuration has most bells and whistles turned on
34 (they're pretty safe). But there's one that may cause problems on some
33 (they're pretty safe). But there's one that may cause problems on some
35 systems: the use of color on screen for displaying information. This is
34 systems: the use of color on screen for displaying information. This is
36 very useful, since IPython can show prompts and exception tracebacks
35 very useful, since IPython can show prompts and exception tracebacks
37 with various colors, display syntax-highlighted source code, and in
36 with various colors, display syntax-highlighted source code, and in
38 general make it easier to visually parse information.
37 general make it easier to visually parse information.
39
38
40 The following terminals seem to handle the color sequences fine:
39 The following terminals seem to handle the color sequences fine:
41
40
42 * Linux main text console, KDE Konsole, Gnome Terminal, E-term,
41 * Linux main text console, KDE Konsole, Gnome Terminal, E-term,
43 rxvt, xterm.
42 rxvt, xterm.
44 * CDE terminal (tested under Solaris). This one boldfaces light colors.
43 * CDE terminal (tested under Solaris). This one boldfaces light colors.
45 * (X)Emacs buffers. See the :ref:`emacs` section for more details on
44 * (X)Emacs buffers. See the :ref:`emacs` section for more details on
46 using IPython with (X)Emacs.
45 using IPython with (X)Emacs.
47 * A Windows (XP/2k) command prompt with pyreadline_.
46 * A Windows (XP/2k) command prompt with pyreadline_.
48 * A Windows (XP/2k) CygWin shell. Although some users have reported
47 * A Windows (XP/2k) CygWin shell. Although some users have reported
49 problems; it is not clear whether there is an issue for everyone
48 problems; it is not clear whether there is an issue for everyone
50 or only under specific configurations. If you have full color
49 or only under specific configurations. If you have full color
51 support under cygwin, please post to the IPython mailing list so
50 support under cygwin, please post to the IPython mailing list so
52 this issue can be resolved for all users.
51 this issue can be resolved for all users.
53
52
54 .. _pyreadline: https://code.launchpad.net/pyreadline
53 .. _pyreadline: https://code.launchpad.net/pyreadline
55
54
56 These have shown problems:
55 These have shown problems:
57
56
58 * Windows command prompt in WinXP/2k logged into a Linux machine via
57 * Windows command prompt in WinXP/2k logged into a Linux machine via
59 telnet or ssh.
58 telnet or ssh.
60 * Windows native command prompt in WinXP/2k, without Gary Bishop's
59 * Windows native command prompt in WinXP/2k, without Gary Bishop's
61 extensions. Once Gary's readline library is installed, the normal
60 extensions. Once Gary's readline library is installed, the normal
62 WinXP/2k command prompt works perfectly.
61 WinXP/2k command prompt works perfectly.
63
62
64 Currently the following color schemes are available:
63 Currently the following color schemes are available:
65
64
66 * NoColor: uses no color escapes at all (all escapes are empty '' ''
65 * NoColor: uses no color escapes at all (all escapes are empty '' ''
67 strings). This 'scheme' is thus fully safe to use in any terminal.
66 strings). This 'scheme' is thus fully safe to use in any terminal.
68 * Linux: works well in Linux console type environments: dark
67 * Linux: works well in Linux console type environments: dark
69 background with light fonts. It uses bright colors for
68 background with light fonts. It uses bright colors for
70 information, so it is difficult to read if you have a light
69 information, so it is difficult to read if you have a light
71 colored background.
70 colored background.
72 * LightBG: the basic colors are similar to those in the Linux scheme
71 * LightBG: the basic colors are similar to those in the Linux scheme
73 but darker. It is easy to read in terminals with light backgrounds.
72 but darker. It is easy to read in terminals with light backgrounds.
74
73
75 IPython uses colors for two main groups of things: prompts and
74 IPython uses colors for two main groups of things: prompts and
76 tracebacks which are directly printed to the terminal, and the object
75 tracebacks which are directly printed to the terminal, and the object
77 introspection system which passes large sets of data through a pager.
76 introspection system which passes large sets of data through a pager.
78
77
79 Input/Output prompts and exception tracebacks
78 Input/Output prompts and exception tracebacks
80 =============================================
79 =============================================
81
80
82 You can test whether the colored prompts and tracebacks work on your
81 You can test whether the colored prompts and tracebacks work on your
83 system interactively by typing '%colors Linux' at the prompt (use
82 system interactively by typing '%colors Linux' at the prompt (use
84 '%colors LightBG' if your terminal has a light background). If the input
83 '%colors LightBG' if your terminal has a light background). If the input
85 prompt shows garbage like::
84 prompt shows garbage like::
86
85
87 [0;32mIn [[1;32m1[0;32m]: [0;00m
86 [0;32mIn [[1;32m1[0;32m]: [0;00m
88
87
89 instead of (in color) something like::
88 instead of (in color) something like::
90
89
91 In [1]:
90 In [1]:
92
91
93 this means that your terminal doesn't properly handle color escape
92 this means that your terminal doesn't properly handle color escape
94 sequences. You can go to a 'no color' mode by typing '%colors NoColor'.
93 sequences. You can go to a 'no color' mode by typing '%colors NoColor'.
95
94
96 You can try using a different terminal emulator program (Emacs users,
95 You can try using a different terminal emulator program (Emacs users,
97 see below). To permanently set your color preferences, edit the file
96 see below). To permanently set your color preferences, edit the file
98 $IPYTHONDIR/ipythonrc and set the colors option to the desired value.
97 $IPYTHONDIR/ipythonrc and set the colors option to the desired value.
99
98
100
99
101 Object details (types, docstrings, source code, etc.)
100 Object details (types, docstrings, source code, etc.)
102 =====================================================
101 =====================================================
103
102
104 IPython has a set of special functions for studying the objects you are working
103 IPython has a set of special functions for studying the objects you are working
105 with, discussed in detail :ref:`here <dynamic_object_info>`. But this system
104 with, discussed in detail :ref:`here <dynamic_object_info>`. But this system
106 relies on passing information which is longer than your screen through a data
105 relies on passing information which is longer than your screen through a data
107 pager, such as the common Unix less and more programs. In order to be able to
106 pager, such as the common Unix less and more programs. In order to be able to
108 see this information in color, your pager needs to be properly configured. I
107 see this information in color, your pager needs to be properly configured. I
109 strongly recommend using less instead of more, as it seems that more simply can
108 strongly recommend using less instead of more, as it seems that more simply can
110 not understand colored text correctly.
109 not understand colored text correctly.
111
110
112 In order to configure less as your default pager, do the following:
111 In order to configure less as your default pager, do the following:
113
112
114 1. Set the environment PAGER variable to less.
113 1. Set the environment PAGER variable to less.
115 2. Set the environment LESS variable to -r (plus any other options
114 2. Set the environment LESS variable to -r (plus any other options
116 you always want to pass to less by default). This tells less to
115 you always want to pass to less by default). This tells less to
117 properly interpret control sequences, which is how color
116 properly interpret control sequences, which is how color
118 information is given to your terminal.
117 information is given to your terminal.
119
118
120 For the bash shell, add to your ~/.bashrc file the lines::
119 For the bash shell, add to your ~/.bashrc file the lines::
121
120
122 export PAGER=less
121 export PAGER=less
123 export LESS=-r
122 export LESS=-r
124
123
125 For the csh or tcsh shells, add to your ~/.cshrc file the lines::
124 For the csh or tcsh shells, add to your ~/.cshrc file the lines::
126
125
127 setenv PAGER less
126 setenv PAGER less
128 setenv LESS -r
127 setenv LESS -r
129
128
130 There is similar syntax for other Unix shells, look at your system
129 There is similar syntax for other Unix shells, look at your system
131 documentation for details.
130 documentation for details.
132
131
133 If you are on a system which lacks proper data pagers (such as Windows),
132 If you are on a system which lacks proper data pagers (such as Windows),
134 IPython will use a very limited builtin pager.
133 IPython will use a very limited builtin pager.
135
134
136 .. _Prompts:
135 .. _Prompts:
137
136
138 Fine-tuning your prompt
137 Fine-tuning your prompt
139 =======================
138 =======================
140
139
141 IPython's prompts can be customized using a syntax similar to that of
140 IPython's prompts can be customized using a syntax similar to that of
142 the bash shell. Many of bash's escapes are supported, as well as a few
141 the bash shell. Many of bash's escapes are supported, as well as a few
143 additional ones. We list them below::
142 additional ones. We list them below::
144
143
145 \#
144 \#
146 the prompt/history count number. This escape is automatically
145 the prompt/history count number. This escape is automatically
147 wrapped in the coloring codes for the currently active color scheme.
146 wrapped in the coloring codes for the currently active color scheme.
148 \N
147 \N
149 the 'naked' prompt/history count number: this is just the number
148 the 'naked' prompt/history count number: this is just the number
150 itself, without any coloring applied to it. This lets you produce
149 itself, without any coloring applied to it. This lets you produce
151 numbered prompts with your own colors.
150 numbered prompts with your own colors.
152 \D
151 \D
153 the prompt/history count, with the actual digits replaced by dots.
152 the prompt/history count, with the actual digits replaced by dots.
154 Used mainly in continuation prompts (prompt_in2)
153 Used mainly in continuation prompts (prompt_in2)
155 \w
154 \w
156 the current working directory
155 the current working directory
157 \W
156 \W
158 the basename of current working directory
157 the basename of current working directory
159 \Xn
158 \Xn
160 where $n=0\ldots5.$ The current working directory, with $HOME
159 where $n=0\ldots5.$ The current working directory, with $HOME
161 replaced by ~, and filtered out to contain only $n$ path elements
160 replaced by ~, and filtered out to contain only $n$ path elements
162 \Yn
161 \Yn
163 Similar to \Xn, but with the $n+1$ element included if it is ~ (this
162 Similar to \Xn, but with the $n+1$ element included if it is ~ (this
164 is similar to the behavior of the %cn escapes in tcsh)
163 is similar to the behavior of the %cn escapes in tcsh)
165 \u
164 \u
166 the username of the current user
165 the username of the current user
167 \$
166 \$
168 if the effective UID is 0, a #, otherwise a $
167 if the effective UID is 0, a #, otherwise a $
169 \h
168 \h
170 the hostname up to the first '.'
169 the hostname up to the first '.'
171 \H
170 \H
172 the hostname
171 the hostname
173 \n
172 \n
174 a newline
173 a newline
175 \r
174 \r
176 a carriage return
175 a carriage return
177 \v
176 \v
178 IPython version string
177 IPython version string
179
178
180 In addition to these, ANSI color escapes can be insterted into the
179 In addition to these, ANSI color escapes can be insterted into the
181 prompts, as \C_ColorName. The list of valid color names is: Black, Blue,
180 prompts, as \C_ColorName. The list of valid color names is: Black, Blue,
182 Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray,
181 Brown, Cyan, DarkGray, Green, LightBlue, LightCyan, LightGray,
183 LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White,
182 LightGreen, LightPurple, LightRed, NoColor, Normal, Purple, Red, White,
184 Yellow.
183 Yellow.
185
184
186 Finally, IPython supports the evaluation of arbitrary expressions in
185 Finally, IPython supports the evaluation of arbitrary expressions in
187 your prompt string. The prompt strings are evaluated through the syntax
186 your prompt string. The prompt strings are evaluated through the syntax
188 of PEP 215, but basically you can use $x.y to expand the value of x.y,
187 of PEP 215, but basically you can use $x.y to expand the value of x.y,
189 and for more complicated expressions you can use braces: ${foo()+x} will
188 and for more complicated expressions you can use braces: ${foo()+x} will
190 call function foo and add to it the value of x, before putting the
189 call function foo and add to it the value of x, before putting the
191 result into your prompt. For example, using
190 result into your prompt. For example, using
192 prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: '
191 prompt_in1 '${commands.getoutput("uptime")}\nIn [\#]: '
193 will print the result of the uptime command on each prompt (assuming the
192 will print the result of the uptime command on each prompt (assuming the
194 commands module has been imported in your ipythonrc file).
193 commands module has been imported in your ipythonrc file).
195
194
196
195
197 Prompt examples
196 Prompt examples
198
197
199 The following options in an ipythonrc file will give you IPython's
198 The following options in an ipythonrc file will give you IPython's
200 default prompts::
199 default prompts::
201
200
202 prompt_in1 'In [\#]:'
201 prompt_in1 'In [\#]:'
203 prompt_in2 ' .\D.:'
202 prompt_in2 ' .\D.:'
204 prompt_out 'Out[\#]:'
203 prompt_out 'Out[\#]:'
205
204
206 which look like this::
205 which look like this::
207
206
208 In [1]: 1+2
207 In [1]: 1+2
209 Out[1]: 3
208 Out[1]: 3
210
209
211 In [2]: for i in (1,2,3):
210 In [2]: for i in (1,2,3):
212 ...: print i,
211 ...: print i,
213 ...:
212 ...:
214 1 2 3
213 1 2 3
215
214
216 These will give you a very colorful prompt with path information::
215 These will give you a very colorful prompt with path information::
217
216
218 #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>'
217 #prompt_in1 '\C_Red\u\C_Blue[\C_Cyan\Y1\C_Blue]\C_LightGreen\#>'
219 prompt_in2 ' ..\D>'
218 prompt_in2 ' ..\D>'
220 prompt_out '<\#>'
219 prompt_out '<\#>'
221
220
222 which look like this::
221 which look like this::
223
222
224 fperez[~/ipython]1> 1+2
223 fperez[~/ipython]1> 1+2
225 <1> 3
224 <1> 3
226 fperez[~/ipython]2> for i in (1,2,3):
225 fperez[~/ipython]2> for i in (1,2,3):
227 ...> print i,
226 ...> print i,
228 ...>
227 ...>
229 1 2 3
228 1 2 3
230
229
231
230
@@ -1,535 +1,529 b''
1 .. _config_overview:
1 .. _config_overview:
2
2
3 ============================================
3 ============================================
4 Overview of the IPython configuration system
4 Overview of the IPython configuration system
5 ============================================
5 ============================================
6
6
7 This section describes the IPython configuration system.
7 This section describes the IPython configuration system.
8
8
9 The following discussion is for users who want to configure
9 The following discussion is for users who want to configure
10 IPython to their liking. Developers who want to know how they can
10 IPython to their liking. Developers who want to know how they can
11 enable their objects to take advantage of the configuration system
11 enable their objects to take advantage of the configuration system
12 should consult the :ref:`developer guide <developer_guide>`
12 should consult the :ref:`developer guide <developer_guide>`
13
13
14 The main concepts
14 The main concepts
15 =================
15 =================
16
16
17 There are a number of abstractions that the IPython configuration system uses.
17 There are a number of abstractions that the IPython configuration system uses.
18 Each of these abstractions is represented by a Python class.
18 Each of these abstractions is represented by a Python class.
19
19
20 Configuration object: :class:`~IPython.config.loader.Config`
20 Configuration object: :class:`~IPython.config.loader.Config`
21 A configuration object is a simple dictionary-like class that holds
21 A configuration object is a simple dictionary-like class that holds
22 configuration attributes and sub-configuration objects. These classes
22 configuration attributes and sub-configuration objects. These classes
23 support dotted attribute style access (``Foo.bar``) in addition to the
23 support dotted attribute style access (``Foo.bar``) in addition to the
24 regular dictionary style access (``Foo['bar']``). Configuration objects
24 regular dictionary style access (``Foo['bar']``). Configuration objects
25 are smart. They know how to merge themselves with other configuration
25 are smart. They know how to merge themselves with other configuration
26 objects and they automatically create sub-configuration objects.
26 objects and they automatically create sub-configuration objects.
27
27
28 Application: :class:`~IPython.config.application.Application`
28 Application: :class:`~IPython.config.application.Application`
29 An application is a process that does a specific job. The most obvious
29 An application is a process that does a specific job. The most obvious
30 application is the :command:`ipython` command line program. Each
30 application is the :command:`ipython` command line program. Each
31 application reads *one or more* configuration files and a single set of
31 application reads *one or more* configuration files and a single set of
32 command line options
32 command line options
33 and then produces a master configuration object for the application. This
33 and then produces a master configuration object for the application. This
34 configuration object is then passed to the configurable objects that the
34 configuration object is then passed to the configurable objects that the
35 application creates. These configurable objects implement the actual logic
35 application creates. These configurable objects implement the actual logic
36 of the application and know how to configure themselves given the
36 of the application and know how to configure themselves given the
37 configuration object.
37 configuration object.
38
38
39 Applications always have a `log` attribute that is a configured Logger.
39 Applications always have a `log` attribute that is a configured Logger.
40 This allows centralized logging configuration per-application.
40 This allows centralized logging configuration per-application.
41
41
42 Configurable: :class:`~IPython.config.configurable.Configurable`
42 Configurable: :class:`~IPython.config.configurable.Configurable`
43 A configurable is a regular Python class that serves as a base class for
43 A configurable is a regular Python class that serves as a base class for
44 all main classes in an application. The
44 all main classes in an application. The
45 :class:`~IPython.config.configurable.Configurable` base class is
45 :class:`~IPython.config.configurable.Configurable` base class is
46 lightweight and only does one things.
46 lightweight and only does one things.
47
47
48 This :class:`~IPython.config.configurable.Configurable` is a subclass
48 This :class:`~IPython.config.configurable.Configurable` is a subclass
49 of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure
49 of :class:`~IPython.utils.traitlets.HasTraits` that knows how to configure
50 itself. Class level traits with the metadata ``config=True`` become
50 itself. Class level traits with the metadata ``config=True`` become
51 values that can be configured from the command line and configuration
51 values that can be configured from the command line and configuration
52 files.
52 files.
53
53
54 Developers create :class:`~IPython.config.configurable.Configurable`
54 Developers create :class:`~IPython.config.configurable.Configurable`
55 subclasses that implement all of the logic in the application. Each of
55 subclasses that implement all of the logic in the application. Each of
56 these subclasses has its own configuration information that controls how
56 these subclasses has its own configuration information that controls how
57 instances are created.
57 instances are created.
58
58
59 Singletons: :class:`~IPython.config.configurable.SingletonConfigurable`
59 Singletons: :class:`~IPython.config.configurable.SingletonConfigurable`
60 Any object for which there is a single canonical instance. These are
60 Any object for which there is a single canonical instance. These are
61 just like Configurables, except they have a class method
61 just like Configurables, except they have a class method
62 :meth:`~IPython.config.configurable.SingletonConfigurable.instance`,
62 :meth:`~IPython.config.configurable.SingletonConfigurable.instance`,
63 that returns the current active instance (or creates one if it
63 that returns the current active instance (or creates one if it
64 does not exist). Examples of singletons include
64 does not exist). Examples of singletons include
65 :class:`~IPython.config.application.Application`s and
65 :class:`~IPython.config.application.Application`s and
66 :class:`~IPython.core.interactiveshell.InteractiveShell`. This lets
66 :class:`~IPython.core.interactiveshell.InteractiveShell`. This lets
67 objects easily connect to the current running Application without passing
67 objects easily connect to the current running Application without passing
68 objects around everywhere. For instance, to get the current running
68 objects around everywhere. For instance, to get the current running
69 Application instance, simply do: ``app = Application.instance()``.
69 Application instance, simply do: ``app = Application.instance()``.
70
70
71
71
72 .. note::
72 .. note::
73
73
74 Singletons are not strictly enforced - you can have many instances
74 Singletons are not strictly enforced - you can have many instances
75 of a given singleton class, but the :meth:`instance` method will always
75 of a given singleton class, but the :meth:`instance` method will always
76 return the same one.
76 return the same one.
77
77
78 Having described these main concepts, we can now state the main idea in our
78 Having described these main concepts, we can now state the main idea in our
79 configuration system: *"configuration" allows the default values of class
79 configuration system: *"configuration" allows the default values of class
80 attributes to be controlled on a class by class basis*. Thus all instances of
80 attributes to be controlled on a class by class basis*. Thus all instances of
81 a given class are configured in the same way. Furthermore, if two instances
81 a given class are configured in the same way. Furthermore, if two instances
82 need to be configured differently, they need to be instances of two different
82 need to be configured differently, they need to be instances of two different
83 classes. While this model may seem a bit restrictive, we have found that it
83 classes. While this model may seem a bit restrictive, we have found that it
84 expresses most things that need to be configured extremely well. However, it
84 expresses most things that need to be configured extremely well. However, it
85 is possible to create two instances of the same class that have different
85 is possible to create two instances of the same class that have different
86 trait values. This is done by overriding the configuration.
86 trait values. This is done by overriding the configuration.
87
87
88 Now, we show what our configuration objects and files look like.
88 Now, we show what our configuration objects and files look like.
89
89
90 Configuration objects and files
90 Configuration objects and files
91 ===============================
91 ===============================
92
92
93 A configuration file is simply a pure Python file that sets the attributes
93 A configuration file is simply a pure Python file that sets the attributes
94 of a global, pre-created configuration object. This configuration object is a
94 of a global, pre-created configuration object. This configuration object is a
95 :class:`~IPython.config.loader.Config` instance. While in a configuration
95 :class:`~IPython.config.loader.Config` instance. While in a configuration
96 file, to get a reference to this object, simply call the :func:`get_config`
96 file, to get a reference to this object, simply call the :func:`get_config`
97 function. We inject this function into the global namespace that the
97 function. We inject this function into the global namespace that the
98 configuration file is executed in.
98 configuration file is executed in.
99
99
100 Here is an example of a super simple configuration file that does nothing::
100 Here is an example of a super simple configuration file that does nothing::
101
101
102 c = get_config()
102 c = get_config()
103
103
104 Once you get a reference to the configuration object, you simply set
104 Once you get a reference to the configuration object, you simply set
105 attributes on it. All you have to know is:
105 attributes on it. All you have to know is:
106
106
107 * The name of each attribute.
107 * The name of each attribute.
108 * The type of each attribute.
108 * The type of each attribute.
109
109
110 The answers to these two questions are provided by the various
110 The answers to these two questions are provided by the various
111 :class:`~IPython.config.configurable.Configurable` subclasses that an
111 :class:`~IPython.config.configurable.Configurable` subclasses that an
112 application uses. Let's look at how this would work for a simple configurable
112 application uses. Let's look at how this would work for a simple configurable
113 subclass::
113 subclass::
114
114
115 # Sample configurable:
115 # Sample configurable:
116 from IPython.config.configurable import Configurable
116 from IPython.config.configurable import Configurable
117 from IPython.utils.traitlets import Int, Float, Unicode, Bool
117 from IPython.utils.traitlets import Int, Float, Unicode, Bool
118
118
119 class MyClass(Configurable):
119 class MyClass(Configurable):
120 name = Unicode(u'defaultname', config=True)
120 name = Unicode(u'defaultname', config=True)
121 ranking = Int(0, config=True)
121 ranking = Int(0, config=True)
122 value = Float(99.0)
122 value = Float(99.0)
123 # The rest of the class implementation would go here..
123 # The rest of the class implementation would go here..
124
124
125 In this example, we see that :class:`MyClass` has three attributes, two
125 In this example, we see that :class:`MyClass` has three attributes, two
126 of whom (``name``, ``ranking``) can be configured. All of the attributes
126 of whom (``name``, ``ranking``) can be configured. All of the attributes
127 are given types and default values. If a :class:`MyClass` is instantiated,
127 are given types and default values. If a :class:`MyClass` is instantiated,
128 but not configured, these default values will be used. But let's see how
128 but not configured, these default values will be used. But let's see how
129 to configure this class in a configuration file::
129 to configure this class in a configuration file::
130
130
131 # Sample config file
131 # Sample config file
132 c = get_config()
132 c = get_config()
133
133
134 c.MyClass.name = 'coolname'
134 c.MyClass.name = 'coolname'
135 c.MyClass.ranking = 10
135 c.MyClass.ranking = 10
136
136
137 After this configuration file is loaded, the values set in it will override
137 After this configuration file is loaded, the values set in it will override
138 the class defaults anytime a :class:`MyClass` is created. Furthermore,
138 the class defaults anytime a :class:`MyClass` is created. Furthermore,
139 these attributes will be type checked and validated anytime they are set.
139 these attributes will be type checked and validated anytime they are set.
140 This type checking is handled by the :mod:`IPython.utils.traitlets` module,
140 This type checking is handled by the :mod:`IPython.utils.traitlets` module,
141 which provides the :class:`Unicode`, :class:`Int` and :class:`Float` types.
141 which provides the :class:`Unicode`, :class:`Int` and :class:`Float` types.
142 In addition to these traitlets, the :mod:`IPython.utils.traitlets` provides
142 In addition to these traitlets, the :mod:`IPython.utils.traitlets` provides
143 traitlets for a number of other types.
143 traitlets for a number of other types.
144
144
145 .. note::
145 .. note::
146
146
147 Underneath the hood, the :class:`Configurable` base class is a subclass of
147 Underneath the hood, the :class:`Configurable` base class is a subclass of
148 :class:`IPython.utils.traitlets.HasTraits`. The
148 :class:`IPython.utils.traitlets.HasTraits`. The
149 :mod:`IPython.utils.traitlets` module is a lightweight version of
149 :mod:`IPython.utils.traitlets` module is a lightweight version of
150 :mod:`enthought.traits`. Our implementation is a pure Python subset
150 :mod:`enthought.traits`. Our implementation is a pure Python subset
151 (mostly API compatible) of :mod:`enthought.traits` that does not have any
151 (mostly API compatible) of :mod:`enthought.traits` that does not have any
152 of the automatic GUI generation capabilities. Our plan is to achieve 100%
152 of the automatic GUI generation capabilities. Our plan is to achieve 100%
153 API compatibility to enable the actual :mod:`enthought.traits` to
153 API compatibility to enable the actual :mod:`enthought.traits` to
154 eventually be used instead. Currently, we cannot use
154 eventually be used instead. Currently, we cannot use
155 :mod:`enthought.traits` as we are committed to the core of IPython being
155 :mod:`enthought.traits` as we are committed to the core of IPython being
156 pure Python.
156 pure Python.
157
157
158 It should be very clear at this point what the naming convention is for
158 It should be very clear at this point what the naming convention is for
159 configuration attributes::
159 configuration attributes::
160
160
161 c.ClassName.attribute_name = attribute_value
161 c.ClassName.attribute_name = attribute_value
162
162
163 Here, ``ClassName`` is the name of the class whose configuration attribute you
163 Here, ``ClassName`` is the name of the class whose configuration attribute you
164 want to set, ``attribute_name`` is the name of the attribute you want to set
164 want to set, ``attribute_name`` is the name of the attribute you want to set
165 and ``attribute_value`` the the value you want it to have. The ``ClassName``
165 and ``attribute_value`` the the value you want it to have. The ``ClassName``
166 attribute of ``c`` is not the actual class, but instead is another
166 attribute of ``c`` is not the actual class, but instead is another
167 :class:`~IPython.config.loader.Config` instance.
167 :class:`~IPython.config.loader.Config` instance.
168
168
169 .. note::
169 .. note::
170
170
171 The careful reader may wonder how the ``ClassName`` (``MyClass`` in
171 The careful reader may wonder how the ``ClassName`` (``MyClass`` in
172 the above example) attribute of the configuration object ``c`` gets
172 the above example) attribute of the configuration object ``c`` gets
173 created. These attributes are created on the fly by the
173 created. These attributes are created on the fly by the
174 :class:`~IPython.config.loader.Config` instance, using a simple naming
174 :class:`~IPython.config.loader.Config` instance, using a simple naming
175 convention. Any attribute of a :class:`~IPython.config.loader.Config`
175 convention. Any attribute of a :class:`~IPython.config.loader.Config`
176 instance whose name begins with an uppercase character is assumed to be a
176 instance whose name begins with an uppercase character is assumed to be a
177 sub-configuration and a new empty :class:`~IPython.config.loader.Config`
177 sub-configuration and a new empty :class:`~IPython.config.loader.Config`
178 instance is dynamically created for that attribute. This allows deeply
178 instance is dynamically created for that attribute. This allows deeply
179 hierarchical information created easily (``c.Foo.Bar.value``) on the fly.
179 hierarchical information created easily (``c.Foo.Bar.value``) on the fly.
180
180
181 Configuration files inheritance
181 Configuration files inheritance
182 ===============================
182 ===============================
183
183
184 Let's say you want to have different configuration files for various purposes.
184 Let's say you want to have different configuration files for various purposes.
185 Our configuration system makes it easy for one configuration file to inherit
185 Our configuration system makes it easy for one configuration file to inherit
186 the information in another configuration file. The :func:`load_subconfig`
186 the information in another configuration file. The :func:`load_subconfig`
187 command can be used in a configuration file for this purpose. Here is a simple
187 command can be used in a configuration file for this purpose. Here is a simple
188 example that loads all of the values from the file :file:`base_config.py`::
188 example that loads all of the values from the file :file:`base_config.py`::
189
189
190 # base_config.py
190 # base_config.py
191 c = get_config()
191 c = get_config()
192 c.MyClass.name = 'coolname'
192 c.MyClass.name = 'coolname'
193 c.MyClass.ranking = 100
193 c.MyClass.ranking = 100
194
194
195 into the configuration file :file:`main_config.py`::
195 into the configuration file :file:`main_config.py`::
196
196
197 # main_config.py
197 # main_config.py
198 c = get_config()
198 c = get_config()
199
199
200 # Load everything from base_config.py
200 # Load everything from base_config.py
201 load_subconfig('base_config.py')
201 load_subconfig('base_config.py')
202
202
203 # Now override one of the values
203 # Now override one of the values
204 c.MyClass.name = 'bettername'
204 c.MyClass.name = 'bettername'
205
205
206 In a situation like this the :func:`load_subconfig` makes sure that the
206 In a situation like this the :func:`load_subconfig` makes sure that the
207 search path for sub-configuration files is inherited from that of the parent.
207 search path for sub-configuration files is inherited from that of the parent.
208 Thus, you can typically put the two in the same directory and everything will
208 Thus, you can typically put the two in the same directory and everything will
209 just work.
209 just work.
210
210
211 You can also load configuration files by profile, for instance:
211 You can also load configuration files by profile, for instance:
212
212
213 .. sourcecode:: python
213 .. sourcecode:: python
214
214
215 load_subconfig('ipython_config.py', profile='default')
215 load_subconfig('ipython_config.py', profile='default')
216
216
217 to inherit your default configuration as a starting point.
217 to inherit your default configuration as a starting point.
218
218
219
219
220 Class based configuration inheritance
220 Class based configuration inheritance
221 =====================================
221 =====================================
222
222
223 There is another aspect of configuration where inheritance comes into play.
223 There is another aspect of configuration where inheritance comes into play.
224 Sometimes, your classes will have an inheritance hierarchy that you want
224 Sometimes, your classes will have an inheritance hierarchy that you want
225 to be reflected in the configuration system. Here is a simple example::
225 to be reflected in the configuration system. Here is a simple example::
226
226
227 from IPython.config.configurable import Configurable
227 from IPython.config.configurable import Configurable
228 from IPython.utils.traitlets import Int, Float, Unicode, Bool
228 from IPython.utils.traitlets import Int, Float, Unicode, Bool
229
229
230 class Foo(Configurable):
230 class Foo(Configurable):
231 name = Unicode(u'fooname', config=True)
231 name = Unicode(u'fooname', config=True)
232 value = Float(100.0, config=True)
232 value = Float(100.0, config=True)
233
233
234 class Bar(Foo):
234 class Bar(Foo):
235 name = Unicode(u'barname', config=True)
235 name = Unicode(u'barname', config=True)
236 othervalue = Int(0, config=True)
236 othervalue = Int(0, config=True)
237
237
238 Now, we can create a configuration file to configure instances of :class:`Foo`
238 Now, we can create a configuration file to configure instances of :class:`Foo`
239 and :class:`Bar`::
239 and :class:`Bar`::
240
240
241 # config file
241 # config file
242 c = get_config()
242 c = get_config()
243
243
244 c.Foo.name = u'bestname'
244 c.Foo.name = u'bestname'
245 c.Bar.othervalue = 10
245 c.Bar.othervalue = 10
246
246
247 This class hierarchy and configuration file accomplishes the following:
247 This class hierarchy and configuration file accomplishes the following:
248
248
249 * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be
249 * The default value for :attr:`Foo.name` and :attr:`Bar.name` will be
250 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also
250 'bestname'. Because :class:`Bar` is a :class:`Foo` subclass it also
251 picks up the configuration information for :class:`Foo`.
251 picks up the configuration information for :class:`Foo`.
252 * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be
252 * The default value for :attr:`Foo.value` and :attr:`Bar.value` will be
253 ``100.0``, which is the value specified as the class default.
253 ``100.0``, which is the value specified as the class default.
254 * The default value for :attr:`Bar.othervalue` will be 10 as set in the
254 * The default value for :attr:`Bar.othervalue` will be 10 as set in the
255 configuration file. Because :class:`Foo` is the parent of :class:`Bar`
255 configuration file. Because :class:`Foo` is the parent of :class:`Bar`
256 it doesn't know anything about the :attr:`othervalue` attribute.
256 it doesn't know anything about the :attr:`othervalue` attribute.
257
257
258
258
259 .. _ipython_dir:
259 .. _ipython_dir:
260
260
261 Configuration file location
261 Configuration file location
262 ===========================
262 ===========================
263
263
264 So where should you put your configuration files? IPython uses "profiles" for
264 So where should you put your configuration files? IPython uses "profiles" for
265 configuration, and by default, all profiles will be stored in the so called
265 configuration, and by default, all profiles will be stored in the so called
266 "IPython directory". The location of this directory is determined by the
266 "IPython directory". The location of this directory is determined by the
267 following algorithm:
267 following algorithm:
268
268
269 * If the ``ipython-dir`` command line flag is given, its value is used.
269 * If the ``ipython-dir`` command line flag is given, its value is used.
270
270
271 * If not, the value returned by :func:`IPython.utils.path.get_ipython_dir`
271 * If not, the value returned by :func:`IPython.utils.path.get_ipython_dir`
272 is used. This function will first look at the :envvar:`IPYTHONDIR`
272 is used. This function will first look at the :envvar:`IPYTHONDIR`
273 environment variable and then default to a platform-specific default.
273 environment variable and then default to :file:`~/.ipython`.
274 Historical support for the :envvar:`IPYTHON_DIR` environment variable will
274 Historical support for the :envvar:`IPYTHON_DIR` environment variable will
275 be removed in a future release.
275 be removed in a future release.
276
276
277 On posix systems (Linux, Unix, etc.), IPython respects the ``$XDG_CONFIG_HOME``
277 For most users, the configuration directory will be :file:`~/.ipython`.
278 part of the `XDG Base Directory`_ specification. If ``$XDG_CONFIG_HOME`` is
279 defined and exists ( ``XDG_CONFIG_HOME`` has a default interpretation of
280 :file:`$HOME/.config`), then IPython's config directory will be located in
281 :file:`$XDG_CONFIG_HOME/ipython`. If users still have an IPython directory
282 in :file:`$HOME/.ipython`, then that will be used. in preference to the
283 system default.
284
278
285 For most users, the default value will simply be something like
279 Previous versions of IPython on Linux would use the XDG config directory,
286 :file:`$HOME/.config/ipython` on Linux, or :file:`$HOME/.ipython`
280 creating :file:`~/.config/ipython` by default. We have decided to go
287 elsewhere.
281 back to :file:`~/.ipython` for consistency among systems. IPython will
282 issue a warning if it finds the XDG location, and will move it to the new
283 location if there isn't already a directory there.
288
284
289 Once the location of the IPython directory has been determined, you need to know
285 Once the location of the IPython directory has been determined, you need to know
290 which profile you are using. For users with a single configuration, this will
286 which profile you are using. For users with a single configuration, this will
291 simply be 'default', and will be located in
287 simply be 'default', and will be located in
292 :file:`<IPYTHONDIR>/profile_default`.
288 :file:`<IPYTHONDIR>/profile_default`.
293
289
294 The next thing you need to know is what to call your configuration file. The
290 The next thing you need to know is what to call your configuration file. The
295 basic idea is that each application has its own default configuration filename.
291 basic idea is that each application has its own default configuration filename.
296 The default named used by the :command:`ipython` command line program is
292 The default named used by the :command:`ipython` command line program is
297 :file:`ipython_config.py`, and *all* IPython applications will use this file.
293 :file:`ipython_config.py`, and *all* IPython applications will use this file.
298 Other applications, such as the parallel :command:`ipcluster` scripts or the
294 Other applications, such as the parallel :command:`ipcluster` scripts or the
299 QtConsole will load their own config files *after* :file:`ipython_config.py`. To
295 QtConsole will load their own config files *after* :file:`ipython_config.py`. To
300 load a particular configuration file instead of the default, the name can be
296 load a particular configuration file instead of the default, the name can be
301 overridden by the ``config_file`` command line flag.
297 overridden by the ``config_file`` command line flag.
302
298
303 To generate the default configuration files, do::
299 To generate the default configuration files, do::
304
300
305 $ ipython profile create
301 $ ipython profile create
306
302
307 and you will have a default :file:`ipython_config.py` in your IPython directory
303 and you will have a default :file:`ipython_config.py` in your IPython directory
308 under :file:`profile_default`. If you want the default config files for the
304 under :file:`profile_default`. If you want the default config files for the
309 :mod:`IPython.parallel` applications, add ``--parallel`` to the end of the
305 :mod:`IPython.parallel` applications, add ``--parallel`` to the end of the
310 command-line args.
306 command-line args.
311
307
312
308
313 Locating these files
309 Locating these files
314 --------------------
310 --------------------
315
311
316 From the command-line, you can quickly locate the IPYTHONDIR or a specific
312 From the command-line, you can quickly locate the IPYTHONDIR or a specific
317 profile with:
313 profile with:
318
314
319 .. sourcecode:: bash
315 .. sourcecode:: bash
320
316
321 $ ipython locate
317 $ ipython locate
322 /home/you/.ipython
318 /home/you/.ipython
323
319
324 $ ipython locate profile foo
320 $ ipython locate profile foo
325 /home/you/.ipython/profile_foo
321 /home/you/.ipython/profile_foo
326
322
327 These map to the utility functions: :func:`IPython.utils.path.get_ipython_dir`
323 These map to the utility functions: :func:`IPython.utils.path.get_ipython_dir`
328 and :func:`IPython.utils.path.locate_profile` respectively.
324 and :func:`IPython.utils.path.locate_profile` respectively.
329
325
330
326
331 .. _Profiles:
327 .. _Profiles:
332
328
333 Profiles
329 Profiles
334 ========
330 ========
335
331
336 A profile is a directory containing configuration and runtime files, such as
332 A profile is a directory containing configuration and runtime files, such as
337 logs, connection info for the parallel apps, and your IPython command history.
333 logs, connection info for the parallel apps, and your IPython command history.
338
334
339 The idea is that users often want to maintain a set of configuration files for
335 The idea is that users often want to maintain a set of configuration files for
340 different purposes: one for doing numerical computing with NumPy and SciPy and
336 different purposes: one for doing numerical computing with NumPy and SciPy and
341 another for doing symbolic computing with SymPy. Profiles make it easy to keep a
337 another for doing symbolic computing with SymPy. Profiles make it easy to keep a
342 separate configuration files, logs, and histories for each of these purposes.
338 separate configuration files, logs, and histories for each of these purposes.
343
339
344 Let's start by showing how a profile is used:
340 Let's start by showing how a profile is used:
345
341
346 .. code-block:: bash
342 .. code-block:: bash
347
343
348 $ ipython --profile=sympy
344 $ ipython --profile=sympy
349
345
350 This tells the :command:`ipython` command line program to get its configuration
346 This tells the :command:`ipython` command line program to get its configuration
351 from the "sympy" profile. The file names for various profiles do not change. The
347 from the "sympy" profile. The file names for various profiles do not change. The
352 only difference is that profiles are named in a special way. In the case above,
348 only difference is that profiles are named in a special way. In the case above,
353 the "sympy" profile means looking for :file:`ipython_config.py` in :file:`<IPYTHONDIR>/profile_sympy`.
349 the "sympy" profile means looking for :file:`ipython_config.py` in :file:`<IPYTHONDIR>/profile_sympy`.
354
350
355 The general pattern is this: simply create a new profile with:
351 The general pattern is this: simply create a new profile with:
356
352
357 .. code-block:: bash
353 .. code-block:: bash
358
354
359 $ ipython profile create <name>
355 $ ipython profile create <name>
360
356
361 which adds a directory called ``profile_<name>`` to your IPython directory. Then
357 which adds a directory called ``profile_<name>`` to your IPython directory. Then
362 you can load this profile by adding ``--profile=<name>`` to your command line
358 you can load this profile by adding ``--profile=<name>`` to your command line
363 options. Profiles are supported by all IPython applications.
359 options. Profiles are supported by all IPython applications.
364
360
365 IPython ships with some sample profiles in :file:`IPython/config/profile`. If
361 IPython ships with some sample profiles in :file:`IPython/config/profile`. If
366 you create profiles with the name of one of our shipped profiles, these config
362 you create profiles with the name of one of our shipped profiles, these config
367 files will be copied over instead of starting with the automatically generated
363 files will be copied over instead of starting with the automatically generated
368 config files.
364 config files.
369
365
370 Security Files
366 Security Files
371 --------------
367 --------------
372
368
373 If you are using the notebook, qtconsole, or parallel code, IPython stores
369 If you are using the notebook, qtconsole, or parallel code, IPython stores
374 connection information in small JSON files in the active profile's security
370 connection information in small JSON files in the active profile's security
375 directory. This directory is made private, so only you can see the files inside. If
371 directory. This directory is made private, so only you can see the files inside. If
376 you need to move connection files around to other computers, this is where they will
372 you need to move connection files around to other computers, this is where they will
377 be. If you want your code to be able to open security files by name, we have a
373 be. If you want your code to be able to open security files by name, we have a
378 convenience function :func:`IPython.utils.path.get_security_file`, which will return
374 convenience function :func:`IPython.utils.path.get_security_file`, which will return
379 the absolute path to a security file from its filename and [optionally] profile
375 the absolute path to a security file from its filename and [optionally] profile
380 name.
376 name.
381
377
382 .. _startup_files:
378 .. _startup_files:
383
379
384 Startup Files
380 Startup Files
385 -------------
381 -------------
386
382
387 If you want some code to be run at the beginning of every IPython session with
383 If you want some code to be run at the beginning of every IPython session with
388 a particular profile, the easiest way is to add Python (``.py``) or
384 a particular profile, the easiest way is to add Python (``.py``) or
389 IPython (``.ipy``) scripts to your :file:`<profile>/startup` directory. Files
385 IPython (``.ipy``) scripts to your :file:`<profile>/startup` directory. Files
390 in this directory will always be executed as soon as the IPython shell is
386 in this directory will always be executed as soon as the IPython shell is
391 constructed, and before any other code or scripts you have specified. If you
387 constructed, and before any other code or scripts you have specified. If you
392 have multiple files in the startup directory, they will be run in
388 have multiple files in the startup directory, they will be run in
393 lexicographical order, so you can control the ordering by adding a '00-'
389 lexicographical order, so you can control the ordering by adding a '00-'
394 prefix.
390 prefix.
395
391
396
392
397 .. _commandline:
393 .. _commandline:
398
394
399 Command-line arguments
395 Command-line arguments
400 ======================
396 ======================
401
397
402 IPython exposes *all* configurable options on the command-line. The command-line
398 IPython exposes *all* configurable options on the command-line. The command-line
403 arguments are generated from the Configurable traits of the classes associated
399 arguments are generated from the Configurable traits of the classes associated
404 with a given Application. Configuring IPython from the command-line may look
400 with a given Application. Configuring IPython from the command-line may look
405 very similar to an IPython config file
401 very similar to an IPython config file
406
402
407 IPython applications use a parser called
403 IPython applications use a parser called
408 :class:`~IPython.config.loader.KeyValueLoader` to load values into a Config
404 :class:`~IPython.config.loader.KeyValueLoader` to load values into a Config
409 object. Values are assigned in much the same way as in a config file:
405 object. Values are assigned in much the same way as in a config file:
410
406
411 .. code-block:: bash
407 .. code-block:: bash
412
408
413 $ ipython --InteractiveShell.use_readline=False --BaseIPythonApplication.profile='myprofile'
409 $ ipython --InteractiveShell.use_readline=False --BaseIPythonApplication.profile='myprofile'
414
410
415 Is the same as adding:
411 Is the same as adding:
416
412
417 .. sourcecode:: python
413 .. sourcecode:: python
418
414
419 c.InteractiveShell.use_readline=False
415 c.InteractiveShell.use_readline=False
420 c.BaseIPythonApplication.profile='myprofile'
416 c.BaseIPythonApplication.profile='myprofile'
421
417
422 to your config file. Key/Value arguments *always* take a value, separated by '='
418 to your config file. Key/Value arguments *always* take a value, separated by '='
423 and no spaces.
419 and no spaces.
424
420
425 Common Arguments
421 Common Arguments
426 ----------------
422 ----------------
427
423
428 Since the strictness and verbosity of the KVLoader above are not ideal for everyday
424 Since the strictness and verbosity of the KVLoader above are not ideal for everyday
429 use, common arguments can be specified as flags_ or aliases_.
425 use, common arguments can be specified as flags_ or aliases_.
430
426
431 Flags and Aliases are handled by :mod:`argparse` instead, allowing for more flexible
427 Flags and Aliases are handled by :mod:`argparse` instead, allowing for more flexible
432 parsing. In general, flags and aliases are prefixed by ``--``, except for those
428 parsing. In general, flags and aliases are prefixed by ``--``, except for those
433 that are single characters, in which case they can be specified with a single ``-``, e.g.:
429 that are single characters, in which case they can be specified with a single ``-``, e.g.:
434
430
435 .. code-block:: bash
431 .. code-block:: bash
436
432
437 $ ipython -i -c "import numpy; x=numpy.linspace(0,1)" --profile testing --colors=lightbg
433 $ ipython -i -c "import numpy; x=numpy.linspace(0,1)" --profile testing --colors=lightbg
438
434
439 Aliases
435 Aliases
440 *******
436 *******
441
437
442 For convenience, applications have a mapping of commonly used traits, so you don't have
438 For convenience, applications have a mapping of commonly used traits, so you don't have
443 to specify the whole class name:
439 to specify the whole class name:
444
440
445 .. code-block:: bash
441 .. code-block:: bash
446
442
447 $ ipython --profile myprofile
443 $ ipython --profile myprofile
448 # and
444 # and
449 $ ipython --profile='myprofile'
445 $ ipython --profile='myprofile'
450 # are equivalent to
446 # are equivalent to
451 $ ipython --BaseIPythonApplication.profile='myprofile'
447 $ ipython --BaseIPythonApplication.profile='myprofile'
452
448
453 Flags
449 Flags
454 *****
450 *****
455
451
456 Applications can also be passed **flags**. Flags are options that take no
452 Applications can also be passed **flags**. Flags are options that take no
457 arguments. They are simply wrappers for
453 arguments. They are simply wrappers for
458 setting one or more configurables with predefined values, often True/False.
454 setting one or more configurables with predefined values, often True/False.
459
455
460 For instance:
456 For instance:
461
457
462 .. code-block:: bash
458 .. code-block:: bash
463
459
464 $ ipcontroller --debug
460 $ ipcontroller --debug
465 # is equivalent to
461 # is equivalent to
466 $ ipcontroller --Application.log_level=DEBUG
462 $ ipcontroller --Application.log_level=DEBUG
467 # and
463 # and
468 $ ipython --matploitlib
464 $ ipython --matploitlib
469 # is equivalent to
465 # is equivalent to
470 $ ipython --matplotlib auto
466 $ ipython --matplotlib auto
471 # or
467 # or
472 $ ipython --no-banner
468 $ ipython --no-banner
473 # is equivalent to
469 # is equivalent to
474 $ ipython --TerminalIPythonApp.display_banner=False
470 $ ipython --TerminalIPythonApp.display_banner=False
475
471
476 Subcommands
472 Subcommands
477 -----------
473 -----------
478
474
479
475
480 Some IPython applications have **subcommands**. Subcommands are modeled after
476 Some IPython applications have **subcommands**. Subcommands are modeled after
481 :command:`git`, and are called with the form :command:`command subcommand
477 :command:`git`, and are called with the form :command:`command subcommand
482 [...args]`. Currently, the QtConsole is a subcommand of terminal IPython:
478 [...args]`. Currently, the QtConsole is a subcommand of terminal IPython:
483
479
484 .. code-block:: bash
480 .. code-block:: bash
485
481
486 $ ipython qtconsole --profile myprofile
482 $ ipython qtconsole --profile myprofile
487
483
488 and :command:`ipcluster` is simply a wrapper for its various subcommands (start,
484 and :command:`ipcluster` is simply a wrapper for its various subcommands (start,
489 stop, engines).
485 stop, engines).
490
486
491 .. code-block:: bash
487 .. code-block:: bash
492
488
493 $ ipcluster start --profile=myprofile -n 4
489 $ ipcluster start --profile=myprofile -n 4
494
490
495
491
496 To see a list of the available aliases, flags, and subcommands for an IPython application, simply pass ``-h`` or ``--help``. And to see the full list of configurable options (*very* long), pass ``--help-all``.
492 To see a list of the available aliases, flags, and subcommands for an IPython application, simply pass ``-h`` or ``--help``. And to see the full list of configurable options (*very* long), pass ``--help-all``.
497
493
498
494
499 Design requirements
495 Design requirements
500 ===================
496 ===================
501
497
502 Here are the main requirements we wanted our configuration system to have:
498 Here are the main requirements we wanted our configuration system to have:
503
499
504 * Support for hierarchical configuration information.
500 * Support for hierarchical configuration information.
505
501
506 * Full integration with command line option parsers. Often, you want to read
502 * Full integration with command line option parsers. Often, you want to read
507 a configuration file, but then override some of the values with command line
503 a configuration file, but then override some of the values with command line
508 options. Our configuration system automates this process and allows each
504 options. Our configuration system automates this process and allows each
509 command line option to be linked to a particular attribute in the
505 command line option to be linked to a particular attribute in the
510 configuration hierarchy that it will override.
506 configuration hierarchy that it will override.
511
507
512 * Configuration files that are themselves valid Python code. This accomplishes
508 * Configuration files that are themselves valid Python code. This accomplishes
513 many things. First, it becomes possible to put logic in your configuration
509 many things. First, it becomes possible to put logic in your configuration
514 files that sets attributes based on your operating system, network setup,
510 files that sets attributes based on your operating system, network setup,
515 Python version, etc. Second, Python has a super simple syntax for accessing
511 Python version, etc. Second, Python has a super simple syntax for accessing
516 hierarchical data structures, namely regular attribute access
512 hierarchical data structures, namely regular attribute access
517 (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to
513 (``Foo.Bar.Bam.name``). Third, using Python makes it easy for users to
518 import configuration attributes from one configuration file to another.
514 import configuration attributes from one configuration file to another.
519 Fourth, even though Python is dynamically typed, it does have types that can
515 Fourth, even though Python is dynamically typed, it does have types that can
520 be checked at runtime. Thus, a ``1`` in a config file is the integer '1',
516 be checked at runtime. Thus, a ``1`` in a config file is the integer '1',
521 while a ``'1'`` is a string.
517 while a ``'1'`` is a string.
522
518
523 * A fully automated method for getting the configuration information to the
519 * A fully automated method for getting the configuration information to the
524 classes that need it at runtime. Writing code that walks a configuration
520 classes that need it at runtime. Writing code that walks a configuration
525 hierarchy to extract a particular attribute is painful. When you have
521 hierarchy to extract a particular attribute is painful. When you have
526 complex configuration information with hundreds of attributes, this makes
522 complex configuration information with hundreds of attributes, this makes
527 you want to cry.
523 you want to cry.
528
524
529 * Type checking and validation that doesn't require the entire configuration
525 * Type checking and validation that doesn't require the entire configuration
530 hierarchy to be specified statically before runtime. Python is a very
526 hierarchy to be specified statically before runtime. Python is a very
531 dynamic language and you don't always know everything that needs to be
527 dynamic language and you don't always know everything that needs to be
532 configured when a program starts.
528 configured when a program starts.
533
529
534
535 .. _`XDG Base Directory`: http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
@@ -1,1164 +1,1164 b''
1 =================
1 =================
2 IPython reference
2 IPython reference
3 =================
3 =================
4
4
5 .. _command_line_options:
5 .. _command_line_options:
6
6
7 Command-line usage
7 Command-line usage
8 ==================
8 ==================
9
9
10 You start IPython with the command::
10 You start IPython with the command::
11
11
12 $ ipython [options] files
12 $ ipython [options] files
13
13
14 .. note::
14 .. note::
15
15
16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
17
17
18 If invoked with no options, it executes all the files listed in sequence
18 If invoked with no options, it executes all the files listed in sequence
19 and drops you into the interpreter while still acknowledging any options
19 and drops you into the interpreter while still acknowledging any options
20 you may have set in your ipython_config.py. This behavior is different from
20 you may have set in your ipython_config.py. This behavior is different from
21 standard Python, which when called as python -i will only execute one
21 standard Python, which when called as python -i will only execute one
22 file and ignore your configuration setup.
22 file and ignore your configuration setup.
23
23
24 Please note that some of the configuration options are not available at
24 Please note that some of the configuration options are not available at
25 the command line, simply because they are not practical here. Look into
25 the command line, simply because they are not practical here. Look into
26 your configuration files for details on those. There are separate configuration
26 your configuration files for details on those. There are separate configuration
27 files for each profile, and the files look like "ipython_config.py" or
27 files for each profile, and the files look like "ipython_config.py" or
28 "ipython_config_<frontendname>.py". Profile directories look like
28 "ipython_config_<frontendname>.py". Profile directories look like
29 "profile_profilename" and are typically installed in the IPYTHONDIR directory.
29 "profile_profilename" and are typically installed in the IPYTHONDIR directory,
30 For Linux users, this will be $HOME/.config/ipython, and for other users it
30 which defaults to :file:`$HOME/.ipython`. For Windows users, :envvar:`HOME`
31 will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
31 resolves to :file:`C:\\Documents and Settings\\YourUserName` in most
32 Settings\\YourUserName in most instances.
32 instances.
33
33
34
34
35 Eventloop integration
35 Eventloop integration
36 ---------------------
36 ---------------------
37
37
38 Previously IPython had command line options for controlling GUI event loop
38 Previously IPython had command line options for controlling GUI event loop
39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
40 version 0.11, these have been removed. Please see the new ``%gui``
40 version 0.11, these have been removed. Please see the new ``%gui``
41 magic command or :ref:`this section <gui_support>` for details on the new
41 magic command or :ref:`this section <gui_support>` for details on the new
42 interface, or specify the gui at the commandline::
42 interface, or specify the gui at the commandline::
43
43
44 $ ipython --gui=qt
44 $ ipython --gui=qt
45
45
46
46
47 Command-line Options
47 Command-line Options
48 --------------------
48 --------------------
49
49
50 To see the options IPython accepts, use ``ipython --help`` (and you probably
50 To see the options IPython accepts, use ``ipython --help`` (and you probably
51 should run the output through a pager such as ``ipython --help | less`` for
51 should run the output through a pager such as ``ipython --help | less`` for
52 more convenient reading). This shows all the options that have a single-word
52 more convenient reading). This shows all the options that have a single-word
53 alias to control them, but IPython lets you configure all of its objects from
53 alias to control them, but IPython lets you configure all of its objects from
54 the command-line by passing the full class name and a corresponding value; type
54 the command-line by passing the full class name and a corresponding value; type
55 ``ipython --help-all`` to see this full list. For example::
55 ``ipython --help-all`` to see this full list. For example::
56
56
57 ipython --matplotlib qt
57 ipython --matplotlib qt
58
58
59 is equivalent to::
59 is equivalent to::
60
60
61 ipython --TerminalIPythonApp.matplotlib='qt'
61 ipython --TerminalIPythonApp.matplotlib='qt'
62
62
63 Note that in the second form, you *must* use the equal sign, as the expression
63 Note that in the second form, you *must* use the equal sign, as the expression
64 is evaluated as an actual Python assignment. While in the above example the
64 is evaluated as an actual Python assignment. While in the above example the
65 short form is more convenient, only the most common options have a short form,
65 short form is more convenient, only the most common options have a short form,
66 while any configurable variable in IPython can be set at the command-line by
66 while any configurable variable in IPython can be set at the command-line by
67 using the long form. This long form is the same syntax used in the
67 using the long form. This long form is the same syntax used in the
68 configuration files, if you want to set these options permanently.
68 configuration files, if you want to set these options permanently.
69
69
70
70
71 Interactive use
71 Interactive use
72 ===============
72 ===============
73
73
74 IPython is meant to work as a drop-in replacement for the standard interactive
74 IPython is meant to work as a drop-in replacement for the standard interactive
75 interpreter. As such, any code which is valid python should execute normally
75 interpreter. As such, any code which is valid python should execute normally
76 under IPython (cases where this is not true should be reported as bugs). It
76 under IPython (cases where this is not true should be reported as bugs). It
77 does, however, offer many features which are not available at a standard python
77 does, however, offer many features which are not available at a standard python
78 prompt. What follows is a list of these.
78 prompt. What follows is a list of these.
79
79
80
80
81 Caution for Windows users
81 Caution for Windows users
82 -------------------------
82 -------------------------
83
83
84 Windows, unfortunately, uses the '\\' character as a path separator. This is a
84 Windows, unfortunately, uses the '\\' character as a path separator. This is a
85 terrible choice, because '\\' also represents the escape character in most
85 terrible choice, because '\\' also represents the escape character in most
86 modern programming languages, including Python. For this reason, using '/'
86 modern programming languages, including Python. For this reason, using '/'
87 character is recommended if you have problems with ``\``. However, in Windows
87 character is recommended if you have problems with ``\``. However, in Windows
88 commands '/' flags options, so you can not use it for the root directory. This
88 commands '/' flags options, so you can not use it for the root directory. This
89 means that paths beginning at the root must be typed in a contrived manner
89 means that paths beginning at the root must be typed in a contrived manner
90 like: ``%copy \opt/foo/bar.txt \tmp``
90 like: ``%copy \opt/foo/bar.txt \tmp``
91
91
92 .. _magic:
92 .. _magic:
93
93
94 Magic command system
94 Magic command system
95 --------------------
95 --------------------
96
96
97 IPython will treat any line whose first character is a % as a special
97 IPython will treat any line whose first character is a % as a special
98 call to a 'magic' function. These allow you to control the behavior of
98 call to a 'magic' function. These allow you to control the behavior of
99 IPython itself, plus a lot of system-type features. They are all
99 IPython itself, plus a lot of system-type features. They are all
100 prefixed with a % character, but parameters are given without
100 prefixed with a % character, but parameters are given without
101 parentheses or quotes.
101 parentheses or quotes.
102
102
103 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
103 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
104 only the rest of the current line, but all lines below them as well, in the
104 only the rest of the current line, but all lines below them as well, in the
105 current execution block. Cell magics can in fact make arbitrary modifications
105 current execution block. Cell magics can in fact make arbitrary modifications
106 to the input they receive, which need not even be valid Python code at all.
106 to the input they receive, which need not even be valid Python code at all.
107 They receive the whole block as a single string.
107 They receive the whole block as a single string.
108
108
109 As a line magic example, the ``%cd`` magic works just like the OS command of
109 As a line magic example, the ``%cd`` magic works just like the OS command of
110 the same name::
110 the same name::
111
111
112 In [8]: %cd
112 In [8]: %cd
113 /home/fperez
113 /home/fperez
114
114
115 The following uses the builtin ``timeit`` in cell mode::
115 The following uses the builtin ``timeit`` in cell mode::
116
116
117 In [10]: %%timeit x = range(10000)
117 In [10]: %%timeit x = range(10000)
118 ...: min(x)
118 ...: min(x)
119 ...: max(x)
119 ...: max(x)
120 ...:
120 ...:
121 1000 loops, best of 3: 438 us per loop
121 1000 loops, best of 3: 438 us per loop
122
122
123 In this case, ``x = range(10000)`` is called as the line argument, and the
123 In this case, ``x = range(10000)`` is called as the line argument, and the
124 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
124 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
125 ``timeit`` magic receives both.
125 ``timeit`` magic receives both.
126
126
127 If you have 'automagic' enabled (as it by default), you don't need to type in
127 If you have 'automagic' enabled (as it by default), you don't need to type in
128 the single ``%`` explicitly for line magics; IPython will scan its internal
128 the single ``%`` explicitly for line magics; IPython will scan its internal
129 list of magic functions and call one if it exists. With automagic on you can
129 list of magic functions and call one if it exists. With automagic on you can
130 then just type ``cd mydir`` to go to directory 'mydir'::
130 then just type ``cd mydir`` to go to directory 'mydir'::
131
131
132 In [9]: cd mydir
132 In [9]: cd mydir
133 /home/fperez/mydir
133 /home/fperez/mydir
134
134
135 Note that cell magics *always* require an explicit ``%%`` prefix, automagic
135 Note that cell magics *always* require an explicit ``%%`` prefix, automagic
136 calling only works for line magics.
136 calling only works for line magics.
137
137
138 The automagic system has the lowest possible precedence in name searches, so
138 The automagic system has the lowest possible precedence in name searches, so
139 defining an identifier with the same name as an existing magic function will
139 defining an identifier with the same name as an existing magic function will
140 shadow it for automagic use. You can still access the shadowed magic function
140 shadow it for automagic use. You can still access the shadowed magic function
141 by explicitly using the ``%`` character at the beginning of the line.
141 by explicitly using the ``%`` character at the beginning of the line.
142
142
143 An example (with automagic on) should clarify all this:
143 An example (with automagic on) should clarify all this:
144
144
145 .. sourcecode:: ipython
145 .. sourcecode:: ipython
146
146
147 In [1]: cd ipython # %cd is called by automagic
147 In [1]: cd ipython # %cd is called by automagic
148 /home/fperez/ipython
148 /home/fperez/ipython
149
149
150 In [2]: cd=1 # now cd is just a variable
150 In [2]: cd=1 # now cd is just a variable
151
151
152 In [3]: cd .. # and doesn't work as a function anymore
152 In [3]: cd .. # and doesn't work as a function anymore
153 File "<ipython-input-3-9fedb3aff56c>", line 1
153 File "<ipython-input-3-9fedb3aff56c>", line 1
154 cd ..
154 cd ..
155 ^
155 ^
156 SyntaxError: invalid syntax
156 SyntaxError: invalid syntax
157
157
158
158
159 In [4]: %cd .. # but %cd always works
159 In [4]: %cd .. # but %cd always works
160 /home/fperez
160 /home/fperez
161
161
162 In [5]: del cd # if you remove the cd variable, automagic works again
162 In [5]: del cd # if you remove the cd variable, automagic works again
163
163
164 In [6]: cd ipython
164 In [6]: cd ipython
165
165
166 /home/fperez/ipython
166 /home/fperez/ipython
167
167
168 Defining your own magics
168 Defining your own magics
169 ++++++++++++++++++++++++
169 ++++++++++++++++++++++++
170
170
171 There are two main ways to define your own magic functions: from standalone
171 There are two main ways to define your own magic functions: from standalone
172 functions and by inheriting from a base class provided by IPython:
172 functions and by inheriting from a base class provided by IPython:
173 :class:`IPython.core.magic.Magics`. Below we show code you can place in a file
173 :class:`IPython.core.magic.Magics`. Below we show code you can place in a file
174 that you load from your configuration, such as any file in the ``startup``
174 that you load from your configuration, such as any file in the ``startup``
175 subdirectory of your default IPython profile.
175 subdirectory of your default IPython profile.
176
176
177 First, let us see the simplest case. The following shows how to create a line
177 First, let us see the simplest case. The following shows how to create a line
178 magic, a cell one and one that works in both modes, using just plain functions:
178 magic, a cell one and one that works in both modes, using just plain functions:
179
179
180 .. sourcecode:: python
180 .. sourcecode:: python
181
181
182 from IPython.core.magic import (register_line_magic, register_cell_magic,
182 from IPython.core.magic import (register_line_magic, register_cell_magic,
183 register_line_cell_magic)
183 register_line_cell_magic)
184
184
185 @register_line_magic
185 @register_line_magic
186 def lmagic(line):
186 def lmagic(line):
187 "my line magic"
187 "my line magic"
188 return line
188 return line
189
189
190 @register_cell_magic
190 @register_cell_magic
191 def cmagic(line, cell):
191 def cmagic(line, cell):
192 "my cell magic"
192 "my cell magic"
193 return line, cell
193 return line, cell
194
194
195 @register_line_cell_magic
195 @register_line_cell_magic
196 def lcmagic(line, cell=None):
196 def lcmagic(line, cell=None):
197 "Magic that works both as %lcmagic and as %%lcmagic"
197 "Magic that works both as %lcmagic and as %%lcmagic"
198 if cell is None:
198 if cell is None:
199 print "Called as line magic"
199 print "Called as line magic"
200 return line
200 return line
201 else:
201 else:
202 print "Called as cell magic"
202 print "Called as cell magic"
203 return line, cell
203 return line, cell
204
204
205 # We delete these to avoid name conflicts for automagic to work
205 # We delete these to avoid name conflicts for automagic to work
206 del lmagic, lcmagic
206 del lmagic, lcmagic
207
207
208
208
209 You can also create magics of all three kinds by inheriting from the
209 You can also create magics of all three kinds by inheriting from the
210 :class:`IPython.core.magic.Magics` class. This lets you create magics that can
210 :class:`IPython.core.magic.Magics` class. This lets you create magics that can
211 potentially hold state in between calls, and that have full access to the main
211 potentially hold state in between calls, and that have full access to the main
212 IPython object:
212 IPython object:
213
213
214 .. sourcecode:: python
214 .. sourcecode:: python
215
215
216 # This code can be put in any Python module, it does not require IPython
216 # This code can be put in any Python module, it does not require IPython
217 # itself to be running already. It only creates the magics subclass but
217 # itself to be running already. It only creates the magics subclass but
218 # doesn't instantiate it yet.
218 # doesn't instantiate it yet.
219 from IPython.core.magic import (Magics, magics_class, line_magic,
219 from IPython.core.magic import (Magics, magics_class, line_magic,
220 cell_magic, line_cell_magic)
220 cell_magic, line_cell_magic)
221
221
222 # The class MUST call this class decorator at creation time
222 # The class MUST call this class decorator at creation time
223 @magics_class
223 @magics_class
224 class MyMagics(Magics):
224 class MyMagics(Magics):
225
225
226 @line_magic
226 @line_magic
227 def lmagic(self, line):
227 def lmagic(self, line):
228 "my line magic"
228 "my line magic"
229 print "Full access to the main IPython object:", self.shell
229 print "Full access to the main IPython object:", self.shell
230 print "Variables in the user namespace:", self.shell.user_ns.keys()
230 print "Variables in the user namespace:", self.shell.user_ns.keys()
231 return line
231 return line
232
232
233 @cell_magic
233 @cell_magic
234 def cmagic(self, line, cell):
234 def cmagic(self, line, cell):
235 "my cell magic"
235 "my cell magic"
236 return line, cell
236 return line, cell
237
237
238 @line_cell_magic
238 @line_cell_magic
239 def lcmagic(self, line, cell=None):
239 def lcmagic(self, line, cell=None):
240 "Magic that works both as %lcmagic and as %%lcmagic"
240 "Magic that works both as %lcmagic and as %%lcmagic"
241 if cell is None:
241 if cell is None:
242 print "Called as line magic"
242 print "Called as line magic"
243 return line
243 return line
244 else:
244 else:
245 print "Called as cell magic"
245 print "Called as cell magic"
246 return line, cell
246 return line, cell
247
247
248
248
249 # In order to actually use these magics, you must register them with a
249 # In order to actually use these magics, you must register them with a
250 # running IPython. This code must be placed in a file that is loaded once
250 # running IPython. This code must be placed in a file that is loaded once
251 # IPython is up and running:
251 # IPython is up and running:
252 ip = get_ipython()
252 ip = get_ipython()
253 # You can register the class itself without instantiating it. IPython will
253 # You can register the class itself without instantiating it. IPython will
254 # call the default constructor on it.
254 # call the default constructor on it.
255 ip.register_magics(MyMagics)
255 ip.register_magics(MyMagics)
256
256
257 If you want to create a class with a different constructor that holds
257 If you want to create a class with a different constructor that holds
258 additional state, then you should always call the parent constructor and
258 additional state, then you should always call the parent constructor and
259 instantiate the class yourself before registration:
259 instantiate the class yourself before registration:
260
260
261 .. sourcecode:: python
261 .. sourcecode:: python
262
262
263 @magics_class
263 @magics_class
264 class StatefulMagics(Magics):
264 class StatefulMagics(Magics):
265 "Magics that hold additional state"
265 "Magics that hold additional state"
266
266
267 def __init__(self, shell, data):
267 def __init__(self, shell, data):
268 # You must call the parent constructor
268 # You must call the parent constructor
269 super(StatefulMagics, self).__init__(shell)
269 super(StatefulMagics, self).__init__(shell)
270 self.data = data
270 self.data = data
271
271
272 # etc...
272 # etc...
273
273
274 # This class must then be registered with a manually created instance,
274 # This class must then be registered with a manually created instance,
275 # since its constructor has different arguments from the default:
275 # since its constructor has different arguments from the default:
276 ip = get_ipython()
276 ip = get_ipython()
277 magics = StatefulMagics(ip, some_data)
277 magics = StatefulMagics(ip, some_data)
278 ip.register_magics(magics)
278 ip.register_magics(magics)
279
279
280
280
281 In earlier versions, IPython had an API for the creation of line magics (cell
281 In earlier versions, IPython had an API for the creation of line magics (cell
282 magics did not exist at the time) that required you to create functions with a
282 magics did not exist at the time) that required you to create functions with a
283 method-looking signature and to manually pass both the function and the name.
283 method-looking signature and to manually pass both the function and the name.
284 While this API is no longer recommended, it remains indefinitely supported for
284 While this API is no longer recommended, it remains indefinitely supported for
285 backwards compatibility purposes. With the old API, you'd create a magic as
285 backwards compatibility purposes. With the old API, you'd create a magic as
286 follows:
286 follows:
287
287
288 .. sourcecode:: python
288 .. sourcecode:: python
289
289
290 def func(self, line):
290 def func(self, line):
291 print "Line magic called with line:", line
291 print "Line magic called with line:", line
292 print "IPython object:", self.shell
292 print "IPython object:", self.shell
293
293
294 ip = get_ipython()
294 ip = get_ipython()
295 # Declare this function as the magic %mycommand
295 # Declare this function as the magic %mycommand
296 ip.define_magic('mycommand', func)
296 ip.define_magic('mycommand', func)
297
297
298 Type ``%magic`` for more information, including a list of all available magic
298 Type ``%magic`` for more information, including a list of all available magic
299 functions at any time and their docstrings. You can also type
299 functions at any time and their docstrings. You can also type
300 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
300 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
301 information on the '?' system) to get information about any particular magic
301 information on the '?' system) to get information about any particular magic
302 function you are interested in.
302 function you are interested in.
303
303
304 The API documentation for the :mod:`IPython.core.magic` module contains the full
304 The API documentation for the :mod:`IPython.core.magic` module contains the full
305 docstrings of all currently available magic commands.
305 docstrings of all currently available magic commands.
306
306
307
307
308 Access to the standard Python help
308 Access to the standard Python help
309 ----------------------------------
309 ----------------------------------
310
310
311 Simply type ``help()`` to access Python's standard help system. You can
311 Simply type ``help()`` to access Python's standard help system. You can
312 also type ``help(object)`` for information about a given object, or
312 also type ``help(object)`` for information about a given object, or
313 ``help('keyword')`` for information on a keyword. You may need to configure your
313 ``help('keyword')`` for information on a keyword. You may need to configure your
314 PYTHONDOCS environment variable for this feature to work correctly.
314 PYTHONDOCS environment variable for this feature to work correctly.
315
315
316 .. _dynamic_object_info:
316 .. _dynamic_object_info:
317
317
318 Dynamic object information
318 Dynamic object information
319 --------------------------
319 --------------------------
320
320
321 Typing ``?word`` or ``word?`` prints detailed information about an object. If
321 Typing ``?word`` or ``word?`` prints detailed information about an object. If
322 certain strings in the object are too long (e.g. function signatures) they get
322 certain strings in the object are too long (e.g. function signatures) they get
323 snipped in the center for brevity. This system gives access variable types and
323 snipped in the center for brevity. This system gives access variable types and
324 values, docstrings, function prototypes and other useful information.
324 values, docstrings, function prototypes and other useful information.
325
325
326 If the information will not fit in the terminal, it is displayed in a pager
326 If the information will not fit in the terminal, it is displayed in a pager
327 (``less`` if available, otherwise a basic internal pager).
327 (``less`` if available, otherwise a basic internal pager).
328
328
329 Typing ``??word`` or ``word??`` gives access to the full information, including
329 Typing ``??word`` or ``word??`` gives access to the full information, including
330 the source code where possible. Long strings are not snipped.
330 the source code where possible. Long strings are not snipped.
331
331
332 The following magic functions are particularly useful for gathering
332 The following magic functions are particularly useful for gathering
333 information about your working environment. You can get more details by
333 information about your working environment. You can get more details by
334 typing ``%magic`` or querying them individually (``%function_name?``);
334 typing ``%magic`` or querying them individually (``%function_name?``);
335 this is just a summary:
335 this is just a summary:
336
336
337 * **%pdoc <object>**: Print (or run through a pager if too long) the
337 * **%pdoc <object>**: Print (or run through a pager if too long) the
338 docstring for an object. If the given object is a class, it will
338 docstring for an object. If the given object is a class, it will
339 print both the class and the constructor docstrings.
339 print both the class and the constructor docstrings.
340 * **%pdef <object>**: Print the call signature for any callable
340 * **%pdef <object>**: Print the call signature for any callable
341 object. If the object is a class, print the constructor information.
341 object. If the object is a class, print the constructor information.
342 * **%psource <object>**: Print (or run through a pager if too long)
342 * **%psource <object>**: Print (or run through a pager if too long)
343 the source code for an object.
343 the source code for an object.
344 * **%pfile <object>**: Show the entire source file where an object was
344 * **%pfile <object>**: Show the entire source file where an object was
345 defined via a pager, opening it at the line where the object
345 defined via a pager, opening it at the line where the object
346 definition begins.
346 definition begins.
347 * **%who/%whos**: These functions give information about identifiers
347 * **%who/%whos**: These functions give information about identifiers
348 you have defined interactively (not things you loaded or defined
348 you have defined interactively (not things you loaded or defined
349 in your configuration files). %who just prints a list of
349 in your configuration files). %who just prints a list of
350 identifiers and %whos prints a table with some basic details about
350 identifiers and %whos prints a table with some basic details about
351 each identifier.
351 each identifier.
352
352
353 Note that the dynamic object information functions (?/??, ``%pdoc``,
353 Note that the dynamic object information functions (?/??, ``%pdoc``,
354 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
354 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
355 directly on variables. For example, after doing ``import os``, you can use
355 directly on variables. For example, after doing ``import os``, you can use
356 ``os.path.abspath??``.
356 ``os.path.abspath??``.
357
357
358 .. _readline:
358 .. _readline:
359
359
360 Readline-based features
360 Readline-based features
361 -----------------------
361 -----------------------
362
362
363 These features require the GNU readline library, so they won't work if your
363 These features require the GNU readline library, so they won't work if your
364 Python installation lacks readline support. We will first describe the default
364 Python installation lacks readline support. We will first describe the default
365 behavior IPython uses, and then how to change it to suit your preferences.
365 behavior IPython uses, and then how to change it to suit your preferences.
366
366
367
367
368 Command line completion
368 Command line completion
369 +++++++++++++++++++++++
369 +++++++++++++++++++++++
370
370
371 At any time, hitting TAB will complete any available python commands or
371 At any time, hitting TAB will complete any available python commands or
372 variable names, and show you a list of the possible completions if
372 variable names, and show you a list of the possible completions if
373 there's no unambiguous one. It will also complete filenames in the
373 there's no unambiguous one. It will also complete filenames in the
374 current directory if no python names match what you've typed so far.
374 current directory if no python names match what you've typed so far.
375
375
376
376
377 Search command history
377 Search command history
378 ++++++++++++++++++++++
378 ++++++++++++++++++++++
379
379
380 IPython provides two ways for searching through previous input and thus
380 IPython provides two ways for searching through previous input and thus
381 reduce the need for repetitive typing:
381 reduce the need for repetitive typing:
382
382
383 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
383 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
384 (next,down) to search through only the history items that match
384 (next,down) to search through only the history items that match
385 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
385 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
386 prompt, they just behave like normal arrow keys.
386 prompt, they just behave like normal arrow keys.
387 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
387 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
388 searches your history for lines that contain what you've typed so
388 searches your history for lines that contain what you've typed so
389 far, completing as much as it can.
389 far, completing as much as it can.
390
390
391
391
392 Persistent command history across sessions
392 Persistent command history across sessions
393 ++++++++++++++++++++++++++++++++++++++++++
393 ++++++++++++++++++++++++++++++++++++++++++
394
394
395 IPython will save your input history when it leaves and reload it next
395 IPython will save your input history when it leaves and reload it next
396 time you restart it. By default, the history file is named
396 time you restart it. By default, the history file is named
397 $IPYTHONDIR/profile_<name>/history.sqlite. This allows you to keep
397 $IPYTHONDIR/profile_<name>/history.sqlite. This allows you to keep
398 separate histories related to various tasks: commands related to
398 separate histories related to various tasks: commands related to
399 numerical work will not be clobbered by a system shell history, for
399 numerical work will not be clobbered by a system shell history, for
400 example.
400 example.
401
401
402
402
403 Autoindent
403 Autoindent
404 ++++++++++
404 ++++++++++
405
405
406 IPython can recognize lines ending in ':' and indent the next line,
406 IPython can recognize lines ending in ':' and indent the next line,
407 while also un-indenting automatically after 'raise' or 'return'.
407 while also un-indenting automatically after 'raise' or 'return'.
408
408
409 This feature uses the readline library, so it will honor your
409 This feature uses the readline library, so it will honor your
410 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
410 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
411 to). Adding the following lines to your :file:`.inputrc` file can make
411 to). Adding the following lines to your :file:`.inputrc` file can make
412 indenting/unindenting more convenient (M-i indents, M-u unindents)::
412 indenting/unindenting more convenient (M-i indents, M-u unindents)::
413
413
414 # if you don't already have a ~/.inputrc file, you need this include:
414 # if you don't already have a ~/.inputrc file, you need this include:
415 $include /etc/inputrc
415 $include /etc/inputrc
416
416
417 $if Python
417 $if Python
418 "\M-i": " "
418 "\M-i": " "
419 "\M-u": "\d\d\d\d"
419 "\M-u": "\d\d\d\d"
420 $endif
420 $endif
421
421
422 Note that there are 4 spaces between the quote marks after "M-i" above.
422 Note that there are 4 spaces between the quote marks after "M-i" above.
423
423
424 .. warning::
424 .. warning::
425
425
426 Setting the above indents will cause problems with unicode text entry in
426 Setting the above indents will cause problems with unicode text entry in
427 the terminal.
427 the terminal.
428
428
429 .. warning::
429 .. warning::
430
430
431 Autoindent is ON by default, but it can cause problems with the pasting of
431 Autoindent is ON by default, but it can cause problems with the pasting of
432 multi-line indented code (the pasted code gets re-indented on each line). A
432 multi-line indented code (the pasted code gets re-indented on each line). A
433 magic function %autoindent allows you to toggle it on/off at runtime. You
433 magic function %autoindent allows you to toggle it on/off at runtime. You
434 can also disable it permanently on in your :file:`ipython_config.py` file
434 can also disable it permanently on in your :file:`ipython_config.py` file
435 (set TerminalInteractiveShell.autoindent=False).
435 (set TerminalInteractiveShell.autoindent=False).
436
436
437 If you want to paste multiple lines in the terminal, it is recommended that
437 If you want to paste multiple lines in the terminal, it is recommended that
438 you use ``%paste``.
438 you use ``%paste``.
439
439
440
440
441 Customizing readline behavior
441 Customizing readline behavior
442 +++++++++++++++++++++++++++++
442 +++++++++++++++++++++++++++++
443
443
444 All these features are based on the GNU readline library, which has an
444 All these features are based on the GNU readline library, which has an
445 extremely customizable interface. Normally, readline is configured via a
445 extremely customizable interface. Normally, readline is configured via a
446 file which defines the behavior of the library; the details of the
446 file which defines the behavior of the library; the details of the
447 syntax for this can be found in the readline documentation available
447 syntax for this can be found in the readline documentation available
448 with your system or on the Internet. IPython doesn't read this file (if
448 with your system or on the Internet. IPython doesn't read this file (if
449 it exists) directly, but it does support passing to readline valid
449 it exists) directly, but it does support passing to readline valid
450 options via a simple interface. In brief, you can customize readline by
450 options via a simple interface. In brief, you can customize readline by
451 setting the following options in your configuration file (note
451 setting the following options in your configuration file (note
452 that these options can not be specified at the command line):
452 that these options can not be specified at the command line):
453
453
454 * **readline_parse_and_bind**: this holds a list of strings to be executed
454 * **readline_parse_and_bind**: this holds a list of strings to be executed
455 via a readline.parse_and_bind() command. The syntax for valid commands
455 via a readline.parse_and_bind() command. The syntax for valid commands
456 of this kind can be found by reading the documentation for the GNU
456 of this kind can be found by reading the documentation for the GNU
457 readline library, as these commands are of the kind which readline
457 readline library, as these commands are of the kind which readline
458 accepts in its configuration file.
458 accepts in its configuration file.
459 * **readline_remove_delims**: a string of characters to be removed
459 * **readline_remove_delims**: a string of characters to be removed
460 from the default word-delimiters list used by readline, so that
460 from the default word-delimiters list used by readline, so that
461 completions may be performed on strings which contain them. Do not
461 completions may be performed on strings which contain them. Do not
462 change the default value unless you know what you're doing.
462 change the default value unless you know what you're doing.
463
463
464 You will find the default values in your configuration file.
464 You will find the default values in your configuration file.
465
465
466
466
467 Session logging and restoring
467 Session logging and restoring
468 -----------------------------
468 -----------------------------
469
469
470 You can log all input from a session either by starting IPython with the
470 You can log all input from a session either by starting IPython with the
471 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
471 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
472 or by activating the logging at any moment with the magic function %logstart.
472 or by activating the logging at any moment with the magic function %logstart.
473
473
474 Log files can later be reloaded by running them as scripts and IPython
474 Log files can later be reloaded by running them as scripts and IPython
475 will attempt to 'replay' the log by executing all the lines in it, thus
475 will attempt to 'replay' the log by executing all the lines in it, thus
476 restoring the state of a previous session. This feature is not quite
476 restoring the state of a previous session. This feature is not quite
477 perfect, but can still be useful in many cases.
477 perfect, but can still be useful in many cases.
478
478
479 The log files can also be used as a way to have a permanent record of
479 The log files can also be used as a way to have a permanent record of
480 any code you wrote while experimenting. Log files are regular text files
480 any code you wrote while experimenting. Log files are regular text files
481 which you can later open in your favorite text editor to extract code or
481 which you can later open in your favorite text editor to extract code or
482 to 'clean them up' before using them to replay a session.
482 to 'clean them up' before using them to replay a session.
483
483
484 The `%logstart` function for activating logging in mid-session is used as
484 The `%logstart` function for activating logging in mid-session is used as
485 follows::
485 follows::
486
486
487 %logstart [log_name [log_mode]]
487 %logstart [log_name [log_mode]]
488
488
489 If no name is given, it defaults to a file named 'ipython_log.py' in your
489 If no name is given, it defaults to a file named 'ipython_log.py' in your
490 current working directory, in 'rotate' mode (see below).
490 current working directory, in 'rotate' mode (see below).
491
491
492 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
492 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
493 history up to that point and then continues logging.
493 history up to that point and then continues logging.
494
494
495 %logstart takes a second optional parameter: logging mode. This can be
495 %logstart takes a second optional parameter: logging mode. This can be
496 one of (note that the modes are given unquoted):
496 one of (note that the modes are given unquoted):
497
497
498 * [over:] overwrite existing log_name.
498 * [over:] overwrite existing log_name.
499 * [backup:] rename (if exists) to log_name~ and start log_name.
499 * [backup:] rename (if exists) to log_name~ and start log_name.
500 * [append:] well, that says it.
500 * [append:] well, that says it.
501 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
501 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
502
502
503 The %logoff and %logon functions allow you to temporarily stop and
503 The %logoff and %logon functions allow you to temporarily stop and
504 resume logging to a file which had previously been started with
504 resume logging to a file which had previously been started with
505 %logstart. They will fail (with an explanation) if you try to use them
505 %logstart. They will fail (with an explanation) if you try to use them
506 before logging has been started.
506 before logging has been started.
507
507
508 .. _system_shell_access:
508 .. _system_shell_access:
509
509
510 System shell access
510 System shell access
511 -------------------
511 -------------------
512
512
513 Any input line beginning with a ! character is passed verbatim (minus
513 Any input line beginning with a ! character is passed verbatim (minus
514 the !, of course) to the underlying operating system. For example,
514 the !, of course) to the underlying operating system. For example,
515 typing ``!ls`` will run 'ls' in the current directory.
515 typing ``!ls`` will run 'ls' in the current directory.
516
516
517 Manual capture of command output
517 Manual capture of command output
518 --------------------------------
518 --------------------------------
519
519
520 You can assign the result of a system command to a Python variable with the
520 You can assign the result of a system command to a Python variable with the
521 syntax ``myfiles = !ls``. This gets machine readable output from stdout
521 syntax ``myfiles = !ls``. This gets machine readable output from stdout
522 (e.g. without colours), and splits on newlines. To explicitly get this sort of
522 (e.g. without colours), and splits on newlines. To explicitly get this sort of
523 output without assigning to a variable, use two exclamation marks (``!!ls``) or
523 output without assigning to a variable, use two exclamation marks (``!!ls``) or
524 the ``%sx`` magic command.
524 the ``%sx`` magic command.
525
525
526 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
526 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
527 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
527 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
528 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
528 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
529 See :ref:`string_lists` for details.
529 See :ref:`string_lists` for details.
530
530
531 IPython also allows you to expand the value of python variables when
531 IPython also allows you to expand the value of python variables when
532 making system calls. Wrap variables or expressions in {braces}::
532 making system calls. Wrap variables or expressions in {braces}::
533
533
534 In [1]: pyvar = 'Hello world'
534 In [1]: pyvar = 'Hello world'
535 In [2]: !echo "A python variable: {pyvar}"
535 In [2]: !echo "A python variable: {pyvar}"
536 A python variable: Hello world
536 A python variable: Hello world
537 In [3]: import math
537 In [3]: import math
538 In [4]: x = 8
538 In [4]: x = 8
539 In [5]: !echo {math.factorial(x)}
539 In [5]: !echo {math.factorial(x)}
540 40320
540 40320
541
541
542 For simple cases, you can alternatively prepend $ to a variable name::
542 For simple cases, you can alternatively prepend $ to a variable name::
543
543
544 In [6]: !echo $sys.argv
544 In [6]: !echo $sys.argv
545 [/home/fperez/usr/bin/ipython]
545 [/home/fperez/usr/bin/ipython]
546 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
546 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
547 A system variable: /home/fperez
547 A system variable: /home/fperez
548
548
549 System command aliases
549 System command aliases
550 ----------------------
550 ----------------------
551
551
552 The %alias magic function allows you to define magic functions which are in fact
552 The %alias magic function allows you to define magic functions which are in fact
553 system shell commands. These aliases can have parameters.
553 system shell commands. These aliases can have parameters.
554
554
555 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
555 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
556
556
557 Then, typing ``alias_name params`` will execute the system command 'cmd
557 Then, typing ``alias_name params`` will execute the system command 'cmd
558 params' (from your underlying operating system).
558 params' (from your underlying operating system).
559
559
560 You can also define aliases with parameters using %s specifiers (one per
560 You can also define aliases with parameters using %s specifiers (one per
561 parameter). The following example defines the parts function as an
561 parameter). The following example defines the parts function as an
562 alias to the command 'echo first %s second %s' where each %s will be
562 alias to the command 'echo first %s second %s' where each %s will be
563 replaced by a positional parameter to the call to %parts::
563 replaced by a positional parameter to the call to %parts::
564
564
565 In [1]: %alias parts echo first %s second %s
565 In [1]: %alias parts echo first %s second %s
566 In [2]: parts A B
566 In [2]: parts A B
567 first A second B
567 first A second B
568 In [3]: parts A
568 In [3]: parts A
569 ERROR: Alias <parts> requires 2 arguments, 1 given.
569 ERROR: Alias <parts> requires 2 arguments, 1 given.
570
570
571 If called with no parameters, %alias prints the table of currently
571 If called with no parameters, %alias prints the table of currently
572 defined aliases.
572 defined aliases.
573
573
574 The %rehashx magic allows you to load your entire $PATH as
574 The %rehashx magic allows you to load your entire $PATH as
575 ipython aliases. See its docstring for further details.
575 ipython aliases. See its docstring for further details.
576
576
577
577
578 .. _dreload:
578 .. _dreload:
579
579
580 Recursive reload
580 Recursive reload
581 ----------------
581 ----------------
582
582
583 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
583 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
584 module: changes made to any of its dependencies will be reloaded without
584 module: changes made to any of its dependencies will be reloaded without
585 having to exit. To start using it, do::
585 having to exit. To start using it, do::
586
586
587 from IPython.lib.deepreload import reload as dreload
587 from IPython.lib.deepreload import reload as dreload
588
588
589
589
590 Verbose and colored exception traceback printouts
590 Verbose and colored exception traceback printouts
591 -------------------------------------------------
591 -------------------------------------------------
592
592
593 IPython provides the option to see very detailed exception tracebacks,
593 IPython provides the option to see very detailed exception tracebacks,
594 which can be especially useful when debugging large programs. You can
594 which can be especially useful when debugging large programs. You can
595 run any Python file with the %run function to benefit from these
595 run any Python file with the %run function to benefit from these
596 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
596 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
597 be colored (if your terminal supports it) which makes them much easier
597 be colored (if your terminal supports it) which makes them much easier
598 to parse visually.
598 to parse visually.
599
599
600 See the magic xmode and colors functions for details (just type %magic).
600 See the magic xmode and colors functions for details (just type %magic).
601
601
602 These features are basically a terminal version of Ka-Ping Yee's cgitb
602 These features are basically a terminal version of Ka-Ping Yee's cgitb
603 module, now part of the standard Python library.
603 module, now part of the standard Python library.
604
604
605
605
606 .. _input_caching:
606 .. _input_caching:
607
607
608 Input caching system
608 Input caching system
609 --------------------
609 --------------------
610
610
611 IPython offers numbered prompts (In/Out) with input and output caching
611 IPython offers numbered prompts (In/Out) with input and output caching
612 (also referred to as 'input history'). All input is saved and can be
612 (also referred to as 'input history'). All input is saved and can be
613 retrieved as variables (besides the usual arrow key recall), in
613 retrieved as variables (besides the usual arrow key recall), in
614 addition to the %rep magic command that brings a history entry
614 addition to the %rep magic command that brings a history entry
615 up for editing on the next command line.
615 up for editing on the next command line.
616
616
617 The following GLOBAL variables always exist (so don't overwrite them!):
617 The following GLOBAL variables always exist (so don't overwrite them!):
618
618
619 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
619 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
620 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
620 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
621 overwrite In with a variable of your own, you can remake the assignment to the
621 overwrite In with a variable of your own, you can remake the assignment to the
622 internal list with a simple ``In=_ih``.
622 internal list with a simple ``In=_ih``.
623
623
624 Additionally, global variables named _i<n> are dynamically created (<n>
624 Additionally, global variables named _i<n> are dynamically created (<n>
625 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
625 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
626
626
627 For example, what you typed at prompt 14 is available as _i14, _ih[14]
627 For example, what you typed at prompt 14 is available as _i14, _ih[14]
628 and In[14].
628 and In[14].
629
629
630 This allows you to easily cut and paste multi line interactive prompts
630 This allows you to easily cut and paste multi line interactive prompts
631 by printing them out: they print like a clean string, without prompt
631 by printing them out: they print like a clean string, without prompt
632 characters. You can also manipulate them like regular variables (they
632 characters. You can also manipulate them like regular variables (they
633 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
633 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
634 contents of input prompt 9.
634 contents of input prompt 9.
635
635
636 You can also re-execute multiple lines of input easily by using the
636 You can also re-execute multiple lines of input easily by using the
637 magic %rerun or %macro functions. The macro system also allows you to re-execute
637 magic %rerun or %macro functions. The macro system also allows you to re-execute
638 previous lines which include magic function calls (which require special
638 previous lines which include magic function calls (which require special
639 processing). Type %macro? for more details on the macro system.
639 processing). Type %macro? for more details on the macro system.
640
640
641 A history function %hist allows you to see any part of your input
641 A history function %hist allows you to see any part of your input
642 history by printing a range of the _i variables.
642 history by printing a range of the _i variables.
643
643
644 You can also search ('grep') through your history by typing
644 You can also search ('grep') through your history by typing
645 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
645 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
646 etc. You can bring history entries listed by '%hist -g' up for editing
646 etc. You can bring history entries listed by '%hist -g' up for editing
647 with the %recall command, or run them immediately with %rerun.
647 with the %recall command, or run them immediately with %rerun.
648
648
649 .. _output_caching:
649 .. _output_caching:
650
650
651 Output caching system
651 Output caching system
652 ---------------------
652 ---------------------
653
653
654 For output that is returned from actions, a system similar to the input
654 For output that is returned from actions, a system similar to the input
655 cache exists but using _ instead of _i. Only actions that produce a
655 cache exists but using _ instead of _i. Only actions that produce a
656 result (NOT assignments, for example) are cached. If you are familiar
656 result (NOT assignments, for example) are cached. If you are familiar
657 with Mathematica, IPython's _ variables behave exactly like
657 with Mathematica, IPython's _ variables behave exactly like
658 Mathematica's % variables.
658 Mathematica's % variables.
659
659
660 The following GLOBAL variables always exist (so don't overwrite them!):
660 The following GLOBAL variables always exist (so don't overwrite them!):
661
661
662 * [_] (a single underscore) : stores previous output, like Python's
662 * [_] (a single underscore) : stores previous output, like Python's
663 default interpreter.
663 default interpreter.
664 * [__] (two underscores): next previous.
664 * [__] (two underscores): next previous.
665 * [___] (three underscores): next-next previous.
665 * [___] (three underscores): next-next previous.
666
666
667 Additionally, global variables named _<n> are dynamically created (<n>
667 Additionally, global variables named _<n> are dynamically created (<n>
668 being the prompt counter), such that the result of output <n> is always
668 being the prompt counter), such that the result of output <n> is always
669 available as _<n> (don't use the angle brackets, just the number, e.g.
669 available as _<n> (don't use the angle brackets, just the number, e.g.
670 _21).
670 _21).
671
671
672 These variables are also stored in a global dictionary (not a
672 These variables are also stored in a global dictionary (not a
673 list, since it only has entries for lines which returned a result)
673 list, since it only has entries for lines which returned a result)
674 available under the names _oh and Out (similar to _ih and In). So the
674 available under the names _oh and Out (similar to _ih and In). So the
675 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
675 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
676 accidentally overwrite the Out variable you can recover it by typing
676 accidentally overwrite the Out variable you can recover it by typing
677 'Out=_oh' at the prompt.
677 'Out=_oh' at the prompt.
678
678
679 This system obviously can potentially put heavy memory demands on your
679 This system obviously can potentially put heavy memory demands on your
680 system, since it prevents Python's garbage collector from removing any
680 system, since it prevents Python's garbage collector from removing any
681 previously computed results. You can control how many results are kept
681 previously computed results. You can control how many results are kept
682 in memory with the option (at the command line or in your configuration
682 in memory with the option (at the command line or in your configuration
683 file) cache_size. If you set it to 0, the whole system is completely
683 file) cache_size. If you set it to 0, the whole system is completely
684 disabled and the prompts revert to the classic '>>>' of normal Python.
684 disabled and the prompts revert to the classic '>>>' of normal Python.
685
685
686
686
687 Directory history
687 Directory history
688 -----------------
688 -----------------
689
689
690 Your history of visited directories is kept in the global list _dh, and
690 Your history of visited directories is kept in the global list _dh, and
691 the magic %cd command can be used to go to any entry in that list. The
691 the magic %cd command can be used to go to any entry in that list. The
692 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
692 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
693 conveniently view the directory history.
693 conveniently view the directory history.
694
694
695
695
696 Automatic parentheses and quotes
696 Automatic parentheses and quotes
697 --------------------------------
697 --------------------------------
698
698
699 These features were adapted from Nathan Gray's LazyPython. They are
699 These features were adapted from Nathan Gray's LazyPython. They are
700 meant to allow less typing for common situations.
700 meant to allow less typing for common situations.
701
701
702
702
703 Automatic parentheses
703 Automatic parentheses
704 +++++++++++++++++++++
704 +++++++++++++++++++++
705
705
706 Callable objects (i.e. functions, methods, etc) can be invoked like this
706 Callable objects (i.e. functions, methods, etc) can be invoked like this
707 (notice the commas between the arguments)::
707 (notice the commas between the arguments)::
708
708
709 In [1]: callable_ob arg1, arg2, arg3
709 In [1]: callable_ob arg1, arg2, arg3
710 ------> callable_ob(arg1, arg2, arg3)
710 ------> callable_ob(arg1, arg2, arg3)
711
711
712 You can force automatic parentheses by using '/' as the first character
712 You can force automatic parentheses by using '/' as the first character
713 of a line. For example::
713 of a line. For example::
714
714
715 In [2]: /globals # becomes 'globals()'
715 In [2]: /globals # becomes 'globals()'
716
716
717 Note that the '/' MUST be the first character on the line! This won't work::
717 Note that the '/' MUST be the first character on the line! This won't work::
718
718
719 In [3]: print /globals # syntax error
719 In [3]: print /globals # syntax error
720
720
721 In most cases the automatic algorithm should work, so you should rarely
721 In most cases the automatic algorithm should work, so you should rarely
722 need to explicitly invoke /. One notable exception is if you are trying
722 need to explicitly invoke /. One notable exception is if you are trying
723 to call a function with a list of tuples as arguments (the parenthesis
723 to call a function with a list of tuples as arguments (the parenthesis
724 will confuse IPython)::
724 will confuse IPython)::
725
725
726 In [4]: zip (1,2,3),(4,5,6) # won't work
726 In [4]: zip (1,2,3),(4,5,6) # won't work
727
727
728 but this will work::
728 but this will work::
729
729
730 In [5]: /zip (1,2,3),(4,5,6)
730 In [5]: /zip (1,2,3),(4,5,6)
731 ------> zip ((1,2,3),(4,5,6))
731 ------> zip ((1,2,3),(4,5,6))
732 Out[5]: [(1, 4), (2, 5), (3, 6)]
732 Out[5]: [(1, 4), (2, 5), (3, 6)]
733
733
734 IPython tells you that it has altered your command line by displaying
734 IPython tells you that it has altered your command line by displaying
735 the new command line preceded by ->. e.g.::
735 the new command line preceded by ->. e.g.::
736
736
737 In [6]: callable list
737 In [6]: callable list
738 ------> callable(list)
738 ------> callable(list)
739
739
740
740
741 Automatic quoting
741 Automatic quoting
742 +++++++++++++++++
742 +++++++++++++++++
743
743
744 You can force automatic quoting of a function's arguments by using ','
744 You can force automatic quoting of a function's arguments by using ','
745 or ';' as the first character of a line. For example::
745 or ';' as the first character of a line. For example::
746
746
747 In [1]: ,my_function /home/me # becomes my_function("/home/me")
747 In [1]: ,my_function /home/me # becomes my_function("/home/me")
748
748
749 If you use ';' the whole argument is quoted as a single string, while ',' splits
749 If you use ';' the whole argument is quoted as a single string, while ',' splits
750 on whitespace::
750 on whitespace::
751
751
752 In [2]: ,my_function a b c # becomes my_function("a","b","c")
752 In [2]: ,my_function a b c # becomes my_function("a","b","c")
753
753
754 In [3]: ;my_function a b c # becomes my_function("a b c")
754 In [3]: ;my_function a b c # becomes my_function("a b c")
755
755
756 Note that the ',' or ';' MUST be the first character on the line! This
756 Note that the ',' or ';' MUST be the first character on the line! This
757 won't work::
757 won't work::
758
758
759 In [4]: x = ,my_function /home/me # syntax error
759 In [4]: x = ,my_function /home/me # syntax error
760
760
761 IPython as your default Python environment
761 IPython as your default Python environment
762 ==========================================
762 ==========================================
763
763
764 Python honors the environment variable PYTHONSTARTUP and will execute at
764 Python honors the environment variable PYTHONSTARTUP and will execute at
765 startup the file referenced by this variable. If you put the following code at
765 startup the file referenced by this variable. If you put the following code at
766 the end of that file, then IPython will be your working environment anytime you
766 the end of that file, then IPython will be your working environment anytime you
767 start Python::
767 start Python::
768
768
769 from IPython.frontend.terminal.ipapp import launch_new_instance
769 from IPython.frontend.terminal.ipapp import launch_new_instance
770 launch_new_instance()
770 launch_new_instance()
771 raise SystemExit
771 raise SystemExit
772
772
773 The ``raise SystemExit`` is needed to exit Python when
773 The ``raise SystemExit`` is needed to exit Python when
774 it finishes, otherwise you'll be back at the normal Python '>>>'
774 it finishes, otherwise you'll be back at the normal Python '>>>'
775 prompt.
775 prompt.
776
776
777 This is probably useful to developers who manage multiple Python
777 This is probably useful to developers who manage multiple Python
778 versions and don't want to have correspondingly multiple IPython
778 versions and don't want to have correspondingly multiple IPython
779 versions. Note that in this mode, there is no way to pass IPython any
779 versions. Note that in this mode, there is no way to pass IPython any
780 command-line options, as those are trapped first by Python itself.
780 command-line options, as those are trapped first by Python itself.
781
781
782 .. _Embedding:
782 .. _Embedding:
783
783
784 Embedding IPython
784 Embedding IPython
785 =================
785 =================
786
786
787 You can start a regular IPython session with
787 You can start a regular IPython session with
788
788
789 .. sourcecode:: python
789 .. sourcecode:: python
790
790
791 import IPython
791 import IPython
792 IPython.start_ipython()
792 IPython.start_ipython()
793
793
794 at any point in your program. This will load IPython configuration,
794 at any point in your program. This will load IPython configuration,
795 startup files, and everything, just as if it were a normal IPython session.
795 startup files, and everything, just as if it were a normal IPython session.
796 In addition to this,
796 In addition to this,
797 it is possible to embed an IPython instance inside your own Python programs.
797 it is possible to embed an IPython instance inside your own Python programs.
798 This allows you to evaluate dynamically the state of your code,
798 This allows you to evaluate dynamically the state of your code,
799 operate with your variables, analyze them, etc. Note however that
799 operate with your variables, analyze them, etc. Note however that
800 any changes you make to values while in the shell do not propagate back
800 any changes you make to values while in the shell do not propagate back
801 to the running code, so it is safe to modify your values because you
801 to the running code, so it is safe to modify your values because you
802 won't break your code in bizarre ways by doing so.
802 won't break your code in bizarre ways by doing so.
803
803
804 .. note::
804 .. note::
805
805
806 At present, embedding IPython cannot be done from inside IPython.
806 At present, embedding IPython cannot be done from inside IPython.
807 Run the code samples below outside IPython.
807 Run the code samples below outside IPython.
808
808
809 This feature allows you to easily have a fully functional python
809 This feature allows you to easily have a fully functional python
810 environment for doing object introspection anywhere in your code with a
810 environment for doing object introspection anywhere in your code with a
811 simple function call. In some cases a simple print statement is enough,
811 simple function call. In some cases a simple print statement is enough,
812 but if you need to do more detailed analysis of a code fragment this
812 but if you need to do more detailed analysis of a code fragment this
813 feature can be very valuable.
813 feature can be very valuable.
814
814
815 It can also be useful in scientific computing situations where it is
815 It can also be useful in scientific computing situations where it is
816 common to need to do some automatic, computationally intensive part and
816 common to need to do some automatic, computationally intensive part and
817 then stop to look at data, plots, etc.
817 then stop to look at data, plots, etc.
818 Opening an IPython instance will give you full access to your data and
818 Opening an IPython instance will give you full access to your data and
819 functions, and you can resume program execution once you are done with
819 functions, and you can resume program execution once you are done with
820 the interactive part (perhaps to stop again later, as many times as
820 the interactive part (perhaps to stop again later, as many times as
821 needed).
821 needed).
822
822
823 The following code snippet is the bare minimum you need to include in
823 The following code snippet is the bare minimum you need to include in
824 your Python programs for this to work (detailed examples follow later)::
824 your Python programs for this to work (detailed examples follow later)::
825
825
826 from IPython import embed
826 from IPython import embed
827
827
828 embed() # this call anywhere in your program will start IPython
828 embed() # this call anywhere in your program will start IPython
829
829
830 .. note::
830 .. note::
831
831
832 As of 0.13, you can embed an IPython *kernel*, for use with qtconsole,
832 As of 0.13, you can embed an IPython *kernel*, for use with qtconsole,
833 etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``.
833 etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``.
834 It should function just the same as regular embed, but you connect
834 It should function just the same as regular embed, but you connect
835 an external frontend rather than IPython starting up in the local
835 an external frontend rather than IPython starting up in the local
836 terminal.
836 terminal.
837
837
838 You can run embedded instances even in code which is itself being run at
838 You can run embedded instances even in code which is itself being run at
839 the IPython interactive prompt with '%run <filename>'. Since it's easy
839 the IPython interactive prompt with '%run <filename>'. Since it's easy
840 to get lost as to where you are (in your top-level IPython or in your
840 to get lost as to where you are (in your top-level IPython or in your
841 embedded one), it's a good idea in such cases to set the in/out prompts
841 embedded one), it's a good idea in such cases to set the in/out prompts
842 to something different for the embedded instances. The code examples
842 to something different for the embedded instances. The code examples
843 below illustrate this.
843 below illustrate this.
844
844
845 You can also have multiple IPython instances in your program and open
845 You can also have multiple IPython instances in your program and open
846 them separately, for example with different options for data
846 them separately, for example with different options for data
847 presentation. If you close and open the same instance multiple times,
847 presentation. If you close and open the same instance multiple times,
848 its prompt counters simply continue from each execution to the next.
848 its prompt counters simply continue from each execution to the next.
849
849
850 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
850 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
851 module for more details on the use of this system.
851 module for more details on the use of this system.
852
852
853 The following sample file illustrating how to use the embedding
853 The following sample file illustrating how to use the embedding
854 functionality is provided in the examples directory as example-embed.py.
854 functionality is provided in the examples directory as example-embed.py.
855 It should be fairly self-explanatory:
855 It should be fairly self-explanatory:
856
856
857 .. literalinclude:: ../../../examples/core/example-embed.py
857 .. literalinclude:: ../../../examples/core/example-embed.py
858 :language: python
858 :language: python
859
859
860 Once you understand how the system functions, you can use the following
860 Once you understand how the system functions, you can use the following
861 code fragments in your programs which are ready for cut and paste:
861 code fragments in your programs which are ready for cut and paste:
862
862
863 .. literalinclude:: ../../../examples/core/example-embed-short.py
863 .. literalinclude:: ../../../examples/core/example-embed-short.py
864 :language: python
864 :language: python
865
865
866 Using the Python debugger (pdb)
866 Using the Python debugger (pdb)
867 ===============================
867 ===============================
868
868
869 Running entire programs via pdb
869 Running entire programs via pdb
870 -------------------------------
870 -------------------------------
871
871
872 pdb, the Python debugger, is a powerful interactive debugger which
872 pdb, the Python debugger, is a powerful interactive debugger which
873 allows you to step through code, set breakpoints, watch variables,
873 allows you to step through code, set breakpoints, watch variables,
874 etc. IPython makes it very easy to start any script under the control
874 etc. IPython makes it very easy to start any script under the control
875 of pdb, regardless of whether you have wrapped it into a 'main()'
875 of pdb, regardless of whether you have wrapped it into a 'main()'
876 function or not. For this, simply type '%run -d myscript' at an
876 function or not. For this, simply type '%run -d myscript' at an
877 IPython prompt. See the %run command's documentation (via '%run?' or
877 IPython prompt. See the %run command's documentation (via '%run?' or
878 in Sec. magic_ for more details, including how to control where pdb
878 in Sec. magic_ for more details, including how to control where pdb
879 will stop execution first.
879 will stop execution first.
880
880
881 For more information on the use of the pdb debugger, read the included
881 For more information on the use of the pdb debugger, read the included
882 pdb.doc file (part of the standard Python distribution). On a stock
882 pdb.doc file (part of the standard Python distribution). On a stock
883 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
883 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
884 easiest way to read it is by using the help() function of the pdb module
884 easiest way to read it is by using the help() function of the pdb module
885 as follows (in an IPython prompt)::
885 as follows (in an IPython prompt)::
886
886
887 In [1]: import pdb
887 In [1]: import pdb
888 In [2]: pdb.help()
888 In [2]: pdb.help()
889
889
890 This will load the pdb.doc document in a file viewer for you automatically.
890 This will load the pdb.doc document in a file viewer for you automatically.
891
891
892
892
893 Automatic invocation of pdb on exceptions
893 Automatic invocation of pdb on exceptions
894 -----------------------------------------
894 -----------------------------------------
895
895
896 IPython, if started with the ``--pdb`` option (or if the option is set in
896 IPython, if started with the ``--pdb`` option (or if the option is set in
897 your config file) can call the Python pdb debugger every time your code
897 your config file) can call the Python pdb debugger every time your code
898 triggers an uncaught exception. This feature
898 triggers an uncaught exception. This feature
899 can also be toggled at any time with the %pdb magic command. This can be
899 can also be toggled at any time with the %pdb magic command. This can be
900 extremely useful in order to find the origin of subtle bugs, because pdb
900 extremely useful in order to find the origin of subtle bugs, because pdb
901 opens up at the point in your code which triggered the exception, and
901 opens up at the point in your code which triggered the exception, and
902 while your program is at this point 'dead', all the data is still
902 while your program is at this point 'dead', all the data is still
903 available and you can walk up and down the stack frame and understand
903 available and you can walk up and down the stack frame and understand
904 the origin of the problem.
904 the origin of the problem.
905
905
906 Furthermore, you can use these debugging facilities both with the
906 Furthermore, you can use these debugging facilities both with the
907 embedded IPython mode and without IPython at all. For an embedded shell
907 embedded IPython mode and without IPython at all. For an embedded shell
908 (see sec. Embedding_), simply call the constructor with
908 (see sec. Embedding_), simply call the constructor with
909 ``--pdb`` in the argument string and pdb will automatically be called if an
909 ``--pdb`` in the argument string and pdb will automatically be called if an
910 uncaught exception is triggered by your code.
910 uncaught exception is triggered by your code.
911
911
912 For stand-alone use of the feature in your programs which do not use
912 For stand-alone use of the feature in your programs which do not use
913 IPython at all, put the following lines toward the top of your 'main'
913 IPython at all, put the following lines toward the top of your 'main'
914 routine::
914 routine::
915
915
916 import sys
916 import sys
917 from IPython.core import ultratb
917 from IPython.core import ultratb
918 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
918 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
919 color_scheme='Linux', call_pdb=1)
919 color_scheme='Linux', call_pdb=1)
920
920
921 The mode keyword can be either 'Verbose' or 'Plain', giving either very
921 The mode keyword can be either 'Verbose' or 'Plain', giving either very
922 detailed or normal tracebacks respectively. The color_scheme keyword can
922 detailed or normal tracebacks respectively. The color_scheme keyword can
923 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
923 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
924 options which can be set in IPython with ``--colors`` and ``--xmode``.
924 options which can be set in IPython with ``--colors`` and ``--xmode``.
925
925
926 This will give any of your programs detailed, colored tracebacks with
926 This will give any of your programs detailed, colored tracebacks with
927 automatic invocation of pdb.
927 automatic invocation of pdb.
928
928
929
929
930 Extensions for syntax processing
930 Extensions for syntax processing
931 ================================
931 ================================
932
932
933 This isn't for the faint of heart, because the potential for breaking
933 This isn't for the faint of heart, because the potential for breaking
934 things is quite high. But it can be a very powerful and useful feature.
934 things is quite high. But it can be a very powerful and useful feature.
935 In a nutshell, you can redefine the way IPython processes the user input
935 In a nutshell, you can redefine the way IPython processes the user input
936 line to accept new, special extensions to the syntax without needing to
936 line to accept new, special extensions to the syntax without needing to
937 change any of IPython's own code.
937 change any of IPython's own code.
938
938
939 In the IPython/extensions directory you will find some examples
939 In the IPython/extensions directory you will find some examples
940 supplied, which we will briefly describe now. These can be used 'as is'
940 supplied, which we will briefly describe now. These can be used 'as is'
941 (and both provide very useful functionality), or you can use them as a
941 (and both provide very useful functionality), or you can use them as a
942 starting point for writing your own extensions.
942 starting point for writing your own extensions.
943
943
944 .. _pasting_with_prompts:
944 .. _pasting_with_prompts:
945
945
946 Pasting of code starting with Python or IPython prompts
946 Pasting of code starting with Python or IPython prompts
947 -------------------------------------------------------
947 -------------------------------------------------------
948
948
949 IPython is smart enough to filter out input prompts, be they plain Python ones
949 IPython is smart enough to filter out input prompts, be they plain Python ones
950 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
950 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
951 therefore copy and paste from existing interactive sessions without worry.
951 therefore copy and paste from existing interactive sessions without worry.
952
952
953 The following is a 'screenshot' of how things work, copying an example from the
953 The following is a 'screenshot' of how things work, copying an example from the
954 standard Python tutorial::
954 standard Python tutorial::
955
955
956 In [1]: >>> # Fibonacci series:
956 In [1]: >>> # Fibonacci series:
957
957
958 In [2]: ... # the sum of two elements defines the next
958 In [2]: ... # the sum of two elements defines the next
959
959
960 In [3]: ... a, b = 0, 1
960 In [3]: ... a, b = 0, 1
961
961
962 In [4]: >>> while b < 10:
962 In [4]: >>> while b < 10:
963 ...: ... print b
963 ...: ... print b
964 ...: ... a, b = b, a+b
964 ...: ... a, b = b, a+b
965 ...:
965 ...:
966 1
966 1
967 1
967 1
968 2
968 2
969 3
969 3
970 5
970 5
971 8
971 8
972
972
973 And pasting from IPython sessions works equally well::
973 And pasting from IPython sessions works equally well::
974
974
975 In [1]: In [5]: def f(x):
975 In [1]: In [5]: def f(x):
976 ...: ...: "A simple function"
976 ...: ...: "A simple function"
977 ...: ...: return x**2
977 ...: ...: return x**2
978 ...: ...:
978 ...: ...:
979
979
980 In [2]: f(3)
980 In [2]: f(3)
981 Out[2]: 9
981 Out[2]: 9
982
982
983 .. _gui_support:
983 .. _gui_support:
984
984
985 GUI event loop support
985 GUI event loop support
986 ======================
986 ======================
987
987
988 .. versionadded:: 0.11
988 .. versionadded:: 0.11
989 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
989 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
990
990
991 IPython has excellent support for working interactively with Graphical User
991 IPython has excellent support for working interactively with Graphical User
992 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
992 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
993 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
993 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
994 is extremely robust compared to our previous thread-based version. The
994 is extremely robust compared to our previous thread-based version. The
995 advantages of this are:
995 advantages of this are:
996
996
997 * GUIs can be enabled and disabled dynamically at runtime.
997 * GUIs can be enabled and disabled dynamically at runtime.
998 * The active GUI can be switched dynamically at runtime.
998 * The active GUI can be switched dynamically at runtime.
999 * In some cases, multiple GUIs can run simultaneously with no problems.
999 * In some cases, multiple GUIs can run simultaneously with no problems.
1000 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1000 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1001 all of these things.
1001 all of these things.
1002
1002
1003 For users, enabling GUI event loop integration is simple. You simple use the
1003 For users, enabling GUI event loop integration is simple. You simple use the
1004 ``%gui`` magic as follows::
1004 ``%gui`` magic as follows::
1005
1005
1006 %gui [GUINAME]
1006 %gui [GUINAME]
1007
1007
1008 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1008 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1009 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
1009 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
1010
1010
1011 Thus, to use wxPython interactively and create a running :class:`wx.App`
1011 Thus, to use wxPython interactively and create a running :class:`wx.App`
1012 object, do::
1012 object, do::
1013
1013
1014 %gui wx
1014 %gui wx
1015
1015
1016 For information on IPython's matplotlib_ integration (and the ``matplotlib``
1016 For information on IPython's matplotlib_ integration (and the ``matplotlib``
1017 mode) see :ref:`this section <matplotlib_support>`.
1017 mode) see :ref:`this section <matplotlib_support>`.
1018
1018
1019 For developers that want to use IPython's GUI event loop integration in the
1019 For developers that want to use IPython's GUI event loop integration in the
1020 form of a library, these capabilities are exposed in library form in the
1020 form of a library, these capabilities are exposed in library form in the
1021 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
1021 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
1022 Interested developers should see the module docstrings for more information,
1022 Interested developers should see the module docstrings for more information,
1023 but there are a few points that should be mentioned here.
1023 but there are a few points that should be mentioned here.
1024
1024
1025 First, the ``PyOSInputHook`` approach only works in command line settings
1025 First, the ``PyOSInputHook`` approach only works in command line settings
1026 where readline is activated. The integration with various eventloops
1026 where readline is activated. The integration with various eventloops
1027 is handled somewhat differently (and more simply) when using the standalone
1027 is handled somewhat differently (and more simply) when using the standalone
1028 kernel, as in the qtconsole and notebook.
1028 kernel, as in the qtconsole and notebook.
1029
1029
1030 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1030 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1031 *not* start its event loop. Instead all of this is handled by the
1031 *not* start its event loop. Instead all of this is handled by the
1032 ``PyOSInputHook``. This means that applications that are meant to be used both
1032 ``PyOSInputHook``. This means that applications that are meant to be used both
1033 in IPython and as standalone apps need to have special code to detects how the
1033 in IPython and as standalone apps need to have special code to detects how the
1034 application is being run. We highly recommend using IPython's support for this.
1034 application is being run. We highly recommend using IPython's support for this.
1035 Since the details vary slightly between toolkits, we point you to the various
1035 Since the details vary slightly between toolkits, we point you to the various
1036 examples in our source directory :file:`examples/lib` that demonstrate
1036 examples in our source directory :file:`examples/lib` that demonstrate
1037 these capabilities.
1037 these capabilities.
1038
1038
1039 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1039 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1040 them with no-ops) the event loops. This is done to allow applications that
1040 them with no-ops) the event loops. This is done to allow applications that
1041 actually need to run the real event loops to do so. This is often needed to
1041 actually need to run the real event loops to do so. This is often needed to
1042 process pending events at critical points.
1042 process pending events at critical points.
1043
1043
1044 Finally, we also have a number of examples in our source directory
1044 Finally, we also have a number of examples in our source directory
1045 :file:`examples/lib` that demonstrate these capabilities.
1045 :file:`examples/lib` that demonstrate these capabilities.
1046
1046
1047 PyQt and PySide
1047 PyQt and PySide
1048 ---------------
1048 ---------------
1049
1049
1050 .. attempt at explanation of the complete mess that is Qt support
1050 .. attempt at explanation of the complete mess that is Qt support
1051
1051
1052 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
1052 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
1053 PyQt4 or PySide. There are three options for configuration here, because
1053 PyQt4 or PySide. There are three options for configuration here, because
1054 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
1054 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
1055 Python 2, and the more natural v2, which is the only API supported by PySide.
1055 Python 2, and the more natural v2, which is the only API supported by PySide.
1056 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
1056 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
1057 uses v2, but you can still use any interface in your code, since the
1057 uses v2, but you can still use any interface in your code, since the
1058 Qt frontend is in a different process.
1058 Qt frontend is in a different process.
1059
1059
1060 The default will be to import PyQt4 without configuration of the APIs, thus
1060 The default will be to import PyQt4 without configuration of the APIs, thus
1061 matching what most applications would expect. It will fall back of PySide if
1061 matching what most applications would expect. It will fall back of PySide if
1062 PyQt4 is unavailable.
1062 PyQt4 is unavailable.
1063
1063
1064 If specified, IPython will respect the environment variable ``QT_API`` used
1064 If specified, IPython will respect the environment variable ``QT_API`` used
1065 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
1065 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
1066 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
1066 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
1067 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
1067 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
1068 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
1068 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
1069
1069
1070 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
1070 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
1071 then IPython will ask matplotlib which Qt library to use (only if QT_API is
1071 then IPython will ask matplotlib which Qt library to use (only if QT_API is
1072 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
1072 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
1073 older, then IPython will always use PyQt4 without setting the v2 APIs, since
1073 older, then IPython will always use PyQt4 without setting the v2 APIs, since
1074 neither v2 PyQt nor PySide work.
1074 neither v2 PyQt nor PySide work.
1075
1075
1076 .. warning::
1076 .. warning::
1077
1077
1078 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
1078 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
1079 to work with IPython's qt integration, because otherwise PyQt4 will be
1079 to work with IPython's qt integration, because otherwise PyQt4 will be
1080 loaded in an incompatible mode.
1080 loaded in an incompatible mode.
1081
1081
1082 It also means that you must *not* have ``QT_API`` set if you want to
1082 It also means that you must *not* have ``QT_API`` set if you want to
1083 use ``--gui=qt`` with code that requires PyQt4 API v1.
1083 use ``--gui=qt`` with code that requires PyQt4 API v1.
1084
1084
1085
1085
1086 .. _matplotlib_support:
1086 .. _matplotlib_support:
1087
1087
1088 Plotting with matplotlib
1088 Plotting with matplotlib
1089 ========================
1089 ========================
1090
1090
1091 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
1091 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
1092 can produce plots on screen using a variety of GUI toolkits, including Tk,
1092 can produce plots on screen using a variety of GUI toolkits, including Tk,
1093 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
1093 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
1094 scientific computing, all with a syntax compatible with that of the popular
1094 scientific computing, all with a syntax compatible with that of the popular
1095 Matlab program.
1095 Matlab program.
1096
1096
1097 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
1097 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
1098 IPython is already running, you can run the ``%matplotlib`` magic. If no
1098 IPython is already running, you can run the ``%matplotlib`` magic. If no
1099 arguments are given, IPython will automatically detect your choice of
1099 arguments are given, IPython will automatically detect your choice of
1100 matplotlib backend. You can also request a specific backend with
1100 matplotlib backend. You can also request a specific backend with
1101 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
1101 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
1102 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
1102 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
1103 backend value, which produces static figures inlined inside the application
1103 backend value, which produces static figures inlined inside the application
1104 window instead of matplotlib's interactive figures that live in separate
1104 window instead of matplotlib's interactive figures that live in separate
1105 windows.
1105 windows.
1106
1106
1107 .. _interactive_demos:
1107 .. _interactive_demos:
1108
1108
1109 Interactive demos with IPython
1109 Interactive demos with IPython
1110 ==============================
1110 ==============================
1111
1111
1112 IPython ships with a basic system for running scripts interactively in
1112 IPython ships with a basic system for running scripts interactively in
1113 sections, useful when presenting code to audiences. A few tags embedded
1113 sections, useful when presenting code to audiences. A few tags embedded
1114 in comments (so that the script remains valid Python code) divide a file
1114 in comments (so that the script remains valid Python code) divide a file
1115 into separate blocks, and the demo can be run one block at a time, with
1115 into separate blocks, and the demo can be run one block at a time, with
1116 IPython printing (with syntax highlighting) the block before executing
1116 IPython printing (with syntax highlighting) the block before executing
1117 it, and returning to the interactive prompt after each block. The
1117 it, and returning to the interactive prompt after each block. The
1118 interactive namespace is updated after each block is run with the
1118 interactive namespace is updated after each block is run with the
1119 contents of the demo's namespace.
1119 contents of the demo's namespace.
1120
1120
1121 This allows you to show a piece of code, run it and then execute
1121 This allows you to show a piece of code, run it and then execute
1122 interactively commands based on the variables just created. Once you
1122 interactively commands based on the variables just created. Once you
1123 want to continue, you simply execute the next block of the demo. The
1123 want to continue, you simply execute the next block of the demo. The
1124 following listing shows the markup necessary for dividing a script into
1124 following listing shows the markup necessary for dividing a script into
1125 sections for execution as a demo:
1125 sections for execution as a demo:
1126
1126
1127 .. literalinclude:: ../../../examples/lib/example-demo.py
1127 .. literalinclude:: ../../../examples/lib/example-demo.py
1128 :language: python
1128 :language: python
1129
1129
1130 In order to run a file as a demo, you must first make a Demo object out
1130 In order to run a file as a demo, you must first make a Demo object out
1131 of it. If the file is named myscript.py, the following code will make a
1131 of it. If the file is named myscript.py, the following code will make a
1132 demo::
1132 demo::
1133
1133
1134 from IPython.lib.demo import Demo
1134 from IPython.lib.demo import Demo
1135
1135
1136 mydemo = Demo('myscript.py')
1136 mydemo = Demo('myscript.py')
1137
1137
1138 This creates the mydemo object, whose blocks you run one at a time by
1138 This creates the mydemo object, whose blocks you run one at a time by
1139 simply calling the object with no arguments. If you have autocall active
1139 simply calling the object with no arguments. If you have autocall active
1140 in IPython (the default), all you need to do is type::
1140 in IPython (the default), all you need to do is type::
1141
1141
1142 mydemo
1142 mydemo
1143
1143
1144 and IPython will call it, executing each block. Demo objects can be
1144 and IPython will call it, executing each block. Demo objects can be
1145 restarted, you can move forward or back skipping blocks, re-execute the
1145 restarted, you can move forward or back skipping blocks, re-execute the
1146 last block, etc. Simply use the Tab key on a demo object to see its
1146 last block, etc. Simply use the Tab key on a demo object to see its
1147 methods, and call '?' on them to see their docstrings for more usage
1147 methods, and call '?' on them to see their docstrings for more usage
1148 details. In addition, the demo module itself contains a comprehensive
1148 details. In addition, the demo module itself contains a comprehensive
1149 docstring, which you can access via::
1149 docstring, which you can access via::
1150
1150
1151 from IPython.lib import demo
1151 from IPython.lib import demo
1152
1152
1153 demo?
1153 demo?
1154
1154
1155 Limitations: It is important to note that these demos are limited to
1155 Limitations: It is important to note that these demos are limited to
1156 fairly simple uses. In particular, you cannot break up sections within
1156 fairly simple uses. In particular, you cannot break up sections within
1157 indented code (loops, if statements, function definitions, etc.)
1157 indented code (loops, if statements, function definitions, etc.)
1158 Supporting something like this would basically require tracking the
1158 Supporting something like this would basically require tracking the
1159 internal execution state of the Python interpreter, so only top-level
1159 internal execution state of the Python interpreter, so only top-level
1160 divisions are allowed. If you want to be able to open an IPython
1160 divisions are allowed. If you want to be able to open an IPython
1161 instance at an arbitrary point in a program, you can use IPython's
1161 instance at an arbitrary point in a program, you can use IPython's
1162 embedding facilities, see :func:`IPython.embed` for details.
1162 embedding facilities, see :func:`IPython.embed` for details.
1163
1163
1164 .. include:: ../links.txt
1164 .. include:: ../links.txt
@@ -1,202 +1,201 b''
1 .. _tutorial:
1 .. _tutorial:
2
2
3 ======================
3 ======================
4 Introducing IPython
4 Introducing IPython
5 ======================
5 ======================
6
6
7 You don't need to know anything beyond Python to start using IPython – just type
7 You don't need to know anything beyond Python to start using IPython – just type
8 commands as you would at the standard Python prompt. But IPython can do much
8 commands as you would at the standard Python prompt. But IPython can do much
9 more than the standard prompt. Some key features are described here. For more
9 more than the standard prompt. Some key features are described here. For more
10 information, check the :ref:`tips page <tips>`, or look at examples in the
10 information, check the :ref:`tips page <tips>`, or look at examples in the
11 `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_.
11 `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_.
12
12
13 If you've never used Python before, you might want to look at `the official
13 If you've never used Python before, you might want to look at `the official
14 tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into
14 tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into
15 Python <http://diveintopython.net/toc/index.html>`_.
15 Python <http://diveintopython.net/toc/index.html>`_.
16
16
17 The four most helpful commands
17 The four most helpful commands
18 ===============================
18 ===============================
19
19
20 The four most helpful commands, as well as their brief description, is shown
20 The four most helpful commands, as well as their brief description, is shown
21 to you in a banner, every time you start IPython:
21 to you in a banner, every time you start IPython:
22
22
23 ========== =========================================================
23 ========== =========================================================
24 command description
24 command description
25 ========== =========================================================
25 ========== =========================================================
26 ? Introduction and overview of IPython's features.
26 ? Introduction and overview of IPython's features.
27 %quickref Quick reference.
27 %quickref Quick reference.
28 help Python's own help system.
28 help Python's own help system.
29 object? Details about 'object', use 'object??' for extra details.
29 object? Details about 'object', use 'object??' for extra details.
30 ========== =========================================================
30 ========== =========================================================
31
31
32 Tab completion
32 Tab completion
33 ==============
33 ==============
34
34
35 Tab completion, especially for attributes, is a convenient way to explore the
35 Tab completion, especially for attributes, is a convenient way to explore the
36 structure of any object you're dealing with. Simply type ``object_name.<TAB>``
36 structure of any object you're dealing with. Simply type ``object_name.<TAB>``
37 to view the object's attributes (see :ref:`the readline section <readline>` for
37 to view the object's attributes (see :ref:`the readline section <readline>` for
38 more). Besides Python objects and keywords, tab completion also works on file
38 more). Besides Python objects and keywords, tab completion also works on file
39 and directory names.
39 and directory names.
40
40
41 Exploring your objects
41 Exploring your objects
42 ======================
42 ======================
43
43
44 Typing ``object_name?`` will print all sorts of details about any object,
44 Typing ``object_name?`` will print all sorts of details about any object,
45 including docstrings, function definition lines (for call arguments) and
45 including docstrings, function definition lines (for call arguments) and
46 constructor details for classes. To get specific information on an object, you
46 constructor details for classes. To get specific information on an object, you
47 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
47 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
48
48
49 .. _magics_explained:
49 .. _magics_explained:
50
50
51 Magic functions
51 Magic functions
52 ===============
52 ===============
53
53
54 IPython has a set of predefined 'magic functions' that you can call with a
54 IPython has a set of predefined 'magic functions' that you can call with a
55 command line style syntax. There are two kinds of magics, line-oriented and
55 command line style syntax. There are two kinds of magics, line-oriented and
56 cell-oriented. **Line magics** are prefixed with the ``%`` character and work much
56 cell-oriented. **Line magics** are prefixed with the ``%`` character and work much
57 like OS command-line calls: they get as an argument the rest of the line, where
57 like OS command-line calls: they get as an argument the rest of the line, where
58 arguments are passed without parentheses or quotes. **Cell magics** are
58 arguments are passed without parentheses or quotes. **Cell magics** are
59 prefixed with a double ``%%``, and they are functions that get as an argument
59 prefixed with a double ``%%``, and they are functions that get as an argument
60 not only the rest of the line, but also the lines below it in a separate
60 not only the rest of the line, but also the lines below it in a separate
61 argument.
61 argument.
62
62
63 The following examples show how to call the builtin ``timeit`` magic, both in
63 The following examples show how to call the builtin ``timeit`` magic, both in
64 line and cell mode::
64 line and cell mode::
65
65
66 In [1]: %timeit range(1000)
66 In [1]: %timeit range(1000)
67 100000 loops, best of 3: 7.76 us per loop
67 100000 loops, best of 3: 7.76 us per loop
68
68
69 In [2]: %%timeit x = range(10000)
69 In [2]: %%timeit x = range(10000)
70 ...: max(x)
70 ...: max(x)
71 ...:
71 ...:
72 1000 loops, best of 3: 223 us per loop
72 1000 loops, best of 3: 223 us per loop
73
73
74 The builtin magics include:
74 The builtin magics include:
75
75
76 - Functions that work with code: ``%run``, ``%edit``, ``%save``, ``%macro``,
76 - Functions that work with code: ``%run``, ``%edit``, ``%save``, ``%macro``,
77 ``%recall``, etc.
77 ``%recall``, etc.
78 - Functions which affect the shell: ``%colors``, ``%xmode``, ``%autoindent``,
78 - Functions which affect the shell: ``%colors``, ``%xmode``, ``%autoindent``,
79 ``%automagic``, etc.
79 ``%automagic``, etc.
80 - Other functions such as ``%reset``, ``%timeit``, ``%%file``, ``%load``, or
80 - Other functions such as ``%reset``, ``%timeit``, ``%%file``, ``%load``, or
81 ``%paste``.
81 ``%paste``.
82
82
83 You can always call them using the ``%`` prefix, and if you're calling a line
83 You can always call them using the ``%`` prefix, and if you're calling a line
84 magic on a line by itself, you can omit even that::
84 magic on a line by itself, you can omit even that::
85
85
86 run thescript.py
86 run thescript.py
87
87
88 You can toggle this behavior by running the ``%automagic`` magic. Cell magics
88 You can toggle this behavior by running the ``%automagic`` magic. Cell magics
89 must always have the ``%%`` prefix.
89 must always have the ``%%`` prefix.
90
90
91 A more detailed explanation of the magic system can be obtained by calling
91 A more detailed explanation of the magic system can be obtained by calling
92 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
92 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
93 read its docstring. To see all the available magic functions, call
93 read its docstring. To see all the available magic functions, call
94 ``%lsmagic``.
94 ``%lsmagic``.
95
95
96 .. seealso::
96 .. seealso::
97
97
98 `Cell magics`_ example notebook
98 `Cell magics`_ example notebook
99
99
100 Running and Editing
100 Running and Editing
101 -------------------
101 -------------------
102
102
103 The ``%run`` magic command allows you to run any python script and load all of
103 The ``%run`` magic command allows you to run any python script and load all of
104 its data directly into the interactive namespace. Since the file is re-read
104 its data directly into the interactive namespace. Since the file is re-read
105 from disk each time, changes you make to it are reflected immediately (unlike
105 from disk each time, changes you make to it are reflected immediately (unlike
106 imported modules, which have to be specifically reloaded). IPython also
106 imported modules, which have to be specifically reloaded). IPython also
107 includes :ref:`dreload <dreload>`, a recursive reload function.
107 includes :ref:`dreload <dreload>`, a recursive reload function.
108
108
109 ``%run`` has special flags for timing the execution of your scripts (-t), or
109 ``%run`` has special flags for timing the execution of your scripts (-t), or
110 for running them under the control of either Python's pdb debugger (-d) or
110 for running them under the control of either Python's pdb debugger (-d) or
111 profiler (-p).
111 profiler (-p).
112
112
113 The ``%edit`` command gives a reasonable approximation of multiline editing,
113 The ``%edit`` command gives a reasonable approximation of multiline editing,
114 by invoking your favorite editor on the spot. IPython will execute the
114 by invoking your favorite editor on the spot. IPython will execute the
115 code you type in there as if it were typed interactively.
115 code you type in there as if it were typed interactively.
116
116
117 Debugging
117 Debugging
118 ---------
118 ---------
119
119
120 After an exception occurs, you can call ``%debug`` to jump into the Python
120 After an exception occurs, you can call ``%debug`` to jump into the Python
121 debugger (pdb) and examine the problem. Alternatively, if you call ``%pdb``,
121 debugger (pdb) and examine the problem. Alternatively, if you call ``%pdb``,
122 IPython will automatically start the debugger on any uncaught exception. You can
122 IPython will automatically start the debugger on any uncaught exception. You can
123 print variables, see code, execute statements and even walk up and down the
123 print variables, see code, execute statements and even walk up and down the
124 call stack to track down the true source of the problem. This can be an efficient
124 call stack to track down the true source of the problem. This can be an efficient
125 way to develop and debug code, in many cases eliminating the need for print
125 way to develop and debug code, in many cases eliminating the need for print
126 statements or external debugging tools.
126 statements or external debugging tools.
127
127
128 You can also step through a program from the beginning by calling
128 You can also step through a program from the beginning by calling
129 ``%run -d theprogram.py``.
129 ``%run -d theprogram.py``.
130
130
131 History
131 History
132 =======
132 =======
133
133
134 IPython stores both the commands you enter, and the results it produces. You
134 IPython stores both the commands you enter, and the results it produces. You
135 can easily go through previous commands with the up- and down-arrow keys, or
135 can easily go through previous commands with the up- and down-arrow keys, or
136 access your history in more sophisticated ways.
136 access your history in more sophisticated ways.
137
137
138 Input and output history are kept in variables called ``In`` and ``Out``, keyed
138 Input and output history are kept in variables called ``In`` and ``Out``, keyed
139 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
139 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
140 are also kept in variables named ``_``, ``__`` and ``___``.
140 are also kept in variables named ``_``, ``__`` and ``___``.
141
141
142 You can use the ``%history`` magic function to examine past input and output.
142 You can use the ``%history`` magic function to examine past input and output.
143 Input history from previous sessions is saved in a database, and IPython can be
143 Input history from previous sessions is saved in a database, and IPython can be
144 configured to save output history.
144 configured to save output history.
145
145
146 Several other magic functions can use your input history, including ``%edit``,
146 Several other magic functions can use your input history, including ``%edit``,
147 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
147 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
148 standard format to refer to lines::
148 standard format to refer to lines::
149
149
150 %pastebin 3 18-20 ~1/1-5
150 %pastebin 3 18-20 ~1/1-5
151
151
152 This will take line 3 and lines 18 to 20 from the current session, and lines
152 This will take line 3 and lines 18 to 20 from the current session, and lines
153 1-5 from the previous session.
153 1-5 from the previous session.
154
154
155 System shell commands
155 System shell commands
156 =====================
156 =====================
157
157
158 To run any command at the system shell, simply prefix it with !, e.g.::
158 To run any command at the system shell, simply prefix it with !, e.g.::
159
159
160 !ping www.bbc.co.uk
160 !ping www.bbc.co.uk
161
161
162 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
162 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
163 the values of Python variables or expressions to system commands, prefix them
163 the values of Python variables or expressions to system commands, prefix them
164 with $: ``!grep -rF $pattern ipython/*``. See :ref:`our shell section
164 with $: ``!grep -rF $pattern ipython/*``. See :ref:`our shell section
165 <system_shell_access>` for more details.
165 <system_shell_access>` for more details.
166
166
167 Define your own system aliases
167 Define your own system aliases
168 ------------------------------
168 ------------------------------
169
169
170 It's convenient to have aliases to the system commands you use most often.
170 It's convenient to have aliases to the system commands you use most often.
171 This allows you to work seamlessly from inside IPython with the same commands
171 This allows you to work seamlessly from inside IPython with the same commands
172 you are used to in your system shell. IPython comes with some pre-defined
172 you are used to in your system shell. IPython comes with some pre-defined
173 aliases and a complete system for changing directories, both via a stack (see
173 aliases and a complete system for changing directories, both via a stack (see
174 %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of
174 %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of
175 visited directories and allows you to go to any previously visited one.
175 visited directories and allows you to go to any previously visited one.
176
176
177
177
178 Configuration
178 Configuration
179 =============
179 =============
180
180
181 Much of IPython can be tweaked through :ref:`configuration <config_overview>`.
181 Much of IPython can be tweaked through :ref:`configuration <config_overview>`.
182 To get started, use the command ``ipython profile create`` to produce the
182 To get started, use the command ``ipython profile create`` to produce the
183 default config files. These will be placed in
183 default config files. These will be placed in
184 :file:`~/.ipython/profile_default` or
184 :file:`~/.ipython/profile_default`, and contain comments explaining
185 :file:`~/.config/ipython/profile_default`, and contain comments explaining
186 what the various options do.
185 what the various options do.
187
186
188 Profiles allow you to use IPython for different tasks, keeping separate config
187 Profiles allow you to use IPython for different tasks, keeping separate config
189 files and history for each one. More details in :ref:`the profiles section
188 files and history for each one. More details in :ref:`the profiles section
190 <profiles>`.
189 <profiles>`.
191
190
192 Startup Files
191 Startup Files
193 -------------
192 -------------
194
193
195 If you want some code to be run at the beginning of every IPython session, the
194 If you want some code to be run at the beginning of every IPython session, the
196 easiest way is to add Python (.py) or IPython (.ipy) scripts to your
195 easiest way is to add Python (.py) or IPython (.ipy) scripts to your
197 :file:`profile_default/startup/` directory. Files here will be executed as soon
196 :file:`profile_default/startup/` directory. Files here will be executed as soon
198 as the IPython shell is constructed, before any other code or scripts you have
197 as the IPython shell is constructed, before any other code or scripts you have
199 specified. The files will be run in order of their names, so you can control the
198 specified. The files will be run in order of their names, so you can control the
200 ordering with prefixes, like ``10-myimports.py``.
199 ordering with prefixes, like ``10-myimports.py``.
201
200
202 .. include:: ../links.txt
201 .. include:: ../links.txt
@@ -1,884 +1,884 b''
1 .. _parallel_process:
1 .. _parallel_process:
2
2
3 ===========================================
3 ===========================================
4 Starting the IPython controller and engines
4 Starting the IPython controller and engines
5 ===========================================
5 ===========================================
6
6
7 To use IPython for parallel computing, you need to start one instance of
7 To use IPython for parallel computing, you need to start one instance of
8 the controller and one or more instances of the engine. The controller
8 the controller and one or more instances of the engine. The controller
9 and each engine can run on different machines or on the same machine.
9 and each engine can run on different machines or on the same machine.
10 Because of this, there are many different possibilities.
10 Because of this, there are many different possibilities.
11
11
12 Broadly speaking, there are two ways of going about starting a controller and engines:
12 Broadly speaking, there are two ways of going about starting a controller and engines:
13
13
14 * In an automated manner using the :command:`ipcluster` command.
14 * In an automated manner using the :command:`ipcluster` command.
15 * In a more manual way using the :command:`ipcontroller` and
15 * In a more manual way using the :command:`ipcontroller` and
16 :command:`ipengine` commands.
16 :command:`ipengine` commands.
17
17
18 This document describes both of these methods. We recommend that new users
18 This document describes both of these methods. We recommend that new users
19 start with the :command:`ipcluster` command as it simplifies many common usage
19 start with the :command:`ipcluster` command as it simplifies many common usage
20 cases.
20 cases.
21
21
22 General considerations
22 General considerations
23 ======================
23 ======================
24
24
25 Before delving into the details about how you can start a controller and
25 Before delving into the details about how you can start a controller and
26 engines using the various methods, we outline some of the general issues that
26 engines using the various methods, we outline some of the general issues that
27 come up when starting the controller and engines. These things come up no
27 come up when starting the controller and engines. These things come up no
28 matter which method you use to start your IPython cluster.
28 matter which method you use to start your IPython cluster.
29
29
30 If you are running engines on multiple machines, you will likely need to instruct the
30 If you are running engines on multiple machines, you will likely need to instruct the
31 controller to listen for connections on an external interface. This can be done by specifying
31 controller to listen for connections on an external interface. This can be done by specifying
32 the ``ip`` argument on the command-line, or the ``HubFactory.ip`` configurable in
32 the ``ip`` argument on the command-line, or the ``HubFactory.ip`` configurable in
33 :file:`ipcontroller_config.py`.
33 :file:`ipcontroller_config.py`.
34
34
35 If your machines are on a trusted network, you can safely instruct the controller to listen
35 If your machines are on a trusted network, you can safely instruct the controller to listen
36 on all interfaces with::
36 on all interfaces with::
37
37
38 $> ipcontroller --ip=*
38 $> ipcontroller --ip=*
39
39
40
40
41 Or you can set the same behavior as the default by adding the following line to your :file:`ipcontroller_config.py`:
41 Or you can set the same behavior as the default by adding the following line to your :file:`ipcontroller_config.py`:
42
42
43 .. sourcecode:: python
43 .. sourcecode:: python
44
44
45 c.HubFactory.ip = '*'
45 c.HubFactory.ip = '*'
46 # c.HubFactory.location = '10.0.1.1'
46 # c.HubFactory.location = '10.0.1.1'
47
47
48
48
49 .. note::
49 .. note::
50
50
51 ``--ip=*`` instructs ZeroMQ to listen on all interfaces,
51 ``--ip=*`` instructs ZeroMQ to listen on all interfaces,
52 but it does not contain the IP needed for engines / clients
52 but it does not contain the IP needed for engines / clients
53 to know where the controller actually is.
53 to know where the controller actually is.
54 This can be specified with ``--location=10.0.0.1``,
54 This can be specified with ``--location=10.0.0.1``,
55 the specific IP address of the controller, as seen from engines and/or clients.
55 the specific IP address of the controller, as seen from engines and/or clients.
56 IPython tries to guess this value by default, but it will not always guess correctly.
56 IPython tries to guess this value by default, but it will not always guess correctly.
57 Check the ``location`` field in your connection files if you are having connection trouble.
57 Check the ``location`` field in your connection files if you are having connection trouble.
58
58
59 .. note::
59 .. note::
60
60
61 Due to the lack of security in ZeroMQ, the controller will only listen for connections on
61 Due to the lack of security in ZeroMQ, the controller will only listen for connections on
62 localhost by default. If you see Timeout errors on engines or clients, then the first
62 localhost by default. If you see Timeout errors on engines or clients, then the first
63 thing you should check is the ip address the controller is listening on, and make sure
63 thing you should check is the ip address the controller is listening on, and make sure
64 that it is visible from the timing out machine.
64 that it is visible from the timing out machine.
65
65
66 .. seealso::
66 .. seealso::
67
67
68 Our `notes <parallel_security>`_ on security in the new parallel computing code.
68 Our `notes <parallel_security>`_ on security in the new parallel computing code.
69
69
70 Let's say that you want to start the controller on ``host0`` and engines on
70 Let's say that you want to start the controller on ``host0`` and engines on
71 hosts ``host1``-``hostn``. The following steps are then required:
71 hosts ``host1``-``hostn``. The following steps are then required:
72
72
73 1. Start the controller on ``host0`` by running :command:`ipcontroller` on
73 1. Start the controller on ``host0`` by running :command:`ipcontroller` on
74 ``host0``. The controller must be instructed to listen on an interface visible
74 ``host0``. The controller must be instructed to listen on an interface visible
75 to the engine machines, via the ``ip`` command-line argument or ``HubFactory.ip``
75 to the engine machines, via the ``ip`` command-line argument or ``HubFactory.ip``
76 in :file:`ipcontroller_config.py`.
76 in :file:`ipcontroller_config.py`.
77 2. Move the JSON file (:file:`ipcontroller-engine.json`) created by the
77 2. Move the JSON file (:file:`ipcontroller-engine.json`) created by the
78 controller from ``host0`` to hosts ``host1``-``hostn``.
78 controller from ``host0`` to hosts ``host1``-``hostn``.
79 3. Start the engines on hosts ``host1``-``hostn`` by running
79 3. Start the engines on hosts ``host1``-``hostn`` by running
80 :command:`ipengine`. This command has to be told where the JSON file
80 :command:`ipengine`. This command has to be told where the JSON file
81 (:file:`ipcontroller-engine.json`) is located.
81 (:file:`ipcontroller-engine.json`) is located.
82
82
83 At this point, the controller and engines will be connected. By default, the JSON files
83 At this point, the controller and engines will be connected. By default, the JSON files
84 created by the controller are put into the :file:`IPYTHONDIR/profile_default/security`
84 created by the controller are put into the :file:`IPYTHONDIR/profile_default/security`
85 directory. If the engines share a filesystem with the controller, step 2 can be skipped as
85 directory. If the engines share a filesystem with the controller, step 2 can be skipped as
86 the engines will automatically look at that location.
86 the engines will automatically look at that location.
87
87
88 The final step required to actually use the running controller from a client is to move
88 The final step required to actually use the running controller from a client is to move
89 the JSON file :file:`ipcontroller-client.json` from ``host0`` to any host where clients
89 the JSON file :file:`ipcontroller-client.json` from ``host0`` to any host where clients
90 will be run. If these file are put into the :file:`IPYTHONDIR/profile_default/security`
90 will be run. If these file are put into the :file:`IPYTHONDIR/profile_default/security`
91 directory of the client's host, they will be found automatically. Otherwise, the full path
91 directory of the client's host, they will be found automatically. Otherwise, the full path
92 to them has to be passed to the client's constructor.
92 to them has to be passed to the client's constructor.
93
93
94 Using :command:`ipcluster`
94 Using :command:`ipcluster`
95 ===========================
95 ===========================
96
96
97 The :command:`ipcluster` command provides a simple way of starting a
97 The :command:`ipcluster` command provides a simple way of starting a
98 controller and engines in the following situations:
98 controller and engines in the following situations:
99
99
100 1. When the controller and engines are all run on localhost. This is useful
100 1. When the controller and engines are all run on localhost. This is useful
101 for testing or running on a multicore computer.
101 for testing or running on a multicore computer.
102 2. When engines are started using the :command:`mpiexec` command that comes
102 2. When engines are started using the :command:`mpiexec` command that comes
103 with most MPI [MPI]_ implementations
103 with most MPI [MPI]_ implementations
104 3. When engines are started using the PBS [PBS]_ batch system
104 3. When engines are started using the PBS [PBS]_ batch system
105 (or other `qsub` systems, such as SGE).
105 (or other `qsub` systems, such as SGE).
106 4. When the controller is started on localhost and the engines are started on
106 4. When the controller is started on localhost and the engines are started on
107 remote nodes using :command:`ssh`.
107 remote nodes using :command:`ssh`.
108 5. When engines are started using the Windows HPC Server batch system.
108 5. When engines are started using the Windows HPC Server batch system.
109
109
110 .. note::
110 .. note::
111
111
112 Currently :command:`ipcluster` requires that the
112 Currently :command:`ipcluster` requires that the
113 :file:`IPYTHONDIR/profile_<name>/security` directory live on a shared filesystem that is
113 :file:`IPYTHONDIR/profile_<name>/security` directory live on a shared filesystem that is
114 seen by both the controller and engines. If you don't have a shared file
114 seen by both the controller and engines. If you don't have a shared file
115 system you will need to use :command:`ipcontroller` and
115 system you will need to use :command:`ipcontroller` and
116 :command:`ipengine` directly.
116 :command:`ipengine` directly.
117
117
118 Under the hood, :command:`ipcluster` just uses :command:`ipcontroller`
118 Under the hood, :command:`ipcluster` just uses :command:`ipcontroller`
119 and :command:`ipengine` to perform the steps described above.
119 and :command:`ipengine` to perform the steps described above.
120
120
121 The simplest way to use ipcluster requires no configuration, and will
121 The simplest way to use ipcluster requires no configuration, and will
122 launch a controller and a number of engines on the local machine. For instance,
122 launch a controller and a number of engines on the local machine. For instance,
123 to start one controller and 4 engines on localhost, just do::
123 to start one controller and 4 engines on localhost, just do::
124
124
125 $ ipcluster start -n 4
125 $ ipcluster start -n 4
126
126
127 To see other command line options, do::
127 To see other command line options, do::
128
128
129 $ ipcluster -h
129 $ ipcluster -h
130
130
131
131
132 Configuring an IPython cluster
132 Configuring an IPython cluster
133 ==============================
133 ==============================
134
134
135 Cluster configurations are stored as `profiles`. You can create a new profile with::
135 Cluster configurations are stored as `profiles`. You can create a new profile with::
136
136
137 $ ipython profile create --parallel --profile=myprofile
137 $ ipython profile create --parallel --profile=myprofile
138
138
139 This will create the directory :file:`IPYTHONDIR/profile_myprofile`, and populate it
139 This will create the directory :file:`IPYTHONDIR/profile_myprofile`, and populate it
140 with the default configuration files for the three IPython cluster commands. Once
140 with the default configuration files for the three IPython cluster commands. Once
141 you edit those files, you can continue to call ipcluster/ipcontroller/ipengine
141 you edit those files, you can continue to call ipcluster/ipcontroller/ipengine
142 with no arguments beyond ``profile=myprofile``, and any configuration will be maintained.
142 with no arguments beyond ``profile=myprofile``, and any configuration will be maintained.
143
143
144 There is no limit to the number of profiles you can have, so you can maintain a profile for each
144 There is no limit to the number of profiles you can have, so you can maintain a profile for each
145 of your common use cases. The default profile will be used whenever the
145 of your common use cases. The default profile will be used whenever the
146 profile argument is not specified, so edit :file:`IPYTHONDIR/profile_default/*_config.py` to
146 profile argument is not specified, so edit :file:`IPYTHONDIR/profile_default/*_config.py` to
147 represent your most common use case.
147 represent your most common use case.
148
148
149 The configuration files are loaded with commented-out settings and explanations,
149 The configuration files are loaded with commented-out settings and explanations,
150 which should cover most of the available possibilities.
150 which should cover most of the available possibilities.
151
151
152 Using various batch systems with :command:`ipcluster`
152 Using various batch systems with :command:`ipcluster`
153 -----------------------------------------------------
153 -----------------------------------------------------
154
154
155 :command:`ipcluster` has a notion of Launchers that can start controllers
155 :command:`ipcluster` has a notion of Launchers that can start controllers
156 and engines with various remote execution schemes. Currently supported
156 and engines with various remote execution schemes. Currently supported
157 models include :command:`ssh`, :command:`mpiexec`, PBS-style (Torque, SGE, LSF),
157 models include :command:`ssh`, :command:`mpiexec`, PBS-style (Torque, SGE, LSF),
158 and Windows HPC Server.
158 and Windows HPC Server.
159
159
160 In general, these are configured by the :attr:`IPClusterEngines.engine_set_launcher_class`,
160 In general, these are configured by the :attr:`IPClusterEngines.engine_set_launcher_class`,
161 and :attr:`IPClusterStart.controller_launcher_class` configurables, which can be the
161 and :attr:`IPClusterStart.controller_launcher_class` configurables, which can be the
162 fully specified object name (e.g. ``'IPython.parallel.apps.launcher.LocalControllerLauncher'``),
162 fully specified object name (e.g. ``'IPython.parallel.apps.launcher.LocalControllerLauncher'``),
163 but if you are using IPython's builtin launchers, you can specify just the class name,
163 but if you are using IPython's builtin launchers, you can specify just the class name,
164 or even just the prefix e.g:
164 or even just the prefix e.g:
165
165
166 .. sourcecode:: python
166 .. sourcecode:: python
167
167
168 c.IPClusterEngines.engine_launcher_class = 'SSH'
168 c.IPClusterEngines.engine_launcher_class = 'SSH'
169 # equivalent to
169 # equivalent to
170 c.IPClusterEngines.engine_launcher_class = 'SSHEngineSetLauncher'
170 c.IPClusterEngines.engine_launcher_class = 'SSHEngineSetLauncher'
171 # both of which expand to
171 # both of which expand to
172 c.IPClusterEngines.engine_launcher_class = 'IPython.parallel.apps.launcher.SSHEngineSetLauncher'
172 c.IPClusterEngines.engine_launcher_class = 'IPython.parallel.apps.launcher.SSHEngineSetLauncher'
173
173
174 The shortest form being of particular use on the command line, where all you need to do to
174 The shortest form being of particular use on the command line, where all you need to do to
175 get an IPython cluster running with engines started with MPI is:
175 get an IPython cluster running with engines started with MPI is:
176
176
177 .. sourcecode:: bash
177 .. sourcecode:: bash
178
178
179 $> ipcluster start --engines=MPI
179 $> ipcluster start --engines=MPI
180
180
181 Assuming that the default MPI config is sufficient.
181 Assuming that the default MPI config is sufficient.
182
182
183 .. note::
183 .. note::
184
184
185 shortcuts for builtin launcher names were added in 0.12, as was the ``_class`` suffix
185 shortcuts for builtin launcher names were added in 0.12, as was the ``_class`` suffix
186 on the configurable names. If you use the old 0.11 names (e.g. ``engine_set_launcher``),
186 on the configurable names. If you use the old 0.11 names (e.g. ``engine_set_launcher``),
187 they will still work, but you will get a deprecation warning that the name has changed.
187 they will still work, but you will get a deprecation warning that the name has changed.
188
188
189
189
190 .. note::
190 .. note::
191
191
192 The Launchers and configuration are designed in such a way that advanced
192 The Launchers and configuration are designed in such a way that advanced
193 users can subclass and configure them to fit their own system that we
193 users can subclass and configure them to fit their own system that we
194 have not yet supported (such as Condor)
194 have not yet supported (such as Condor)
195
195
196 Using :command:`ipcluster` in mpiexec/mpirun mode
196 Using :command:`ipcluster` in mpiexec/mpirun mode
197 -------------------------------------------------
197 -------------------------------------------------
198
198
199
199
200 The mpiexec/mpirun mode is useful if you:
200 The mpiexec/mpirun mode is useful if you:
201
201
202 1. Have MPI installed.
202 1. Have MPI installed.
203 2. Your systems are configured to use the :command:`mpiexec` or
203 2. Your systems are configured to use the :command:`mpiexec` or
204 :command:`mpirun` commands to start MPI processes.
204 :command:`mpirun` commands to start MPI processes.
205
205
206 If these are satisfied, you can create a new profile::
206 If these are satisfied, you can create a new profile::
207
207
208 $ ipython profile create --parallel --profile=mpi
208 $ ipython profile create --parallel --profile=mpi
209
209
210 and edit the file :file:`IPYTHONDIR/profile_mpi/ipcluster_config.py`.
210 and edit the file :file:`IPYTHONDIR/profile_mpi/ipcluster_config.py`.
211
211
212 There, instruct ipcluster to use the MPI launchers by adding the lines:
212 There, instruct ipcluster to use the MPI launchers by adding the lines:
213
213
214 .. sourcecode:: python
214 .. sourcecode:: python
215
215
216 c.IPClusterEngines.engine_launcher_class = 'MPIEngineSetLauncher'
216 c.IPClusterEngines.engine_launcher_class = 'MPIEngineSetLauncher'
217
217
218 If the default MPI configuration is correct, then you can now start your cluster, with::
218 If the default MPI configuration is correct, then you can now start your cluster, with::
219
219
220 $ ipcluster start -n 4 --profile=mpi
220 $ ipcluster start -n 4 --profile=mpi
221
221
222 This does the following:
222 This does the following:
223
223
224 1. Starts the IPython controller on current host.
224 1. Starts the IPython controller on current host.
225 2. Uses :command:`mpiexec` to start 4 engines.
225 2. Uses :command:`mpiexec` to start 4 engines.
226
226
227 If you have a reason to also start the Controller with mpi, you can specify:
227 If you have a reason to also start the Controller with mpi, you can specify:
228
228
229 .. sourcecode:: python
229 .. sourcecode:: python
230
230
231 c.IPClusterStart.controller_launcher_class = 'MPIControllerLauncher'
231 c.IPClusterStart.controller_launcher_class = 'MPIControllerLauncher'
232
232
233 .. note::
233 .. note::
234
234
235 The Controller *will not* be in the same MPI universe as the engines, so there is not
235 The Controller *will not* be in the same MPI universe as the engines, so there is not
236 much reason to do this unless sysadmins demand it.
236 much reason to do this unless sysadmins demand it.
237
237
238 On newer MPI implementations (such as OpenMPI), this will work even if you
238 On newer MPI implementations (such as OpenMPI), this will work even if you
239 don't make any calls to MPI or call :func:`MPI_Init`. However, older MPI
239 don't make any calls to MPI or call :func:`MPI_Init`. However, older MPI
240 implementations actually require each process to call :func:`MPI_Init` upon
240 implementations actually require each process to call :func:`MPI_Init` upon
241 starting. The easiest way of having this done is to install the mpi4py
241 starting. The easiest way of having this done is to install the mpi4py
242 [mpi4py]_ package and then specify the ``c.MPI.use`` option in :file:`ipengine_config.py`:
242 [mpi4py]_ package and then specify the ``c.MPI.use`` option in :file:`ipengine_config.py`:
243
243
244 .. sourcecode:: python
244 .. sourcecode:: python
245
245
246 c.MPI.use = 'mpi4py'
246 c.MPI.use = 'mpi4py'
247
247
248 Unfortunately, even this won't work for some MPI implementations. If you are
248 Unfortunately, even this won't work for some MPI implementations. If you are
249 having problems with this, you will likely have to use a custom Python
249 having problems with this, you will likely have to use a custom Python
250 executable that itself calls :func:`MPI_Init` at the appropriate time.
250 executable that itself calls :func:`MPI_Init` at the appropriate time.
251 Fortunately, mpi4py comes with such a custom Python executable that is easy to
251 Fortunately, mpi4py comes with such a custom Python executable that is easy to
252 install and use. However, this custom Python executable approach will not work
252 install and use. However, this custom Python executable approach will not work
253 with :command:`ipcluster` currently.
253 with :command:`ipcluster` currently.
254
254
255 More details on using MPI with IPython can be found :ref:`here <parallelmpi>`.
255 More details on using MPI with IPython can be found :ref:`here <parallelmpi>`.
256
256
257
257
258 Using :command:`ipcluster` in PBS mode
258 Using :command:`ipcluster` in PBS mode
259 --------------------------------------
259 --------------------------------------
260
260
261 The PBS mode uses the Portable Batch System (PBS) to start the engines.
261 The PBS mode uses the Portable Batch System (PBS) to start the engines.
262
262
263 As usual, we will start by creating a fresh profile::
263 As usual, we will start by creating a fresh profile::
264
264
265 $ ipython profile create --parallel --profile=pbs
265 $ ipython profile create --parallel --profile=pbs
266
266
267 And in :file:`ipcluster_config.py`, we will select the PBS launchers for the controller
267 And in :file:`ipcluster_config.py`, we will select the PBS launchers for the controller
268 and engines:
268 and engines:
269
269
270 .. sourcecode:: python
270 .. sourcecode:: python
271
271
272 c.IPClusterStart.controller_launcher_class = 'PBSControllerLauncher'
272 c.IPClusterStart.controller_launcher_class = 'PBSControllerLauncher'
273 c.IPClusterEngines.engine_launcher_class = 'PBSEngineSetLauncher'
273 c.IPClusterEngines.engine_launcher_class = 'PBSEngineSetLauncher'
274
274
275 .. note::
275 .. note::
276
276
277 Note that the configurable is IPClusterEngines for the engine launcher, and
277 Note that the configurable is IPClusterEngines for the engine launcher, and
278 IPClusterStart for the controller launcher. This is because the start command is a
278 IPClusterStart for the controller launcher. This is because the start command is a
279 subclass of the engine command, adding a controller launcher. Since it is a subclass,
279 subclass of the engine command, adding a controller launcher. Since it is a subclass,
280 any configuration made in IPClusterEngines is inherited by IPClusterStart unless it is
280 any configuration made in IPClusterEngines is inherited by IPClusterStart unless it is
281 overridden.
281 overridden.
282
282
283 IPython does provide simple default batch templates for PBS and SGE, but you may need
283 IPython does provide simple default batch templates for PBS and SGE, but you may need
284 to specify your own. Here is a sample PBS script template:
284 to specify your own. Here is a sample PBS script template:
285
285
286 .. sourcecode:: bash
286 .. sourcecode:: bash
287
287
288 #PBS -N ipython
288 #PBS -N ipython
289 #PBS -j oe
289 #PBS -j oe
290 #PBS -l walltime=00:10:00
290 #PBS -l walltime=00:10:00
291 #PBS -l nodes={n/4}:ppn=4
291 #PBS -l nodes={n/4}:ppn=4
292 #PBS -q {queue}
292 #PBS -q {queue}
293
293
294 cd $PBS_O_WORKDIR
294 cd $PBS_O_WORKDIR
295 export PATH=$HOME/usr/local/bin
295 export PATH=$HOME/usr/local/bin
296 export PYTHONPATH=$HOME/usr/local/lib/python2.7/site-packages
296 export PYTHONPATH=$HOME/usr/local/lib/python2.7/site-packages
297 /usr/local/bin/mpiexec -n {n} ipengine --profile-dir={profile_dir}
297 /usr/local/bin/mpiexec -n {n} ipengine --profile-dir={profile_dir}
298
298
299 There are a few important points about this template:
299 There are a few important points about this template:
300
300
301 1. This template will be rendered at runtime using IPython's :class:`EvalFormatter`.
301 1. This template will be rendered at runtime using IPython's :class:`EvalFormatter`.
302 This is simply a subclass of :class:`string.Formatter` that allows simple expressions
302 This is simply a subclass of :class:`string.Formatter` that allows simple expressions
303 on keys.
303 on keys.
304
304
305 2. Instead of putting in the actual number of engines, use the notation
305 2. Instead of putting in the actual number of engines, use the notation
306 ``{n}`` to indicate the number of engines to be started. You can also use
306 ``{n}`` to indicate the number of engines to be started. You can also use
307 expressions like ``{n/4}`` in the template to indicate the number of nodes.
307 expressions like ``{n/4}`` in the template to indicate the number of nodes.
308 There will always be ``{n}`` and ``{profile_dir}`` variables passed to the formatter.
308 There will always be ``{n}`` and ``{profile_dir}`` variables passed to the formatter.
309 These allow the batch system to know how many engines, and where the configuration
309 These allow the batch system to know how many engines, and where the configuration
310 files reside. The same is true for the batch queue, with the template variable
310 files reside. The same is true for the batch queue, with the template variable
311 ``{queue}``.
311 ``{queue}``.
312
312
313 3. Any options to :command:`ipengine` can be given in the batch script
313 3. Any options to :command:`ipengine` can be given in the batch script
314 template, or in :file:`ipengine_config.py`.
314 template, or in :file:`ipengine_config.py`.
315
315
316 4. Depending on the configuration of you system, you may have to set
316 4. Depending on the configuration of you system, you may have to set
317 environment variables in the script template.
317 environment variables in the script template.
318
318
319 The controller template should be similar, but simpler:
319 The controller template should be similar, but simpler:
320
320
321 .. sourcecode:: bash
321 .. sourcecode:: bash
322
322
323 #PBS -N ipython
323 #PBS -N ipython
324 #PBS -j oe
324 #PBS -j oe
325 #PBS -l walltime=00:10:00
325 #PBS -l walltime=00:10:00
326 #PBS -l nodes=1:ppn=4
326 #PBS -l nodes=1:ppn=4
327 #PBS -q {queue}
327 #PBS -q {queue}
328
328
329 cd $PBS_O_WORKDIR
329 cd $PBS_O_WORKDIR
330 export PATH=$HOME/usr/local/bin
330 export PATH=$HOME/usr/local/bin
331 export PYTHONPATH=$HOME/usr/local/lib/python2.7/site-packages
331 export PYTHONPATH=$HOME/usr/local/lib/python2.7/site-packages
332 ipcontroller --profile-dir={profile_dir}
332 ipcontroller --profile-dir={profile_dir}
333
333
334
334
335 Once you have created these scripts, save them with names like
335 Once you have created these scripts, save them with names like
336 :file:`pbs.engine.template`. Now you can load them into the :file:`ipcluster_config` with:
336 :file:`pbs.engine.template`. Now you can load them into the :file:`ipcluster_config` with:
337
337
338 .. sourcecode:: python
338 .. sourcecode:: python
339
339
340 c.PBSEngineSetLauncher.batch_template_file = "pbs.engine.template"
340 c.PBSEngineSetLauncher.batch_template_file = "pbs.engine.template"
341
341
342 c.PBSControllerLauncher.batch_template_file = "pbs.controller.template"
342 c.PBSControllerLauncher.batch_template_file = "pbs.controller.template"
343
343
344
344
345 Alternately, you can just define the templates as strings inside :file:`ipcluster_config`.
345 Alternately, you can just define the templates as strings inside :file:`ipcluster_config`.
346
346
347 Whether you are using your own templates or our defaults, the extra configurables available are
347 Whether you are using your own templates or our defaults, the extra configurables available are
348 the number of engines to launch (``{n}``, and the batch system queue to which the jobs are to be
348 the number of engines to launch (``{n}``, and the batch system queue to which the jobs are to be
349 submitted (``{queue}``)). These are configurables, and can be specified in
349 submitted (``{queue}``)). These are configurables, and can be specified in
350 :file:`ipcluster_config`:
350 :file:`ipcluster_config`:
351
351
352 .. sourcecode:: python
352 .. sourcecode:: python
353
353
354 c.PBSLauncher.queue = 'veryshort.q'
354 c.PBSLauncher.queue = 'veryshort.q'
355 c.IPClusterEngines.n = 64
355 c.IPClusterEngines.n = 64
356
356
357 Note that assuming you are running PBS on a multi-node cluster, the Controller's default behavior
357 Note that assuming you are running PBS on a multi-node cluster, the Controller's default behavior
358 of listening only on localhost is likely too restrictive. In this case, also assuming the
358 of listening only on localhost is likely too restrictive. In this case, also assuming the
359 nodes are safely behind a firewall, you can simply instruct the Controller to listen for
359 nodes are safely behind a firewall, you can simply instruct the Controller to listen for
360 connections on all its interfaces, by adding in :file:`ipcontroller_config`:
360 connections on all its interfaces, by adding in :file:`ipcontroller_config`:
361
361
362 .. sourcecode:: python
362 .. sourcecode:: python
363
363
364 c.HubFactory.ip = '*'
364 c.HubFactory.ip = '*'
365
365
366 You can now run the cluster with::
366 You can now run the cluster with::
367
367
368 $ ipcluster start --profile=pbs -n 128
368 $ ipcluster start --profile=pbs -n 128
369
369
370 Additional configuration options can be found in the PBS section of :file:`ipcluster_config`.
370 Additional configuration options can be found in the PBS section of :file:`ipcluster_config`.
371
371
372 .. note::
372 .. note::
373
373
374 Due to the flexibility of configuration, the PBS launchers work with simple changes
374 Due to the flexibility of configuration, the PBS launchers work with simple changes
375 to the template for other :command:`qsub`-using systems, such as Sun Grid Engine,
375 to the template for other :command:`qsub`-using systems, such as Sun Grid Engine,
376 and with further configuration in similar batch systems like Condor.
376 and with further configuration in similar batch systems like Condor.
377
377
378
378
379 Using :command:`ipcluster` in SSH mode
379 Using :command:`ipcluster` in SSH mode
380 --------------------------------------
380 --------------------------------------
381
381
382
382
383 The SSH mode uses :command:`ssh` to execute :command:`ipengine` on remote
383 The SSH mode uses :command:`ssh` to execute :command:`ipengine` on remote
384 nodes and :command:`ipcontroller` can be run remotely as well, or on localhost.
384 nodes and :command:`ipcontroller` can be run remotely as well, or on localhost.
385
385
386 .. note::
386 .. note::
387
387
388 When using this mode it highly recommended that you have set up SSH keys
388 When using this mode it highly recommended that you have set up SSH keys
389 and are using ssh-agent [SSH]_ for password-less logins.
389 and are using ssh-agent [SSH]_ for password-less logins.
390
390
391 As usual, we start by creating a clean profile::
391 As usual, we start by creating a clean profile::
392
392
393 $ ipython profile create --parallel --profile=ssh
393 $ ipython profile create --parallel --profile=ssh
394
394
395 To use this mode, select the SSH launchers in :file:`ipcluster_config.py`:
395 To use this mode, select the SSH launchers in :file:`ipcluster_config.py`:
396
396
397 .. sourcecode:: python
397 .. sourcecode:: python
398
398
399 c.IPClusterEngines.engine_launcher_class = 'SSHEngineSetLauncher'
399 c.IPClusterEngines.engine_launcher_class = 'SSHEngineSetLauncher'
400 # and if the Controller is also to be remote:
400 # and if the Controller is also to be remote:
401 c.IPClusterStart.controller_launcher_class = 'SSHControllerLauncher'
401 c.IPClusterStart.controller_launcher_class = 'SSHControllerLauncher'
402
402
403
403
404
404
405 The controller's remote location and configuration can be specified:
405 The controller's remote location and configuration can be specified:
406
406
407 .. sourcecode:: python
407 .. sourcecode:: python
408
408
409 # Set the user and hostname for the controller
409 # Set the user and hostname for the controller
410 # c.SSHControllerLauncher.hostname = 'controller.example.com'
410 # c.SSHControllerLauncher.hostname = 'controller.example.com'
411 # c.SSHControllerLauncher.user = os.environ.get('USER','username')
411 # c.SSHControllerLauncher.user = os.environ.get('USER','username')
412
412
413 # Set the arguments to be passed to ipcontroller
413 # Set the arguments to be passed to ipcontroller
414 # note that remotely launched ipcontroller will not get the contents of
414 # note that remotely launched ipcontroller will not get the contents of
415 # the local ipcontroller_config.py unless it resides on the *remote host*
415 # the local ipcontroller_config.py unless it resides on the *remote host*
416 # in the location specified by the `profile-dir` argument.
416 # in the location specified by the `profile-dir` argument.
417 # c.SSHControllerLauncher.controller_args = ['--reuse', '--ip=*', '--profile-dir=/path/to/cd']
417 # c.SSHControllerLauncher.controller_args = ['--reuse', '--ip=*', '--profile-dir=/path/to/cd']
418
418
419 Engines are specified in a dictionary, by hostname and the number of engines to be run
419 Engines are specified in a dictionary, by hostname and the number of engines to be run
420 on that host.
420 on that host.
421
421
422 .. sourcecode:: python
422 .. sourcecode:: python
423
423
424 c.SSHEngineSetLauncher.engines = { 'host1.example.com' : 2,
424 c.SSHEngineSetLauncher.engines = { 'host1.example.com' : 2,
425 'host2.example.com' : 5,
425 'host2.example.com' : 5,
426 'host3.example.com' : (1, ['--profile-dir=/home/different/location']),
426 'host3.example.com' : (1, ['--profile-dir=/home/different/location']),
427 'host4.example.com' : 8 }
427 'host4.example.com' : 8 }
428
428
429 * The `engines` dict, where the keys are the host we want to run engines on and
429 * The `engines` dict, where the keys are the host we want to run engines on and
430 the value is the number of engines to run on that host.
430 the value is the number of engines to run on that host.
431 * on host3, the value is a tuple, where the number of engines is first, and the arguments
431 * on host3, the value is a tuple, where the number of engines is first, and the arguments
432 to be passed to :command:`ipengine` are the second element.
432 to be passed to :command:`ipengine` are the second element.
433
433
434 For engines without explicitly specified arguments, the default arguments are set in
434 For engines without explicitly specified arguments, the default arguments are set in
435 a single location:
435 a single location:
436
436
437 .. sourcecode:: python
437 .. sourcecode:: python
438
438
439 c.SSHEngineSetLauncher.engine_args = ['--profile-dir=/path/to/profile_ssh']
439 c.SSHEngineSetLauncher.engine_args = ['--profile-dir=/path/to/profile_ssh']
440
440
441 Current limitations of the SSH mode of :command:`ipcluster` are:
441 Current limitations of the SSH mode of :command:`ipcluster` are:
442
442
443 * Untested and unsupported on Windows. Would require a working :command:`ssh` on Windows.
443 * Untested and unsupported on Windows. Would require a working :command:`ssh` on Windows.
444 Also, we are using shell scripts to setup and execute commands on remote hosts.
444 Also, we are using shell scripts to setup and execute commands on remote hosts.
445
445
446
446
447 Moving files with SSH
447 Moving files with SSH
448 *********************
448 *********************
449
449
450 SSH launchers will try to move connection files, controlled by the ``to_send`` and
450 SSH launchers will try to move connection files, controlled by the ``to_send`` and
451 ``to_fetch`` configurables. If your machines are on a shared filesystem, this step is
451 ``to_fetch`` configurables. If your machines are on a shared filesystem, this step is
452 unnecessary, and can be skipped by setting these to empty lists:
452 unnecessary, and can be skipped by setting these to empty lists:
453
453
454 .. sourcecode:: python
454 .. sourcecode:: python
455
455
456 c.SSHLauncher.to_send = []
456 c.SSHLauncher.to_send = []
457 c.SSHLauncher.to_fetch = []
457 c.SSHLauncher.to_fetch = []
458
458
459 If our default guesses about paths don't work for you, or other files
459 If our default guesses about paths don't work for you, or other files
460 should be moved, you can manually specify these lists as tuples of (local_path,
460 should be moved, you can manually specify these lists as tuples of (local_path,
461 remote_path) for to_send, and (remote_path, local_path) for to_fetch. If you do
461 remote_path) for to_send, and (remote_path, local_path) for to_fetch. If you do
462 specify these lists explicitly, IPython *will not* automatically send connection files,
462 specify these lists explicitly, IPython *will not* automatically send connection files,
463 so you must include this yourself if they should still be sent/retrieved.
463 so you must include this yourself if they should still be sent/retrieved.
464
464
465
465
466 IPython on EC2 with StarCluster
466 IPython on EC2 with StarCluster
467 ===============================
467 ===============================
468
468
469 The excellent StarCluster_ toolkit for managing `Amazon EC2`_ clusters has a plugin
469 The excellent StarCluster_ toolkit for managing `Amazon EC2`_ clusters has a plugin
470 which makes deploying IPython on EC2 quite simple. The starcluster plugin uses
470 which makes deploying IPython on EC2 quite simple. The starcluster plugin uses
471 :command:`ipcluster` with the SGE launchers to distribute engines across the
471 :command:`ipcluster` with the SGE launchers to distribute engines across the
472 EC2 cluster. See their `ipcluster plugin documentation`_ for more information.
472 EC2 cluster. See their `ipcluster plugin documentation`_ for more information.
473
473
474 .. _StarCluster: http://web.mit.edu/starcluster
474 .. _StarCluster: http://web.mit.edu/starcluster
475 .. _Amazon EC2: http://aws.amazon.com/ec2/
475 .. _Amazon EC2: http://aws.amazon.com/ec2/
476 .. _ipcluster plugin documentation: http://web.mit.edu/starcluster/docs/latest/plugins/ipython.html
476 .. _ipcluster plugin documentation: http://web.mit.edu/starcluster/docs/latest/plugins/ipython.html
477
477
478
478
479 Using the :command:`ipcontroller` and :command:`ipengine` commands
479 Using the :command:`ipcontroller` and :command:`ipengine` commands
480 ==================================================================
480 ==================================================================
481
481
482 It is also possible to use the :command:`ipcontroller` and :command:`ipengine`
482 It is also possible to use the :command:`ipcontroller` and :command:`ipengine`
483 commands to start your controller and engines. This approach gives you full
483 commands to start your controller and engines. This approach gives you full
484 control over all aspects of the startup process.
484 control over all aspects of the startup process.
485
485
486 Starting the controller and engine on your local machine
486 Starting the controller and engine on your local machine
487 --------------------------------------------------------
487 --------------------------------------------------------
488
488
489 To use :command:`ipcontroller` and :command:`ipengine` to start things on your
489 To use :command:`ipcontroller` and :command:`ipengine` to start things on your
490 local machine, do the following.
490 local machine, do the following.
491
491
492 First start the controller::
492 First start the controller::
493
493
494 $ ipcontroller
494 $ ipcontroller
495
495
496 Next, start however many instances of the engine you want using (repeatedly)
496 Next, start however many instances of the engine you want using (repeatedly)
497 the command::
497 the command::
498
498
499 $ ipengine
499 $ ipengine
500
500
501 The engines should start and automatically connect to the controller using the
501 The engines should start and automatically connect to the controller using the
502 JSON files in :file:`IPYTHONDIR/profile_default/security`. You are now ready to use the
502 JSON files in :file:`IPYTHONDIR/profile_default/security`. You are now ready to use the
503 controller and engines from IPython.
503 controller and engines from IPython.
504
504
505 .. warning::
505 .. warning::
506
506
507 The order of the above operations may be important. You *must*
507 The order of the above operations may be important. You *must*
508 start the controller before the engines, unless you are reusing connection
508 start the controller before the engines, unless you are reusing connection
509 information (via ``--reuse``), in which case ordering is not important.
509 information (via ``--reuse``), in which case ordering is not important.
510
510
511 .. note::
511 .. note::
512
512
513 On some platforms (OS X), to put the controller and engine into the
513 On some platforms (OS X), to put the controller and engine into the
514 background you may need to give these commands in the form ``(ipcontroller
514 background you may need to give these commands in the form ``(ipcontroller
515 &)`` and ``(ipengine &)`` (with the parentheses) for them to work
515 &)`` and ``(ipengine &)`` (with the parentheses) for them to work
516 properly.
516 properly.
517
517
518 Starting the controller and engines on different hosts
518 Starting the controller and engines on different hosts
519 ------------------------------------------------------
519 ------------------------------------------------------
520
520
521 When the controller and engines are running on different hosts, things are
521 When the controller and engines are running on different hosts, things are
522 slightly more complicated, but the underlying ideas are the same:
522 slightly more complicated, but the underlying ideas are the same:
523
523
524 1. Start the controller on a host using :command:`ipcontroller`. The controller must be
524 1. Start the controller on a host using :command:`ipcontroller`. The controller must be
525 instructed to listen on an interface visible to the engine machines, via the ``ip``
525 instructed to listen on an interface visible to the engine machines, via the ``ip``
526 command-line argument or ``HubFactory.ip`` in :file:`ipcontroller_config.py`::
526 command-line argument or ``HubFactory.ip`` in :file:`ipcontroller_config.py`::
527
527
528 $ ipcontroller --ip=192.168.1.16
528 $ ipcontroller --ip=192.168.1.16
529
529
530 .. sourcecode:: python
530 .. sourcecode:: python
531
531
532 # in ipcontroller_config.py
532 # in ipcontroller_config.py
533 HubFactory.ip = '192.168.1.16'
533 HubFactory.ip = '192.168.1.16'
534
534
535 2. Copy :file:`ipcontroller-engine.json` from :file:`IPYTHONDIR/profile_<name>/security` on
535 2. Copy :file:`ipcontroller-engine.json` from :file:`IPYTHONDIR/profile_<name>/security` on
536 the controller's host to the host where the engines will run.
536 the controller's host to the host where the engines will run.
537 3. Use :command:`ipengine` on the engine's hosts to start the engines.
537 3. Use :command:`ipengine` on the engine's hosts to start the engines.
538
538
539 The only thing you have to be careful of is to tell :command:`ipengine` where
539 The only thing you have to be careful of is to tell :command:`ipengine` where
540 the :file:`ipcontroller-engine.json` file is located. There are two ways you
540 the :file:`ipcontroller-engine.json` file is located. There are two ways you
541 can do this:
541 can do this:
542
542
543 * Put :file:`ipcontroller-engine.json` in the :file:`IPYTHONDIR/profile_<name>/security`
543 * Put :file:`ipcontroller-engine.json` in the :file:`IPYTHONDIR/profile_<name>/security`
544 directory on the engine's host, where it will be found automatically.
544 directory on the engine's host, where it will be found automatically.
545 * Call :command:`ipengine` with the ``--file=full_path_to_the_file``
545 * Call :command:`ipengine` with the ``--file=full_path_to_the_file``
546 flag.
546 flag.
547
547
548 The ``file`` flag works like this::
548 The ``file`` flag works like this::
549
549
550 $ ipengine --file=/path/to/my/ipcontroller-engine.json
550 $ ipengine --file=/path/to/my/ipcontroller-engine.json
551
551
552 .. note::
552 .. note::
553
553
554 If the controller's and engine's hosts all have a shared file system
554 If the controller's and engine's hosts all have a shared file system
555 (:file:`IPYTHONDIR/profile_<name>/security` is the same on all of them), then things
555 (:file:`IPYTHONDIR/profile_<name>/security` is the same on all of them), then things
556 will just work!
556 will just work!
557
557
558 SSH Tunnels
558 SSH Tunnels
559 ***********
559 ***********
560
560
561 If your engines are not on the same LAN as the controller, or you are on a highly
561 If your engines are not on the same LAN as the controller, or you are on a highly
562 restricted network where your nodes cannot see each others ports, then you can
562 restricted network where your nodes cannot see each others ports, then you can
563 use SSH tunnels to connect engines to the controller.
563 use SSH tunnels to connect engines to the controller.
564
564
565 .. note::
565 .. note::
566
566
567 This does not work in all cases. Manual tunnels may be an option, but are
567 This does not work in all cases. Manual tunnels may be an option, but are
568 highly inconvenient. Support for manual tunnels will be improved.
568 highly inconvenient. Support for manual tunnels will be improved.
569
569
570 You can instruct all engines to use ssh, by specifying the ssh server in
570 You can instruct all engines to use ssh, by specifying the ssh server in
571 :file:`ipcontroller-engine.json`:
571 :file:`ipcontroller-engine.json`:
572
572
573 .. I know this is really JSON, but the example is a subset of Python:
573 .. I know this is really JSON, but the example is a subset of Python:
574 .. sourcecode:: python
574 .. sourcecode:: python
575
575
576 {
576 {
577 "url":"tcp://192.168.1.123:56951",
577 "url":"tcp://192.168.1.123:56951",
578 "exec_key":"26f4c040-587d-4a4e-b58b-030b96399584",
578 "exec_key":"26f4c040-587d-4a4e-b58b-030b96399584",
579 "ssh":"user@example.com",
579 "ssh":"user@example.com",
580 "location":"192.168.1.123"
580 "location":"192.168.1.123"
581 }
581 }
582
582
583 This will be specified if you give the ``--enginessh=use@example.com`` argument when
583 This will be specified if you give the ``--enginessh=use@example.com`` argument when
584 starting :command:`ipcontroller`.
584 starting :command:`ipcontroller`.
585
585
586 Or you can specify an ssh server on the command-line when starting an engine::
586 Or you can specify an ssh server on the command-line when starting an engine::
587
587
588 $> ipengine --profile=foo --ssh=my.login.node
588 $> ipengine --profile=foo --ssh=my.login.node
589
589
590 For example, if your system is totally restricted, then all connections will actually be
590 For example, if your system is totally restricted, then all connections will actually be
591 loopback, and ssh tunnels will be used to connect engines to the controller::
591 loopback, and ssh tunnels will be used to connect engines to the controller::
592
592
593 [node1] $> ipcontroller --enginessh=node1
593 [node1] $> ipcontroller --enginessh=node1
594 [node2] $> ipengine
594 [node2] $> ipengine
595 [node3] $> ipcluster engines --n=4
595 [node3] $> ipcluster engines --n=4
596
596
597 Or if you want to start many engines on each node, the command `ipcluster engines --n=4`
597 Or if you want to start many engines on each node, the command `ipcluster engines --n=4`
598 without any configuration is equivalent to running ipengine 4 times.
598 without any configuration is equivalent to running ipengine 4 times.
599
599
600 An example using ipcontroller/engine with ssh
600 An example using ipcontroller/engine with ssh
601 ---------------------------------------------
601 ---------------------------------------------
602
602
603 No configuration files are necessary to use ipcontroller/engine in an SSH environment
603 No configuration files are necessary to use ipcontroller/engine in an SSH environment
604 without a shared filesystem. You simply need to make sure that the controller is listening
604 without a shared filesystem. You simply need to make sure that the controller is listening
605 on an interface visible to the engines, and move the connection file from the controller to
605 on an interface visible to the engines, and move the connection file from the controller to
606 the engines.
606 the engines.
607
607
608 1. start the controller, listening on an ip-address visible to the engine machines::
608 1. start the controller, listening on an ip-address visible to the engine machines::
609
609
610 [controller.host] $ ipcontroller --ip=192.168.1.16
610 [controller.host] $ ipcontroller --ip=192.168.1.16
611
611
612 [IPControllerApp] Using existing profile dir: u'/Users/me/.ipython/profile_default'
612 [IPControllerApp] Using existing profile dir: u'/Users/me/.ipython/profile_default'
613 [IPControllerApp] Hub listening on tcp://192.168.1.16:63320 for registration.
613 [IPControllerApp] Hub listening on tcp://192.168.1.16:63320 for registration.
614 [IPControllerApp] Hub using DB backend: 'IPython.parallel.controller.dictdb.DictDB'
614 [IPControllerApp] Hub using DB backend: 'IPython.parallel.controller.dictdb.DictDB'
615 [IPControllerApp] hub::created hub
615 [IPControllerApp] hub::created hub
616 [IPControllerApp] writing connection info to /Users/me/.ipython/profile_default/security/ipcontroller-client.json
616 [IPControllerApp] writing connection info to /Users/me/.ipython/profile_default/security/ipcontroller-client.json
617 [IPControllerApp] writing connection info to /Users/me/.ipython/profile_default/security/ipcontroller-engine.json
617 [IPControllerApp] writing connection info to /Users/me/.ipython/profile_default/security/ipcontroller-engine.json
618 [IPControllerApp] task::using Python leastload Task scheduler
618 [IPControllerApp] task::using Python leastload Task scheduler
619 [IPControllerApp] Heartmonitor started
619 [IPControllerApp] Heartmonitor started
620 [IPControllerApp] Creating pid file: /Users/me/.ipython/profile_default/pid/ipcontroller.pid
620 [IPControllerApp] Creating pid file: /Users/me/.ipython/profile_default/pid/ipcontroller.pid
621 Scheduler started [leastload]
621 Scheduler started [leastload]
622
622
623 2. on each engine, fetch the connection file with scp::
623 2. on each engine, fetch the connection file with scp::
624
624
625 [engine.host.n] $ scp controller.host:.ipython/profile_default/security/ipcontroller-engine.json ./
625 [engine.host.n] $ scp controller.host:.ipython/profile_default/security/ipcontroller-engine.json ./
626
626
627 .. note::
627 .. note::
628
628
629 The log output of ipcontroller above shows you where the json files were written.
629 The log output of ipcontroller above shows you where the json files were written.
630 They will be in :file:`~/.ipython` (or :file:`~/.config/ipython`) under
630 They will be in :file:`~/.ipython` under
631 :file:`profile_default/security/ipcontroller-engine.json`
631 :file:`profile_default/security/ipcontroller-engine.json`
632
632
633 3. start the engines, using the connection file::
633 3. start the engines, using the connection file::
634
634
635 [engine.host.n] $ ipengine --file=./ipcontroller-engine.json
635 [engine.host.n] $ ipengine --file=./ipcontroller-engine.json
636
636
637 A couple of notes:
637 A couple of notes:
638
638
639 * You can avoid having to fetch the connection file every time by adding ``--reuse`` flag
639 * You can avoid having to fetch the connection file every time by adding ``--reuse`` flag
640 to ipcontroller, which instructs the controller to read the previous connection file for
640 to ipcontroller, which instructs the controller to read the previous connection file for
641 connection info, rather than generate a new one with randomized ports.
641 connection info, rather than generate a new one with randomized ports.
642
642
643 * In step 2, if you fetch the connection file directly into the security dir of a profile,
643 * In step 2, if you fetch the connection file directly into the security dir of a profile,
644 then you need not specify its path directly, only the profile (assumes the path exists,
644 then you need not specify its path directly, only the profile (assumes the path exists,
645 otherwise you must create it first)::
645 otherwise you must create it first)::
646
646
647 [engine.host.n] $ scp controller.host:.ipython/profile_default/security/ipcontroller-engine.json ~/.config/ipython/profile_ssh/security/
647 [engine.host.n] $ scp controller.host:.ipython/profile_default/security/ipcontroller-engine.json ~/.ipython/profile_ssh/security/
648 [engine.host.n] $ ipengine --profile=ssh
648 [engine.host.n] $ ipengine --profile=ssh
649
649
650 Of course, if you fetch the file into the default profile, no arguments must be passed to
650 Of course, if you fetch the file into the default profile, no arguments must be passed to
651 ipengine at all.
651 ipengine at all.
652
652
653 * Note that ipengine *did not* specify the ip argument. In general, it is unlikely for any
653 * Note that ipengine *did not* specify the ip argument. In general, it is unlikely for any
654 connection information to be specified at the command-line to ipengine, as all of this
654 connection information to be specified at the command-line to ipengine, as all of this
655 information should be contained in the connection file written by ipcontroller.
655 information should be contained in the connection file written by ipcontroller.
656
656
657 Make JSON files persistent
657 Make JSON files persistent
658 --------------------------
658 --------------------------
659
659
660 At fist glance it may seem that that managing the JSON files is a bit
660 At fist glance it may seem that that managing the JSON files is a bit
661 annoying. Going back to the house and key analogy, copying the JSON around
661 annoying. Going back to the house and key analogy, copying the JSON around
662 each time you start the controller is like having to make a new key every time
662 each time you start the controller is like having to make a new key every time
663 you want to unlock the door and enter your house. As with your house, you want
663 you want to unlock the door and enter your house. As with your house, you want
664 to be able to create the key (or JSON file) once, and then simply use it at
664 to be able to create the key (or JSON file) once, and then simply use it at
665 any point in the future.
665 any point in the future.
666
666
667 To do this, the only thing you have to do is specify the `--reuse` flag, so that
667 To do this, the only thing you have to do is specify the `--reuse` flag, so that
668 the connection information in the JSON files remains accurate::
668 the connection information in the JSON files remains accurate::
669
669
670 $ ipcontroller --reuse
670 $ ipcontroller --reuse
671
671
672 Then, just copy the JSON files over the first time and you are set. You can
672 Then, just copy the JSON files over the first time and you are set. You can
673 start and stop the controller and engines any many times as you want in the
673 start and stop the controller and engines any many times as you want in the
674 future, just make sure to tell the controller to reuse the file.
674 future, just make sure to tell the controller to reuse the file.
675
675
676 .. note::
676 .. note::
677
677
678 You may ask the question: what ports does the controller listen on if you
678 You may ask the question: what ports does the controller listen on if you
679 don't tell is to use specific ones? The default is to use high random port
679 don't tell is to use specific ones? The default is to use high random port
680 numbers. We do this for two reasons: i) to increase security through
680 numbers. We do this for two reasons: i) to increase security through
681 obscurity and ii) to multiple controllers on a given host to start and
681 obscurity and ii) to multiple controllers on a given host to start and
682 automatically use different ports.
682 automatically use different ports.
683
683
684 Log files
684 Log files
685 ---------
685 ---------
686
686
687 All of the components of IPython have log files associated with them.
687 All of the components of IPython have log files associated with them.
688 These log files can be extremely useful in debugging problems with
688 These log files can be extremely useful in debugging problems with
689 IPython and can be found in the directory :file:`IPYTHONDIR/profile_<name>/log`.
689 IPython and can be found in the directory :file:`IPYTHONDIR/profile_<name>/log`.
690 Sending the log files to us will often help us to debug any problems.
690 Sending the log files to us will often help us to debug any problems.
691
691
692
692
693 Configuring `ipcontroller`
693 Configuring `ipcontroller`
694 ---------------------------
694 ---------------------------
695
695
696 The IPython Controller takes its configuration from the file :file:`ipcontroller_config.py`
696 The IPython Controller takes its configuration from the file :file:`ipcontroller_config.py`
697 in the active profile directory.
697 in the active profile directory.
698
698
699 Ports and addresses
699 Ports and addresses
700 *******************
700 *******************
701
701
702 In many cases, you will want to configure the Controller's network identity. By default,
702 In many cases, you will want to configure the Controller's network identity. By default,
703 the Controller listens only on loopback, which is the most secure but often impractical.
703 the Controller listens only on loopback, which is the most secure but often impractical.
704 To instruct the controller to listen on a specific interface, you can set the
704 To instruct the controller to listen on a specific interface, you can set the
705 :attr:`HubFactory.ip` trait. To listen on all interfaces, simply specify:
705 :attr:`HubFactory.ip` trait. To listen on all interfaces, simply specify:
706
706
707 .. sourcecode:: python
707 .. sourcecode:: python
708
708
709 c.HubFactory.ip = '*'
709 c.HubFactory.ip = '*'
710
710
711 When connecting to a Controller that is listening on loopback or behind a firewall, it may
711 When connecting to a Controller that is listening on loopback or behind a firewall, it may
712 be necessary to specify an SSH server to use for tunnels, and the external IP of the
712 be necessary to specify an SSH server to use for tunnels, and the external IP of the
713 Controller. If you specified that the HubFactory listen on loopback, or all interfaces,
713 Controller. If you specified that the HubFactory listen on loopback, or all interfaces,
714 then IPython will try to guess the external IP. If you are on a system with VM network
714 then IPython will try to guess the external IP. If you are on a system with VM network
715 devices, or many interfaces, this guess may be incorrect. In these cases, you will want
715 devices, or many interfaces, this guess may be incorrect. In these cases, you will want
716 to specify the 'location' of the Controller. This is the IP of the machine the Controller
716 to specify the 'location' of the Controller. This is the IP of the machine the Controller
717 is on, as seen by the clients, engines, or the SSH server used to tunnel connections.
717 is on, as seen by the clients, engines, or the SSH server used to tunnel connections.
718
718
719 For example, to set up a cluster with a Controller on a work node, using ssh tunnels
719 For example, to set up a cluster with a Controller on a work node, using ssh tunnels
720 through the login node, an example :file:`ipcontroller_config.py` might contain:
720 through the login node, an example :file:`ipcontroller_config.py` might contain:
721
721
722 .. sourcecode:: python
722 .. sourcecode:: python
723
723
724 # allow connections on all interfaces from engines
724 # allow connections on all interfaces from engines
725 # engines on the same node will use loopback, while engines
725 # engines on the same node will use loopback, while engines
726 # from other nodes will use an external IP
726 # from other nodes will use an external IP
727 c.HubFactory.ip = '*'
727 c.HubFactory.ip = '*'
728
728
729 # you typically only need to specify the location when there are extra
729 # you typically only need to specify the location when there are extra
730 # interfaces that may not be visible to peer nodes (e.g. VM interfaces)
730 # interfaces that may not be visible to peer nodes (e.g. VM interfaces)
731 c.HubFactory.location = '10.0.1.5'
731 c.HubFactory.location = '10.0.1.5'
732 # or to get an automatic value, try this:
732 # or to get an automatic value, try this:
733 import socket
733 import socket
734 hostname = socket.gethostname()
734 hostname = socket.gethostname()
735 # alternate choices for hostname include `socket.getfqdn()`
735 # alternate choices for hostname include `socket.getfqdn()`
736 # or `socket.gethostname() + '.local'`
736 # or `socket.gethostname() + '.local'`
737
737
738 ex_ip = socket.gethostbyname_ex(hostname)[-1][-1]
738 ex_ip = socket.gethostbyname_ex(hostname)[-1][-1]
739 c.HubFactory.location = ex_ip
739 c.HubFactory.location = ex_ip
740
740
741 # now instruct clients to use the login node for SSH tunnels:
741 # now instruct clients to use the login node for SSH tunnels:
742 c.HubFactory.ssh_server = 'login.mycluster.net'
742 c.HubFactory.ssh_server = 'login.mycluster.net'
743
743
744 After doing this, your :file:`ipcontroller-client.json` file will look something like this:
744 After doing this, your :file:`ipcontroller-client.json` file will look something like this:
745
745
746 .. this can be Python, despite the fact that it's actually JSON, because it's
746 .. this can be Python, despite the fact that it's actually JSON, because it's
747 .. still valid Python
747 .. still valid Python
748
748
749 .. sourcecode:: python
749 .. sourcecode:: python
750
750
751 {
751 {
752 "url":"tcp:\/\/*:43447",
752 "url":"tcp:\/\/*:43447",
753 "exec_key":"9c7779e4-d08a-4c3b-ba8e-db1f80b562c1",
753 "exec_key":"9c7779e4-d08a-4c3b-ba8e-db1f80b562c1",
754 "ssh":"login.mycluster.net",
754 "ssh":"login.mycluster.net",
755 "location":"10.0.1.5"
755 "location":"10.0.1.5"
756 }
756 }
757
757
758 Then this file will be all you need for a client to connect to the controller, tunneling
758 Then this file will be all you need for a client to connect to the controller, tunneling
759 SSH connections through login.mycluster.net.
759 SSH connections through login.mycluster.net.
760
760
761 Database Backend
761 Database Backend
762 ****************
762 ****************
763
763
764 The Hub stores all messages and results passed between Clients and Engines.
764 The Hub stores all messages and results passed between Clients and Engines.
765 For large and/or long-running clusters, it would be unreasonable to keep all
765 For large and/or long-running clusters, it would be unreasonable to keep all
766 of this information in memory. For this reason, we have two database backends:
766 of this information in memory. For this reason, we have two database backends:
767 [MongoDB]_ via PyMongo_, and SQLite with the stdlib :py:mod:`sqlite`.
767 [MongoDB]_ via PyMongo_, and SQLite with the stdlib :py:mod:`sqlite`.
768
768
769 MongoDB is our design target, and the dict-like model it uses has driven our design. As far
769 MongoDB is our design target, and the dict-like model it uses has driven our design. As far
770 as we are concerned, BSON can be considered essentially the same as JSON, adding support
770 as we are concerned, BSON can be considered essentially the same as JSON, adding support
771 for binary data and datetime objects, and any new database backend must support the same
771 for binary data and datetime objects, and any new database backend must support the same
772 data types.
772 data types.
773
773
774 .. seealso::
774 .. seealso::
775
775
776 MongoDB `BSON doc <http://www.mongodb.org/display/DOCS/BSON>`_
776 MongoDB `BSON doc <http://www.mongodb.org/display/DOCS/BSON>`_
777
777
778 To use one of these backends, you must set the :attr:`HubFactory.db_class` trait:
778 To use one of these backends, you must set the :attr:`HubFactory.db_class` trait:
779
779
780 .. sourcecode:: python
780 .. sourcecode:: python
781
781
782 # for a simple dict-based in-memory implementation, use dictdb
782 # for a simple dict-based in-memory implementation, use dictdb
783 # This is the default and the fastest, since it doesn't involve the filesystem
783 # This is the default and the fastest, since it doesn't involve the filesystem
784 c.HubFactory.db_class = 'IPython.parallel.controller.dictdb.DictDB'
784 c.HubFactory.db_class = 'IPython.parallel.controller.dictdb.DictDB'
785
785
786 # To use MongoDB:
786 # To use MongoDB:
787 c.HubFactory.db_class = 'IPython.parallel.controller.mongodb.MongoDB'
787 c.HubFactory.db_class = 'IPython.parallel.controller.mongodb.MongoDB'
788
788
789 # and SQLite:
789 # and SQLite:
790 c.HubFactory.db_class = 'IPython.parallel.controller.sqlitedb.SQLiteDB'
790 c.HubFactory.db_class = 'IPython.parallel.controller.sqlitedb.SQLiteDB'
791
791
792 # You can use NoDB to disable the database altogether, in case you don't need
792 # You can use NoDB to disable the database altogether, in case you don't need
793 # to reuse tasks or results, and want to keep memory consumption under control.
793 # to reuse tasks or results, and want to keep memory consumption under control.
794 c.HubFactory.db_class = 'IPython.parallel.controller.dictdb.NoDB'
794 c.HubFactory.db_class = 'IPython.parallel.controller.dictdb.NoDB'
795
795
796 When using the proper databases, you can actually allow for tasks to persist from
796 When using the proper databases, you can actually allow for tasks to persist from
797 one session to the next by specifying the MongoDB database or SQLite table in
797 one session to the next by specifying the MongoDB database or SQLite table in
798 which tasks are to be stored. The default is to use a table named for the Hub's Session,
798 which tasks are to be stored. The default is to use a table named for the Hub's Session,
799 which is a UUID, and thus different every time.
799 which is a UUID, and thus different every time.
800
800
801 .. sourcecode:: python
801 .. sourcecode:: python
802
802
803 # To keep persistant task history in MongoDB:
803 # To keep persistant task history in MongoDB:
804 c.MongoDB.database = 'tasks'
804 c.MongoDB.database = 'tasks'
805
805
806 # and in SQLite:
806 # and in SQLite:
807 c.SQLiteDB.table = 'tasks'
807 c.SQLiteDB.table = 'tasks'
808
808
809
809
810 Since MongoDB servers can be running remotely or configured to listen on a particular port,
810 Since MongoDB servers can be running remotely or configured to listen on a particular port,
811 you can specify any arguments you may need to the PyMongo `Connection
811 you can specify any arguments you may need to the PyMongo `Connection
812 <http://api.mongodb.org/python/1.9/api/pymongo/connection.html#pymongo.connection.Connection>`_:
812 <http://api.mongodb.org/python/1.9/api/pymongo/connection.html#pymongo.connection.Connection>`_:
813
813
814 .. sourcecode:: python
814 .. sourcecode:: python
815
815
816 # positional args to pymongo.Connection
816 # positional args to pymongo.Connection
817 c.MongoDB.connection_args = []
817 c.MongoDB.connection_args = []
818
818
819 # keyword args to pymongo.Connection
819 # keyword args to pymongo.Connection
820 c.MongoDB.connection_kwargs = {}
820 c.MongoDB.connection_kwargs = {}
821
821
822 But sometimes you are moving lots of data around quickly, and you don't need
822 But sometimes you are moving lots of data around quickly, and you don't need
823 that information to be stored for later access, even by other Clients to this
823 that information to be stored for later access, even by other Clients to this
824 same session. For this case, we have a dummy database, which doesn't actually
824 same session. For this case, we have a dummy database, which doesn't actually
825 store anything. This lets the Hub stay small in memory, at the obvious expense
825 store anything. This lets the Hub stay small in memory, at the obvious expense
826 of being able to access the information that would have been stored in the
826 of being able to access the information that would have been stored in the
827 database (used for task resubmission, requesting results of tasks you didn't
827 database (used for task resubmission, requesting results of tasks you didn't
828 submit, etc.). To use this backend, simply pass ``--nodb`` to
828 submit, etc.). To use this backend, simply pass ``--nodb`` to
829 :command:`ipcontroller` on the command-line, or specify the :class:`NoDB` class
829 :command:`ipcontroller` on the command-line, or specify the :class:`NoDB` class
830 in your :file:`ipcontroller_config.py` as described above.
830 in your :file:`ipcontroller_config.py` as described above.
831
831
832
832
833 .. seealso::
833 .. seealso::
834
834
835 For more information on the database backends, see the :ref:`db backend reference <parallel_db>`.
835 For more information on the database backends, see the :ref:`db backend reference <parallel_db>`.
836
836
837
837
838 .. _PyMongo: http://api.mongodb.org/python/1.9/
838 .. _PyMongo: http://api.mongodb.org/python/1.9/
839
839
840 Configuring `ipengine`
840 Configuring `ipengine`
841 -----------------------
841 -----------------------
842
842
843 The IPython Engine takes its configuration from the file :file:`ipengine_config.py`
843 The IPython Engine takes its configuration from the file :file:`ipengine_config.py`
844
844
845 The Engine itself also has some amount of configuration. Most of this
845 The Engine itself also has some amount of configuration. Most of this
846 has to do with initializing MPI or connecting to the controller.
846 has to do with initializing MPI or connecting to the controller.
847
847
848 To instruct the Engine to initialize with an MPI environment set up by
848 To instruct the Engine to initialize with an MPI environment set up by
849 mpi4py, add:
849 mpi4py, add:
850
850
851 .. sourcecode:: python
851 .. sourcecode:: python
852
852
853 c.MPI.use = 'mpi4py'
853 c.MPI.use = 'mpi4py'
854
854
855 In this case, the Engine will use our default mpi4py init script to set up
855 In this case, the Engine will use our default mpi4py init script to set up
856 the MPI environment prior to exection. We have default init scripts for
856 the MPI environment prior to exection. We have default init scripts for
857 mpi4py and pytrilinos. If you want to specify your own code to be run
857 mpi4py and pytrilinos. If you want to specify your own code to be run
858 at the beginning, specify `c.MPI.init_script`.
858 at the beginning, specify `c.MPI.init_script`.
859
859
860 You can also specify a file or python command to be run at startup of the
860 You can also specify a file or python command to be run at startup of the
861 Engine:
861 Engine:
862
862
863 .. sourcecode:: python
863 .. sourcecode:: python
864
864
865 c.IPEngineApp.startup_script = u'/path/to/my/startup.py'
865 c.IPEngineApp.startup_script = u'/path/to/my/startup.py'
866
866
867 c.IPEngineApp.startup_command = 'import numpy, scipy, mpi4py'
867 c.IPEngineApp.startup_command = 'import numpy, scipy, mpi4py'
868
868
869 These commands/files will be run again, after each
869 These commands/files will be run again, after each
870
870
871 It's also useful on systems with shared filesystems to run the engines
871 It's also useful on systems with shared filesystems to run the engines
872 in some scratch directory. This can be set with:
872 in some scratch directory. This can be set with:
873
873
874 .. sourcecode:: python
874 .. sourcecode:: python
875
875
876 c.IPEngineApp.work_dir = u'/path/to/scratch/'
876 c.IPEngineApp.work_dir = u'/path/to/scratch/'
877
877
878
878
879
879
880 .. [MongoDB] MongoDB database http://www.mongodb.org
880 .. [MongoDB] MongoDB database http://www.mongodb.org
881
881
882 .. [PBS] Portable Batch System http://www.openpbs.org
882 .. [PBS] Portable Batch System http://www.openpbs.org
883
883
884 .. [SSH] SSH-Agent http://en.wikipedia.org/wiki/ssh-agent
884 .. [SSH] SSH-Agent http://en.wikipedia.org/wiki/ssh-agent
General Comments 0
You need to be logged in to leave comments. Login now