##// END OF EJS Templates
Merge pull request #4022 from ivanov/doc-links...
Paul Ivanov -
r12185:6537445b merge
parent child Browse files
Show More
@@ -1,258 +1,259 b''
1 {% extends "page.html" %}
1 {% extends "page.html" %}
2
2
3 {% block stylesheet %}
3 {% block stylesheet %}
4
4
5 {% if mathjax_url %}
5 {% if mathjax_url %}
6 <script type="text/javascript" src="{{mathjax_url}}?config=TeX-AMS_HTML-full&delayStartupUntil=configured" charset="utf-8"></script>
6 <script type="text/javascript" src="{{mathjax_url}}?config=TeX-AMS_HTML-full&delayStartupUntil=configured" charset="utf-8"></script>
7 {% endif %}
7 {% endif %}
8 <script type="text/javascript">
8 <script type="text/javascript">
9 // MathJax disabled, set as null to distingish from *missing* MathJax,
9 // MathJax disabled, set as null to distingish from *missing* MathJax,
10 // where it will be undefined, and should prompt a dialog later.
10 // where it will be undefined, and should prompt a dialog later.
11 window.mathjax_url = "{{mathjax_url}}";
11 window.mathjax_url = "{{mathjax_url}}";
12 </script>
12 </script>
13
13
14 <link rel="stylesheet" href="{{ static_url("components/codemirror/lib/codemirror.css") }}">
14 <link rel="stylesheet" href="{{ static_url("components/codemirror/lib/codemirror.css") }}">
15
15
16 {{super()}}
16 {{super()}}
17
17
18 <link rel="stylesheet" href="{{ static_url("notebook/css/override.css") }}" type="text/css" />
18 <link rel="stylesheet" href="{{ static_url("notebook/css/override.css") }}" type="text/css" />
19
19
20 {% endblock %}
20 {% endblock %}
21
21
22 {% block params %}
22 {% block params %}
23
23
24 data-project={{project}}
24 data-project={{project}}
25 data-base-project-url={{base_project_url}}
25 data-base-project-url={{base_project_url}}
26 data-base-kernel-url={{base_kernel_url}}
26 data-base-kernel-url={{base_kernel_url}}
27 data-notebook-id={{notebook_id}}
27 data-notebook-id={{notebook_id}}
28 class="notebook_app"
28 class="notebook_app"
29
29
30 {% endblock %}
30 {% endblock %}
31
31
32
32
33 {% block header %}
33 {% block header %}
34
34
35 <span id="save_widget" class="nav pull-left">
35 <span id="save_widget" class="nav pull-left">
36 <span id="notebook_name"></span>
36 <span id="notebook_name"></span>
37 <span id="checkpoint_status"></span>
37 <span id="checkpoint_status"></span>
38 <span id="autosave_status"></span>
38 <span id="autosave_status"></span>
39 </span>
39 </span>
40
40
41 {% endblock %}
41 {% endblock %}
42
42
43
43
44 {% block site %}
44 {% block site %}
45
45
46 <div id="menubar-container" class="container">
46 <div id="menubar-container" class="container">
47 <div id="menubar">
47 <div id="menubar">
48 <div class="navbar">
48 <div class="navbar">
49 <div class="navbar-inner">
49 <div class="navbar-inner">
50 <div class="container">
50 <div class="container">
51 <ul id="menus" class="nav">
51 <ul id="menus" class="nav">
52 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">File</a>
52 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">File</a>
53 <ul class="dropdown-menu">
53 <ul class="dropdown-menu">
54 <li id="new_notebook"><a href="#">New</a></li>
54 <li id="new_notebook"><a href="#">New</a></li>
55 <li id="open_notebook"><a href="#">Open...</a></li>
55 <li id="open_notebook"><a href="#">Open...</a></li>
56 <!-- <hr/> -->
56 <!-- <hr/> -->
57 <li class="divider"></li>
57 <li class="divider"></li>
58 <li id="copy_notebook"><a href="#">Make a Copy...</a></li>
58 <li id="copy_notebook"><a href="#">Make a Copy...</a></li>
59 <li id="rename_notebook"><a href="#">Rename...</a></li>
59 <li id="rename_notebook"><a href="#">Rename...</a></li>
60 <li id="save_checkpoint"><a href="#">Save and Checkpoint</a></li>
60 <li id="save_checkpoint"><a href="#">Save and Checkpoint</a></li>
61 <!-- <hr/> -->
61 <!-- <hr/> -->
62 <li class="divider"></li>
62 <li class="divider"></li>
63 <li id="restore_checkpoint" class="dropdown-submenu"><a href="#">Revert to Checkpoint</a>
63 <li id="restore_checkpoint" class="dropdown-submenu"><a href="#">Revert to Checkpoint</a>
64 <ul class="dropdown-menu">
64 <ul class="dropdown-menu">
65 <li><a href="#"></a></li>
65 <li><a href="#"></a></li>
66 <li><a href="#"></a></li>
66 <li><a href="#"></a></li>
67 <li><a href="#"></a></li>
67 <li><a href="#"></a></li>
68 <li><a href="#"></a></li>
68 <li><a href="#"></a></li>
69 <li><a href="#"></a></li>
69 <li><a href="#"></a></li>
70 </ul>
70 </ul>
71 </li>
71 </li>
72 <li class="divider"></li>
72 <li class="divider"></li>
73 <li class="dropdown-submenu"><a href="#">Download as</a>
73 <li class="dropdown-submenu"><a href="#">Download as</a>
74 <ul class="dropdown-menu">
74 <ul class="dropdown-menu">
75 <li id="download_ipynb"><a href="#">IPython (.ipynb)</a></li>
75 <li id="download_ipynb"><a href="#">IPython (.ipynb)</a></li>
76 <li id="download_py"><a href="#">Python (.py)</a></li>
76 <li id="download_py"><a href="#">Python (.py)</a></li>
77 </ul>
77 </ul>
78 </li>
78 </li>
79 <li class="divider"></li>
79 <li class="divider"></li>
80
80
81 <li id="kill_and_exit"><a href="#" >Close and halt</a></li>
81 <li id="kill_and_exit"><a href="#" >Close and halt</a></li>
82 </ul>
82 </ul>
83 </li>
83 </li>
84 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Edit</a>
84 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Edit</a>
85 <ul class="dropdown-menu">
85 <ul class="dropdown-menu">
86 <li id="cut_cell"><a href="#">Cut Cell</a></li>
86 <li id="cut_cell"><a href="#">Cut Cell</a></li>
87 <li id="copy_cell"><a href="#">Copy Cell</a></li>
87 <li id="copy_cell"><a href="#">Copy Cell</a></li>
88 <li id="paste_cell_above" class="disabled"><a href="#">Paste Cell Above</a></li>
88 <li id="paste_cell_above" class="disabled"><a href="#">Paste Cell Above</a></li>
89 <li id="paste_cell_below" class="disabled"><a href="#">Paste Cell Below</a></li>
89 <li id="paste_cell_below" class="disabled"><a href="#">Paste Cell Below</a></li>
90 <li id="paste_cell_replace" class="disabled"><a href="#">Paste Cell &amp; Replace</a></li>
90 <li id="paste_cell_replace" class="disabled"><a href="#">Paste Cell &amp; Replace</a></li>
91 <li id="delete_cell"><a href="#">Delete Cell</a></li>
91 <li id="delete_cell"><a href="#">Delete Cell</a></li>
92 <li id="undelete_cell" class="disabled"><a href="#">Undo Delete Cell</a></li>
92 <li id="undelete_cell" class="disabled"><a href="#">Undo Delete Cell</a></li>
93 <li class="divider"></li>
93 <li class="divider"></li>
94 <li id="split_cell"><a href="#">Split Cell</a></li>
94 <li id="split_cell"><a href="#">Split Cell</a></li>
95 <li id="merge_cell_above"><a href="#">Merge Cell Above</a></li>
95 <li id="merge_cell_above"><a href="#">Merge Cell Above</a></li>
96 <li id="merge_cell_below"><a href="#">Merge Cell Below</a></li>
96 <li id="merge_cell_below"><a href="#">Merge Cell Below</a></li>
97 <li class="divider"></li>
97 <li class="divider"></li>
98 <li id="move_cell_up"><a href="#">Move Cell Up</a></li>
98 <li id="move_cell_up"><a href="#">Move Cell Up</a></li>
99 <li id="move_cell_down"><a href="#">Move Cell Down</a></li>
99 <li id="move_cell_down"><a href="#">Move Cell Down</a></li>
100 <li class="divider"></li>
100 <li class="divider"></li>
101 <li id="select_previous"><a href="#">Select Previous Cell</a></li>
101 <li id="select_previous"><a href="#">Select Previous Cell</a></li>
102 <li id="select_next"><a href="#">Select Next Cell</a></li>
102 <li id="select_next"><a href="#">Select Next Cell</a></li>
103 </ul>
103 </ul>
104 </li>
104 </li>
105 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">View</a>
105 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">View</a>
106 <ul class="dropdown-menu">
106 <ul class="dropdown-menu">
107 <li id="toggle_header"><a href="#">Toggle Header</a></li>
107 <li id="toggle_header"><a href="#">Toggle Header</a></li>
108 <li id="toggle_toolbar"><a href="#">Toggle Toolbar</a></li>
108 <li id="toggle_toolbar"><a href="#">Toggle Toolbar</a></li>
109 </ul>
109 </ul>
110 </li>
110 </li>
111 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Insert</a>
111 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Insert</a>
112 <ul class="dropdown-menu">
112 <ul class="dropdown-menu">
113 <li id="insert_cell_above"><a href="#">Insert Cell Above</a></li>
113 <li id="insert_cell_above"><a href="#">Insert Cell Above</a></li>
114 <li id="insert_cell_below"><a href="#">Insert Cell Below</a></li>
114 <li id="insert_cell_below"><a href="#">Insert Cell Below</a></li>
115 </ul>
115 </ul>
116 </li>
116 </li>
117 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Cell</a>
117 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Cell</a>
118 <ul class="dropdown-menu">
118 <ul class="dropdown-menu">
119 <li id="run_cell"><a href="#">Run</a></li>
119 <li id="run_cell"><a href="#">Run</a></li>
120 <li id="run_cell_in_place"><a href="#">Run in Place</a></li>
120 <li id="run_cell_in_place"><a href="#">Run in Place</a></li>
121 <li id="run_all_cells"><a href="#">Run All</a></li>
121 <li id="run_all_cells"><a href="#">Run All</a></li>
122 <li id="run_all_cells_above"><a href="#">Run All Above</a></li>
122 <li id="run_all_cells_above"><a href="#">Run All Above</a></li>
123 <li id="run_all_cells_below"><a href="#">Run All Below</a></li>
123 <li id="run_all_cells_below"><a href="#">Run All Below</a></li>
124 <li class="divider"></li>
124 <li class="divider"></li>
125 <li id="change_cell_type" class="dropdown-submenu"><a href="#">Cell Type</a>
125 <li id="change_cell_type" class="dropdown-submenu"><a href="#">Cell Type</a>
126 <ul class="dropdown-menu">
126 <ul class="dropdown-menu">
127 <li id="to_code"><a href="#">Code</a></li>
127 <li id="to_code"><a href="#">Code</a></li>
128 <li id="to_markdown"><a href="#">Markdown </a></li>
128 <li id="to_markdown"><a href="#">Markdown </a></li>
129 <li id="to_raw"><a href="#">Raw Text</a></li>
129 <li id="to_raw"><a href="#">Raw Text</a></li>
130 <li id="to_heading1"><a href="#">Heading 1</a></li>
130 <li id="to_heading1"><a href="#">Heading 1</a></li>
131 <li id="to_heading2"><a href="#">Heading 2</a></li>
131 <li id="to_heading2"><a href="#">Heading 2</a></li>
132 <li id="to_heading3"><a href="#">Heading 3</a></li>
132 <li id="to_heading3"><a href="#">Heading 3</a></li>
133 <li id="to_heading4"><a href="#">Heading 4</a></li>
133 <li id="to_heading4"><a href="#">Heading 4</a></li>
134 <li id="to_heading5"><a href="#">Heading 5</a></li>
134 <li id="to_heading5"><a href="#">Heading 5</a></li>
135 <li id="to_heading6"><a href="#">Heading 6</a></li>
135 <li id="to_heading6"><a href="#">Heading 6</a></li>
136 </ul>
136 </ul>
137 </li>
137 </li>
138 <li class="divider"></li>
138 <li class="divider"></li>
139 <li id="toggle_output"><a href="#">Toggle Current Output</a></li>
139 <li id="toggle_output"><a href="#">Toggle Current Output</a></li>
140 <li id="all_outputs" class="dropdown-submenu"><a href="#">All Output</a>
140 <li id="all_outputs" class="dropdown-submenu"><a href="#">All Output</a>
141 <ul class="dropdown-menu">
141 <ul class="dropdown-menu">
142 <li id="expand_all_output"><a href="#">Expand</a></li>
142 <li id="expand_all_output"><a href="#">Expand</a></li>
143 <li id="scroll_all_output"><a href="#">Scroll Long</a></li>
143 <li id="scroll_all_output"><a href="#">Scroll Long</a></li>
144 <li id="collapse_all_output"><a href="#">Collapse</a></li>
144 <li id="collapse_all_output"><a href="#">Collapse</a></li>
145 <li id="clear_all_output"><a href="#">Clear</a></li>
145 <li id="clear_all_output"><a href="#">Clear</a></li>
146 </ul>
146 </ul>
147 </li>
147 </li>
148 </ul>
148 </ul>
149 </li>
149 </li>
150 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Kernel</a>
150 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Kernel</a>
151 <ul class="dropdown-menu">
151 <ul class="dropdown-menu">
152 <li id="int_kernel"><a href="#">Interrupt</a></li>
152 <li id="int_kernel"><a href="#">Interrupt</a></li>
153 <li id="restart_kernel"><a href="#">Restart</a></li>
153 <li id="restart_kernel"><a href="#">Restart</a></li>
154 </ul>
154 </ul>
155 </li>
155 </li>
156 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Help</a>
156 <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Help</a>
157 <ul class="dropdown-menu">
157 <ul class="dropdown-menu">
158 <li><a href="http://ipython.org/documentation.html" target="_blank">IPython Help</a></li>
158 <li><a href="http://ipython.org/documentation.html" target="_blank">IPython Help</a></li>
159 <li><a href="http://ipython.org/ipython-doc/stable/interactive/htmlnotebook.html" target="_blank">Notebook Help</a></li>
159 <li><a href="http://ipython.org/ipython-doc/stable/interactive/notebook.html" target="_blank">Notebook Help</a></li>
160 <li id="keyboard_shortcuts"><a href="#">Keyboard Shortcuts</a></li>
160 <li id="keyboard_shortcuts"><a href="#">Keyboard Shortcuts</a></li>
161 <li class="divider"></li>
161 <li class="divider"></li>
162 <li><a href="http://docs.python.org" target="_blank">Python</a></li>
162 <li><a href="http://docs.python.org" target="_blank">Python</a></li>
163 <li><a href="http://docs.scipy.org/doc/numpy/reference/" target="_blank">NumPy</a></li>
163 <li><a href="http://docs.scipy.org/doc/numpy/reference/" target="_blank">NumPy</a></li>
164 <li><a href="http://docs.scipy.org/doc/scipy/reference/" target="_blank">SciPy</a></li>
164 <li><a href="http://docs.scipy.org/doc/scipy/reference/" target="_blank">SciPy</a></li>
165 <li><a href="http://matplotlib.org/" target="_blank">Matplotlib</a></li>
165 <li><a href="http://docs.sympy.org/dev/index.html" target="_blank">SymPy</a></li>
166 <li><a href="http://docs.sympy.org/dev/index.html" target="_blank">SymPy</a></li>
166 <li><a href="http://matplotlib.sourceforge.net/" target="_blank">Matplotlib</a></li>
167 <li><a href="http://pandas.pydata.org/pandas-docs/stable/" target="_blank">pandas</a></li>
167 </ul>
168 </ul>
168 </li>
169 </li>
169 </ul>
170 </ul>
170 <div id="notification_area"></div>
171 <div id="notification_area"></div>
171 </div>
172 </div>
172 </div>
173 </div>
173 </div>
174 </div>
174 </div>
175 </div>
175 <div id="maintoolbar" class="navbar">
176 <div id="maintoolbar" class="navbar">
176 <div class="toolbar-inner navbar-inner navbar-nobg">
177 <div class="toolbar-inner navbar-inner navbar-nobg">
177 <div id="maintoolbar-container" class="container"></div>
178 <div id="maintoolbar-container" class="container"></div>
178 </div>
179 </div>
179 </div>
180 </div>
180 </div>
181 </div>
181
182
182 <div id="ipython-main-app">
183 <div id="ipython-main-app">
183
184
184 <div id="notebook_panel">
185 <div id="notebook_panel">
185 <div id="notebook"></div>
186 <div id="notebook"></div>
186 <div id="pager_splitter"></div>
187 <div id="pager_splitter"></div>
187 <div id="pager">
188 <div id="pager">
188 <div id='pager_button_area'>
189 <div id='pager_button_area'>
189 </div>
190 </div>
190 <div id="pager-container" class="container"></div>
191 <div id="pager-container" class="container"></div>
191 </div>
192 </div>
192 </div>
193 </div>
193
194
194 </div>
195 </div>
195 <div id='tooltip' class='ipython_tooltip' style='display:none'></div>
196 <div id='tooltip' class='ipython_tooltip' style='display:none'></div>
196
197
197
198
198 {% endblock %}
199 {% endblock %}
199
200
200
201
201 {% block script %}
202 {% block script %}
202
203
203 {{super()}}
204 {{super()}}
204
205
205 <script src="{{ static_url("components/codemirror/lib/codemirror.js") }}" charset="utf-8"></script>
206 <script src="{{ static_url("components/codemirror/lib/codemirror.js") }}" charset="utf-8"></script>
206 <script type="text/javascript">
207 <script type="text/javascript">
207 CodeMirror.modeURL = "{{ static_url("components/codemirror/mode/%N/%N.js") }}";
208 CodeMirror.modeURL = "{{ static_url("components/codemirror/mode/%N/%N.js") }}";
208 </script>
209 </script>
209 <script src="{{ static_url("components/codemirror/addon/mode/loadmode.js") }}" charset="utf-8"></script>
210 <script src="{{ static_url("components/codemirror/addon/mode/loadmode.js") }}" charset="utf-8"></script>
210 <script src="{{ static_url("components/codemirror/addon/mode/multiplex.js") }}" charset="utf-8"></script>
211 <script src="{{ static_url("components/codemirror/addon/mode/multiplex.js") }}" charset="utf-8"></script>
211 <script src="{{ static_url("components/codemirror/addon/mode/overlay.js") }}" charset="utf-8"></script>
212 <script src="{{ static_url("components/codemirror/addon/mode/overlay.js") }}" charset="utf-8"></script>
212 <script src="{{ static_url("components/codemirror/addon/edit/matchbrackets.js") }}" charset="utf-8"></script>
213 <script src="{{ static_url("components/codemirror/addon/edit/matchbrackets.js") }}" charset="utf-8"></script>
213 <script src="{{ static_url("components/codemirror/addon/comment/comment.js") }}" charset="utf-8"></script>
214 <script src="{{ static_url("components/codemirror/addon/comment/comment.js") }}" charset="utf-8"></script>
214 <script src="{{ static_url("components/codemirror/mode/htmlmixed/htmlmixed.js") }}" charset="utf-8"></script>
215 <script src="{{ static_url("components/codemirror/mode/htmlmixed/htmlmixed.js") }}" charset="utf-8"></script>
215 <script src="{{ static_url("components/codemirror/mode/xml/xml.js") }}" charset="utf-8"></script>
216 <script src="{{ static_url("components/codemirror/mode/xml/xml.js") }}" charset="utf-8"></script>
216 <script src="{{ static_url("components/codemirror/mode/javascript/javascript.js") }}" charset="utf-8"></script>
217 <script src="{{ static_url("components/codemirror/mode/javascript/javascript.js") }}" charset="utf-8"></script>
217 <script src="{{ static_url("components/codemirror/mode/css/css.js") }}" charset="utf-8"></script>
218 <script src="{{ static_url("components/codemirror/mode/css/css.js") }}" charset="utf-8"></script>
218 <script src="{{ static_url("components/codemirror/mode/rst/rst.js") }}" charset="utf-8"></script>
219 <script src="{{ static_url("components/codemirror/mode/rst/rst.js") }}" charset="utf-8"></script>
219 <script src="{{ static_url("components/codemirror/mode/markdown/markdown.js") }}" charset="utf-8"></script>
220 <script src="{{ static_url("components/codemirror/mode/markdown/markdown.js") }}" charset="utf-8"></script>
220 <script src="{{ static_url("components/codemirror/mode/gfm/gfm.js") }}" charset="utf-8"></script>
221 <script src="{{ static_url("components/codemirror/mode/gfm/gfm.js") }}" charset="utf-8"></script>
221 <script src="{{ static_url("components/codemirror/mode/python/python.js") }}" charset="utf-8"></script>
222 <script src="{{ static_url("components/codemirror/mode/python/python.js") }}" charset="utf-8"></script>
222 <script src="{{ static_url("notebook/js/codemirror-ipython.js") }}" charset="utf-8"></script>
223 <script src="{{ static_url("notebook/js/codemirror-ipython.js") }}" charset="utf-8"></script>
223
224
224 <script src="{{ static_url("components/highlight.js/build/highlight.pack.js") }}" charset="utf-8"></script>
225 <script src="{{ static_url("components/highlight.js/build/highlight.pack.js") }}" charset="utf-8"></script>
225
226
226 <script src="{{ static_url("dateformat/date.format.js") }}" charset="utf-8"></script>
227 <script src="{{ static_url("dateformat/date.format.js") }}" charset="utf-8"></script>
227
228
228 <script src="{{ static_url("base/js/events.js") }}" type="text/javascript" charset="utf-8"></script>
229 <script src="{{ static_url("base/js/events.js") }}" type="text/javascript" charset="utf-8"></script>
229 <script src="{{ static_url("base/js/utils.js") }}" type="text/javascript" charset="utf-8"></script>
230 <script src="{{ static_url("base/js/utils.js") }}" type="text/javascript" charset="utf-8"></script>
230 <script src="{{ static_url("base/js/dialog.js") }}" type="text/javascript" charset="utf-8"></script>
231 <script src="{{ static_url("base/js/dialog.js") }}" type="text/javascript" charset="utf-8"></script>
231 <script src="{{ static_url("notebook/js/layoutmanager.js") }}" type="text/javascript" charset="utf-8"></script>
232 <script src="{{ static_url("notebook/js/layoutmanager.js") }}" type="text/javascript" charset="utf-8"></script>
232 <script src="{{ static_url("notebook/js/mathjaxutils.js") }}" type="text/javascript" charset="utf-8"></script>
233 <script src="{{ static_url("notebook/js/mathjaxutils.js") }}" type="text/javascript" charset="utf-8"></script>
233 <script src="{{ static_url("notebook/js/outputarea.js") }}" type="text/javascript" charset="utf-8"></script>
234 <script src="{{ static_url("notebook/js/outputarea.js") }}" type="text/javascript" charset="utf-8"></script>
234 <script src="{{ static_url("notebook/js/cell.js") }}" type="text/javascript" charset="utf-8"></script>
235 <script src="{{ static_url("notebook/js/cell.js") }}" type="text/javascript" charset="utf-8"></script>
235 <script src="{{ static_url("notebook/js/celltoolbar.js") }}" type="text/javascript" charset="utf-8"></script>
236 <script src="{{ static_url("notebook/js/celltoolbar.js") }}" type="text/javascript" charset="utf-8"></script>
236 <script src="{{ static_url("notebook/js/codecell.js") }}" type="text/javascript" charset="utf-8"></script>
237 <script src="{{ static_url("notebook/js/codecell.js") }}" type="text/javascript" charset="utf-8"></script>
237 <script src="{{ static_url("notebook/js/completer.js") }}" type="text/javascript" charset="utf-8"></script>
238 <script src="{{ static_url("notebook/js/completer.js") }}" type="text/javascript" charset="utf-8"></script>
238 <script src="{{ static_url("notebook/js/textcell.js") }}" type="text/javascript" charset="utf-8"></script>
239 <script src="{{ static_url("notebook/js/textcell.js") }}" type="text/javascript" charset="utf-8"></script>
239 <script src="{{ static_url("services/kernels/js/kernel.js") }}" type="text/javascript" charset="utf-8"></script>
240 <script src="{{ static_url("services/kernels/js/kernel.js") }}" type="text/javascript" charset="utf-8"></script>
240 <script src="{{ static_url("notebook/js/savewidget.js") }}" type="text/javascript" charset="utf-8"></script>
241 <script src="{{ static_url("notebook/js/savewidget.js") }}" type="text/javascript" charset="utf-8"></script>
241 <script src="{{ static_url("notebook/js/quickhelp.js") }}" type="text/javascript" charset="utf-8"></script>
242 <script src="{{ static_url("notebook/js/quickhelp.js") }}" type="text/javascript" charset="utf-8"></script>
242 <script src="{{ static_url("notebook/js/pager.js") }}" type="text/javascript" charset="utf-8"></script>
243 <script src="{{ static_url("notebook/js/pager.js") }}" type="text/javascript" charset="utf-8"></script>
243 <script src="{{ static_url("notebook/js/menubar.js") }}" type="text/javascript" charset="utf-8"></script>
244 <script src="{{ static_url("notebook/js/menubar.js") }}" type="text/javascript" charset="utf-8"></script>
244 <script src="{{ static_url("notebook/js/toolbar.js") }}" type="text/javascript" charset="utf-8"></script>
245 <script src="{{ static_url("notebook/js/toolbar.js") }}" type="text/javascript" charset="utf-8"></script>
245 <script src="{{ static_url("notebook/js/maintoolbar.js") }}" type="text/javascript" charset="utf-8"></script>
246 <script src="{{ static_url("notebook/js/maintoolbar.js") }}" type="text/javascript" charset="utf-8"></script>
246 <script src="{{ static_url("notebook/js/notebook.js") }}" type="text/javascript" charset="utf-8"></script>
247 <script src="{{ static_url("notebook/js/notebook.js") }}" type="text/javascript" charset="utf-8"></script>
247 <script src="{{ static_url("notebook/js/notificationwidget.js") }}" type="text/javascript" charset="utf-8"></script>
248 <script src="{{ static_url("notebook/js/notificationwidget.js") }}" type="text/javascript" charset="utf-8"></script>
248 <script src="{{ static_url("notebook/js/notificationarea.js") }}" type="text/javascript" charset="utf-8"></script>
249 <script src="{{ static_url("notebook/js/notificationarea.js") }}" type="text/javascript" charset="utf-8"></script>
249 <script src="{{ static_url("notebook/js/tooltip.js") }}" type="text/javascript" charset="utf-8"></script>
250 <script src="{{ static_url("notebook/js/tooltip.js") }}" type="text/javascript" charset="utf-8"></script>
250 <script src="{{ static_url("notebook/js/config.js") }}" type="text/javascript" charset="utf-8"></script>
251 <script src="{{ static_url("notebook/js/config.js") }}" type="text/javascript" charset="utf-8"></script>
251 <script src="{{ static_url("notebook/js/main.js") }}" type="text/javascript" charset="utf-8"></script>
252 <script src="{{ static_url("notebook/js/main.js") }}" type="text/javascript" charset="utf-8"></script>
252
253
253 <script src="{{ static_url("notebook/js/contexthint.js") }}" charset="utf-8"></script>
254 <script src="{{ static_url("notebook/js/contexthint.js") }}" charset="utf-8"></script>
254
255
255 <script src="{{ static_url("notebook/js/celltoolbarpresets/default.js") }}" type="text/javascript" charset="utf-8"></script>
256 <script src="{{ static_url("notebook/js/celltoolbarpresets/default.js") }}" type="text/javascript" charset="utf-8"></script>
256 <script src="{{ static_url("notebook/js/celltoolbarpresets/slideshow.js") }}" type="text/javascript" charset="utf-8"></script>
257 <script src="{{ static_url("notebook/js/celltoolbarpresets/slideshow.js") }}" type="text/javascript" charset="utf-8"></script>
257
258
258 {% endblock %}
259 {% endblock %}
@@ -1,610 +1,610 b''
1 .. _qtconsole:
1 .. _qtconsole:
2
2
3 =========================
3 =========================
4 A Qt Console for IPython
4 A Qt Console for IPython
5 =========================
5 =========================
6
6
7 We now have a version of IPython, using the new two-process :ref:`ZeroMQ Kernel
7 We now have a version of IPython, using the new two-process :ref:`ZeroMQ Kernel
8 <ipythonzmq>`, running in a PyQt_ GUI. This is a very lightweight widget that
8 <ipythonzmq>`, running in a PyQt_ GUI. This is a very lightweight widget that
9 largely feels like a terminal, but provides a number of enhancements only
9 largely feels like a terminal, but provides a number of enhancements only
10 possible in a GUI, such as inline figures, proper multiline editing with syntax
10 possible in a GUI, such as inline figures, proper multiline editing with syntax
11 highlighting, graphical calltips, and much more.
11 highlighting, graphical calltips, and much more.
12
12
13 .. figure:: ../../_images/qtconsole.png
13 .. figure:: ../../_images/qtconsole.png
14 :width: 400px
14 :width: 400px
15 :alt: IPython Qt console with embedded plots
15 :alt: IPython Qt console with embedded plots
16 :align: center
16 :align: center
17 :target: ../_images/qtconsole.png
17 :target: ../_images/qtconsole.png
18
18
19 The Qt console for IPython, using inline matplotlib plots.
19 The Qt console for IPython, using inline matplotlib plots.
20
20
21 To get acquainted with the Qt console, type `%guiref` to see a quick
21 To get acquainted with the Qt console, type `%guiref` to see a quick
22 introduction of its main features.
22 introduction of its main features.
23
23
24 The Qt frontend has hand-coded emacs-style bindings for text navigation. This
24 The Qt frontend has hand-coded emacs-style bindings for text navigation. This
25 is not yet configurable.
25 is not yet configurable.
26
26
27 .. tip::
27 .. tip::
28
28
29 Since the Qt console tries hard to behave like a terminal, by default it
29 Since the Qt console tries hard to behave like a terminal, by default it
30 immediately executes single lines of input that are complete. If you want
30 immediately executes single lines of input that are complete. If you want
31 to force multiline input, hit :kbd:`Ctrl-Enter` at the end of the first line
31 to force multiline input, hit :kbd:`Ctrl-Enter` at the end of the first line
32 instead of :kbd:`Enter`, and it will open a new line for input. At any
32 instead of :kbd:`Enter`, and it will open a new line for input. At any
33 point in a multiline block, you can force its execution (without having to
33 point in a multiline block, you can force its execution (without having to
34 go to the bottom) with :kbd:`Shift-Enter`.
34 go to the bottom) with :kbd:`Shift-Enter`.
35
35
36 ``%load``
36 ``%load``
37 =========
37 =========
38
38
39 The new ``%load`` magic (previously ``%loadpy``) takes any script, and pastes
39 The new ``%load`` magic (previously ``%loadpy``) takes any script, and pastes
40 its contents as your next input, so you can edit it before executing. The
40 its contents as your next input, so you can edit it before executing. The
41 script may be on your machine, but you can also specify an history range, or a
41 script may be on your machine, but you can also specify an history range, or a
42 url, and it will download the script from the web. This is particularly useful
42 url, and it will download the script from the web. This is particularly useful
43 for playing with examples from documentation, such as matplotlib.
43 for playing with examples from documentation, such as matplotlib.
44
44
45 .. sourcecode:: ipython
45 .. sourcecode:: ipython
46
46
47 In [6]: %load http://matplotlib.sourceforge.net/plot_directive/mpl_examples/mplot3d/contour3d_demo.py
47 In [6]: %load http://matplotlib.org/plot_directive/mpl_examples/mplot3d/contour3d_demo.py
48
48
49 In [7]: from mpl_toolkits.mplot3d import axes3d
49 In [7]: from mpl_toolkits.mplot3d import axes3d
50 ...: import matplotlib.pyplot as plt
50 ...: import matplotlib.pyplot as plt
51 ...:
51 ...:
52 ...: fig = plt.figure()
52 ...: fig = plt.figure()
53 ...: ax = fig.add_subplot(111, projection='3d')
53 ...: ax = fig.add_subplot(111, projection='3d')
54 ...: X, Y, Z = axes3d.get_test_data(0.05)
54 ...: X, Y, Z = axes3d.get_test_data(0.05)
55 ...: cset = ax.contour(X, Y, Z)
55 ...: cset = ax.contour(X, Y, Z)
56 ...: ax.clabel(cset, fontsize=9, inline=1)
56 ...: ax.clabel(cset, fontsize=9, inline=1)
57 ...:
57 ...:
58 ...: plt.show()
58 ...: plt.show()
59
59
60 Inline Matplotlib
60 Inline Matplotlib
61 =================
61 =================
62
62
63 One of the most exciting features of the QtConsole is embedded matplotlib
63 One of the most exciting features of the QtConsole is embedded matplotlib
64 figures. You can use any standard matplotlib GUI backend
64 figures. You can use any standard matplotlib GUI backend
65 to draw the figures, and since there is now a two-process model, there is no
65 to draw the figures, and since there is now a two-process model, there is no
66 longer a conflict between user input and the drawing eventloop.
66 longer a conflict between user input and the drawing eventloop.
67
67
68 .. image:: figs/besselj.png
68 .. image:: figs/besselj.png
69 :width: 519px
69 :width: 519px
70
70
71 .. _display:
71 .. _display:
72
72
73 :func:`display`
73 :func:`display`
74 ***************
74 ***************
75
75
76 IPython provides a function :func:`display` for displaying rich representations
76 IPython provides a function :func:`display` for displaying rich representations
77 of objects if they are available. The IPython display
77 of objects if they are available. The IPython display
78 system provides a mechanism for specifying PNG or SVG (and more)
78 system provides a mechanism for specifying PNG or SVG (and more)
79 representations of objects for GUI frontends.
79 representations of objects for GUI frontends.
80 When you enable matplotlib integration via the ``%matplotlib`` magic, IPython registers
80 When you enable matplotlib integration via the ``%matplotlib`` magic, IPython registers
81 convenient PNG and SVG renderers for matplotlib figures, so you can embed them
81 convenient PNG and SVG renderers for matplotlib figures, so you can embed them
82 in your document by calling :func:`display` on one or more of them. This is
82 in your document by calling :func:`display` on one or more of them. This is
83 especially useful for saving_ your work.
83 especially useful for saving_ your work.
84
84
85 .. sourcecode:: ipython
85 .. sourcecode:: ipython
86
86
87 In [4]: from IPython.display import display
87 In [4]: from IPython.display import display
88
88
89 In [5]: plt.plot(range(5)) # plots in the matplotlib window
89 In [5]: plt.plot(range(5)) # plots in the matplotlib window
90
90
91 In [6]: display(plt.gcf()) # embeds the current figure in the qtconsole
91 In [6]: display(plt.gcf()) # embeds the current figure in the qtconsole
92
92
93 In [7]: display(*getfigs()) # embeds all active figures in the qtconsole
93 In [7]: display(*getfigs()) # embeds all active figures in the qtconsole
94
94
95 If you have a reference to a matplotlib figure object, you can always display
95 If you have a reference to a matplotlib figure object, you can always display
96 that specific figure:
96 that specific figure:
97
97
98 .. sourcecode:: ipython
98 .. sourcecode:: ipython
99
99
100 In [1]: f = plt.figure()
100 In [1]: f = plt.figure()
101
101
102 In [2]: plt.plot(np.rand(100))
102 In [2]: plt.plot(np.rand(100))
103 Out[2]: [<matplotlib.lines.Line2D at 0x7fc6ac03dd90>]
103 Out[2]: [<matplotlib.lines.Line2D at 0x7fc6ac03dd90>]
104
104
105 In [3]: display(f)
105 In [3]: display(f)
106
106
107 # Plot is shown here
107 # Plot is shown here
108
108
109 In [4]: plt.title('A title')
109 In [4]: plt.title('A title')
110 Out[4]: <matplotlib.text.Text at 0x7fc6ac023450>
110 Out[4]: <matplotlib.text.Text at 0x7fc6ac023450>
111
111
112 In [5]: display(f)
112 In [5]: display(f)
113
113
114 # Updated plot with title is shown here.
114 # Updated plot with title is shown here.
115
115
116 .. _inline:
116 .. _inline:
117
117
118 ``--matplotlib inline``
118 ``--matplotlib inline``
119 ***********************
119 ***********************
120
120
121 If you want to have all of your figures embedded in your session, instead of
121 If you want to have all of your figures embedded in your session, instead of
122 calling :func:`display`, you can specify ``--matplotlib inline`` when you start the
122 calling :func:`display`, you can specify ``--matplotlib inline`` when you start the
123 console, and each time you make a plot, it will show up in your document, as if
123 console, and each time you make a plot, it will show up in your document, as if
124 you had called :func:`display(fig)`.
124 you had called :func:`display(fig)`.
125
125
126 The inline backend can use either SVG or PNG figures (PNG being the default).
126 The inline backend can use either SVG or PNG figures (PNG being the default).
127 It also supports the special key ``'retina'``, which is 2x PNG for high-DPI displays.
127 It also supports the special key ``'retina'``, which is 2x PNG for high-DPI displays.
128 To switch between them, set the ``InlineBackend.figure_format`` configurable
128 To switch between them, set the ``InlineBackend.figure_format`` configurable
129 in a config file, or via the ``%config`` magic:
129 in a config file, or via the ``%config`` magic:
130
130
131 .. sourcecode:: ipython
131 .. sourcecode:: ipython
132
132
133 In [10]: %config InlineBackend.figure_format = 'svg'
133 In [10]: %config InlineBackend.figure_format = 'svg'
134
134
135 .. note::
135 .. note::
136
136
137 Changing the inline figure format also affects calls to :func:`display` above,
137 Changing the inline figure format also affects calls to :func:`display` above,
138 even if you are not using the inline backend for all figures.
138 even if you are not using the inline backend for all figures.
139
139
140 By default, IPython closes all figures at the completion of each execution. This means you
140 By default, IPython closes all figures at the completion of each execution. This means you
141 don't have to manually close figures, which is less convenient when figures aren't attached
141 don't have to manually close figures, which is less convenient when figures aren't attached
142 to windows with an obvious close button. It also means that the first matplotlib call in
142 to windows with an obvious close button. It also means that the first matplotlib call in
143 each cell will always create a new figure:
143 each cell will always create a new figure:
144
144
145 .. sourcecode:: ipython
145 .. sourcecode:: ipython
146
146
147 In [11]: plt.plot(range(100))
147 In [11]: plt.plot(range(100))
148 <single-line plot>
148 <single-line plot>
149
149
150 In [12]: plt.plot([1,3,2])
150 In [12]: plt.plot([1,3,2])
151 <another single-line plot>
151 <another single-line plot>
152
152
153
153
154 However, it does prevent the list of active figures surviving from one input cell to the
154 However, it does prevent the list of active figures surviving from one input cell to the
155 next, so if you want to continue working with a figure, you must hold on to a reference to
155 next, so if you want to continue working with a figure, you must hold on to a reference to
156 it:
156 it:
157
157
158 .. sourcecode:: ipython
158 .. sourcecode:: ipython
159
159
160 In [11]: fig = gcf()
160 In [11]: fig = gcf()
161 ....: fig.plot(rand(100))
161 ....: fig.plot(rand(100))
162 <plot>
162 <plot>
163 In [12]: fig.title('Random Title')
163 In [12]: fig.title('Random Title')
164 <redraw plot with title>
164 <redraw plot with title>
165
165
166 This behavior is controlled by the :attr:`InlineBackend.close_figures` configurable, and
166 This behavior is controlled by the :attr:`InlineBackend.close_figures` configurable, and
167 if you set it to False, via %config or config file, then IPython will *not* close figures,
167 if you set it to False, via %config or config file, then IPython will *not* close figures,
168 and tools like :func:`gcf`, :func:`gca`, :func:`getfigs` will behave the same as they
168 and tools like :func:`gcf`, :func:`gca`, :func:`getfigs` will behave the same as they
169 do with other backends. You will, however, have to manually close figures:
169 do with other backends. You will, however, have to manually close figures:
170
170
171 .. sourcecode:: ipython
171 .. sourcecode:: ipython
172
172
173 # close all active figures:
173 # close all active figures:
174 In [13]: [ fig.close() for fig in getfigs() ]
174 In [13]: [ fig.close() for fig in getfigs() ]
175
175
176
176
177
177
178 .. _saving:
178 .. _saving:
179
179
180 Saving and Printing
180 Saving and Printing
181 ===================
181 ===================
182
182
183 IPythonQt has the ability to save your current session, as either HTML or
183 IPythonQt has the ability to save your current session, as either HTML or
184 XHTML. If you have been using :func:`display` or inline_ matplotlib, your figures
184 XHTML. If you have been using :func:`display` or inline_ matplotlib, your figures
185 will be PNG in HTML, or inlined as SVG in XHTML. PNG images have the option to
185 will be PNG in HTML, or inlined as SVG in XHTML. PNG images have the option to
186 be either in an external folder, as in many browsers' "Webpage, Complete"
186 be either in an external folder, as in many browsers' "Webpage, Complete"
187 option, or inlined as well, for a larger, but more portable file.
187 option, or inlined as well, for a larger, but more portable file.
188
188
189 .. note::
189 .. note::
190
190
191 Export to SVG+XHTML requires that you are using SVG figures, which is *not*
191 Export to SVG+XHTML requires that you are using SVG figures, which is *not*
192 the default. To switch the inline figure format to use SVG during an active
192 the default. To switch the inline figure format to use SVG during an active
193 session, do:
193 session, do:
194
194
195 .. sourcecode:: ipython
195 .. sourcecode:: ipython
196
196
197 In [10]: %config InlineBackend.figure_format = 'svg'
197 In [10]: %config InlineBackend.figure_format = 'svg'
198
198
199 Or, you can add the same line (c.Inline... instead of %config Inline...) to
199 Or, you can add the same line (c.Inline... instead of %config Inline...) to
200 your config files.
200 your config files.
201
201
202 This will only affect figures plotted after making this call
202 This will only affect figures plotted after making this call
203
203
204
204
205 The widget also exposes the ability to print directly, via the default print
205 The widget also exposes the ability to print directly, via the default print
206 shortcut or context menu.
206 shortcut or context menu.
207
207
208
208
209 .. Note::
209 .. Note::
210
210
211 Saving is only available to richtext Qt widgets, which are used by default,
211 Saving is only available to richtext Qt widgets, which are used by default,
212 but if you pass the ``--plain`` flag, saving will not be available to you.
212 but if you pass the ``--plain`` flag, saving will not be available to you.
213
213
214
214
215 See these examples of :download:`png/html<figs/jn.html>` and
215 See these examples of :download:`png/html<figs/jn.html>` and
216 :download:`svg/xhtml <figs/jn.xhtml>` output. Note that syntax highlighting
216 :download:`svg/xhtml <figs/jn.xhtml>` output. Note that syntax highlighting
217 does not survive export. This is a known issue, and is being investigated.
217 does not survive export. This is a known issue, and is being investigated.
218
218
219
219
220 Colors and Highlighting
220 Colors and Highlighting
221 =======================
221 =======================
222
222
223 Terminal IPython has always had some coloring, but never syntax
223 Terminal IPython has always had some coloring, but never syntax
224 highlighting. There are a few simple color choices, specified by the ``colors``
224 highlighting. There are a few simple color choices, specified by the ``colors``
225 flag or ``%colors`` magic:
225 flag or ``%colors`` magic:
226
226
227 * LightBG for light backgrounds
227 * LightBG for light backgrounds
228 * Linux for dark backgrounds
228 * Linux for dark backgrounds
229 * NoColor for a simple colorless terminal
229 * NoColor for a simple colorless terminal
230
230
231 The Qt widget has full support for the ``colors`` flag used in the terminal shell.
231 The Qt widget has full support for the ``colors`` flag used in the terminal shell.
232
232
233 The Qt widget, however, has full syntax highlighting as you type, handled by
233 The Qt widget, however, has full syntax highlighting as you type, handled by
234 the `pygments`_ library. The ``style`` argument exposes access to any style by
234 the `pygments`_ library. The ``style`` argument exposes access to any style by
235 name that can be found by pygments, and there are several already
235 name that can be found by pygments, and there are several already
236 installed. The ``colors`` argument, if unspecified, will be guessed based on
236 installed. The ``colors`` argument, if unspecified, will be guessed based on
237 the chosen style. Similarly, there are default styles associated with each
237 the chosen style. Similarly, there are default styles associated with each
238 ``colors`` option.
238 ``colors`` option.
239
239
240
240
241 Screenshot of ``ipython qtconsole --colors=linux``, which uses the 'monokai'
241 Screenshot of ``ipython qtconsole --colors=linux``, which uses the 'monokai'
242 theme by default:
242 theme by default:
243
243
244 .. image:: figs/colors_dark.png
244 .. image:: figs/colors_dark.png
245 :width: 627px
245 :width: 627px
246
246
247 .. Note::
247 .. Note::
248
248
249 Calling ``ipython qtconsole -h`` will show all the style names that
249 Calling ``ipython qtconsole -h`` will show all the style names that
250 pygments can find on your system.
250 pygments can find on your system.
251
251
252 You can also pass the filename of a custom CSS stylesheet, if you want to do
252 You can also pass the filename of a custom CSS stylesheet, if you want to do
253 your own coloring, via the ``stylesheet`` argument. The default LightBG
253 your own coloring, via the ``stylesheet`` argument. The default LightBG
254 stylesheet:
254 stylesheet:
255
255
256 .. sourcecode:: css
256 .. sourcecode:: css
257
257
258 QPlainTextEdit, QTextEdit { background-color: white;
258 QPlainTextEdit, QTextEdit { background-color: white;
259 color: black ;
259 color: black ;
260 selection-background-color: #ccc}
260 selection-background-color: #ccc}
261 .error { color: red; }
261 .error { color: red; }
262 .in-prompt { color: navy; }
262 .in-prompt { color: navy; }
263 .in-prompt-number { font-weight: bold; }
263 .in-prompt-number { font-weight: bold; }
264 .out-prompt { color: darkred; }
264 .out-prompt { color: darkred; }
265 .out-prompt-number { font-weight: bold; }
265 .out-prompt-number { font-weight: bold; }
266 /* .inverted is used to highlight selected completion */
266 /* .inverted is used to highlight selected completion */
267 .inverted { background-color: black ; color: white; }
267 .inverted { background-color: black ; color: white; }
268
268
269 Fonts
269 Fonts
270 =====
270 =====
271
271
272 The QtConsole has configurable via the ConsoleWidget. To change these, set the
272 The QtConsole has configurable via the ConsoleWidget. To change these, set the
273 ``font_family`` or ``font_size`` traits of the ConsoleWidget. For instance, to
273 ``font_family`` or ``font_size`` traits of the ConsoleWidget. For instance, to
274 use 9pt Anonymous Pro::
274 use 9pt Anonymous Pro::
275
275
276 $> ipython qtconsole --ConsoleWidget.font_family="Anonymous Pro" --ConsoleWidget.font_size=9
276 $> ipython qtconsole --ConsoleWidget.font_family="Anonymous Pro" --ConsoleWidget.font_size=9
277
277
278 Process Management
278 Process Management
279 ==================
279 ==================
280
280
281 With the two-process ZMQ model, the frontend does not block input during
281 With the two-process ZMQ model, the frontend does not block input during
282 execution. This means that actions can be taken by the frontend while the
282 execution. This means that actions can be taken by the frontend while the
283 Kernel is executing, or even after it crashes. The most basic such command is
283 Kernel is executing, or even after it crashes. The most basic such command is
284 via 'Ctrl-.', which restarts the kernel. This can be done in the middle of a
284 via 'Ctrl-.', which restarts the kernel. This can be done in the middle of a
285 blocking execution. The frontend can also know, via a heartbeat mechanism, that
285 blocking execution. The frontend can also know, via a heartbeat mechanism, that
286 the kernel has died. This means that the frontend can safely restart the
286 the kernel has died. This means that the frontend can safely restart the
287 kernel.
287 kernel.
288
288
289 .. _multiple_consoles:
289 .. _multiple_consoles:
290
290
291 Multiple Consoles
291 Multiple Consoles
292 *****************
292 *****************
293
293
294 Since the Kernel listens on the network, multiple frontends can connect to it.
294 Since the Kernel listens on the network, multiple frontends can connect to it.
295 These do not have to all be qt frontends - any IPython frontend can connect and
295 These do not have to all be qt frontends - any IPython frontend can connect and
296 run code. When you start ipython qtconsole, there will be an output line,
296 run code. When you start ipython qtconsole, there will be an output line,
297 like::
297 like::
298
298
299 [IPKernelApp] To connect another client to this kernel, use:
299 [IPKernelApp] To connect another client to this kernel, use:
300 [IPKernelApp] --existing kernel-12345.json
300 [IPKernelApp] --existing kernel-12345.json
301
301
302 Other frontends can connect to your kernel, and share in the execution. This is
302 Other frontends can connect to your kernel, and share in the execution. This is
303 great for collaboration. The ``--existing`` flag means connect to a kernel
303 great for collaboration. The ``--existing`` flag means connect to a kernel
304 that already exists. Starting other consoles
304 that already exists. Starting other consoles
305 with that flag will not try to start their own kernel, but rather connect to
305 with that flag will not try to start their own kernel, but rather connect to
306 yours. :file:`kernel-12345.json` is a small JSON file with the ip, port, and
306 yours. :file:`kernel-12345.json` is a small JSON file with the ip, port, and
307 authentication information necessary to connect to your kernel. By default, this file
307 authentication information necessary to connect to your kernel. By default, this file
308 will be in your default profile's security directory. If it is somewhere else,
308 will be in your default profile's security directory. If it is somewhere else,
309 the output line will print the full path of the connection file, rather than
309 the output line will print the full path of the connection file, rather than
310 just its filename.
310 just its filename.
311
311
312 If you need to find the connection info to send, and don't know where your connection file
312 If you need to find the connection info to send, and don't know where your connection file
313 lives, there are a couple of ways to get it. If you are already running an IPython console
313 lives, there are a couple of ways to get it. If you are already running an IPython console
314 connected to the kernel, you can use the ``%connect_info`` magic to display the information
314 connected to the kernel, you can use the ``%connect_info`` magic to display the information
315 necessary to connect another frontend to the kernel.
315 necessary to connect another frontend to the kernel.
316
316
317 .. sourcecode:: ipython
317 .. sourcecode:: ipython
318
318
319 In [2]: %connect_info
319 In [2]: %connect_info
320 {
320 {
321 "stdin_port":50255,
321 "stdin_port":50255,
322 "ip":"127.0.0.1",
322 "ip":"127.0.0.1",
323 "hb_port":50256,
323 "hb_port":50256,
324 "key":"70be6f0f-1564-4218-8cda-31be40a4d6aa",
324 "key":"70be6f0f-1564-4218-8cda-31be40a4d6aa",
325 "shell_port":50253,
325 "shell_port":50253,
326 "iopub_port":50254
326 "iopub_port":50254
327 }
327 }
328
328
329 Paste the above JSON into a file, and connect with:
329 Paste the above JSON into a file, and connect with:
330 $> ipython <app> --existing <file>
330 $> ipython <app> --existing <file>
331 or, if you are local, you can connect with just:
331 or, if you are local, you can connect with just:
332 $> ipython <app> --existing kernel-12345.json
332 $> ipython <app> --existing kernel-12345.json
333 or even just:
333 or even just:
334 $> ipython <app> --existing
334 $> ipython <app> --existing
335 if this is the most recent IPython session you have started.
335 if this is the most recent IPython session you have started.
336
336
337 Otherwise, you can find a connection file by name (and optionally profile) with
337 Otherwise, you can find a connection file by name (and optionally profile) with
338 :func:`IPython.lib.kernel.find_connection_file`:
338 :func:`IPython.lib.kernel.find_connection_file`:
339
339
340 .. sourcecode:: bash
340 .. sourcecode:: bash
341
341
342 $> python -c "from IPython.lib.kernel import find_connection_file;\
342 $> python -c "from IPython.lib.kernel import find_connection_file;\
343 print find_connection_file('kernel-12345.json')"
343 print find_connection_file('kernel-12345.json')"
344 /home/you/.ipython/profile_default/security/kernel-12345.json
344 /home/you/.ipython/profile_default/security/kernel-12345.json
345
345
346 And if you are using a particular IPython profile:
346 And if you are using a particular IPython profile:
347
347
348 .. sourcecode:: bash
348 .. sourcecode:: bash
349
349
350 $> python -c "from IPython.lib.kernel import find_connection_file;\
350 $> python -c "from IPython.lib.kernel import find_connection_file;\
351 print find_connection_file('kernel-12345.json', profile='foo')"
351 print find_connection_file('kernel-12345.json', profile='foo')"
352 /home/you/.ipython/profile_foo/security/kernel-12345.json
352 /home/you/.ipython/profile_foo/security/kernel-12345.json
353
353
354 You can even launch a standalone kernel, and connect and disconnect Qt Consoles
354 You can even launch a standalone kernel, and connect and disconnect Qt Consoles
355 from various machines. This lets you keep the same running IPython session
355 from various machines. This lets you keep the same running IPython session
356 on your work machine (with matplotlib plots and everything), logging in from home,
356 on your work machine (with matplotlib plots and everything), logging in from home,
357 cafΓ©s, etc.::
357 cafΓ©s, etc.::
358
358
359 $> ipython kernel
359 $> ipython kernel
360 [IPKernelApp] To connect another client to this kernel, use:
360 [IPKernelApp] To connect another client to this kernel, use:
361 [IPKernelApp] --existing kernel-12345.json
361 [IPKernelApp] --existing kernel-12345.json
362
362
363 This is actually exactly the same as the subprocess launched by the qtconsole, so
363 This is actually exactly the same as the subprocess launched by the qtconsole, so
364 all the information about connecting to a standalone kernel is identical to that
364 all the information about connecting to a standalone kernel is identical to that
365 of connecting to the kernel attached to a running console.
365 of connecting to the kernel attached to a running console.
366
366
367 .. _kernel_security:
367 .. _kernel_security:
368
368
369 Security
369 Security
370 --------
370 --------
371
371
372 .. warning::
372 .. warning::
373
373
374 Since the ZMQ code currently has no encryption, listening on an
374 Since the ZMQ code currently has no encryption, listening on an
375 external-facing IP is dangerous. You are giving any computer that can see
375 external-facing IP is dangerous. You are giving any computer that can see
376 you on the network the ability to connect to your kernel, and view your traffic.
376 you on the network the ability to connect to your kernel, and view your traffic.
377 Read the rest of this section before listening on external ports
377 Read the rest of this section before listening on external ports
378 or running an IPython kernel on a shared machine.
378 or running an IPython kernel on a shared machine.
379
379
380 By default (for security reasons), the kernel only listens on localhost, so you
380 By default (for security reasons), the kernel only listens on localhost, so you
381 can only connect multiple frontends to the kernel from your local machine. You
381 can only connect multiple frontends to the kernel from your local machine. You
382 can specify to listen on an external interface by specifying the ``ip``
382 can specify to listen on an external interface by specifying the ``ip``
383 argument::
383 argument::
384
384
385 $> ipython qtconsole --ip=192.168.1.123
385 $> ipython qtconsole --ip=192.168.1.123
386
386
387 If you specify the ip as 0.0.0.0 or '*', that means all interfaces, so any
387 If you specify the ip as 0.0.0.0 or '*', that means all interfaces, so any
388 computer that can see yours on the network can connect to the kernel.
388 computer that can see yours on the network can connect to the kernel.
389
389
390 Messages are not encrypted, so users with access to the ports your kernel is using will be
390 Messages are not encrypted, so users with access to the ports your kernel is using will be
391 able to see any output of the kernel. They will **NOT** be able to issue shell commands as
391 able to see any output of the kernel. They will **NOT** be able to issue shell commands as
392 you due to message signatures, which are enabled by default as of IPython 0.12.
392 you due to message signatures, which are enabled by default as of IPython 0.12.
393
393
394 .. warning::
394 .. warning::
395
395
396 If you disable message signatures, then any user with access to the ports your
396 If you disable message signatures, then any user with access to the ports your
397 kernel is listening on can issue arbitrary code as you. **DO NOT** disable message
397 kernel is listening on can issue arbitrary code as you. **DO NOT** disable message
398 signatures unless you have a lot of trust in your environment.
398 signatures unless you have a lot of trust in your environment.
399
399
400 The one security feature IPython does provide is protection from unauthorized execution.
400 The one security feature IPython does provide is protection from unauthorized execution.
401 IPython's messaging system will sign messages with HMAC digests using a shared-key. The key
401 IPython's messaging system will sign messages with HMAC digests using a shared-key. The key
402 is never sent over the network, it is only used to generate a unique hash for each message,
402 is never sent over the network, it is only used to generate a unique hash for each message,
403 based on its content. When IPython receives a message, it will check that the digest
403 based on its content. When IPython receives a message, it will check that the digest
404 matches, and discard the message. You can use any file that only you have access to to
404 matches, and discard the message. You can use any file that only you have access to to
405 generate this key, but the default is just to generate a new UUID. You can generate a random
405 generate this key, but the default is just to generate a new UUID. You can generate a random
406 private key with::
406 private key with::
407
407
408 # generate 1024b of random data, and store in a file only you can read:
408 # generate 1024b of random data, and store in a file only you can read:
409 # (assumes IPYTHONDIR is defined, otherwise use your IPython directory)
409 # (assumes IPYTHONDIR is defined, otherwise use your IPython directory)
410 $> python -c "import os; print os.urandom(128).encode('base64')" > $IPYTHONDIR/sessionkey
410 $> python -c "import os; print os.urandom(128).encode('base64')" > $IPYTHONDIR/sessionkey
411 $> chmod 600 $IPYTHONDIR/sessionkey
411 $> chmod 600 $IPYTHONDIR/sessionkey
412
412
413 The *contents* of this file will be stored in the JSON connection file, so that file
413 The *contents* of this file will be stored in the JSON connection file, so that file
414 contains everything you need to connect to and use a kernel.
414 contains everything you need to connect to and use a kernel.
415
415
416 To use this generated key, simply specify the ``Session.keyfile`` configurable
416 To use this generated key, simply specify the ``Session.keyfile`` configurable
417 in :file:`ipython_config.py` or at the command-line, as in::
417 in :file:`ipython_config.py` or at the command-line, as in::
418
418
419 # instruct IPython to sign messages with that key, instead of a new UUID
419 # instruct IPython to sign messages with that key, instead of a new UUID
420 $> ipython qtconsole --Session.keyfile=$IPYTHONDIR/sessionkey
420 $> ipython qtconsole --Session.keyfile=$IPYTHONDIR/sessionkey
421
421
422 .. _ssh_tunnels:
422 .. _ssh_tunnels:
423
423
424 SSH Tunnels
424 SSH Tunnels
425 -----------
425 -----------
426
426
427 Sometimes you want to connect to machines across the internet, or just across
427 Sometimes you want to connect to machines across the internet, or just across
428 a LAN that either doesn't permit open ports or you don't trust the other
428 a LAN that either doesn't permit open ports or you don't trust the other
429 machines on the network. To do this, you can use SSH tunnels. SSH tunnels
429 machines on the network. To do this, you can use SSH tunnels. SSH tunnels
430 are a way to securely forward ports on your local machine to ports on another
430 are a way to securely forward ports on your local machine to ports on another
431 machine, to which you have SSH access.
431 machine, to which you have SSH access.
432
432
433 In simple cases, IPython's tools can forward ports over ssh by simply adding the
433 In simple cases, IPython's tools can forward ports over ssh by simply adding the
434 ``--ssh=remote`` argument to the usual ``--existing...`` set of flags for connecting
434 ``--ssh=remote`` argument to the usual ``--existing...`` set of flags for connecting
435 to a running kernel, after copying the JSON connection file (or its contents) to
435 to a running kernel, after copying the JSON connection file (or its contents) to
436 the second computer.
436 the second computer.
437
437
438 .. warning::
438 .. warning::
439
439
440 Using SSH tunnels does *not* increase localhost security. In fact, when
440 Using SSH tunnels does *not* increase localhost security. In fact, when
441 tunneling from one machine to another *both* machines have open
441 tunneling from one machine to another *both* machines have open
442 ports on localhost available for connections to the kernel.
442 ports on localhost available for connections to the kernel.
443
443
444 There are two primary models for using SSH tunnels with IPython. The first
444 There are two primary models for using SSH tunnels with IPython. The first
445 is to have the Kernel listen only on localhost, and connect to it from
445 is to have the Kernel listen only on localhost, and connect to it from
446 another machine on the same LAN.
446 another machine on the same LAN.
447
447
448 First, let's start a kernel on machine **worker**, listening only
448 First, let's start a kernel on machine **worker**, listening only
449 on loopback::
449 on loopback::
450
450
451 user@worker $> ipython kernel
451 user@worker $> ipython kernel
452 [IPKernelApp] To connect another client to this kernel, use:
452 [IPKernelApp] To connect another client to this kernel, use:
453 [IPKernelApp] --existing kernel-12345.json
453 [IPKernelApp] --existing kernel-12345.json
454
454
455 In this case, the IP that you would connect
455 In this case, the IP that you would connect
456 to would still be 127.0.0.1, but you want to specify the additional ``--ssh`` argument
456 to would still be 127.0.0.1, but you want to specify the additional ``--ssh`` argument
457 with the hostname of the kernel (in this example, it's 'worker')::
457 with the hostname of the kernel (in this example, it's 'worker')::
458
458
459 user@client $> ipython qtconsole --ssh=worker --existing /path/to/kernel-12345.json
459 user@client $> ipython qtconsole --ssh=worker --existing /path/to/kernel-12345.json
460
460
461 Which will write a new connection file with the forwarded ports, so you can reuse them::
461 Which will write a new connection file with the forwarded ports, so you can reuse them::
462
462
463 [IPythonQtConsoleApp] To connect another client via this tunnel, use:
463 [IPythonQtConsoleApp] To connect another client via this tunnel, use:
464 [IPythonQtConsoleApp] --existing kernel-12345-ssh.json
464 [IPythonQtConsoleApp] --existing kernel-12345-ssh.json
465
465
466 Note again that this opens ports on the *client* machine that point to your kernel.
466 Note again that this opens ports on the *client* machine that point to your kernel.
467
467
468 .. note::
468 .. note::
469
469
470 the ssh argument is simply passed to openssh, so it can be fully specified ``user@host:port``
470 the ssh argument is simply passed to openssh, so it can be fully specified ``user@host:port``
471 but it will also respect your aliases, etc. in :file:`.ssh/config` if you have any.
471 but it will also respect your aliases, etc. in :file:`.ssh/config` if you have any.
472
472
473 The second pattern is for connecting to a machine behind a firewall across the internet
473 The second pattern is for connecting to a machine behind a firewall across the internet
474 (or otherwise wide network). This time, we have a machine **login** that you have ssh access
474 (or otherwise wide network). This time, we have a machine **login** that you have ssh access
475 to, which can see **kernel**, but **client** is on another network. The important difference
475 to, which can see **kernel**, but **client** is on another network. The important difference
476 now is that **client** can see **login**, but *not* **worker**. So we need to forward ports from
476 now is that **client** can see **login**, but *not* **worker**. So we need to forward ports from
477 client to worker *via* login. This means that the kernel must be started listening
477 client to worker *via* login. This means that the kernel must be started listening
478 on external interfaces, so that its ports are visible to `login`::
478 on external interfaces, so that its ports are visible to `login`::
479
479
480 user@worker $> ipython kernel --ip=0.0.0.0
480 user@worker $> ipython kernel --ip=0.0.0.0
481 [IPKernelApp] To connect another client to this kernel, use:
481 [IPKernelApp] To connect another client to this kernel, use:
482 [IPKernelApp] --existing kernel-12345.json
482 [IPKernelApp] --existing kernel-12345.json
483
483
484 Which we can connect to from the client with::
484 Which we can connect to from the client with::
485
485
486 user@client $> ipython qtconsole --ssh=login --ip=192.168.1.123 --existing /path/to/kernel-12345.json
486 user@client $> ipython qtconsole --ssh=login --ip=192.168.1.123 --existing /path/to/kernel-12345.json
487
487
488 .. note::
488 .. note::
489
489
490 The IP here is the address of worker as seen from *login*, and need only be specified if
490 The IP here is the address of worker as seen from *login*, and need only be specified if
491 the kernel used the ambiguous 0.0.0.0 (all interfaces) address. If it had used
491 the kernel used the ambiguous 0.0.0.0 (all interfaces) address. If it had used
492 192.168.1.123 to start with, it would not be needed.
492 192.168.1.123 to start with, it would not be needed.
493
493
494
494
495 Manual SSH tunnels
495 Manual SSH tunnels
496 ------------------
496 ------------------
497
497
498 It's possible that IPython's ssh helper functions won't work for you, for various
498 It's possible that IPython's ssh helper functions won't work for you, for various
499 reasons. You can still connect to remote machines, as long as you set up the tunnels
499 reasons. You can still connect to remote machines, as long as you set up the tunnels
500 yourself. The basic format of forwarding a local port to a remote one is::
500 yourself. The basic format of forwarding a local port to a remote one is::
501
501
502 [client] $> ssh <server> <localport>:<remoteip>:<remoteport> -f -N
502 [client] $> ssh <server> <localport>:<remoteip>:<remoteport> -f -N
503
503
504 This will forward local connections to **localport** on client to **remoteip:remoteport**
504 This will forward local connections to **localport** on client to **remoteip:remoteport**
505 *via* **server**. Note that remoteip is interpreted relative to *server*, not the client.
505 *via* **server**. Note that remoteip is interpreted relative to *server*, not the client.
506 So if you have direct ssh access to the machine to which you want to forward connections,
506 So if you have direct ssh access to the machine to which you want to forward connections,
507 then the server *is* the remote machine, and remoteip should be server's IP as seen from the
507 then the server *is* the remote machine, and remoteip should be server's IP as seen from the
508 server itself, i.e. 127.0.0.1. Thus, to forward local port 12345 to remote port 54321 on
508 server itself, i.e. 127.0.0.1. Thus, to forward local port 12345 to remote port 54321 on
509 a machine you can see, do::
509 a machine you can see, do::
510
510
511 [client] $> ssh machine 12345:127.0.0.1:54321 -f -N
511 [client] $> ssh machine 12345:127.0.0.1:54321 -f -N
512
512
513 But if your target is actually on a LAN at 192.168.1.123, behind another machine called **login**,
513 But if your target is actually on a LAN at 192.168.1.123, behind another machine called **login**,
514 then you would do::
514 then you would do::
515
515
516 [client] $> ssh login 12345:192.168.1.16:54321 -f -N
516 [client] $> ssh login 12345:192.168.1.16:54321 -f -N
517
517
518 The ``-f -N`` on the end are flags that tell ssh to run in the background,
518 The ``-f -N`` on the end are flags that tell ssh to run in the background,
519 and don't actually run any commands beyond creating the tunnel.
519 and don't actually run any commands beyond creating the tunnel.
520
520
521 .. seealso::
521 .. seealso::
522
522
523 A short discussion of ssh tunnels: http://www.revsys.com/writings/quicktips/ssh-tunnel.html
523 A short discussion of ssh tunnels: http://www.revsys.com/writings/quicktips/ssh-tunnel.html
524
524
525
525
526
526
527 Stopping Kernels and Consoles
527 Stopping Kernels and Consoles
528 *****************************
528 *****************************
529
529
530 Since there can be many consoles per kernel, the shutdown mechanism and dialog
530 Since there can be many consoles per kernel, the shutdown mechanism and dialog
531 are probably more complicated than you are used to. Since you don't always want
531 are probably more complicated than you are used to. Since you don't always want
532 to shutdown a kernel when you close a window, you are given the option to just
532 to shutdown a kernel when you close a window, you are given the option to just
533 close the console window or also close the Kernel and *all other windows*. Note
533 close the console window or also close the Kernel and *all other windows*. Note
534 that this only refers to all other *local* windows, as remote Consoles are not
534 that this only refers to all other *local* windows, as remote Consoles are not
535 allowed to shutdown the kernel, and shutdowns do not close Remote consoles (to
535 allowed to shutdown the kernel, and shutdowns do not close Remote consoles (to
536 allow for saving, etc.).
536 allow for saving, etc.).
537
537
538 Rules:
538 Rules:
539
539
540 * Restarting the kernel automatically clears all *local* Consoles, and prompts remote
540 * Restarting the kernel automatically clears all *local* Consoles, and prompts remote
541 Consoles about the reset.
541 Consoles about the reset.
542 * Shutdown closes all *local* Consoles, and notifies remotes that
542 * Shutdown closes all *local* Consoles, and notifies remotes that
543 the Kernel has been shutdown.
543 the Kernel has been shutdown.
544 * Remote Consoles may not restart or shutdown the kernel.
544 * Remote Consoles may not restart or shutdown the kernel.
545
545
546 Qt and the QtConsole
546 Qt and the QtConsole
547 ====================
547 ====================
548
548
549 An important part of working with the QtConsole when you are writing your own
549 An important part of working with the QtConsole when you are writing your own
550 Qt code is to remember that user code (in the kernel) is *not* in the same
550 Qt code is to remember that user code (in the kernel) is *not* in the same
551 process as the frontend. This means that there is not necessarily any Qt code
551 process as the frontend. This means that there is not necessarily any Qt code
552 running in the kernel, and under most normal circumstances there isn't. If,
552 running in the kernel, and under most normal circumstances there isn't. If,
553 however, you specify ``--matplotlib qt`` at the command-line, then there *will* be a
553 however, you specify ``--matplotlib qt`` at the command-line, then there *will* be a
554 :class:`QCoreApplication` instance running in the kernel process along with
554 :class:`QCoreApplication` instance running in the kernel process along with
555 user-code. To get a reference to this application, do:
555 user-code. To get a reference to this application, do:
556
556
557 .. sourcecode:: python
557 .. sourcecode:: python
558
558
559 from PyQt4 import QtCore
559 from PyQt4 import QtCore
560 app = QtCore.QCoreApplication.instance()
560 app = QtCore.QCoreApplication.instance()
561 # app will be None if there is no such instance
561 # app will be None if there is no such instance
562
562
563 A common problem listed in the PyQt4 Gotchas_ is the fact that Python's garbage
563 A common problem listed in the PyQt4 Gotchas_ is the fact that Python's garbage
564 collection will destroy Qt objects (Windows, etc.) once there is no longer a
564 collection will destroy Qt objects (Windows, etc.) once there is no longer a
565 Python reference to them, so you have to hold on to them. For instance, in:
565 Python reference to them, so you have to hold on to them. For instance, in:
566
566
567 .. sourcecode:: python
567 .. sourcecode:: python
568
568
569 def make_window():
569 def make_window():
570 win = QtGui.QMainWindow()
570 win = QtGui.QMainWindow()
571
571
572 def make_and_return_window():
572 def make_and_return_window():
573 win = QtGui.QMainWindow()
573 win = QtGui.QMainWindow()
574 return win
574 return win
575
575
576 :func:`make_window` will never draw a window, because garbage collection will
576 :func:`make_window` will never draw a window, because garbage collection will
577 destroy it before it is drawn, whereas :func:`make_and_return_window` lets the
577 destroy it before it is drawn, whereas :func:`make_and_return_window` lets the
578 caller decide when the window object should be destroyed. If, as a developer,
578 caller decide when the window object should be destroyed. If, as a developer,
579 you know that you always want your objects to last as long as the process, you
579 you know that you always want your objects to last as long as the process, you
580 can attach them to the QApplication instance itself:
580 can attach them to the QApplication instance itself:
581
581
582 .. sourcecode:: python
582 .. sourcecode:: python
583
583
584 # do this just once:
584 # do this just once:
585 app = QtCore.QCoreApplication.instance()
585 app = QtCore.QCoreApplication.instance()
586 app.references = set()
586 app.references = set()
587 # then when you create Windows, add them to the set
587 # then when you create Windows, add them to the set
588 def make_window():
588 def make_window():
589 win = QtGui.QMainWindow()
589 win = QtGui.QMainWindow()
590 app.references.add(win)
590 app.references.add(win)
591
591
592 Now the QApplication itself holds a reference to ``win``, so it will never be
592 Now the QApplication itself holds a reference to ``win``, so it will never be
593 garbage collected until the application itself is destroyed.
593 garbage collected until the application itself is destroyed.
594
594
595 .. _Gotchas: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/gotchas.html#garbage-collection
595 .. _Gotchas: http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/gotchas.html#garbage-collection
596
596
597 Regressions
597 Regressions
598 ===========
598 ===========
599
599
600 There are some features, where the qt console lags behind the Terminal
600 There are some features, where the qt console lags behind the Terminal
601 frontend:
601 frontend:
602
602
603 * !cmd input: Due to our use of pexpect, we cannot pass input to subprocesses
603 * !cmd input: Due to our use of pexpect, we cannot pass input to subprocesses
604 launched using the '!' escape, so you should never call a command that
604 launched using the '!' escape, so you should never call a command that
605 requires interactive input. For such cases, use the terminal IPython. This
605 requires interactive input. For such cases, use the terminal IPython. This
606 will not be fixed, as abandoning pexpect would significantly degrade the
606 will not be fixed, as abandoning pexpect would significantly degrade the
607 console experience.
607 console experience.
608
608
609 .. _PyQt: http://www.riverbankcomputing.co.uk/software/pyqt/download
609 .. _PyQt: http://www.riverbankcomputing.co.uk/software/pyqt/download
610 .. _pygments: http://pygments.org/
610 .. _pygments: http://pygments.org/
@@ -1,1165 +1,1164 b''
1 =================
1 =================
2 IPython reference
2 IPython reference
3 =================
3 =================
4
4
5 .. _command_line_options:
5 .. _command_line_options:
6
6
7 Command-line usage
7 Command-line usage
8 ==================
8 ==================
9
9
10 You start IPython with the command::
10 You start IPython with the command::
11
11
12 $ ipython [options] files
12 $ ipython [options] files
13
13
14 .. note::
14 .. note::
15
15
16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
16 For IPython on Python 3, use ``ipython3`` in place of ``ipython``.
17
17
18 If invoked with no options, it executes all the files listed in sequence
18 If invoked with no options, it executes all the files listed in sequence
19 and drops you into the interpreter while still acknowledging any options
19 and drops you into the interpreter while still acknowledging any options
20 you may have set in your ipython_config.py. This behavior is different from
20 you may have set in your ipython_config.py. This behavior is different from
21 standard Python, which when called as python -i will only execute one
21 standard Python, which when called as python -i will only execute one
22 file and ignore your configuration setup.
22 file and ignore your configuration setup.
23
23
24 Please note that some of the configuration options are not available at
24 Please note that some of the configuration options are not available at
25 the command line, simply because they are not practical here. Look into
25 the command line, simply because they are not practical here. Look into
26 your configuration files for details on those. There are separate configuration
26 your configuration files for details on those. There are separate configuration
27 files for each profile, and the files look like "ipython_config.py" or
27 files for each profile, and the files look like "ipython_config.py" or
28 "ipython_config_<frontendname>.py". Profile directories look like
28 "ipython_config_<frontendname>.py". Profile directories look like
29 "profile_profilename" and are typically installed in the IPYTHONDIR directory.
29 "profile_profilename" and are typically installed in the IPYTHONDIR directory.
30 For Linux users, this will be $HOME/.config/ipython, and for other users it
30 For Linux users, this will be $HOME/.config/ipython, and for other users it
31 will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
31 will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and
32 Settings\\YourUserName in most instances.
32 Settings\\YourUserName in most instances.
33
33
34
34
35 Eventloop integration
35 Eventloop integration
36 ---------------------
36 ---------------------
37
37
38 Previously IPython had command line options for controlling GUI event loop
38 Previously IPython had command line options for controlling GUI event loop
39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
39 integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython
40 version 0.11, these have been removed. Please see the new ``%gui``
40 version 0.11, these have been removed. Please see the new ``%gui``
41 magic command or :ref:`this section <gui_support>` for details on the new
41 magic command or :ref:`this section <gui_support>` for details on the new
42 interface, or specify the gui at the commandline::
42 interface, or specify the gui at the commandline::
43
43
44 $ ipython --gui=qt
44 $ ipython --gui=qt
45
45
46
46
47 Command-line Options
47 Command-line Options
48 --------------------
48 --------------------
49
49
50 To see the options IPython accepts, use ``ipython --help`` (and you probably
50 To see the options IPython accepts, use ``ipython --help`` (and you probably
51 should run the output through a pager such as ``ipython --help | less`` for
51 should run the output through a pager such as ``ipython --help | less`` for
52 more convenient reading). This shows all the options that have a single-word
52 more convenient reading). This shows all the options that have a single-word
53 alias to control them, but IPython lets you configure all of its objects from
53 alias to control them, but IPython lets you configure all of its objects from
54 the command-line by passing the full class name and a corresponding value; type
54 the command-line by passing the full class name and a corresponding value; type
55 ``ipython --help-all`` to see this full list. For example::
55 ``ipython --help-all`` to see this full list. For example::
56
56
57 ipython --matplotlib qt
57 ipython --matplotlib qt
58
58
59 is equivalent to::
59 is equivalent to::
60
60
61 ipython --TerminalIPythonApp.matplotlib='qt'
61 ipython --TerminalIPythonApp.matplotlib='qt'
62
62
63 Note that in the second form, you *must* use the equal sign, as the expression
63 Note that in the second form, you *must* use the equal sign, as the expression
64 is evaluated as an actual Python assignment. While in the above example the
64 is evaluated as an actual Python assignment. While in the above example the
65 short form is more convenient, only the most common options have a short form,
65 short form is more convenient, only the most common options have a short form,
66 while any configurable variable in IPython can be set at the command-line by
66 while any configurable variable in IPython can be set at the command-line by
67 using the long form. This long form is the same syntax used in the
67 using the long form. This long form is the same syntax used in the
68 configuration files, if you want to set these options permanently.
68 configuration files, if you want to set these options permanently.
69
69
70
70
71 Interactive use
71 Interactive use
72 ===============
72 ===============
73
73
74 IPython is meant to work as a drop-in replacement for the standard interactive
74 IPython is meant to work as a drop-in replacement for the standard interactive
75 interpreter. As such, any code which is valid python should execute normally
75 interpreter. As such, any code which is valid python should execute normally
76 under IPython (cases where this is not true should be reported as bugs). It
76 under IPython (cases where this is not true should be reported as bugs). It
77 does, however, offer many features which are not available at a standard python
77 does, however, offer many features which are not available at a standard python
78 prompt. What follows is a list of these.
78 prompt. What follows is a list of these.
79
79
80
80
81 Caution for Windows users
81 Caution for Windows users
82 -------------------------
82 -------------------------
83
83
84 Windows, unfortunately, uses the '\\' character as a path separator. This is a
84 Windows, unfortunately, uses the '\\' character as a path separator. This is a
85 terrible choice, because '\\' also represents the escape character in most
85 terrible choice, because '\\' also represents the escape character in most
86 modern programming languages, including Python. For this reason, using '/'
86 modern programming languages, including Python. For this reason, using '/'
87 character is recommended if you have problems with ``\``. However, in Windows
87 character is recommended if you have problems with ``\``. However, in Windows
88 commands '/' flags options, so you can not use it for the root directory. This
88 commands '/' flags options, so you can not use it for the root directory. This
89 means that paths beginning at the root must be typed in a contrived manner
89 means that paths beginning at the root must be typed in a contrived manner
90 like: ``%copy \opt/foo/bar.txt \tmp``
90 like: ``%copy \opt/foo/bar.txt \tmp``
91
91
92 .. _magic:
92 .. _magic:
93
93
94 Magic command system
94 Magic command system
95 --------------------
95 --------------------
96
96
97 IPython will treat any line whose first character is a % as a special
97 IPython will treat any line whose first character is a % as a special
98 call to a 'magic' function. These allow you to control the behavior of
98 call to a 'magic' function. These allow you to control the behavior of
99 IPython itself, plus a lot of system-type features. They are all
99 IPython itself, plus a lot of system-type features. They are all
100 prefixed with a % character, but parameters are given without
100 prefixed with a % character, but parameters are given without
101 parentheses or quotes.
101 parentheses or quotes.
102
102
103 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
103 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
104 only the rest of the current line, but all lines below them as well, in the
104 only the rest of the current line, but all lines below them as well, in the
105 current execution block. Cell magics can in fact make arbitrary modifications
105 current execution block. Cell magics can in fact make arbitrary modifications
106 to the input they receive, which need not even be valid Python code at all.
106 to the input they receive, which need not even be valid Python code at all.
107 They receive the whole block as a single string.
107 They receive the whole block as a single string.
108
108
109 As a line magic example, the ``%cd`` magic works just like the OS command of
109 As a line magic example, the ``%cd`` magic works just like the OS command of
110 the same name::
110 the same name::
111
111
112 In [8]: %cd
112 In [8]: %cd
113 /home/fperez
113 /home/fperez
114
114
115 The following uses the builtin ``timeit`` in cell mode::
115 The following uses the builtin ``timeit`` in cell mode::
116
116
117 In [10]: %%timeit x = range(10000)
117 In [10]: %%timeit x = range(10000)
118 ...: min(x)
118 ...: min(x)
119 ...: max(x)
119 ...: max(x)
120 ...:
120 ...:
121 1000 loops, best of 3: 438 us per loop
121 1000 loops, best of 3: 438 us per loop
122
122
123 In this case, ``x = range(10000)`` is called as the line argument, and the
123 In this case, ``x = range(10000)`` is called as the line argument, and the
124 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
124 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
125 ``timeit`` magic receives both.
125 ``timeit`` magic receives both.
126
126
127 If you have 'automagic' enabled (as it by default), you don't need to type in
127 If you have 'automagic' enabled (as it by default), you don't need to type in
128 the single ``%`` explicitly for line magics; IPython will scan its internal
128 the single ``%`` explicitly for line magics; IPython will scan its internal
129 list of magic functions and call one if it exists. With automagic on you can
129 list of magic functions and call one if it exists. With automagic on you can
130 then just type ``cd mydir`` to go to directory 'mydir'::
130 then just type ``cd mydir`` to go to directory 'mydir'::
131
131
132 In [9]: cd mydir
132 In [9]: cd mydir
133 /home/fperez/mydir
133 /home/fperez/mydir
134
134
135 Note that cell magics *always* require an explicit ``%%`` prefix, automagic
135 Note that cell magics *always* require an explicit ``%%`` prefix, automagic
136 calling only works for line magics.
136 calling only works for line magics.
137
137
138 The automagic system has the lowest possible precedence in name searches, so
138 The automagic system has the lowest possible precedence in name searches, so
139 defining an identifier with the same name as an existing magic function will
139 defining an identifier with the same name as an existing magic function will
140 shadow it for automagic use. You can still access the shadowed magic function
140 shadow it for automagic use. You can still access the shadowed magic function
141 by explicitly using the ``%`` character at the beginning of the line.
141 by explicitly using the ``%`` character at the beginning of the line.
142
142
143 An example (with automagic on) should clarify all this:
143 An example (with automagic on) should clarify all this:
144
144
145 .. sourcecode:: ipython
145 .. sourcecode:: ipython
146
146
147 In [1]: cd ipython # %cd is called by automagic
147 In [1]: cd ipython # %cd is called by automagic
148 /home/fperez/ipython
148 /home/fperez/ipython
149
149
150 In [2]: cd=1 # now cd is just a variable
150 In [2]: cd=1 # now cd is just a variable
151
151
152 In [3]: cd .. # and doesn't work as a function anymore
152 In [3]: cd .. # and doesn't work as a function anymore
153 File "<ipython-input-3-9fedb3aff56c>", line 1
153 File "<ipython-input-3-9fedb3aff56c>", line 1
154 cd ..
154 cd ..
155 ^
155 ^
156 SyntaxError: invalid syntax
156 SyntaxError: invalid syntax
157
157
158
158
159 In [4]: %cd .. # but %cd always works
159 In [4]: %cd .. # but %cd always works
160 /home/fperez
160 /home/fperez
161
161
162 In [5]: del cd # if you remove the cd variable, automagic works again
162 In [5]: del cd # if you remove the cd variable, automagic works again
163
163
164 In [6]: cd ipython
164 In [6]: cd ipython
165
165
166 /home/fperez/ipython
166 /home/fperez/ipython
167
167
168 Defining your own magics
168 Defining your own magics
169 ++++++++++++++++++++++++
169 ++++++++++++++++++++++++
170
170
171 There are two main ways to define your own magic functions: from standalone
171 There are two main ways to define your own magic functions: from standalone
172 functions and by inheriting from a base class provided by IPython:
172 functions and by inheriting from a base class provided by IPython:
173 :class:`IPython.core.magic.Magics`. Below we show code you can place in a file
173 :class:`IPython.core.magic.Magics`. Below we show code you can place in a file
174 that you load from your configuration, such as any file in the ``startup``
174 that you load from your configuration, such as any file in the ``startup``
175 subdirectory of your default IPython profile.
175 subdirectory of your default IPython profile.
176
176
177 First, let us see the simplest case. The following shows how to create a line
177 First, let us see the simplest case. The following shows how to create a line
178 magic, a cell one and one that works in both modes, using just plain functions:
178 magic, a cell one and one that works in both modes, using just plain functions:
179
179
180 .. sourcecode:: python
180 .. sourcecode:: python
181
181
182 from IPython.core.magic import (register_line_magic, register_cell_magic,
182 from IPython.core.magic import (register_line_magic, register_cell_magic,
183 register_line_cell_magic)
183 register_line_cell_magic)
184
184
185 @register_line_magic
185 @register_line_magic
186 def lmagic(line):
186 def lmagic(line):
187 "my line magic"
187 "my line magic"
188 return line
188 return line
189
189
190 @register_cell_magic
190 @register_cell_magic
191 def cmagic(line, cell):
191 def cmagic(line, cell):
192 "my cell magic"
192 "my cell magic"
193 return line, cell
193 return line, cell
194
194
195 @register_line_cell_magic
195 @register_line_cell_magic
196 def lcmagic(line, cell=None):
196 def lcmagic(line, cell=None):
197 "Magic that works both as %lcmagic and as %%lcmagic"
197 "Magic that works both as %lcmagic and as %%lcmagic"
198 if cell is None:
198 if cell is None:
199 print "Called as line magic"
199 print "Called as line magic"
200 return line
200 return line
201 else:
201 else:
202 print "Called as cell magic"
202 print "Called as cell magic"
203 return line, cell
203 return line, cell
204
204
205 # We delete these to avoid name conflicts for automagic to work
205 # We delete these to avoid name conflicts for automagic to work
206 del lmagic, lcmagic
206 del lmagic, lcmagic
207
207
208
208
209 You can also create magics of all three kinds by inheriting from the
209 You can also create magics of all three kinds by inheriting from the
210 :class:`IPython.core.magic.Magics` class. This lets you create magics that can
210 :class:`IPython.core.magic.Magics` class. This lets you create magics that can
211 potentially hold state in between calls, and that have full access to the main
211 potentially hold state in between calls, and that have full access to the main
212 IPython object:
212 IPython object:
213
213
214 .. sourcecode:: python
214 .. sourcecode:: python
215
215
216 # This code can be put in any Python module, it does not require IPython
216 # This code can be put in any Python module, it does not require IPython
217 # itself to be running already. It only creates the magics subclass but
217 # itself to be running already. It only creates the magics subclass but
218 # doesn't instantiate it yet.
218 # doesn't instantiate it yet.
219 from IPython.core.magic import (Magics, magics_class, line_magic,
219 from IPython.core.magic import (Magics, magics_class, line_magic,
220 cell_magic, line_cell_magic)
220 cell_magic, line_cell_magic)
221
221
222 # The class MUST call this class decorator at creation time
222 # The class MUST call this class decorator at creation time
223 @magics_class
223 @magics_class
224 class MyMagics(Magics):
224 class MyMagics(Magics):
225
225
226 @line_magic
226 @line_magic
227 def lmagic(self, line):
227 def lmagic(self, line):
228 "my line magic"
228 "my line magic"
229 print "Full access to the main IPython object:", self.shell
229 print "Full access to the main IPython object:", self.shell
230 print "Variables in the user namespace:", self.shell.user_ns.keys()
230 print "Variables in the user namespace:", self.shell.user_ns.keys()
231 return line
231 return line
232
232
233 @cell_magic
233 @cell_magic
234 def cmagic(self, line, cell):
234 def cmagic(self, line, cell):
235 "my cell magic"
235 "my cell magic"
236 return line, cell
236 return line, cell
237
237
238 @line_cell_magic
238 @line_cell_magic
239 def lcmagic(self, line, cell=None):
239 def lcmagic(self, line, cell=None):
240 "Magic that works both as %lcmagic and as %%lcmagic"
240 "Magic that works both as %lcmagic and as %%lcmagic"
241 if cell is None:
241 if cell is None:
242 print "Called as line magic"
242 print "Called as line magic"
243 return line
243 return line
244 else:
244 else:
245 print "Called as cell magic"
245 print "Called as cell magic"
246 return line, cell
246 return line, cell
247
247
248
248
249 # In order to actually use these magics, you must register them with a
249 # In order to actually use these magics, you must register them with a
250 # running IPython. This code must be placed in a file that is loaded once
250 # running IPython. This code must be placed in a file that is loaded once
251 # IPython is up and running:
251 # IPython is up and running:
252 ip = get_ipython()
252 ip = get_ipython()
253 # You can register the class itself without instantiating it. IPython will
253 # You can register the class itself without instantiating it. IPython will
254 # call the default constructor on it.
254 # call the default constructor on it.
255 ip.register_magics(MyMagics)
255 ip.register_magics(MyMagics)
256
256
257 If you want to create a class with a different constructor that holds
257 If you want to create a class with a different constructor that holds
258 additional state, then you should always call the parent constructor and
258 additional state, then you should always call the parent constructor and
259 instantiate the class yourself before registration:
259 instantiate the class yourself before registration:
260
260
261 .. sourcecode:: python
261 .. sourcecode:: python
262
262
263 @magics_class
263 @magics_class
264 class StatefulMagics(Magics):
264 class StatefulMagics(Magics):
265 "Magics that hold additional state"
265 "Magics that hold additional state"
266
266
267 def __init__(self, shell, data):
267 def __init__(self, shell, data):
268 # You must call the parent constructor
268 # You must call the parent constructor
269 super(StatefulMagics, self).__init__(shell)
269 super(StatefulMagics, self).__init__(shell)
270 self.data = data
270 self.data = data
271
271
272 # etc...
272 # etc...
273
273
274 # This class must then be registered with a manually created instance,
274 # This class must then be registered with a manually created instance,
275 # since its constructor has different arguments from the default:
275 # since its constructor has different arguments from the default:
276 ip = get_ipython()
276 ip = get_ipython()
277 magics = StatefulMagics(ip, some_data)
277 magics = StatefulMagics(ip, some_data)
278 ip.register_magics(magics)
278 ip.register_magics(magics)
279
279
280
280
281 In earlier versions, IPython had an API for the creation of line magics (cell
281 In earlier versions, IPython had an API for the creation of line magics (cell
282 magics did not exist at the time) that required you to create functions with a
282 magics did not exist at the time) that required you to create functions with a
283 method-looking signature and to manually pass both the function and the name.
283 method-looking signature and to manually pass both the function and the name.
284 While this API is no longer recommended, it remains indefinitely supported for
284 While this API is no longer recommended, it remains indefinitely supported for
285 backwards compatibility purposes. With the old API, you'd create a magic as
285 backwards compatibility purposes. With the old API, you'd create a magic as
286 follows:
286 follows:
287
287
288 .. sourcecode:: python
288 .. sourcecode:: python
289
289
290 def func(self, line):
290 def func(self, line):
291 print "Line magic called with line:", line
291 print "Line magic called with line:", line
292 print "IPython object:", self.shell
292 print "IPython object:", self.shell
293
293
294 ip = get_ipython()
294 ip = get_ipython()
295 # Declare this function as the magic %mycommand
295 # Declare this function as the magic %mycommand
296 ip.define_magic('mycommand', func)
296 ip.define_magic('mycommand', func)
297
297
298 Type ``%magic`` for more information, including a list of all available magic
298 Type ``%magic`` for more information, including a list of all available magic
299 functions at any time and their docstrings. You can also type
299 functions at any time and their docstrings. You can also type
300 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
300 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
301 information on the '?' system) to get information about any particular magic
301 information on the '?' system) to get information about any particular magic
302 function you are interested in.
302 function you are interested in.
303
303
304 The API documentation for the :mod:`IPython.core.magic` module contains the full
304 The API documentation for the :mod:`IPython.core.magic` module contains the full
305 docstrings of all currently available magic commands.
305 docstrings of all currently available magic commands.
306
306
307
307
308 Access to the standard Python help
308 Access to the standard Python help
309 ----------------------------------
309 ----------------------------------
310
310
311 Simply type ``help()`` to access Python's standard help system. You can
311 Simply type ``help()`` to access Python's standard help system. You can
312 also type ``help(object)`` for information about a given object, or
312 also type ``help(object)`` for information about a given object, or
313 ``help('keyword')`` for information on a keyword. You may need to configure your
313 ``help('keyword')`` for information on a keyword. You may need to configure your
314 PYTHONDOCS environment variable for this feature to work correctly.
314 PYTHONDOCS environment variable for this feature to work correctly.
315
315
316 .. _dynamic_object_info:
316 .. _dynamic_object_info:
317
317
318 Dynamic object information
318 Dynamic object information
319 --------------------------
319 --------------------------
320
320
321 Typing ``?word`` or ``word?`` prints detailed information about an object. If
321 Typing ``?word`` or ``word?`` prints detailed information about an object. If
322 certain strings in the object are too long (e.g. function signatures) they get
322 certain strings in the object are too long (e.g. function signatures) they get
323 snipped in the center for brevity. This system gives access variable types and
323 snipped in the center for brevity. This system gives access variable types and
324 values, docstrings, function prototypes and other useful information.
324 values, docstrings, function prototypes and other useful information.
325
325
326 If the information will not fit in the terminal, it is displayed in a pager
326 If the information will not fit in the terminal, it is displayed in a pager
327 (``less`` if available, otherwise a basic internal pager).
327 (``less`` if available, otherwise a basic internal pager).
328
328
329 Typing ``??word`` or ``word??`` gives access to the full information, including
329 Typing ``??word`` or ``word??`` gives access to the full information, including
330 the source code where possible. Long strings are not snipped.
330 the source code where possible. Long strings are not snipped.
331
331
332 The following magic functions are particularly useful for gathering
332 The following magic functions are particularly useful for gathering
333 information about your working environment. You can get more details by
333 information about your working environment. You can get more details by
334 typing ``%magic`` or querying them individually (``%function_name?``);
334 typing ``%magic`` or querying them individually (``%function_name?``);
335 this is just a summary:
335 this is just a summary:
336
336
337 * **%pdoc <object>**: Print (or run through a pager if too long) the
337 * **%pdoc <object>**: Print (or run through a pager if too long) the
338 docstring for an object. If the given object is a class, it will
338 docstring for an object. If the given object is a class, it will
339 print both the class and the constructor docstrings.
339 print both the class and the constructor docstrings.
340 * **%pdef <object>**: Print the call signature for any callable
340 * **%pdef <object>**: Print the call signature for any callable
341 object. If the object is a class, print the constructor information.
341 object. If the object is a class, print the constructor information.
342 * **%psource <object>**: Print (or run through a pager if too long)
342 * **%psource <object>**: Print (or run through a pager if too long)
343 the source code for an object.
343 the source code for an object.
344 * **%pfile <object>**: Show the entire source file where an object was
344 * **%pfile <object>**: Show the entire source file where an object was
345 defined via a pager, opening it at the line where the object
345 defined via a pager, opening it at the line where the object
346 definition begins.
346 definition begins.
347 * **%who/%whos**: These functions give information about identifiers
347 * **%who/%whos**: These functions give information about identifiers
348 you have defined interactively (not things you loaded or defined
348 you have defined interactively (not things you loaded or defined
349 in your configuration files). %who just prints a list of
349 in your configuration files). %who just prints a list of
350 identifiers and %whos prints a table with some basic details about
350 identifiers and %whos prints a table with some basic details about
351 each identifier.
351 each identifier.
352
352
353 Note that the dynamic object information functions (?/??, ``%pdoc``,
353 Note that the dynamic object information functions (?/??, ``%pdoc``,
354 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
354 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
355 directly on variables. For example, after doing ``import os``, you can use
355 directly on variables. For example, after doing ``import os``, you can use
356 ``os.path.abspath??``.
356 ``os.path.abspath??``.
357
357
358 .. _readline:
358 .. _readline:
359
359
360 Readline-based features
360 Readline-based features
361 -----------------------
361 -----------------------
362
362
363 These features require the GNU readline library, so they won't work if your
363 These features require the GNU readline library, so they won't work if your
364 Python installation lacks readline support. We will first describe the default
364 Python installation lacks readline support. We will first describe the default
365 behavior IPython uses, and then how to change it to suit your preferences.
365 behavior IPython uses, and then how to change it to suit your preferences.
366
366
367
367
368 Command line completion
368 Command line completion
369 +++++++++++++++++++++++
369 +++++++++++++++++++++++
370
370
371 At any time, hitting TAB will complete any available python commands or
371 At any time, hitting TAB will complete any available python commands or
372 variable names, and show you a list of the possible completions if
372 variable names, and show you a list of the possible completions if
373 there's no unambiguous one. It will also complete filenames in the
373 there's no unambiguous one. It will also complete filenames in the
374 current directory if no python names match what you've typed so far.
374 current directory if no python names match what you've typed so far.
375
375
376
376
377 Search command history
377 Search command history
378 ++++++++++++++++++++++
378 ++++++++++++++++++++++
379
379
380 IPython provides two ways for searching through previous input and thus
380 IPython provides two ways for searching through previous input and thus
381 reduce the need for repetitive typing:
381 reduce the need for repetitive typing:
382
382
383 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
383 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n
384 (next,down) to search through only the history items that match
384 (next,down) to search through only the history items that match
385 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
385 what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank
386 prompt, they just behave like normal arrow keys.
386 prompt, they just behave like normal arrow keys.
387 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
387 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system
388 searches your history for lines that contain what you've typed so
388 searches your history for lines that contain what you've typed so
389 far, completing as much as it can.
389 far, completing as much as it can.
390
390
391
391
392 Persistent command history across sessions
392 Persistent command history across sessions
393 ++++++++++++++++++++++++++++++++++++++++++
393 ++++++++++++++++++++++++++++++++++++++++++
394
394
395 IPython will save your input history when it leaves and reload it next
395 IPython will save your input history when it leaves and reload it next
396 time you restart it. By default, the history file is named
396 time you restart it. By default, the history file is named
397 $IPYTHONDIR/profile_<name>/history.sqlite. This allows you to keep
397 $IPYTHONDIR/profile_<name>/history.sqlite. This allows you to keep
398 separate histories related to various tasks: commands related to
398 separate histories related to various tasks: commands related to
399 numerical work will not be clobbered by a system shell history, for
399 numerical work will not be clobbered by a system shell history, for
400 example.
400 example.
401
401
402
402
403 Autoindent
403 Autoindent
404 ++++++++++
404 ++++++++++
405
405
406 IPython can recognize lines ending in ':' and indent the next line,
406 IPython can recognize lines ending in ':' and indent the next line,
407 while also un-indenting automatically after 'raise' or 'return'.
407 while also un-indenting automatically after 'raise' or 'return'.
408
408
409 This feature uses the readline library, so it will honor your
409 This feature uses the readline library, so it will honor your
410 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
410 :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points
411 to). Adding the following lines to your :file:`.inputrc` file can make
411 to). Adding the following lines to your :file:`.inputrc` file can make
412 indenting/unindenting more convenient (M-i indents, M-u unindents)::
412 indenting/unindenting more convenient (M-i indents, M-u unindents)::
413
413
414 # if you don't already have a ~/.inputrc file, you need this include:
414 # if you don't already have a ~/.inputrc file, you need this include:
415 $include /etc/inputrc
415 $include /etc/inputrc
416
416
417 $if Python
417 $if Python
418 "\M-i": " "
418 "\M-i": " "
419 "\M-u": "\d\d\d\d"
419 "\M-u": "\d\d\d\d"
420 $endif
420 $endif
421
421
422 Note that there are 4 spaces between the quote marks after "M-i" above.
422 Note that there are 4 spaces between the quote marks after "M-i" above.
423
423
424 .. warning::
424 .. warning::
425
425
426 Setting the above indents will cause problems with unicode text entry in
426 Setting the above indents will cause problems with unicode text entry in
427 the terminal.
427 the terminal.
428
428
429 .. warning::
429 .. warning::
430
430
431 Autoindent is ON by default, but it can cause problems with the pasting of
431 Autoindent is ON by default, but it can cause problems with the pasting of
432 multi-line indented code (the pasted code gets re-indented on each line). A
432 multi-line indented code (the pasted code gets re-indented on each line). A
433 magic function %autoindent allows you to toggle it on/off at runtime. You
433 magic function %autoindent allows you to toggle it on/off at runtime. You
434 can also disable it permanently on in your :file:`ipython_config.py` file
434 can also disable it permanently on in your :file:`ipython_config.py` file
435 (set TerminalInteractiveShell.autoindent=False).
435 (set TerminalInteractiveShell.autoindent=False).
436
436
437 If you want to paste multiple lines in the terminal, it is recommended that
437 If you want to paste multiple lines in the terminal, it is recommended that
438 you use ``%paste``.
438 you use ``%paste``.
439
439
440
440
441 Customizing readline behavior
441 Customizing readline behavior
442 +++++++++++++++++++++++++++++
442 +++++++++++++++++++++++++++++
443
443
444 All these features are based on the GNU readline library, which has an
444 All these features are based on the GNU readline library, which has an
445 extremely customizable interface. Normally, readline is configured via a
445 extremely customizable interface. Normally, readline is configured via a
446 file which defines the behavior of the library; the details of the
446 file which defines the behavior of the library; the details of the
447 syntax for this can be found in the readline documentation available
447 syntax for this can be found in the readline documentation available
448 with your system or on the Internet. IPython doesn't read this file (if
448 with your system or on the Internet. IPython doesn't read this file (if
449 it exists) directly, but it does support passing to readline valid
449 it exists) directly, but it does support passing to readline valid
450 options via a simple interface. In brief, you can customize readline by
450 options via a simple interface. In brief, you can customize readline by
451 setting the following options in your configuration file (note
451 setting the following options in your configuration file (note
452 that these options can not be specified at the command line):
452 that these options can not be specified at the command line):
453
453
454 * **readline_parse_and_bind**: this holds a list of strings to be executed
454 * **readline_parse_and_bind**: this holds a list of strings to be executed
455 via a readline.parse_and_bind() command. The syntax for valid commands
455 via a readline.parse_and_bind() command. The syntax for valid commands
456 of this kind can be found by reading the documentation for the GNU
456 of this kind can be found by reading the documentation for the GNU
457 readline library, as these commands are of the kind which readline
457 readline library, as these commands are of the kind which readline
458 accepts in its configuration file.
458 accepts in its configuration file.
459 * **readline_remove_delims**: a string of characters to be removed
459 * **readline_remove_delims**: a string of characters to be removed
460 from the default word-delimiters list used by readline, so that
460 from the default word-delimiters list used by readline, so that
461 completions may be performed on strings which contain them. Do not
461 completions may be performed on strings which contain them. Do not
462 change the default value unless you know what you're doing.
462 change the default value unless you know what you're doing.
463
463
464 You will find the default values in your configuration file.
464 You will find the default values in your configuration file.
465
465
466
466
467 Session logging and restoring
467 Session logging and restoring
468 -----------------------------
468 -----------------------------
469
469
470 You can log all input from a session either by starting IPython with the
470 You can log all input from a session either by starting IPython with the
471 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
471 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
472 or by activating the logging at any moment with the magic function %logstart.
472 or by activating the logging at any moment with the magic function %logstart.
473
473
474 Log files can later be reloaded by running them as scripts and IPython
474 Log files can later be reloaded by running them as scripts and IPython
475 will attempt to 'replay' the log by executing all the lines in it, thus
475 will attempt to 'replay' the log by executing all the lines in it, thus
476 restoring the state of a previous session. This feature is not quite
476 restoring the state of a previous session. This feature is not quite
477 perfect, but can still be useful in many cases.
477 perfect, but can still be useful in many cases.
478
478
479 The log files can also be used as a way to have a permanent record of
479 The log files can also be used as a way to have a permanent record of
480 any code you wrote while experimenting. Log files are regular text files
480 any code you wrote while experimenting. Log files are regular text files
481 which you can later open in your favorite text editor to extract code or
481 which you can later open in your favorite text editor to extract code or
482 to 'clean them up' before using them to replay a session.
482 to 'clean them up' before using them to replay a session.
483
483
484 The `%logstart` function for activating logging in mid-session is used as
484 The `%logstart` function for activating logging in mid-session is used as
485 follows::
485 follows::
486
486
487 %logstart [log_name [log_mode]]
487 %logstart [log_name [log_mode]]
488
488
489 If no name is given, it defaults to a file named 'ipython_log.py' in your
489 If no name is given, it defaults to a file named 'ipython_log.py' in your
490 current working directory, in 'rotate' mode (see below).
490 current working directory, in 'rotate' mode (see below).
491
491
492 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
492 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
493 history up to that point and then continues logging.
493 history up to that point and then continues logging.
494
494
495 %logstart takes a second optional parameter: logging mode. This can be
495 %logstart takes a second optional parameter: logging mode. This can be
496 one of (note that the modes are given unquoted):
496 one of (note that the modes are given unquoted):
497
497
498 * [over:] overwrite existing log_name.
498 * [over:] overwrite existing log_name.
499 * [backup:] rename (if exists) to log_name~ and start log_name.
499 * [backup:] rename (if exists) to log_name~ and start log_name.
500 * [append:] well, that says it.
500 * [append:] well, that says it.
501 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
501 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
502
502
503 The %logoff and %logon functions allow you to temporarily stop and
503 The %logoff and %logon functions allow you to temporarily stop and
504 resume logging to a file which had previously been started with
504 resume logging to a file which had previously been started with
505 %logstart. They will fail (with an explanation) if you try to use them
505 %logstart. They will fail (with an explanation) if you try to use them
506 before logging has been started.
506 before logging has been started.
507
507
508 .. _system_shell_access:
508 .. _system_shell_access:
509
509
510 System shell access
510 System shell access
511 -------------------
511 -------------------
512
512
513 Any input line beginning with a ! character is passed verbatim (minus
513 Any input line beginning with a ! character is passed verbatim (minus
514 the !, of course) to the underlying operating system. For example,
514 the !, of course) to the underlying operating system. For example,
515 typing ``!ls`` will run 'ls' in the current directory.
515 typing ``!ls`` will run 'ls' in the current directory.
516
516
517 Manual capture of command output
517 Manual capture of command output
518 --------------------------------
518 --------------------------------
519
519
520 You can assign the result of a system command to a Python variable with the
520 You can assign the result of a system command to a Python variable with the
521 syntax ``myfiles = !ls``. This gets machine readable output from stdout
521 syntax ``myfiles = !ls``. This gets machine readable output from stdout
522 (e.g. without colours), and splits on newlines. To explicitly get this sort of
522 (e.g. without colours), and splits on newlines. To explicitly get this sort of
523 output without assigning to a variable, use two exclamation marks (``!!ls``) or
523 output without assigning to a variable, use two exclamation marks (``!!ls``) or
524 the ``%sx`` magic command.
524 the ``%sx`` magic command.
525
525
526 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
526 The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s``
527 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
527 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
528 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
528 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
529 See :ref:`string_lists` for details.
529 See :ref:`string_lists` for details.
530
530
531 IPython also allows you to expand the value of python variables when
531 IPython also allows you to expand the value of python variables when
532 making system calls. Wrap variables or expressions in {braces}::
532 making system calls. Wrap variables or expressions in {braces}::
533
533
534 In [1]: pyvar = 'Hello world'
534 In [1]: pyvar = 'Hello world'
535 In [2]: !echo "A python variable: {pyvar}"
535 In [2]: !echo "A python variable: {pyvar}"
536 A python variable: Hello world
536 A python variable: Hello world
537 In [3]: import math
537 In [3]: import math
538 In [4]: x = 8
538 In [4]: x = 8
539 In [5]: !echo {math.factorial(x)}
539 In [5]: !echo {math.factorial(x)}
540 40320
540 40320
541
541
542 For simple cases, you can alternatively prepend $ to a variable name::
542 For simple cases, you can alternatively prepend $ to a variable name::
543
543
544 In [6]: !echo $sys.argv
544 In [6]: !echo $sys.argv
545 [/home/fperez/usr/bin/ipython]
545 [/home/fperez/usr/bin/ipython]
546 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
546 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
547 A system variable: /home/fperez
547 A system variable: /home/fperez
548
548
549 System command aliases
549 System command aliases
550 ----------------------
550 ----------------------
551
551
552 The %alias magic function allows you to define magic functions which are in fact
552 The %alias magic function allows you to define magic functions which are in fact
553 system shell commands. These aliases can have parameters.
553 system shell commands. These aliases can have parameters.
554
554
555 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
555 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
556
556
557 Then, typing ``alias_name params`` will execute the system command 'cmd
557 Then, typing ``alias_name params`` will execute the system command 'cmd
558 params' (from your underlying operating system).
558 params' (from your underlying operating system).
559
559
560 You can also define aliases with parameters using %s specifiers (one per
560 You can also define aliases with parameters using %s specifiers (one per
561 parameter). The following example defines the parts function as an
561 parameter). The following example defines the parts function as an
562 alias to the command 'echo first %s second %s' where each %s will be
562 alias to the command 'echo first %s second %s' where each %s will be
563 replaced by a positional parameter to the call to %parts::
563 replaced by a positional parameter to the call to %parts::
564
564
565 In [1]: %alias parts echo first %s second %s
565 In [1]: %alias parts echo first %s second %s
566 In [2]: parts A B
566 In [2]: parts A B
567 first A second B
567 first A second B
568 In [3]: parts A
568 In [3]: parts A
569 ERROR: Alias <parts> requires 2 arguments, 1 given.
569 ERROR: Alias <parts> requires 2 arguments, 1 given.
570
570
571 If called with no parameters, %alias prints the table of currently
571 If called with no parameters, %alias prints the table of currently
572 defined aliases.
572 defined aliases.
573
573
574 The %rehashx magic allows you to load your entire $PATH as
574 The %rehashx magic allows you to load your entire $PATH as
575 ipython aliases. See its docstring for further details.
575 ipython aliases. See its docstring for further details.
576
576
577
577
578 .. _dreload:
578 .. _dreload:
579
579
580 Recursive reload
580 Recursive reload
581 ----------------
581 ----------------
582
582
583 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
583 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
584 module: changes made to any of its dependencies will be reloaded without
584 module: changes made to any of its dependencies will be reloaded without
585 having to exit. To start using it, do::
585 having to exit. To start using it, do::
586
586
587 from IPython.lib.deepreload import reload as dreload
587 from IPython.lib.deepreload import reload as dreload
588
588
589
589
590 Verbose and colored exception traceback printouts
590 Verbose and colored exception traceback printouts
591 -------------------------------------------------
591 -------------------------------------------------
592
592
593 IPython provides the option to see very detailed exception tracebacks,
593 IPython provides the option to see very detailed exception tracebacks,
594 which can be especially useful when debugging large programs. You can
594 which can be especially useful when debugging large programs. You can
595 run any Python file with the %run function to benefit from these
595 run any Python file with the %run function to benefit from these
596 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
596 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
597 be colored (if your terminal supports it) which makes them much easier
597 be colored (if your terminal supports it) which makes them much easier
598 to parse visually.
598 to parse visually.
599
599
600 See the magic xmode and colors functions for details (just type %magic).
600 See the magic xmode and colors functions for details (just type %magic).
601
601
602 These features are basically a terminal version of Ka-Ping Yee's cgitb
602 These features are basically a terminal version of Ka-Ping Yee's cgitb
603 module, now part of the standard Python library.
603 module, now part of the standard Python library.
604
604
605
605
606 .. _input_caching:
606 .. _input_caching:
607
607
608 Input caching system
608 Input caching system
609 --------------------
609 --------------------
610
610
611 IPython offers numbered prompts (In/Out) with input and output caching
611 IPython offers numbered prompts (In/Out) with input and output caching
612 (also referred to as 'input history'). All input is saved and can be
612 (also referred to as 'input history'). All input is saved and can be
613 retrieved as variables (besides the usual arrow key recall), in
613 retrieved as variables (besides the usual arrow key recall), in
614 addition to the %rep magic command that brings a history entry
614 addition to the %rep magic command that brings a history entry
615 up for editing on the next command line.
615 up for editing on the next command line.
616
616
617 The following GLOBAL variables always exist (so don't overwrite them!):
617 The following GLOBAL variables always exist (so don't overwrite them!):
618
618
619 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
619 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
620 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
620 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
621 overwrite In with a variable of your own, you can remake the assignment to the
621 overwrite In with a variable of your own, you can remake the assignment to the
622 internal list with a simple ``In=_ih``.
622 internal list with a simple ``In=_ih``.
623
623
624 Additionally, global variables named _i<n> are dynamically created (<n>
624 Additionally, global variables named _i<n> are dynamically created (<n>
625 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
625 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
626
626
627 For example, what you typed at prompt 14 is available as _i14, _ih[14]
627 For example, what you typed at prompt 14 is available as _i14, _ih[14]
628 and In[14].
628 and In[14].
629
629
630 This allows you to easily cut and paste multi line interactive prompts
630 This allows you to easily cut and paste multi line interactive prompts
631 by printing them out: they print like a clean string, without prompt
631 by printing them out: they print like a clean string, without prompt
632 characters. You can also manipulate them like regular variables (they
632 characters. You can also manipulate them like regular variables (they
633 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
633 are strings), modify or exec them (typing ``exec _i9`` will re-execute the
634 contents of input prompt 9.
634 contents of input prompt 9.
635
635
636 You can also re-execute multiple lines of input easily by using the
636 You can also re-execute multiple lines of input easily by using the
637 magic %rerun or %macro functions. The macro system also allows you to re-execute
637 magic %rerun or %macro functions. The macro system also allows you to re-execute
638 previous lines which include magic function calls (which require special
638 previous lines which include magic function calls (which require special
639 processing). Type %macro? for more details on the macro system.
639 processing). Type %macro? for more details on the macro system.
640
640
641 A history function %hist allows you to see any part of your input
641 A history function %hist allows you to see any part of your input
642 history by printing a range of the _i variables.
642 history by printing a range of the _i variables.
643
643
644 You can also search ('grep') through your history by typing
644 You can also search ('grep') through your history by typing
645 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
645 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
646 etc. You can bring history entries listed by '%hist -g' up for editing
646 etc. You can bring history entries listed by '%hist -g' up for editing
647 with the %recall command, or run them immediately with %rerun.
647 with the %recall command, or run them immediately with %rerun.
648
648
649 .. _output_caching:
649 .. _output_caching:
650
650
651 Output caching system
651 Output caching system
652 ---------------------
652 ---------------------
653
653
654 For output that is returned from actions, a system similar to the input
654 For output that is returned from actions, a system similar to the input
655 cache exists but using _ instead of _i. Only actions that produce a
655 cache exists but using _ instead of _i. Only actions that produce a
656 result (NOT assignments, for example) are cached. If you are familiar
656 result (NOT assignments, for example) are cached. If you are familiar
657 with Mathematica, IPython's _ variables behave exactly like
657 with Mathematica, IPython's _ variables behave exactly like
658 Mathematica's % variables.
658 Mathematica's % variables.
659
659
660 The following GLOBAL variables always exist (so don't overwrite them!):
660 The following GLOBAL variables always exist (so don't overwrite them!):
661
661
662 * [_] (a single underscore) : stores previous output, like Python's
662 * [_] (a single underscore) : stores previous output, like Python's
663 default interpreter.
663 default interpreter.
664 * [__] (two underscores): next previous.
664 * [__] (two underscores): next previous.
665 * [___] (three underscores): next-next previous.
665 * [___] (three underscores): next-next previous.
666
666
667 Additionally, global variables named _<n> are dynamically created (<n>
667 Additionally, global variables named _<n> are dynamically created (<n>
668 being the prompt counter), such that the result of output <n> is always
668 being the prompt counter), such that the result of output <n> is always
669 available as _<n> (don't use the angle brackets, just the number, e.g.
669 available as _<n> (don't use the angle brackets, just the number, e.g.
670 _21).
670 _21).
671
671
672 These variables are also stored in a global dictionary (not a
672 These variables are also stored in a global dictionary (not a
673 list, since it only has entries for lines which returned a result)
673 list, since it only has entries for lines which returned a result)
674 available under the names _oh and Out (similar to _ih and In). So the
674 available under the names _oh and Out (similar to _ih and In). So the
675 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
675 output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you
676 accidentally overwrite the Out variable you can recover it by typing
676 accidentally overwrite the Out variable you can recover it by typing
677 'Out=_oh' at the prompt.
677 'Out=_oh' at the prompt.
678
678
679 This system obviously can potentially put heavy memory demands on your
679 This system obviously can potentially put heavy memory demands on your
680 system, since it prevents Python's garbage collector from removing any
680 system, since it prevents Python's garbage collector from removing any
681 previously computed results. You can control how many results are kept
681 previously computed results. You can control how many results are kept
682 in memory with the option (at the command line or in your configuration
682 in memory with the option (at the command line or in your configuration
683 file) cache_size. If you set it to 0, the whole system is completely
683 file) cache_size. If you set it to 0, the whole system is completely
684 disabled and the prompts revert to the classic '>>>' of normal Python.
684 disabled and the prompts revert to the classic '>>>' of normal Python.
685
685
686
686
687 Directory history
687 Directory history
688 -----------------
688 -----------------
689
689
690 Your history of visited directories is kept in the global list _dh, and
690 Your history of visited directories is kept in the global list _dh, and
691 the magic %cd command can be used to go to any entry in that list. The
691 the magic %cd command can be used to go to any entry in that list. The
692 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
692 %dhist command allows you to view this history. Do ``cd -<TAB>`` to
693 conveniently view the directory history.
693 conveniently view the directory history.
694
694
695
695
696 Automatic parentheses and quotes
696 Automatic parentheses and quotes
697 --------------------------------
697 --------------------------------
698
698
699 These features were adapted from Nathan Gray's LazyPython. They are
699 These features were adapted from Nathan Gray's LazyPython. They are
700 meant to allow less typing for common situations.
700 meant to allow less typing for common situations.
701
701
702
702
703 Automatic parentheses
703 Automatic parentheses
704 +++++++++++++++++++++
704 +++++++++++++++++++++
705
705
706 Callable objects (i.e. functions, methods, etc) can be invoked like this
706 Callable objects (i.e. functions, methods, etc) can be invoked like this
707 (notice the commas between the arguments)::
707 (notice the commas between the arguments)::
708
708
709 In [1]: callable_ob arg1, arg2, arg3
709 In [1]: callable_ob arg1, arg2, arg3
710 ------> callable_ob(arg1, arg2, arg3)
710 ------> callable_ob(arg1, arg2, arg3)
711
711
712 You can force automatic parentheses by using '/' as the first character
712 You can force automatic parentheses by using '/' as the first character
713 of a line. For example::
713 of a line. For example::
714
714
715 In [2]: /globals # becomes 'globals()'
715 In [2]: /globals # becomes 'globals()'
716
716
717 Note that the '/' MUST be the first character on the line! This won't work::
717 Note that the '/' MUST be the first character on the line! This won't work::
718
718
719 In [3]: print /globals # syntax error
719 In [3]: print /globals # syntax error
720
720
721 In most cases the automatic algorithm should work, so you should rarely
721 In most cases the automatic algorithm should work, so you should rarely
722 need to explicitly invoke /. One notable exception is if you are trying
722 need to explicitly invoke /. One notable exception is if you are trying
723 to call a function with a list of tuples as arguments (the parenthesis
723 to call a function with a list of tuples as arguments (the parenthesis
724 will confuse IPython)::
724 will confuse IPython)::
725
725
726 In [4]: zip (1,2,3),(4,5,6) # won't work
726 In [4]: zip (1,2,3),(4,5,6) # won't work
727
727
728 but this will work::
728 but this will work::
729
729
730 In [5]: /zip (1,2,3),(4,5,6)
730 In [5]: /zip (1,2,3),(4,5,6)
731 ------> zip ((1,2,3),(4,5,6))
731 ------> zip ((1,2,3),(4,5,6))
732 Out[5]: [(1, 4), (2, 5), (3, 6)]
732 Out[5]: [(1, 4), (2, 5), (3, 6)]
733
733
734 IPython tells you that it has altered your command line by displaying
734 IPython tells you that it has altered your command line by displaying
735 the new command line preceded by ->. e.g.::
735 the new command line preceded by ->. e.g.::
736
736
737 In [6]: callable list
737 In [6]: callable list
738 ------> callable(list)
738 ------> callable(list)
739
739
740
740
741 Automatic quoting
741 Automatic quoting
742 +++++++++++++++++
742 +++++++++++++++++
743
743
744 You can force automatic quoting of a function's arguments by using ','
744 You can force automatic quoting of a function's arguments by using ','
745 or ';' as the first character of a line. For example::
745 or ';' as the first character of a line. For example::
746
746
747 In [1]: ,my_function /home/me # becomes my_function("/home/me")
747 In [1]: ,my_function /home/me # becomes my_function("/home/me")
748
748
749 If you use ';' the whole argument is quoted as a single string, while ',' splits
749 If you use ';' the whole argument is quoted as a single string, while ',' splits
750 on whitespace::
750 on whitespace::
751
751
752 In [2]: ,my_function a b c # becomes my_function("a","b","c")
752 In [2]: ,my_function a b c # becomes my_function("a","b","c")
753
753
754 In [3]: ;my_function a b c # becomes my_function("a b c")
754 In [3]: ;my_function a b c # becomes my_function("a b c")
755
755
756 Note that the ',' or ';' MUST be the first character on the line! This
756 Note that the ',' or ';' MUST be the first character on the line! This
757 won't work::
757 won't work::
758
758
759 In [4]: x = ,my_function /home/me # syntax error
759 In [4]: x = ,my_function /home/me # syntax error
760
760
761 IPython as your default Python environment
761 IPython as your default Python environment
762 ==========================================
762 ==========================================
763
763
764 Python honors the environment variable PYTHONSTARTUP and will execute at
764 Python honors the environment variable PYTHONSTARTUP and will execute at
765 startup the file referenced by this variable. If you put the following code at
765 startup the file referenced by this variable. If you put the following code at
766 the end of that file, then IPython will be your working environment anytime you
766 the end of that file, then IPython will be your working environment anytime you
767 start Python::
767 start Python::
768
768
769 from IPython.frontend.terminal.ipapp import launch_new_instance
769 from IPython.frontend.terminal.ipapp import launch_new_instance
770 launch_new_instance()
770 launch_new_instance()
771 raise SystemExit
771 raise SystemExit
772
772
773 The ``raise SystemExit`` is needed to exit Python when
773 The ``raise SystemExit`` is needed to exit Python when
774 it finishes, otherwise you'll be back at the normal Python '>>>'
774 it finishes, otherwise you'll be back at the normal Python '>>>'
775 prompt.
775 prompt.
776
776
777 This is probably useful to developers who manage multiple Python
777 This is probably useful to developers who manage multiple Python
778 versions and don't want to have correspondingly multiple IPython
778 versions and don't want to have correspondingly multiple IPython
779 versions. Note that in this mode, there is no way to pass IPython any
779 versions. Note that in this mode, there is no way to pass IPython any
780 command-line options, as those are trapped first by Python itself.
780 command-line options, as those are trapped first by Python itself.
781
781
782 .. _Embedding:
782 .. _Embedding:
783
783
784 Embedding IPython
784 Embedding IPython
785 =================
785 =================
786
786
787 You can start a regular IPython session with
787 You can start a regular IPython session with
788
788
789 .. sourcecode:: python
789 .. sourcecode:: python
790
790
791 import IPython
791 import IPython
792 IPython.start_ipython()
792 IPython.start_ipython()
793
793
794 at any point in your program. This will load IPython configuration,
794 at any point in your program. This will load IPython configuration,
795 startup files, and everything, just as if it were a normal IPython session.
795 startup files, and everything, just as if it were a normal IPython session.
796 In addition to this,
796 In addition to this,
797 it is possible to embed an IPython instance inside your own Python programs.
797 it is possible to embed an IPython instance inside your own Python programs.
798 This allows you to evaluate dynamically the state of your code,
798 This allows you to evaluate dynamically the state of your code,
799 operate with your variables, analyze them, etc. Note however that
799 operate with your variables, analyze them, etc. Note however that
800 any changes you make to values while in the shell do not propagate back
800 any changes you make to values while in the shell do not propagate back
801 to the running code, so it is safe to modify your values because you
801 to the running code, so it is safe to modify your values because you
802 won't break your code in bizarre ways by doing so.
802 won't break your code in bizarre ways by doing so.
803
803
804 .. note::
804 .. note::
805
805
806 At present, embedding IPython cannot be done from inside IPython.
806 At present, embedding IPython cannot be done from inside IPython.
807 Run the code samples below outside IPython.
807 Run the code samples below outside IPython.
808
808
809 This feature allows you to easily have a fully functional python
809 This feature allows you to easily have a fully functional python
810 environment for doing object introspection anywhere in your code with a
810 environment for doing object introspection anywhere in your code with a
811 simple function call. In some cases a simple print statement is enough,
811 simple function call. In some cases a simple print statement is enough,
812 but if you need to do more detailed analysis of a code fragment this
812 but if you need to do more detailed analysis of a code fragment this
813 feature can be very valuable.
813 feature can be very valuable.
814
814
815 It can also be useful in scientific computing situations where it is
815 It can also be useful in scientific computing situations where it is
816 common to need to do some automatic, computationally intensive part and
816 common to need to do some automatic, computationally intensive part and
817 then stop to look at data, plots, etc.
817 then stop to look at data, plots, etc.
818 Opening an IPython instance will give you full access to your data and
818 Opening an IPython instance will give you full access to your data and
819 functions, and you can resume program execution once you are done with
819 functions, and you can resume program execution once you are done with
820 the interactive part (perhaps to stop again later, as many times as
820 the interactive part (perhaps to stop again later, as many times as
821 needed).
821 needed).
822
822
823 The following code snippet is the bare minimum you need to include in
823 The following code snippet is the bare minimum you need to include in
824 your Python programs for this to work (detailed examples follow later)::
824 your Python programs for this to work (detailed examples follow later)::
825
825
826 from IPython import embed
826 from IPython import embed
827
827
828 embed() # this call anywhere in your program will start IPython
828 embed() # this call anywhere in your program will start IPython
829
829
830 .. note::
830 .. note::
831
831
832 As of 0.13, you can embed an IPython *kernel*, for use with qtconsole,
832 As of 0.13, you can embed an IPython *kernel*, for use with qtconsole,
833 etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``.
833 etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``.
834 It should function just the same as regular embed, but you connect
834 It should function just the same as regular embed, but you connect
835 an external frontend rather than IPython starting up in the local
835 an external frontend rather than IPython starting up in the local
836 terminal.
836 terminal.
837
837
838 You can run embedded instances even in code which is itself being run at
838 You can run embedded instances even in code which is itself being run at
839 the IPython interactive prompt with '%run <filename>'. Since it's easy
839 the IPython interactive prompt with '%run <filename>'. Since it's easy
840 to get lost as to where you are (in your top-level IPython or in your
840 to get lost as to where you are (in your top-level IPython or in your
841 embedded one), it's a good idea in such cases to set the in/out prompts
841 embedded one), it's a good idea in such cases to set the in/out prompts
842 to something different for the embedded instances. The code examples
842 to something different for the embedded instances. The code examples
843 below illustrate this.
843 below illustrate this.
844
844
845 You can also have multiple IPython instances in your program and open
845 You can also have multiple IPython instances in your program and open
846 them separately, for example with different options for data
846 them separately, for example with different options for data
847 presentation. If you close and open the same instance multiple times,
847 presentation. If you close and open the same instance multiple times,
848 its prompt counters simply continue from each execution to the next.
848 its prompt counters simply continue from each execution to the next.
849
849
850 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
850 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
851 module for more details on the use of this system.
851 module for more details on the use of this system.
852
852
853 The following sample file illustrating how to use the embedding
853 The following sample file illustrating how to use the embedding
854 functionality is provided in the examples directory as example-embed.py.
854 functionality is provided in the examples directory as example-embed.py.
855 It should be fairly self-explanatory:
855 It should be fairly self-explanatory:
856
856
857 .. literalinclude:: ../../../examples/core/example-embed.py
857 .. literalinclude:: ../../../examples/core/example-embed.py
858 :language: python
858 :language: python
859
859
860 Once you understand how the system functions, you can use the following
860 Once you understand how the system functions, you can use the following
861 code fragments in your programs which are ready for cut and paste:
861 code fragments in your programs which are ready for cut and paste:
862
862
863 .. literalinclude:: ../../../examples/core/example-embed-short.py
863 .. literalinclude:: ../../../examples/core/example-embed-short.py
864 :language: python
864 :language: python
865
865
866 Using the Python debugger (pdb)
866 Using the Python debugger (pdb)
867 ===============================
867 ===============================
868
868
869 Running entire programs via pdb
869 Running entire programs via pdb
870 -------------------------------
870 -------------------------------
871
871
872 pdb, the Python debugger, is a powerful interactive debugger which
872 pdb, the Python debugger, is a powerful interactive debugger which
873 allows you to step through code, set breakpoints, watch variables,
873 allows you to step through code, set breakpoints, watch variables,
874 etc. IPython makes it very easy to start any script under the control
874 etc. IPython makes it very easy to start any script under the control
875 of pdb, regardless of whether you have wrapped it into a 'main()'
875 of pdb, regardless of whether you have wrapped it into a 'main()'
876 function or not. For this, simply type '%run -d myscript' at an
876 function or not. For this, simply type '%run -d myscript' at an
877 IPython prompt. See the %run command's documentation (via '%run?' or
877 IPython prompt. See the %run command's documentation (via '%run?' or
878 in Sec. magic_ for more details, including how to control where pdb
878 in Sec. magic_ for more details, including how to control where pdb
879 will stop execution first.
879 will stop execution first.
880
880
881 For more information on the use of the pdb debugger, read the included
881 For more information on the use of the pdb debugger, read the included
882 pdb.doc file (part of the standard Python distribution). On a stock
882 pdb.doc file (part of the standard Python distribution). On a stock
883 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
883 Linux system it is located at /usr/lib/python2.3/pdb.doc, but the
884 easiest way to read it is by using the help() function of the pdb module
884 easiest way to read it is by using the help() function of the pdb module
885 as follows (in an IPython prompt)::
885 as follows (in an IPython prompt)::
886
886
887 In [1]: import pdb
887 In [1]: import pdb
888 In [2]: pdb.help()
888 In [2]: pdb.help()
889
889
890 This will load the pdb.doc document in a file viewer for you automatically.
890 This will load the pdb.doc document in a file viewer for you automatically.
891
891
892
892
893 Automatic invocation of pdb on exceptions
893 Automatic invocation of pdb on exceptions
894 -----------------------------------------
894 -----------------------------------------
895
895
896 IPython, if started with the ``--pdb`` option (or if the option is set in
896 IPython, if started with the ``--pdb`` option (or if the option is set in
897 your config file) can call the Python pdb debugger every time your code
897 your config file) can call the Python pdb debugger every time your code
898 triggers an uncaught exception. This feature
898 triggers an uncaught exception. This feature
899 can also be toggled at any time with the %pdb magic command. This can be
899 can also be toggled at any time with the %pdb magic command. This can be
900 extremely useful in order to find the origin of subtle bugs, because pdb
900 extremely useful in order to find the origin of subtle bugs, because pdb
901 opens up at the point in your code which triggered the exception, and
901 opens up at the point in your code which triggered the exception, and
902 while your program is at this point 'dead', all the data is still
902 while your program is at this point 'dead', all the data is still
903 available and you can walk up and down the stack frame and understand
903 available and you can walk up and down the stack frame and understand
904 the origin of the problem.
904 the origin of the problem.
905
905
906 Furthermore, you can use these debugging facilities both with the
906 Furthermore, you can use these debugging facilities both with the
907 embedded IPython mode and without IPython at all. For an embedded shell
907 embedded IPython mode and without IPython at all. For an embedded shell
908 (see sec. Embedding_), simply call the constructor with
908 (see sec. Embedding_), simply call the constructor with
909 ``--pdb`` in the argument string and pdb will automatically be called if an
909 ``--pdb`` in the argument string and pdb will automatically be called if an
910 uncaught exception is triggered by your code.
910 uncaught exception is triggered by your code.
911
911
912 For stand-alone use of the feature in your programs which do not use
912 For stand-alone use of the feature in your programs which do not use
913 IPython at all, put the following lines toward the top of your 'main'
913 IPython at all, put the following lines toward the top of your 'main'
914 routine::
914 routine::
915
915
916 import sys
916 import sys
917 from IPython.core import ultratb
917 from IPython.core import ultratb
918 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
918 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
919 color_scheme='Linux', call_pdb=1)
919 color_scheme='Linux', call_pdb=1)
920
920
921 The mode keyword can be either 'Verbose' or 'Plain', giving either very
921 The mode keyword can be either 'Verbose' or 'Plain', giving either very
922 detailed or normal tracebacks respectively. The color_scheme keyword can
922 detailed or normal tracebacks respectively. The color_scheme keyword can
923 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
923 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
924 options which can be set in IPython with ``--colors`` and ``--xmode``.
924 options which can be set in IPython with ``--colors`` and ``--xmode``.
925
925
926 This will give any of your programs detailed, colored tracebacks with
926 This will give any of your programs detailed, colored tracebacks with
927 automatic invocation of pdb.
927 automatic invocation of pdb.
928
928
929
929
930 Extensions for syntax processing
930 Extensions for syntax processing
931 ================================
931 ================================
932
932
933 This isn't for the faint of heart, because the potential for breaking
933 This isn't for the faint of heart, because the potential for breaking
934 things is quite high. But it can be a very powerful and useful feature.
934 things is quite high. But it can be a very powerful and useful feature.
935 In a nutshell, you can redefine the way IPython processes the user input
935 In a nutshell, you can redefine the way IPython processes the user input
936 line to accept new, special extensions to the syntax without needing to
936 line to accept new, special extensions to the syntax without needing to
937 change any of IPython's own code.
937 change any of IPython's own code.
938
938
939 In the IPython/extensions directory you will find some examples
939 In the IPython/extensions directory you will find some examples
940 supplied, which we will briefly describe now. These can be used 'as is'
940 supplied, which we will briefly describe now. These can be used 'as is'
941 (and both provide very useful functionality), or you can use them as a
941 (and both provide very useful functionality), or you can use them as a
942 starting point for writing your own extensions.
942 starting point for writing your own extensions.
943
943
944 .. _pasting_with_prompts:
944 .. _pasting_with_prompts:
945
945
946 Pasting of code starting with Python or IPython prompts
946 Pasting of code starting with Python or IPython prompts
947 -------------------------------------------------------
947 -------------------------------------------------------
948
948
949 IPython is smart enough to filter out input prompts, be they plain Python ones
949 IPython is smart enough to filter out input prompts, be they plain Python ones
950 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
950 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
951 therefore copy and paste from existing interactive sessions without worry.
951 therefore copy and paste from existing interactive sessions without worry.
952
952
953 The following is a 'screenshot' of how things work, copying an example from the
953 The following is a 'screenshot' of how things work, copying an example from the
954 standard Python tutorial::
954 standard Python tutorial::
955
955
956 In [1]: >>> # Fibonacci series:
956 In [1]: >>> # Fibonacci series:
957
957
958 In [2]: ... # the sum of two elements defines the next
958 In [2]: ... # the sum of two elements defines the next
959
959
960 In [3]: ... a, b = 0, 1
960 In [3]: ... a, b = 0, 1
961
961
962 In [4]: >>> while b < 10:
962 In [4]: >>> while b < 10:
963 ...: ... print b
963 ...: ... print b
964 ...: ... a, b = b, a+b
964 ...: ... a, b = b, a+b
965 ...:
965 ...:
966 1
966 1
967 1
967 1
968 2
968 2
969 3
969 3
970 5
970 5
971 8
971 8
972
972
973 And pasting from IPython sessions works equally well::
973 And pasting from IPython sessions works equally well::
974
974
975 In [1]: In [5]: def f(x):
975 In [1]: In [5]: def f(x):
976 ...: ...: "A simple function"
976 ...: ...: "A simple function"
977 ...: ...: return x**2
977 ...: ...: return x**2
978 ...: ...:
978 ...: ...:
979
979
980 In [2]: f(3)
980 In [2]: f(3)
981 Out[2]: 9
981 Out[2]: 9
982
982
983 .. _gui_support:
983 .. _gui_support:
984
984
985 GUI event loop support
985 GUI event loop support
986 ======================
986 ======================
987
987
988 .. versionadded:: 0.11
988 .. versionadded:: 0.11
989 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
989 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
990
990
991 IPython has excellent support for working interactively with Graphical User
991 IPython has excellent support for working interactively with Graphical User
992 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
992 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
993 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
993 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
994 is extremely robust compared to our previous thread-based version. The
994 is extremely robust compared to our previous thread-based version. The
995 advantages of this are:
995 advantages of this are:
996
996
997 * GUIs can be enabled and disabled dynamically at runtime.
997 * GUIs can be enabled and disabled dynamically at runtime.
998 * The active GUI can be switched dynamically at runtime.
998 * The active GUI can be switched dynamically at runtime.
999 * In some cases, multiple GUIs can run simultaneously with no problems.
999 * In some cases, multiple GUIs can run simultaneously with no problems.
1000 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1000 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
1001 all of these things.
1001 all of these things.
1002
1002
1003 For users, enabling GUI event loop integration is simple. You simple use the
1003 For users, enabling GUI event loop integration is simple. You simple use the
1004 ``%gui`` magic as follows::
1004 ``%gui`` magic as follows::
1005
1005
1006 %gui [GUINAME]
1006 %gui [GUINAME]
1007
1007
1008 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1008 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
1009 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
1009 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
1010
1010
1011 Thus, to use wxPython interactively and create a running :class:`wx.App`
1011 Thus, to use wxPython interactively and create a running :class:`wx.App`
1012 object, do::
1012 object, do::
1013
1013
1014 %gui wx
1014 %gui wx
1015
1015
1016 For information on IPython's Matplotlib integration (and the ``matplotlib``
1016 For information on IPython's matplotlib_ integration (and the ``matplotlib``
1017 mode) see :ref:`this section <matplotlib_support>`.
1017 mode) see :ref:`this section <matplotlib_support>`.
1018
1018
1019 For developers that want to use IPython's GUI event loop integration in the
1019 For developers that want to use IPython's GUI event loop integration in the
1020 form of a library, these capabilities are exposed in library form in the
1020 form of a library, these capabilities are exposed in library form in the
1021 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
1021 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
1022 Interested developers should see the module docstrings for more information,
1022 Interested developers should see the module docstrings for more information,
1023 but there are a few points that should be mentioned here.
1023 but there are a few points that should be mentioned here.
1024
1024
1025 First, the ``PyOSInputHook`` approach only works in command line settings
1025 First, the ``PyOSInputHook`` approach only works in command line settings
1026 where readline is activated. The integration with various eventloops
1026 where readline is activated. The integration with various eventloops
1027 is handled somewhat differently (and more simply) when using the standalone
1027 is handled somewhat differently (and more simply) when using the standalone
1028 kernel, as in the qtconsole and notebook.
1028 kernel, as in the qtconsole and notebook.
1029
1029
1030 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1030 Second, when using the ``PyOSInputHook`` approach, a GUI application should
1031 *not* start its event loop. Instead all of this is handled by the
1031 *not* start its event loop. Instead all of this is handled by the
1032 ``PyOSInputHook``. This means that applications that are meant to be used both
1032 ``PyOSInputHook``. This means that applications that are meant to be used both
1033 in IPython and as standalone apps need to have special code to detects how the
1033 in IPython and as standalone apps need to have special code to detects how the
1034 application is being run. We highly recommend using IPython's support for this.
1034 application is being run. We highly recommend using IPython's support for this.
1035 Since the details vary slightly between toolkits, we point you to the various
1035 Since the details vary slightly between toolkits, we point you to the various
1036 examples in our source directory :file:`examples/lib` that demonstrate
1036 examples in our source directory :file:`examples/lib` that demonstrate
1037 these capabilities.
1037 these capabilities.
1038
1038
1039 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1039 Third, unlike previous versions of IPython, we no longer "hijack" (replace
1040 them with no-ops) the event loops. This is done to allow applications that
1040 them with no-ops) the event loops. This is done to allow applications that
1041 actually need to run the real event loops to do so. This is often needed to
1041 actually need to run the real event loops to do so. This is often needed to
1042 process pending events at critical points.
1042 process pending events at critical points.
1043
1043
1044 Finally, we also have a number of examples in our source directory
1044 Finally, we also have a number of examples in our source directory
1045 :file:`examples/lib` that demonstrate these capabilities.
1045 :file:`examples/lib` that demonstrate these capabilities.
1046
1046
1047 PyQt and PySide
1047 PyQt and PySide
1048 ---------------
1048 ---------------
1049
1049
1050 .. attempt at explanation of the complete mess that is Qt support
1050 .. attempt at explanation of the complete mess that is Qt support
1051
1051
1052 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
1052 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
1053 PyQt4 or PySide. There are three options for configuration here, because
1053 PyQt4 or PySide. There are three options for configuration here, because
1054 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
1054 PyQt4 has two APIs for QString and QVariant - v1, which is the default on
1055 Python 2, and the more natural v2, which is the only API supported by PySide.
1055 Python 2, and the more natural v2, which is the only API supported by PySide.
1056 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
1056 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
1057 uses v2, but you can still use any interface in your code, since the
1057 uses v2, but you can still use any interface in your code, since the
1058 Qt frontend is in a different process.
1058 Qt frontend is in a different process.
1059
1059
1060 The default will be to import PyQt4 without configuration of the APIs, thus
1060 The default will be to import PyQt4 without configuration of the APIs, thus
1061 matching what most applications would expect. It will fall back of PySide if
1061 matching what most applications would expect. It will fall back of PySide if
1062 PyQt4 is unavailable.
1062 PyQt4 is unavailable.
1063
1063
1064 If specified, IPython will respect the environment variable ``QT_API`` used
1064 If specified, IPython will respect the environment variable ``QT_API`` used
1065 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
1065 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
1066 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
1066 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
1067 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
1067 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
1068 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
1068 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
1069
1069
1070 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
1070 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
1071 then IPython will ask matplotlib which Qt library to use (only if QT_API is
1071 then IPython will ask matplotlib which Qt library to use (only if QT_API is
1072 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
1072 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
1073 older, then IPython will always use PyQt4 without setting the v2 APIs, since
1073 older, then IPython will always use PyQt4 without setting the v2 APIs, since
1074 neither v2 PyQt nor PySide work.
1074 neither v2 PyQt nor PySide work.
1075
1075
1076 .. warning::
1076 .. warning::
1077
1077
1078 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
1078 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
1079 to work with IPython's qt integration, because otherwise PyQt4 will be
1079 to work with IPython's qt integration, because otherwise PyQt4 will be
1080 loaded in an incompatible mode.
1080 loaded in an incompatible mode.
1081
1081
1082 It also means that you must *not* have ``QT_API`` set if you want to
1082 It also means that you must *not* have ``QT_API`` set if you want to
1083 use ``--gui=qt`` with code that requires PyQt4 API v1.
1083 use ``--gui=qt`` with code that requires PyQt4 API v1.
1084
1084
1085
1085
1086 .. _matplotlib_support:
1086 .. _matplotlib_support:
1087
1087
1088 Plotting with matplotlib
1088 Plotting with matplotlib
1089 ========================
1089 ========================
1090
1090
1091 `Matplotlib`_ provides high quality 2D and 3D plotting for Python. Matplotlib
1091 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
1092 can produce plots on screen using a variety of GUI toolkits, including Tk,
1092 can produce plots on screen using a variety of GUI toolkits, including Tk,
1093 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
1093 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
1094 scientific computing, all with a syntax compatible with that of the popular
1094 scientific computing, all with a syntax compatible with that of the popular
1095 Matlab program.
1095 Matlab program.
1096
1096
1097 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
1097 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
1098 IPython is already running, you can run the ``%matplotlib`` magic. If no
1098 IPython is already running, you can run the ``%matplotlib`` magic. If no
1099 arguments are given, IPython will automatically detect your choice of
1099 arguments are given, IPython will automatically detect your choice of
1100 matplotlib backend. You can also request a specific backend with
1100 matplotlib backend. You can also request a specific backend with
1101 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
1101 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
1102 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
1102 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
1103 backend value, which produces static figures inlined inside the application
1103 backend value, which produces static figures inlined inside the application
1104 window instead of matplotlib's interactive figures that live in separate
1104 window instead of matplotlib's interactive figures that live in separate
1105 windows.
1105 windows.
1106
1106
1107 .. _Matplotlib: http://matplotlib.sourceforge.net
1108
1109 .. _interactive_demos:
1107 .. _interactive_demos:
1110
1108
1111 Interactive demos with IPython
1109 Interactive demos with IPython
1112 ==============================
1110 ==============================
1113
1111
1114 IPython ships with a basic system for running scripts interactively in
1112 IPython ships with a basic system for running scripts interactively in
1115 sections, useful when presenting code to audiences. A few tags embedded
1113 sections, useful when presenting code to audiences. A few tags embedded
1116 in comments (so that the script remains valid Python code) divide a file
1114 in comments (so that the script remains valid Python code) divide a file
1117 into separate blocks, and the demo can be run one block at a time, with
1115 into separate blocks, and the demo can be run one block at a time, with
1118 IPython printing (with syntax highlighting) the block before executing
1116 IPython printing (with syntax highlighting) the block before executing
1119 it, and returning to the interactive prompt after each block. The
1117 it, and returning to the interactive prompt after each block. The
1120 interactive namespace is updated after each block is run with the
1118 interactive namespace is updated after each block is run with the
1121 contents of the demo's namespace.
1119 contents of the demo's namespace.
1122
1120
1123 This allows you to show a piece of code, run it and then execute
1121 This allows you to show a piece of code, run it and then execute
1124 interactively commands based on the variables just created. Once you
1122 interactively commands based on the variables just created. Once you
1125 want to continue, you simply execute the next block of the demo. The
1123 want to continue, you simply execute the next block of the demo. The
1126 following listing shows the markup necessary for dividing a script into
1124 following listing shows the markup necessary for dividing a script into
1127 sections for execution as a demo:
1125 sections for execution as a demo:
1128
1126
1129 .. literalinclude:: ../../../examples/lib/example-demo.py
1127 .. literalinclude:: ../../../examples/lib/example-demo.py
1130 :language: python
1128 :language: python
1131
1129
1132 In order to run a file as a demo, you must first make a Demo object out
1130 In order to run a file as a demo, you must first make a Demo object out
1133 of it. If the file is named myscript.py, the following code will make a
1131 of it. If the file is named myscript.py, the following code will make a
1134 demo::
1132 demo::
1135
1133
1136 from IPython.lib.demo import Demo
1134 from IPython.lib.demo import Demo
1137
1135
1138 mydemo = Demo('myscript.py')
1136 mydemo = Demo('myscript.py')
1139
1137
1140 This creates the mydemo object, whose blocks you run one at a time by
1138 This creates the mydemo object, whose blocks you run one at a time by
1141 simply calling the object with no arguments. If you have autocall active
1139 simply calling the object with no arguments. If you have autocall active
1142 in IPython (the default), all you need to do is type::
1140 in IPython (the default), all you need to do is type::
1143
1141
1144 mydemo
1142 mydemo
1145
1143
1146 and IPython will call it, executing each block. Demo objects can be
1144 and IPython will call it, executing each block. Demo objects can be
1147 restarted, you can move forward or back skipping blocks, re-execute the
1145 restarted, you can move forward or back skipping blocks, re-execute the
1148 last block, etc. Simply use the Tab key on a demo object to see its
1146 last block, etc. Simply use the Tab key on a demo object to see its
1149 methods, and call '?' on them to see their docstrings for more usage
1147 methods, and call '?' on them to see their docstrings for more usage
1150 details. In addition, the demo module itself contains a comprehensive
1148 details. In addition, the demo module itself contains a comprehensive
1151 docstring, which you can access via::
1149 docstring, which you can access via::
1152
1150
1153 from IPython.lib import demo
1151 from IPython.lib import demo
1154
1152
1155 demo?
1153 demo?
1156
1154
1157 Limitations: It is important to note that these demos are limited to
1155 Limitations: It is important to note that these demos are limited to
1158 fairly simple uses. In particular, you cannot break up sections within
1156 fairly simple uses. In particular, you cannot break up sections within
1159 indented code (loops, if statements, function definitions, etc.)
1157 indented code (loops, if statements, function definitions, etc.)
1160 Supporting something like this would basically require tracking the
1158 Supporting something like this would basically require tracking the
1161 internal execution state of the Python interpreter, so only top-level
1159 internal execution state of the Python interpreter, so only top-level
1162 divisions are allowed. If you want to be able to open an IPython
1160 divisions are allowed. If you want to be able to open an IPython
1163 instance at an arbitrary point in a program, you can use IPython's
1161 instance at an arbitrary point in a program, you can use IPython's
1164 embedding facilities, see :func:`IPython.embed` for details.
1162 embedding facilities, see :func:`IPython.embed` for details.
1165
1163
1164 .. include:: ../links.txt
@@ -1,101 +1,101 b''
1 .. This (-*- rst -*-) format file contains commonly used link targets
1 .. This (-*- rst -*-) format file contains commonly used link targets
2 and name substitutions. It may be included in many files,
2 and name substitutions. It may be included in many files,
3 therefore it should only contain link targets and name
3 therefore it should only contain link targets and name
4 substitutions. Try grepping for "^\.\. _" to find plausible
4 substitutions. Try grepping for "^\.\. _" to find plausible
5 candidates for this list.
5 candidates for this list.
6
6
7 NOTE: this file must have an extension *opposite* to that of the main reST
7 NOTE: this file must have an extension *opposite* to that of the main reST
8 files in the manuals, so that we can include it with ".. include::"
8 files in the manuals, so that we can include it with ".. include::"
9 directives, but without triggering warnings from Sphinx for not being listed
9 directives, but without triggering warnings from Sphinx for not being listed
10 in any toctree. Since IPython uses .txt for the main files, this wone will
10 in any toctree. Since IPython uses .txt for the main files, this wone will
11 use .rst.
11 use .rst.
12
12
13 NOTE: reST targets are
13 NOTE: reST targets are
14 __not_case_sensitive__, so only one target definition is needed for
14 __not_case_sensitive__, so only one target definition is needed for
15 ipython, IPython, etc.
15 ipython, IPython, etc.
16
16
17 NOTE: Some of these were taken from the nipy links compendium.
17 NOTE: Some of these were taken from the nipy links compendium.
18
18
19 .. Main IPython links
19 .. Main IPython links
20 .. _ipython: http://ipython.org
20 .. _ipython: http://ipython.org
21 .. _`ipython manual`: http://ipython.org/documentation.html
21 .. _`ipython manual`: http://ipython.org/documentation.html
22 .. _ipython_github: http://github.com/ipython/ipython/
22 .. _ipython_github: http://github.com/ipython/ipython/
23 .. _ipython_github_repo: http://github.com/ipython/ipython/
23 .. _ipython_github_repo: http://github.com/ipython/ipython/
24 .. _ipython_downloads: http://ipython.org/download.html
24 .. _ipython_downloads: http://ipython.org/download.html
25 .. _ipython_pypi: http://pypi.python.org/pypi/ipython
25 .. _ipython_pypi: http://pypi.python.org/pypi/ipython
26 .. _nbviewer: http://nbviewer.ipython.org
26 .. _nbviewer: http://nbviewer.ipython.org
27
27
28 .. _ZeroMQ: http://zeromq.org
28 .. _ZeroMQ: http://zeromq.org
29
29
30 .. Documentation tools and related links
30 .. Documentation tools and related links
31 .. _graphviz: http://www.graphviz.org
31 .. _graphviz: http://www.graphviz.org
32 .. _Sphinx: http://sphinx.pocoo.org
32 .. _Sphinx: http://sphinx.pocoo.org
33 .. _`Sphinx reST`: http://sphinx.pocoo.org/rest.html
33 .. _`Sphinx reST`: http://sphinx.pocoo.org/rest.html
34 .. _sampledoc: http://matplotlib.sourceforge.net/sampledoc
34 .. _sampledoc: http://matplotlib.org/sampledoc
35 .. _reST: http://docutils.sourceforge.net/rst.html
35 .. _reST: http://docutils.sourceforge.net/rst.html
36 .. _docutils: http://docutils.sourceforge.net
36 .. _docutils: http://docutils.sourceforge.net
37 .. _lyx: http://www.lyx.org
37 .. _lyx: http://www.lyx.org
38 .. _pep8: http://www.python.org/dev/peps/pep-0008
38 .. _pep8: http://www.python.org/dev/peps/pep-0008
39 .. _numpy_coding_guide: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
39 .. _numpy_coding_guide: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
40
40
41 .. Licenses
41 .. Licenses
42 .. _GPL: http://www.gnu.org/licenses/gpl.html
42 .. _GPL: http://www.gnu.org/licenses/gpl.html
43 .. _BSD: http://www.opensource.org/licenses/bsd-license.php
43 .. _BSD: http://www.opensource.org/licenses/bsd-license.php
44 .. _LGPL: http://www.gnu.org/copyleft/lesser.html
44 .. _LGPL: http://www.gnu.org/copyleft/lesser.html
45
45
46 .. Other python projects
46 .. Other python projects
47 .. _numpy: http://numpy.scipy.org
47 .. _numpy: http://numpy.scipy.org
48 .. _scipy: http://www.scipy.org
48 .. _scipy: http://www.scipy.org
49 .. _scipy_conference: http://conference.scipy.org
49 .. _scipy_conference: http://conference.scipy.org
50 .. _matplotlib: http://matplotlib.org
50 .. _matplotlib: http://matplotlib.org
51 .. _pythonxy: http://www.pythonxy.com
51 .. _pythonxy: http://www.pythonxy.com
52 .. _ETS: http://code.enthought.com/projects/tool-suite.php
52 .. _ETS: http://code.enthought.com/projects/tool-suite.php
53 .. _EPD: http://www.enthought.com/products/epd.php
53 .. _EPD: http://www.enthought.com/products/epd.php
54 .. _python: http://www.python.org
54 .. _python: http://www.python.org
55 .. _mayavi: http://code.enthought.com/projects/mayavi
55 .. _mayavi: http://code.enthought.com/projects/mayavi
56 .. _sympy: http://code.google.com/p/sympy
56 .. _sympy: http://code.google.com/p/sympy
57 .. _sage: http://sagemath.org
57 .. _sage: http://sagemath.org
58 .. _pydy: http://code.google.com/p/pydy
58 .. _pydy: http://code.google.com/p/pydy
59 .. _vpython: http://vpython.org
59 .. _vpython: http://vpython.org
60 .. _cython: http://cython.org
60 .. _cython: http://cython.org
61 .. _software carpentry: http://software-carpentry.org
61 .. _software carpentry: http://software-carpentry.org
62
62
63 .. Not so python scientific computing tools
63 .. Not so python scientific computing tools
64 .. _matlab: http://www.mathworks.com
64 .. _matlab: http://www.mathworks.com
65 .. _VTK: http://vtk.org
65 .. _VTK: http://vtk.org
66
66
67 .. Other organizations
67 .. Other organizations
68 .. _enthought: http://www.enthought.com
68 .. _enthought: http://www.enthought.com
69 .. _kitware: http://www.kitware.com
69 .. _kitware: http://www.kitware.com
70 .. _netlib: http://netlib.org
70 .. _netlib: http://netlib.org
71
71
72 .. Other tools and projects
72 .. Other tools and projects
73 .. _indefero: http://www.indefero.net
73 .. _indefero: http://www.indefero.net
74 .. _git: http://git-scm.com
74 .. _git: http://git-scm.com
75 .. _github: http://github.com
75 .. _github: http://github.com
76 .. _Markdown: http://daringfireball.net/projects/markdown/syntax
76 .. _Markdown: http://daringfireball.net/projects/markdown/syntax
77
77
78 .. _Running Code in the IPython Notebook: notebook_p1_
78 .. _Running Code in the IPython Notebook: notebook_p1_
79 .. _notebook_p1: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%25201%2520-%2520Running%2520Code.ipynb
79 .. _notebook_p1: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%25201%2520-%2520Running%2520Code.ipynb
80
80
81 .. _Basic Output: notebook_p2_
81 .. _Basic Output: notebook_p2_
82 .. _notebook_p2: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%202%20-%20Basic%20Output.ipynb
82 .. _notebook_p2: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%202%20-%20Basic%20Output.ipynb
83
83
84 .. _Plotting with Matplotlib: notebook_p3_
84 .. _Plotting with Matplotlib: notebook_p3_
85 .. _notebook_p3: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb
85 .. _notebook_p3: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb
86
86
87 .. _Markdown Cells: notebook_p4
87 .. _Markdown Cells: notebook_p4
88 .. _notebook_p4: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%204%20-%20Markdown%20Cells.ipynb
88 .. _notebook_p4: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%204%20-%20Markdown%20Cells.ipynb
89
89
90 .. _Rich Display System: notebook_p5_
90 .. _Rich Display System: notebook_p5_
91 .. _notebook_p5: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%205%20-%20Rich%20Display%20System.ipynb
91 .. _notebook_p5: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Part%205%20-%20Rich%20Display%20System.ipynb
92
92
93 .. _notebook_custom_display: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Custom%20Display%20Logic.ipynb
93 .. _notebook_custom_display: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Custom%20Display%20Logic.ipynb
94
94
95 .. _Frontend/Kernel Model: notebook_two_proc_
95 .. _Frontend/Kernel Model: notebook_two_proc_
96 .. _notebook_two_proc: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Frontend-Kernel%20Model.ipynb
96 .. _notebook_two_proc: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Frontend-Kernel%20Model.ipynb
97
97
98 .. _Cell magics: notebook_cell_magics_
98 .. _Cell magics: notebook_cell_magics_
99 .. _notebook_cell_magics: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Cell%20Magics.ipynb
99 .. _notebook_cell_magics: http://nbviewer.ipython.org/urls/raw.github.com/ipython/ipython/1.x/examples/notebooks/Cell%20Magics.ipynb
100
100
101
101
@@ -1,360 +1,361 b''
1 ============================================
1 ============================================
2 Getting started with Windows HPC Server 2008
2 Getting started with Windows HPC Server 2008
3 ============================================
3 ============================================
4
4
5 Introduction
5 Introduction
6 ============
6 ============
7
7
8 The Python programming language is an increasingly popular language for
8 The Python programming language is an increasingly popular language for
9 numerical computing. This is due to a unique combination of factors. First,
9 numerical computing. This is due to a unique combination of factors. First,
10 Python is a high-level and *interactive* language that is well matched to
10 Python is a high-level and *interactive* language that is well matched to
11 interactive numerical work. Second, it is easy (often times trivial) to
11 interactive numerical work. Second, it is easy (often times trivial) to
12 integrate legacy C/C++/Fortran code into Python. Third, a large number of
12 integrate legacy C/C++/Fortran code into Python. Third, a large number of
13 high-quality open source projects provide all the needed building blocks for
13 high-quality open source projects provide all the needed building blocks for
14 numerical computing: numerical arrays (NumPy), algorithms (SciPy), 2D/3D
14 numerical computing: numerical arrays (NumPy), algorithms (SciPy), 2D/3D
15 Visualization (Matplotlib, Mayavi, Chaco), Symbolic Mathematics (Sage, Sympy)
15 Visualization (matplotlib_, Mayavi, Chaco), Symbolic Mathematics (Sage, Sympy)
16 and others.
16 and others.
17
17
18 The IPython project is a core part of this open-source toolchain and is
18 The IPython project is a core part of this open-source toolchain and is
19 focused on creating a comprehensive environment for interactive and
19 focused on creating a comprehensive environment for interactive and
20 exploratory computing in the Python programming language. It enables all of
20 exploratory computing in the Python programming language. It enables all of
21 the above tools to be used interactively and consists of two main components:
21 the above tools to be used interactively and consists of two main components:
22
22
23 * An enhanced interactive Python shell with support for interactive plotting
23 * An enhanced interactive Python shell with support for interactive plotting
24 and visualization.
24 and visualization.
25 * An architecture for interactive parallel computing.
25 * An architecture for interactive parallel computing.
26
26
27 With these components, it is possible to perform all aspects of a parallel
27 With these components, it is possible to perform all aspects of a parallel
28 computation interactively. This type of workflow is particularly relevant in
28 computation interactively. This type of workflow is particularly relevant in
29 scientific and numerical computing where algorithms, code and data are
29 scientific and numerical computing where algorithms, code and data are
30 continually evolving as the user/developer explores a problem. The broad
30 continually evolving as the user/developer explores a problem. The broad
31 threads in computing (commodity clusters, multicore, cloud computing, etc.)
31 threads in computing (commodity clusters, multicore, cloud computing, etc.)
32 make these capabilities of IPython particularly relevant.
32 make these capabilities of IPython particularly relevant.
33
33
34 While IPython is a cross platform tool, it has particularly strong support for
34 While IPython is a cross platform tool, it has particularly strong support for
35 Windows based compute clusters running Windows HPC Server 2008. This document
35 Windows based compute clusters running Windows HPC Server 2008. This document
36 describes how to get started with IPython on Windows HPC Server 2008. The
36 describes how to get started with IPython on Windows HPC Server 2008. The
37 content and emphasis here is practical: installing IPython, configuring
37 content and emphasis here is practical: installing IPython, configuring
38 IPython to use the Windows job scheduler and running example parallel programs
38 IPython to use the Windows job scheduler and running example parallel programs
39 interactively. A more complete description of IPython's parallel computing
39 interactively. A more complete description of IPython's parallel computing
40 capabilities can be found in IPython's online documentation
40 capabilities can be found in IPython's online documentation
41 (http://ipython.org/documentation.html).
41 (http://ipython.org/documentation.html).
42
42
43 Setting up your Windows cluster
43 Setting up your Windows cluster
44 ===============================
44 ===============================
45
45
46 This document assumes that you already have a cluster running Windows
46 This document assumes that you already have a cluster running Windows
47 HPC Server 2008. Here is a broad overview of what is involved with setting up
47 HPC Server 2008. Here is a broad overview of what is involved with setting up
48 such a cluster:
48 such a cluster:
49
49
50 1. Install Windows Server 2008 on the head and compute nodes in the cluster.
50 1. Install Windows Server 2008 on the head and compute nodes in the cluster.
51 2. Setup the network configuration on each host. Each host should have a
51 2. Setup the network configuration on each host. Each host should have a
52 static IP address.
52 static IP address.
53 3. On the head node, activate the "Active Directory Domain Services" role
53 3. On the head node, activate the "Active Directory Domain Services" role
54 and make the head node the domain controller.
54 and make the head node the domain controller.
55 4. Join the compute nodes to the newly created Active Directory (AD) domain.
55 4. Join the compute nodes to the newly created Active Directory (AD) domain.
56 5. Setup user accounts in the domain with shared home directories.
56 5. Setup user accounts in the domain with shared home directories.
57 6. Install the HPC Pack 2008 on the head node to create a cluster.
57 6. Install the HPC Pack 2008 on the head node to create a cluster.
58 7. Install the HPC Pack 2008 on the compute nodes.
58 7. Install the HPC Pack 2008 on the compute nodes.
59
59
60 More details about installing and configuring Windows HPC Server 2008 can be
60 More details about installing and configuring Windows HPC Server 2008 can be
61 found on the Windows HPC Home Page (http://www.microsoft.com/hpc). Regardless
61 found on the Windows HPC Home Page (http://www.microsoft.com/hpc). Regardless
62 of what steps you follow to set up your cluster, the remainder of this
62 of what steps you follow to set up your cluster, the remainder of this
63 document will assume that:
63 document will assume that:
64
64
65 * There are domain users that can log on to the AD domain and submit jobs
65 * There are domain users that can log on to the AD domain and submit jobs
66 to the cluster scheduler.
66 to the cluster scheduler.
67 * These domain users have shared home directories. While shared home
67 * These domain users have shared home directories. While shared home
68 directories are not required to use IPython, they make it much easier to
68 directories are not required to use IPython, they make it much easier to
69 use IPython.
69 use IPython.
70
70
71 Installation of IPython and its dependencies
71 Installation of IPython and its dependencies
72 ============================================
72 ============================================
73
73
74 IPython and all of its dependencies are freely available and open source.
74 IPython and all of its dependencies are freely available and open source.
75 These packages provide a powerful and cost-effective approach to numerical and
75 These packages provide a powerful and cost-effective approach to numerical and
76 scientific computing on Windows. The following dependencies are needed to run
76 scientific computing on Windows. The following dependencies are needed to run
77 IPython on Windows:
77 IPython on Windows:
78
78
79 * Python 2.6 or 2.7 (http://www.python.org)
79 * Python 2.6 or 2.7 (http://www.python.org)
80 * pywin32 (http://sourceforge.net/projects/pywin32/)
80 * pywin32 (http://sourceforge.net/projects/pywin32/)
81 * PyReadline (https://launchpad.net/pyreadline)
81 * PyReadline (https://launchpad.net/pyreadline)
82 * pyzmq (http://github.com/zeromq/pyzmq/downloads)
82 * pyzmq (http://github.com/zeromq/pyzmq/downloads)
83 * IPython (http://ipython.org)
83 * IPython (http://ipython.org)
84
84
85 In addition, the following dependencies are needed to run the demos described
85 In addition, the following dependencies are needed to run the demos described
86 in this document.
86 in this document.
87
87
88 * NumPy and SciPy (http://www.scipy.org)
88 * NumPy and SciPy (http://www.scipy.org)
89 * Matplotlib (http://matplotlib.sourceforge.net/)
89 * matplotlib_ (http://matplotlib.org)
90
90
91 The easiest way of obtaining these dependencies is through the Enthought
91 The easiest way of obtaining these dependencies is through the Enthought
92 Python Distribution (EPD) (http://www.enthought.com/products/epd.php). EPD is
92 Python Distribution (EPD) (http://www.enthought.com/products/epd.php). EPD is
93 produced by Enthought, Inc. and contains all of these packages and others in a
93 produced by Enthought, Inc. and contains all of these packages and others in a
94 single installer and is available free for academic users. While it is also
94 single installer and is available free for academic users. While it is also
95 possible to download and install each package individually, this is a tedious
95 possible to download and install each package individually, this is a tedious
96 process. Thus, we highly recommend using EPD to install these packages on
96 process. Thus, we highly recommend using EPD to install these packages on
97 Windows.
97 Windows.
98
98
99 Regardless of how you install the dependencies, here are the steps you will
99 Regardless of how you install the dependencies, here are the steps you will
100 need to follow:
100 need to follow:
101
101
102 1. Install all of the packages listed above, either individually or using EPD
102 1. Install all of the packages listed above, either individually or using EPD
103 on the head node, compute nodes and user workstations.
103 on the head node, compute nodes and user workstations.
104
104
105 2. Make sure that :file:`C:\\Python27` and :file:`C:\\Python27\\Scripts` are
105 2. Make sure that :file:`C:\\Python27` and :file:`C:\\Python27\\Scripts` are
106 in the system :envvar:`%PATH%` variable on each node.
106 in the system :envvar:`%PATH%` variable on each node.
107
107
108 3. Install the latest development version of IPython. This can be done by
108 3. Install the latest development version of IPython. This can be done by
109 downloading the the development version from the IPython website
109 downloading the the development version from the IPython website
110 (http://ipython.org) and following the installation instructions.
110 (http://ipython.org) and following the installation instructions.
111
111
112 Further details about installing IPython or its dependencies can be found in
112 Further details about installing IPython or its dependencies can be found in
113 the online IPython documentation (http://ipython.org/documentation.html)
113 the online IPython documentation (http://ipython.org/documentation.html)
114 Once you are finished with the installation, you can try IPython out by
114 Once you are finished with the installation, you can try IPython out by
115 opening a Windows Command Prompt and typing ``ipython``. This will
115 opening a Windows Command Prompt and typing ``ipython``. This will
116 start IPython's interactive shell and you should see something like the
116 start IPython's interactive shell and you should see something like the
117 following::
117 following::
118
118
119 Microsoft Windows [Version 6.0.6001]
119 Microsoft Windows [Version 6.0.6001]
120 Copyright (c) 2006 Microsoft Corporation. All rights reserved.
120 Copyright (c) 2006 Microsoft Corporation. All rights reserved.
121
121
122 Z:\>ipython
122 Z:\>ipython
123 Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
123 Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)]
124 Type "copyright", "credits" or "license" for more information.
124 Type "copyright", "credits" or "license" for more information.
125
125
126 IPython 0.12.dev -- An enhanced Interactive Python.
126 IPython 0.12.dev -- An enhanced Interactive Python.
127 ? -> Introduction and overview of IPython's features.
127 ? -> Introduction and overview of IPython's features.
128 %quickref -> Quick reference.
128 %quickref -> Quick reference.
129 help -> Python's own help system.
129 help -> Python's own help system.
130 object? -> Details about 'object', use 'object??' for extra details.
130 object? -> Details about 'object', use 'object??' for extra details.
131
131
132 In [1]:
132 In [1]:
133
133
134
134
135 Starting an IPython cluster
135 Starting an IPython cluster
136 ===========================
136 ===========================
137
137
138 To use IPython's parallel computing capabilities, you will need to start an
138 To use IPython's parallel computing capabilities, you will need to start an
139 IPython cluster. An IPython cluster consists of one controller and multiple
139 IPython cluster. An IPython cluster consists of one controller and multiple
140 engines:
140 engines:
141
141
142 IPython controller
142 IPython controller
143 The IPython controller manages the engines and acts as a gateway between
143 The IPython controller manages the engines and acts as a gateway between
144 the engines and the client, which runs in the user's interactive IPython
144 the engines and the client, which runs in the user's interactive IPython
145 session. The controller is started using the :command:`ipcontroller`
145 session. The controller is started using the :command:`ipcontroller`
146 command.
146 command.
147
147
148 IPython engine
148 IPython engine
149 IPython engines run a user's Python code in parallel on the compute nodes.
149 IPython engines run a user's Python code in parallel on the compute nodes.
150 Engines are starting using the :command:`ipengine` command.
150 Engines are starting using the :command:`ipengine` command.
151
151
152 Once these processes are started, a user can run Python code interactively and
152 Once these processes are started, a user can run Python code interactively and
153 in parallel on the engines from within the IPython shell using an appropriate
153 in parallel on the engines from within the IPython shell using an appropriate
154 client. This includes the ability to interact with, plot and visualize data
154 client. This includes the ability to interact with, plot and visualize data
155 from the engines.
155 from the engines.
156
156
157 IPython has a command line program called :command:`ipcluster` that automates
157 IPython has a command line program called :command:`ipcluster` that automates
158 all aspects of starting the controller and engines on the compute nodes.
158 all aspects of starting the controller and engines on the compute nodes.
159 :command:`ipcluster` has full support for the Windows HPC job scheduler,
159 :command:`ipcluster` has full support for the Windows HPC job scheduler,
160 meaning that :command:`ipcluster` can use this job scheduler to start the
160 meaning that :command:`ipcluster` can use this job scheduler to start the
161 controller and engines. In our experience, the Windows HPC job scheduler is
161 controller and engines. In our experience, the Windows HPC job scheduler is
162 particularly well suited for interactive applications, such as IPython. Once
162 particularly well suited for interactive applications, such as IPython. Once
163 :command:`ipcluster` is configured properly, a user can start an IPython
163 :command:`ipcluster` is configured properly, a user can start an IPython
164 cluster from their local workstation almost instantly, without having to log
164 cluster from their local workstation almost instantly, without having to log
165 on to the head node (as is typically required by Unix based job schedulers).
165 on to the head node (as is typically required by Unix based job schedulers).
166 This enables a user to move seamlessly between serial and parallel
166 This enables a user to move seamlessly between serial and parallel
167 computations.
167 computations.
168
168
169 In this section we show how to use :command:`ipcluster` to start an IPython
169 In this section we show how to use :command:`ipcluster` to start an IPython
170 cluster using the Windows HPC Server 2008 job scheduler. To make sure that
170 cluster using the Windows HPC Server 2008 job scheduler. To make sure that
171 :command:`ipcluster` is installed and working properly, you should first try
171 :command:`ipcluster` is installed and working properly, you should first try
172 to start an IPython cluster on your local host. To do this, open a Windows
172 to start an IPython cluster on your local host. To do this, open a Windows
173 Command Prompt and type the following command::
173 Command Prompt and type the following command::
174
174
175 ipcluster start -n 2
175 ipcluster start -n 2
176
176
177 You should see a number of messages printed to the screen.
177 You should see a number of messages printed to the screen.
178 The result should look something like this::
178 The result should look something like this::
179
179
180 Microsoft Windows [Version 6.1.7600]
180 Microsoft Windows [Version 6.1.7600]
181 Copyright (c) 2009 Microsoft Corporation. All rights reserved.
181 Copyright (c) 2009 Microsoft Corporation. All rights reserved.
182
182
183 Z:\>ipcluster start --profile=mycluster
183 Z:\>ipcluster start --profile=mycluster
184 [IPClusterStart] Using existing profile dir: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster'
184 [IPClusterStart] Using existing profile dir: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster'
185 [IPClusterStart] Starting ipcluster with [daemon=False]
185 [IPClusterStart] Starting ipcluster with [daemon=False]
186 [IPClusterStart] Creating pid file: \\blue\domainusers$\bgranger\.ipython\profile_mycluster\pid\ipcluster.pid
186 [IPClusterStart] Creating pid file: \\blue\domainusers$\bgranger\.ipython\profile_mycluster\pid\ipcluster.pid
187 [IPClusterStart] Writing job description file: \\blue\domainusers$\bgranger\.ipython\profile_mycluster\ipcontroller_job.xml
187 [IPClusterStart] Writing job description file: \\blue\domainusers$\bgranger\.ipython\profile_mycluster\ipcontroller_job.xml
188 [IPClusterStart] Starting Win HPC Job: job submit /jobfile:\\blue\domainusers$\bgranger\.ipython\profile_mycluster\ipcontroller_job.xml /scheduler:HEADNODE
188 [IPClusterStart] Starting Win HPC Job: job submit /jobfile:\\blue\domainusers$\bgranger\.ipython\profile_mycluster\ipcontroller_job.xml /scheduler:HEADNODE
189 [IPClusterStart] Starting 15 engines
189 [IPClusterStart] Starting 15 engines
190 [IPClusterStart] Writing job description file: \\blue\domainusers$\bgranger\.ipython\profile_mycluster\ipcontroller_job.xml
190 [IPClusterStart] Writing job description file: \\blue\domainusers$\bgranger\.ipython\profile_mycluster\ipcontroller_job.xml
191 [IPClusterStart] Starting Win HPC Job: job submit /jobfile:\\blue\domainusers$\bgranger\.ipython\profile_mycluster\ipengineset_job.xml /scheduler:HEADNODE
191 [IPClusterStart] Starting Win HPC Job: job submit /jobfile:\\blue\domainusers$\bgranger\.ipython\profile_mycluster\ipengineset_job.xml /scheduler:HEADNODE
192
192
193
193
194 At this point, the controller and two engines are running on your local host.
194 At this point, the controller and two engines are running on your local host.
195 This configuration is useful for testing and for situations where you want to
195 This configuration is useful for testing and for situations where you want to
196 take advantage of multiple cores on your local computer.
196 take advantage of multiple cores on your local computer.
197
197
198 Now that we have confirmed that :command:`ipcluster` is working properly, we
198 Now that we have confirmed that :command:`ipcluster` is working properly, we
199 describe how to configure and run an IPython cluster on an actual compute
199 describe how to configure and run an IPython cluster on an actual compute
200 cluster running Windows HPC Server 2008. Here is an outline of the needed
200 cluster running Windows HPC Server 2008. Here is an outline of the needed
201 steps:
201 steps:
202
202
203 1. Create a cluster profile using: ``ipython profile create mycluster --parallel``
203 1. Create a cluster profile using: ``ipython profile create mycluster --parallel``
204
204
205 2. Edit configuration files in the directory :file:`.ipython\\cluster_mycluster`
205 2. Edit configuration files in the directory :file:`.ipython\\cluster_mycluster`
206
206
207 3. Start the cluster using: ``ipcluster start --profile=mycluster -n 32``
207 3. Start the cluster using: ``ipcluster start --profile=mycluster -n 32``
208
208
209 Creating a cluster profile
209 Creating a cluster profile
210 --------------------------
210 --------------------------
211
211
212 In most cases, you will have to create a cluster profile to use IPython on a
212 In most cases, you will have to create a cluster profile to use IPython on a
213 cluster. A cluster profile is a name (like "mycluster") that is associated
213 cluster. A cluster profile is a name (like "mycluster") that is associated
214 with a particular cluster configuration. The profile name is used by
214 with a particular cluster configuration. The profile name is used by
215 :command:`ipcluster` when working with the cluster.
215 :command:`ipcluster` when working with the cluster.
216
216
217 Associated with each cluster profile is a cluster directory. This cluster
217 Associated with each cluster profile is a cluster directory. This cluster
218 directory is a specially named directory (typically located in the
218 directory is a specially named directory (typically located in the
219 :file:`.ipython` subdirectory of your home directory) that contains the
219 :file:`.ipython` subdirectory of your home directory) that contains the
220 configuration files for a particular cluster profile, as well as log files and
220 configuration files for a particular cluster profile, as well as log files and
221 security keys. The naming convention for cluster directories is:
221 security keys. The naming convention for cluster directories is:
222 :file:`profile_<profile name>`. Thus, the cluster directory for a profile named
222 :file:`profile_<profile name>`. Thus, the cluster directory for a profile named
223 "foo" would be :file:`.ipython\\cluster_foo`.
223 "foo" would be :file:`.ipython\\cluster_foo`.
224
224
225 To create a new cluster profile (named "mycluster") and the associated cluster
225 To create a new cluster profile (named "mycluster") and the associated cluster
226 directory, type the following command at the Windows Command Prompt::
226 directory, type the following command at the Windows Command Prompt::
227
227
228 ipython profile create --parallel --profile=mycluster
228 ipython profile create --parallel --profile=mycluster
229
229
230 The output of this command is shown in the screenshot below. Notice how
230 The output of this command is shown in the screenshot below. Notice how
231 :command:`ipcluster` prints out the location of the newly created profile
231 :command:`ipcluster` prints out the location of the newly created profile
232 directory::
232 directory::
233
233
234 Z:\>ipython profile create mycluster --parallel
234 Z:\>ipython profile create mycluster --parallel
235 [ProfileCreate] Generating default config file: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster\\ipython_config.py'
235 [ProfileCreate] Generating default config file: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster\\ipython_config.py'
236 [ProfileCreate] Generating default config file: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster\\ipcontroller_config.py'
236 [ProfileCreate] Generating default config file: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster\\ipcontroller_config.py'
237 [ProfileCreate] Generating default config file: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster\\ipengine_config.py'
237 [ProfileCreate] Generating default config file: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster\\ipengine_config.py'
238 [ProfileCreate] Generating default config file: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster\\ipcluster_config.py'
238 [ProfileCreate] Generating default config file: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster\\ipcluster_config.py'
239 [ProfileCreate] Generating default config file: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster\\iplogger_config.py'
239 [ProfileCreate] Generating default config file: u'\\\\blue\\domainusers$\\bgranger\\.ipython\\profile_mycluster\\iplogger_config.py'
240
240
241 Z:\>
241 Z:\>
242
242
243 Configuring a cluster profile
243 Configuring a cluster profile
244 -----------------------------
244 -----------------------------
245
245
246 Next, you will need to configure the newly created cluster profile by editing
246 Next, you will need to configure the newly created cluster profile by editing
247 the following configuration files in the cluster directory:
247 the following configuration files in the cluster directory:
248
248
249 * :file:`ipcluster_config.py`
249 * :file:`ipcluster_config.py`
250 * :file:`ipcontroller_config.py`
250 * :file:`ipcontroller_config.py`
251 * :file:`ipengine_config.py`
251 * :file:`ipengine_config.py`
252
252
253 When :command:`ipcluster` is run, these configuration files are used to
253 When :command:`ipcluster` is run, these configuration files are used to
254 determine how the engines and controller will be started. In most cases,
254 determine how the engines and controller will be started. In most cases,
255 you will only have to set a few of the attributes in these files.
255 you will only have to set a few of the attributes in these files.
256
256
257 To configure :command:`ipcluster` to use the Windows HPC job scheduler, you
257 To configure :command:`ipcluster` to use the Windows HPC job scheduler, you
258 will need to edit the following attributes in the file
258 will need to edit the following attributes in the file
259 :file:`ipcluster_config.py`::
259 :file:`ipcluster_config.py`::
260
260
261 # Set these at the top of the file to tell ipcluster to use the
261 # Set these at the top of the file to tell ipcluster to use the
262 # Windows HPC job scheduler.
262 # Windows HPC job scheduler.
263 c.IPClusterStart.controller_launcher_class = 'WindowsHPCControllerLauncher'
263 c.IPClusterStart.controller_launcher_class = 'WindowsHPCControllerLauncher'
264 c.IPClusterEngines.engine_launcher_class = 'WindowsHPCEngineSetLauncher'
264 c.IPClusterEngines.engine_launcher_class = 'WindowsHPCEngineSetLauncher'
265
265
266 # Set these to the host name of the scheduler (head node) of your cluster.
266 # Set these to the host name of the scheduler (head node) of your cluster.
267 c.WindowsHPCControllerLauncher.scheduler = 'HEADNODE'
267 c.WindowsHPCControllerLauncher.scheduler = 'HEADNODE'
268 c.WindowsHPCEngineSetLauncher.scheduler = 'HEADNODE'
268 c.WindowsHPCEngineSetLauncher.scheduler = 'HEADNODE'
269
269
270 There are a number of other configuration attributes that can be set, but
270 There are a number of other configuration attributes that can be set, but
271 in most cases these will be sufficient to get you started.
271 in most cases these will be sufficient to get you started.
272
272
273 .. warning::
273 .. warning::
274 If any of your configuration attributes involve specifying the location
274 If any of your configuration attributes involve specifying the location
275 of shared directories or files, you must make sure that you use UNC paths
275 of shared directories or files, you must make sure that you use UNC paths
276 like :file:`\\\\host\\share`. It is helpful to specify
276 like :file:`\\\\host\\share`. It is helpful to specify
277 these paths using raw Python strings: ``r'\\host\share'`` to make sure
277 these paths using raw Python strings: ``r'\\host\share'`` to make sure
278 that the backslashes are properly escaped.
278 that the backslashes are properly escaped.
279
279
280 Starting the cluster profile
280 Starting the cluster profile
281 ----------------------------
281 ----------------------------
282
282
283 Once a cluster profile has been configured, starting an IPython cluster using
283 Once a cluster profile has been configured, starting an IPython cluster using
284 the profile is simple::
284 the profile is simple::
285
285
286 ipcluster start --profile=mycluster -n 32
286 ipcluster start --profile=mycluster -n 32
287
287
288 The ``-n`` option tells :command:`ipcluster` how many engines to start (in
288 The ``-n`` option tells :command:`ipcluster` how many engines to start (in
289 this case 32). Stopping the cluster is as simple as typing Control-C.
289 this case 32). Stopping the cluster is as simple as typing Control-C.
290
290
291 Using the HPC Job Manager
291 Using the HPC Job Manager
292 -------------------------
292 -------------------------
293 fΓΈΓΈ
293 fΓΈΓΈ
294 When ``ipcluster start`` is run the first time, :command:`ipcluster` creates
294 When ``ipcluster start`` is run the first time, :command:`ipcluster` creates
295 two XML job description files in the cluster directory:
295 two XML job description files in the cluster directory:
296
296
297 * :file:`ipcontroller_job.xml`
297 * :file:`ipcontroller_job.xml`
298 * :file:`ipengineset_job.xml`
298 * :file:`ipengineset_job.xml`
299
299
300 Once these files have been created, they can be imported into the HPC Job
300 Once these files have been created, they can be imported into the HPC Job
301 Manager application. Then, the controller and engines for that profile can be
301 Manager application. Then, the controller and engines for that profile can be
302 started using the HPC Job Manager directly, without using :command:`ipcluster`.
302 started using the HPC Job Manager directly, without using :command:`ipcluster`.
303 However, anytime the cluster profile is re-configured, ``ipcluster start``
303 However, anytime the cluster profile is re-configured, ``ipcluster start``
304 must be run again to regenerate the XML job description files. The
304 must be run again to regenerate the XML job description files. The
305 following screenshot shows what the HPC Job Manager interface looks like
305 following screenshot shows what the HPC Job Manager interface looks like
306 with a running IPython cluster.
306 with a running IPython cluster.
307
307
308 .. image:: figs/hpc_job_manager.*
308 .. image:: figs/hpc_job_manager.*
309
309
310 Performing a simple interactive parallel computation
310 Performing a simple interactive parallel computation
311 ====================================================
311 ====================================================
312
312
313 Once you have started your IPython cluster, you can start to use it. To do
313 Once you have started your IPython cluster, you can start to use it. To do
314 this, open up a new Windows Command Prompt and start up IPython's interactive
314 this, open up a new Windows Command Prompt and start up IPython's interactive
315 shell by typing::
315 shell by typing::
316
316
317 ipython
317 ipython
318
318
319 Then you can create a :class:`DirectView` instance for your profile and
319 Then you can create a :class:`DirectView` instance for your profile and
320 use the resulting instance to do a simple interactive parallel computation. In
320 use the resulting instance to do a simple interactive parallel computation. In
321 the code and screenshot that follows, we take a simple Python function and
321 the code and screenshot that follows, we take a simple Python function and
322 apply it to each element of an array of integers in parallel using the
322 apply it to each element of an array of integers in parallel using the
323 :meth:`DirectView.map` method:
323 :meth:`DirectView.map` method:
324
324
325 .. sourcecode:: ipython
325 .. sourcecode:: ipython
326
326
327 In [1]: from IPython.parallel import *
327 In [1]: from IPython.parallel import *
328
328
329 In [2]: c = Client(profile='mycluster')
329 In [2]: c = Client(profile='mycluster')
330
330
331 In [3]: view = c[:]
331 In [3]: view = c[:]
332
332
333 In [4]: c.ids
333 In [4]: c.ids
334 Out[4]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
334 Out[4]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
335
335
336 In [5]: def f(x):
336 In [5]: def f(x):
337 ...: return x**10
337 ...: return x**10
338
338
339 In [6]: view.map(f, range(15)) # f is applied in parallel
339 In [6]: view.map(f, range(15)) # f is applied in parallel
340 Out[6]:
340 Out[6]:
341 [0,
341 [0,
342 1,
342 1,
343 1024,
343 1024,
344 59049,
344 59049,
345 1048576,
345 1048576,
346 9765625,
346 9765625,
347 60466176,
347 60466176,
348 282475249,
348 282475249,
349 1073741824,
349 1073741824,
350 3486784401L,
350 3486784401L,
351 10000000000L,
351 10000000000L,
352 25937424601L,
352 25937424601L,
353 61917364224L,
353 61917364224L,
354 137858491849L,
354 137858491849L,
355 289254654976L]
355 289254654976L]
356
356
357 The :meth:`map` method has the same signature as Python's builtin :func:`map`
357 The :meth:`map` method has the same signature as Python's builtin :func:`map`
358 function, but runs the calculation in parallel. More involved examples of using
358 function, but runs the calculation in parallel. More involved examples of using
359 :class:`DirectView` are provided in the examples that follow.
359 :class:`DirectView` are provided in the examples that follow.
360
360
361 .. include:: ../links.txt
General Comments 0
You need to be logged in to leave comments. Login now