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