Show More
@@ -1,991 +1,998 b'' | |||||
1 | """ History related magics and functionality """ |
|
1 | """ History related magics and functionality """ | |
2 | #----------------------------------------------------------------------------- |
|
2 | #----------------------------------------------------------------------------- | |
3 | # Copyright (C) 2010-2011 The IPython Development Team. |
|
3 | # Copyright (C) 2010-2011 The IPython Development Team. | |
4 | # |
|
4 | # | |
5 | # Distributed under the terms of the BSD License. |
|
5 | # Distributed under the terms of the BSD License. | |
6 | # |
|
6 | # | |
7 | # The full license is in the file COPYING.txt, distributed with this software. |
|
7 | # The full license is in the file COPYING.txt, distributed with this software. | |
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 |
|
9 | |||
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 | # Imports |
|
11 | # Imports | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | from __future__ import print_function |
|
13 | from __future__ import print_function | |
14 |
|
14 | |||
15 | # Stdlib imports |
|
15 | # Stdlib imports | |
16 | import atexit |
|
16 | import atexit | |
17 | import datetime |
|
17 | import datetime | |
18 | from io import open as io_open |
|
18 | from io import open as io_open | |
19 | import os |
|
19 | import os | |
20 | import re |
|
20 | import re | |
21 | try: |
|
21 | try: | |
22 | import sqlite3 |
|
22 | import sqlite3 | |
23 | except ImportError: |
|
23 | except ImportError: | |
24 | sqlite3 = None |
|
24 | sqlite3 = None | |
25 | import threading |
|
25 | import threading | |
26 |
|
26 | |||
27 | # Our own packages |
|
27 | # Our own packages | |
28 | from IPython.core.error import StdinNotImplementedError |
|
28 | from IPython.core.error import StdinNotImplementedError | |
29 | from IPython.core.magic import Magics, register_magics, line_magic |
|
29 | from IPython.core.magic import Magics, register_magics, line_magic | |
30 | from IPython.config.configurable import Configurable |
|
30 | from IPython.config.configurable import Configurable | |
31 | from IPython.external.decorator import decorator |
|
31 | from IPython.external.decorator import decorator | |
32 | from IPython.testing.skipdoctest import skip_doctest |
|
32 | from IPython.testing.skipdoctest import skip_doctest | |
33 | from IPython.utils import io |
|
33 | from IPython.utils import io | |
34 | from IPython.utils.path import locate_profile |
|
34 | from IPython.utils.path import locate_profile | |
35 | from IPython.utils.traitlets import Bool, Dict, Instance, Integer, List, Unicode |
|
35 | from IPython.utils.traitlets import Bool, Dict, Instance, Integer, List, Unicode | |
36 | from IPython.utils.warn import warn |
|
36 | from IPython.utils.warn import warn | |
37 |
|
37 | |||
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 | # Classes and functions |
|
39 | # Classes and functions | |
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 |
|
41 | |||
42 | class DummyDB(object): |
|
42 | class DummyDB(object): | |
43 | """Dummy DB that will act as a black hole for history. |
|
43 | """Dummy DB that will act as a black hole for history. | |
44 |
|
44 | |||
45 | Only used in the absence of sqlite""" |
|
45 | Only used in the absence of sqlite""" | |
46 | def execute(*args, **kwargs): |
|
46 | def execute(*args, **kwargs): | |
47 | return [] |
|
47 | return [] | |
48 |
|
48 | |||
49 | def commit(self, *args, **kwargs): |
|
49 | def commit(self, *args, **kwargs): | |
50 | pass |
|
50 | pass | |
51 |
|
51 | |||
52 | def __enter__(self, *args, **kwargs): |
|
52 | def __enter__(self, *args, **kwargs): | |
53 | pass |
|
53 | pass | |
54 |
|
54 | |||
55 | def __exit__(self, *args, **kwargs): |
|
55 | def __exit__(self, *args, **kwargs): | |
56 | pass |
|
56 | pass | |
57 |
|
57 | |||
58 |
|
58 | |||
59 | @decorator |
|
59 | @decorator | |
60 | def needs_sqlite(f,*a,**kw): |
|
60 | def needs_sqlite(f,*a,**kw): | |
61 | """return an empty list in the absence of sqlite""" |
|
61 | """return an empty list in the absence of sqlite""" | |
62 | if sqlite3 is None: |
|
62 | if sqlite3 is None: | |
63 | return [] |
|
63 | return [] | |
64 | else: |
|
64 | else: | |
65 | return f(*a,**kw) |
|
65 | return f(*a,**kw) | |
66 |
|
66 | |||
67 |
|
67 | |||
68 | class HistoryAccessor(Configurable): |
|
68 | class HistoryAccessor(Configurable): | |
69 | """Access the history database without adding to it. |
|
69 | """Access the history database without adding to it. | |
70 |
|
70 | |||
71 | This is intended for use by standalone history tools. IPython shells use |
|
71 | This is intended for use by standalone history tools. IPython shells use | |
72 | HistoryManager, below, which is a subclass of this.""" |
|
72 | HistoryManager, below, which is a subclass of this.""" | |
73 |
|
73 | |||
74 | # String holding the path to the history file |
|
74 | # String holding the path to the history file | |
75 | hist_file = Unicode(config=True, |
|
75 | hist_file = Unicode(config=True, | |
76 | help="""Path to file to use for SQLite history database. |
|
76 | help="""Path to file to use for SQLite history database. | |
77 |
|
77 | |||
78 | By default, IPython will put the history database in the IPython |
|
78 | By default, IPython will put the history database in the IPython | |
79 | profile directory. If you would rather share one history among |
|
79 | profile directory. If you would rather share one history among | |
80 | profiles, you ca set this value in each, so that they are consistent. |
|
80 | profiles, you ca set this value in each, so that they are consistent. | |
81 |
|
81 | |||
82 | Due to an issue with fcntl, SQLite is known to misbehave on some NFS |
|
82 | Due to an issue with fcntl, SQLite is known to misbehave on some NFS | |
83 | mounts. If you see IPython hanging, try setting this to something on a |
|
83 | mounts. If you see IPython hanging, try setting this to something on a | |
84 | local disk, e.g:: |
|
84 | local disk, e.g:: | |
85 |
|
85 | |||
86 | ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite |
|
86 | ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite | |
87 |
|
87 | |||
88 | """) |
|
88 | """) | |
89 |
|
89 | |||
90 | # The SQLite database |
|
90 | # The SQLite database | |
91 | if sqlite3: |
|
91 | if sqlite3: | |
92 | db = Instance(sqlite3.Connection) |
|
92 | db = Instance(sqlite3.Connection) | |
93 | else: |
|
93 | else: | |
94 | db = Instance(DummyDB) |
|
94 | db = Instance(DummyDB) | |
95 |
|
95 | |||
96 | def __init__(self, profile='default', hist_file=u'', config=None, **traits): |
|
96 | def __init__(self, profile='default', hist_file=u'', config=None, **traits): | |
97 | """Create a new history accessor. |
|
97 | """Create a new history accessor. | |
98 |
|
98 | |||
99 | Parameters |
|
99 | Parameters | |
100 | ---------- |
|
100 | ---------- | |
101 | profile : str |
|
101 | profile : str | |
102 | The name of the profile from which to open history. |
|
102 | The name of the profile from which to open history. | |
103 | hist_file : str |
|
103 | hist_file : str | |
104 | Path to an SQLite history database stored by IPython. If specified, |
|
104 | Path to an SQLite history database stored by IPython. If specified, | |
105 | hist_file overrides profile. |
|
105 | hist_file overrides profile. | |
106 | config : |
|
106 | config : | |
107 | Config object. hist_file can also be set through this. |
|
107 | Config object. hist_file can also be set through this. | |
108 | """ |
|
108 | """ | |
109 | # We need a pointer back to the shell for various tasks. |
|
109 | # We need a pointer back to the shell for various tasks. | |
110 | super(HistoryAccessor, self).__init__(config=config, **traits) |
|
110 | super(HistoryAccessor, self).__init__(config=config, **traits) | |
111 | # defer setting hist_file from kwarg until after init, |
|
111 | # defer setting hist_file from kwarg until after init, | |
112 | # otherwise the default kwarg value would clobber any value |
|
112 | # otherwise the default kwarg value would clobber any value | |
113 | # set by config |
|
113 | # set by config | |
114 | if hist_file: |
|
114 | if hist_file: | |
115 | self.hist_file = hist_file |
|
115 | self.hist_file = hist_file | |
116 |
|
116 | |||
117 | if self.hist_file == u'': |
|
117 | if self.hist_file == u'': | |
118 | # No one has set the hist_file, yet. |
|
118 | # No one has set the hist_file, yet. | |
119 | self.hist_file = self._get_hist_file_name(profile) |
|
119 | self.hist_file = self._get_hist_file_name(profile) | |
120 |
|
120 | |||
121 | if sqlite3 is None: |
|
121 | if sqlite3 is None: | |
122 | warn("IPython History requires SQLite, your history will not be saved\n") |
|
122 | warn("IPython History requires SQLite, your history will not be saved\n") | |
123 | self.db = DummyDB() |
|
123 | self.db = DummyDB() | |
124 | return |
|
124 | return | |
125 |
|
125 | |||
126 | try: |
|
126 | try: | |
127 | self.init_db() |
|
127 | self.init_db() | |
128 | except sqlite3.DatabaseError: |
|
128 | except sqlite3.DatabaseError: | |
129 | if os.path.isfile(self.hist_file): |
|
129 | if os.path.isfile(self.hist_file): | |
130 | # Try to move the file out of the way |
|
130 | # Try to move the file out of the way | |
131 | base,ext = os.path.splitext(self.hist_file) |
|
131 | base,ext = os.path.splitext(self.hist_file) | |
132 | newpath = base + '-corrupt' + ext |
|
132 | newpath = base + '-corrupt' + ext | |
133 | os.rename(self.hist_file, newpath) |
|
133 | os.rename(self.hist_file, newpath) | |
134 | print("ERROR! History file wasn't a valid SQLite database.", |
|
134 | print("ERROR! History file wasn't a valid SQLite database.", | |
135 | "It was moved to %s" % newpath, "and a new file created.") |
|
135 | "It was moved to %s" % newpath, "and a new file created.") | |
136 | self.init_db() |
|
136 | self.init_db() | |
137 | else: |
|
137 | else: | |
138 | # The hist_file is probably :memory: or something else. |
|
138 | # The hist_file is probably :memory: or something else. | |
139 | raise |
|
139 | raise | |
140 |
|
140 | |||
141 | def _get_hist_file_name(self, profile='default'): |
|
141 | def _get_hist_file_name(self, profile='default'): | |
142 | """Find the history file for the given profile name. |
|
142 | """Find the history file for the given profile name. | |
143 |
|
143 | |||
144 | This is overridden by the HistoryManager subclass, to use the shell's |
|
144 | This is overridden by the HistoryManager subclass, to use the shell's | |
145 | active profile. |
|
145 | active profile. | |
146 |
|
146 | |||
147 | Parameters |
|
147 | Parameters | |
148 | ---------- |
|
148 | ---------- | |
149 | profile : str |
|
149 | profile : str | |
150 | The name of a profile which has a history file. |
|
150 | The name of a profile which has a history file. | |
151 | """ |
|
151 | """ | |
152 | return os.path.join(locate_profile(profile), 'history.sqlite') |
|
152 | return os.path.join(locate_profile(profile), 'history.sqlite') | |
153 |
|
153 | |||
154 | def init_db(self): |
|
154 | def init_db(self): | |
155 | """Connect to the database, and create tables if necessary.""" |
|
155 | """Connect to the database, and create tables if necessary.""" | |
156 | # use detect_types so that timestamps return datetime objects |
|
156 | # use detect_types so that timestamps return datetime objects | |
157 | self.db = sqlite3.connect(self.hist_file, |
|
157 | self.db = sqlite3.connect(self.hist_file, | |
158 | detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) |
|
158 | detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) | |
159 | self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer |
|
159 | self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer | |
160 | primary key autoincrement, start timestamp, |
|
160 | primary key autoincrement, start timestamp, | |
161 | end timestamp, num_cmds integer, remark text)""") |
|
161 | end timestamp, num_cmds integer, remark text)""") | |
162 | self.db.execute("""CREATE TABLE IF NOT EXISTS history |
|
162 | self.db.execute("""CREATE TABLE IF NOT EXISTS history | |
163 | (session integer, line integer, source text, source_raw text, |
|
163 | (session integer, line integer, source text, source_raw text, | |
164 | PRIMARY KEY (session, line))""") |
|
164 | PRIMARY KEY (session, line))""") | |
165 | # Output history is optional, but ensure the table's there so it can be |
|
165 | # Output history is optional, but ensure the table's there so it can be | |
166 | # enabled later. |
|
166 | # enabled later. | |
167 | self.db.execute("""CREATE TABLE IF NOT EXISTS output_history |
|
167 | self.db.execute("""CREATE TABLE IF NOT EXISTS output_history | |
168 | (session integer, line integer, output text, |
|
168 | (session integer, line integer, output text, | |
169 | PRIMARY KEY (session, line))""") |
|
169 | PRIMARY KEY (session, line))""") | |
170 | self.db.commit() |
|
170 | self.db.commit() | |
171 |
|
171 | |||
172 | def writeout_cache(self): |
|
172 | def writeout_cache(self): | |
173 | """Overridden by HistoryManager to dump the cache before certain |
|
173 | """Overridden by HistoryManager to dump the cache before certain | |
174 | database lookups.""" |
|
174 | database lookups.""" | |
175 | pass |
|
175 | pass | |
176 |
|
176 | |||
177 | ## ------------------------------- |
|
177 | ## ------------------------------- | |
178 | ## Methods for retrieving history: |
|
178 | ## Methods for retrieving history: | |
179 | ## ------------------------------- |
|
179 | ## ------------------------------- | |
180 | def _run_sql(self, sql, params, raw=True, output=False): |
|
180 | def _run_sql(self, sql, params, raw=True, output=False): | |
181 | """Prepares and runs an SQL query for the history database. |
|
181 | """Prepares and runs an SQL query for the history database. | |
182 |
|
182 | |||
183 | Parameters |
|
183 | Parameters | |
184 | ---------- |
|
184 | ---------- | |
185 | sql : str |
|
185 | sql : str | |
186 | Any filtering expressions to go after SELECT ... FROM ... |
|
186 | Any filtering expressions to go after SELECT ... FROM ... | |
187 | params : tuple |
|
187 | params : tuple | |
188 | Parameters passed to the SQL query (to replace "?") |
|
188 | Parameters passed to the SQL query (to replace "?") | |
189 | raw, output : bool |
|
189 | raw, output : bool | |
190 | See :meth:`get_range` |
|
190 | See :meth:`get_range` | |
191 |
|
191 | |||
192 | Returns |
|
192 | Returns | |
193 | ------- |
|
193 | ------- | |
194 | Tuples as :meth:`get_range` |
|
194 | Tuples as :meth:`get_range` | |
195 | """ |
|
195 | """ | |
196 | toget = 'source_raw' if raw else 'source' |
|
196 | toget = 'source_raw' if raw else 'source' | |
197 | sqlfrom = "history" |
|
197 | sqlfrom = "history" | |
198 | if output: |
|
198 | if output: | |
199 | sqlfrom = "history LEFT JOIN output_history USING (session, line)" |
|
199 | sqlfrom = "history LEFT JOIN output_history USING (session, line)" | |
200 | toget = "history.%s, output_history.output" % toget |
|
200 | toget = "history.%s, output_history.output" % toget | |
201 | cur = self.db.execute("SELECT session, line, %s FROM %s " %\ |
|
201 | cur = self.db.execute("SELECT session, line, %s FROM %s " %\ | |
202 | (toget, sqlfrom) + sql, params) |
|
202 | (toget, sqlfrom) + sql, params) | |
203 | if output: # Regroup into 3-tuples, and parse JSON |
|
203 | if output: # Regroup into 3-tuples, and parse JSON | |
204 | return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur) |
|
204 | return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur) | |
205 | return cur |
|
205 | return cur | |
206 |
|
206 | |||
207 | @needs_sqlite |
|
207 | @needs_sqlite | |
208 | def get_session_info(self, session=0): |
|
208 | def get_session_info(self, session=0): | |
209 | """get info about a session |
|
209 | """get info about a session | |
210 |
|
210 | |||
211 | Parameters |
|
211 | Parameters | |
212 | ---------- |
|
212 | ---------- | |
213 |
|
213 | |||
214 | session : int |
|
214 | session : int | |
215 | Session number to retrieve. The current session is 0, and negative |
|
215 | Session number to retrieve. The current session is 0, and negative | |
216 | numbers count back from current session, so -1 is previous session. |
|
216 | numbers count back from current session, so -1 is previous session. | |
217 |
|
217 | |||
218 | Returns |
|
218 | Returns | |
219 | ------- |
|
219 | ------- | |
220 |
|
220 | |||
221 | (session_id [int], start [datetime], end [datetime], num_cmds [int], |
|
221 | (session_id [int], start [datetime], end [datetime], num_cmds [int], | |
222 | remark [unicode]) |
|
222 | remark [unicode]) | |
223 |
|
223 | |||
224 | Sessions that are running or did not exit cleanly will have `end=None` |
|
224 | Sessions that are running or did not exit cleanly will have `end=None` | |
225 | and `num_cmds=None`. |
|
225 | and `num_cmds=None`. | |
226 |
|
226 | |||
227 | """ |
|
227 | """ | |
228 |
|
228 | |||
229 | if session <= 0: |
|
229 | if session <= 0: | |
230 | session += self.session_number |
|
230 | session += self.session_number | |
231 |
|
231 | |||
232 | query = "SELECT * from sessions where session == ?" |
|
232 | query = "SELECT * from sessions where session == ?" | |
233 | return self.db.execute(query, (session,)).fetchone() |
|
233 | return self.db.execute(query, (session,)).fetchone() | |
234 |
|
234 | |||
235 | def get_tail(self, n=10, raw=True, output=False, include_latest=False): |
|
235 | def get_tail(self, n=10, raw=True, output=False, include_latest=False): | |
236 | """Get the last n lines from the history database. |
|
236 | """Get the last n lines from the history database. | |
237 |
|
237 | |||
238 | Parameters |
|
238 | Parameters | |
239 | ---------- |
|
239 | ---------- | |
240 | n : int |
|
240 | n : int | |
241 | The number of lines to get |
|
241 | The number of lines to get | |
242 | raw, output : bool |
|
242 | raw, output : bool | |
243 | See :meth:`get_range` |
|
243 | See :meth:`get_range` | |
244 | include_latest : bool |
|
244 | include_latest : bool | |
245 | If False (default), n+1 lines are fetched, and the latest one |
|
245 | If False (default), n+1 lines are fetched, and the latest one | |
246 | is discarded. This is intended to be used where the function |
|
246 | is discarded. This is intended to be used where the function | |
247 | is called by a user command, which it should not return. |
|
247 | is called by a user command, which it should not return. | |
248 |
|
248 | |||
249 | Returns |
|
249 | Returns | |
250 | ------- |
|
250 | ------- | |
251 | Tuples as :meth:`get_range` |
|
251 | Tuples as :meth:`get_range` | |
252 | """ |
|
252 | """ | |
253 | self.writeout_cache() |
|
253 | self.writeout_cache() | |
254 | if not include_latest: |
|
254 | if not include_latest: | |
255 | n += 1 |
|
255 | n += 1 | |
256 | cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?", |
|
256 | cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?", | |
257 | (n,), raw=raw, output=output) |
|
257 | (n,), raw=raw, output=output) | |
258 | if not include_latest: |
|
258 | if not include_latest: | |
259 | return reversed(list(cur)[1:]) |
|
259 | return reversed(list(cur)[1:]) | |
260 | return reversed(list(cur)) |
|
260 | return reversed(list(cur)) | |
261 |
|
261 | |||
262 | def search(self, pattern="*", raw=True, search_raw=True, |
|
262 | def search(self, pattern="*", raw=True, search_raw=True, | |
263 | output=False): |
|
263 | output=False): | |
264 | """Search the database using unix glob-style matching (wildcards |
|
264 | """Search the database using unix glob-style matching (wildcards | |
265 | * and ?). |
|
265 | * and ?). | |
266 |
|
266 | |||
267 | Parameters |
|
267 | Parameters | |
268 | ---------- |
|
268 | ---------- | |
269 | pattern : str |
|
269 | pattern : str | |
270 | The wildcarded pattern to match when searching |
|
270 | The wildcarded pattern to match when searching | |
271 | search_raw : bool |
|
271 | search_raw : bool | |
272 | If True, search the raw input, otherwise, the parsed input |
|
272 | If True, search the raw input, otherwise, the parsed input | |
273 | raw, output : bool |
|
273 | raw, output : bool | |
274 | See :meth:`get_range` |
|
274 | See :meth:`get_range` | |
275 |
|
275 | |||
276 | Returns |
|
276 | Returns | |
277 | ------- |
|
277 | ------- | |
278 | Tuples as :meth:`get_range` |
|
278 | Tuples as :meth:`get_range` | |
279 | """ |
|
279 | """ | |
280 | tosearch = "source_raw" if search_raw else "source" |
|
280 | tosearch = "source_raw" if search_raw else "source" | |
281 | if output: |
|
281 | if output: | |
282 | tosearch = "history." + tosearch |
|
282 | tosearch = "history." + tosearch | |
283 | self.writeout_cache() |
|
283 | self.writeout_cache() | |
284 | return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,), |
|
284 | return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,), | |
285 | raw=raw, output=output) |
|
285 | raw=raw, output=output) | |
286 |
|
286 | |||
287 | def get_range(self, session, start=1, stop=None, raw=True,output=False): |
|
287 | def get_range(self, session, start=1, stop=None, raw=True,output=False): | |
288 | """Retrieve input by session. |
|
288 | """Retrieve input by session. | |
289 |
|
289 | |||
290 | Parameters |
|
290 | Parameters | |
291 | ---------- |
|
291 | ---------- | |
292 | session : int |
|
292 | session : int | |
293 | Session number to retrieve. |
|
293 | Session number to retrieve. | |
294 | start : int |
|
294 | start : int | |
295 | First line to retrieve. |
|
295 | First line to retrieve. | |
296 | stop : int |
|
296 | stop : int | |
297 | End of line range (excluded from output itself). If None, retrieve |
|
297 | End of line range (excluded from output itself). If None, retrieve | |
298 | to the end of the session. |
|
298 | to the end of the session. | |
299 | raw : bool |
|
299 | raw : bool | |
300 | If True, return untranslated input |
|
300 | If True, return untranslated input | |
301 | output : bool |
|
301 | output : bool | |
302 | If True, attempt to include output. This will be 'real' Python |
|
302 | If True, attempt to include output. This will be 'real' Python | |
303 | objects for the current session, or text reprs from previous |
|
303 | objects for the current session, or text reprs from previous | |
304 | sessions if db_log_output was enabled at the time. Where no output |
|
304 | sessions if db_log_output was enabled at the time. Where no output | |
305 | is found, None is used. |
|
305 | is found, None is used. | |
306 |
|
306 | |||
307 | Returns |
|
307 | Returns | |
308 | ------- |
|
308 | ------- | |
309 | An iterator over the desired lines. Each line is a 3-tuple, either |
|
309 | An iterator over the desired lines. Each line is a 3-tuple, either | |
310 | (session, line, input) if output is False, or |
|
310 | (session, line, input) if output is False, or | |
311 | (session, line, (input, output)) if output is True. |
|
311 | (session, line, (input, output)) if output is True. | |
312 | """ |
|
312 | """ | |
313 | if stop: |
|
313 | if stop: | |
314 | lineclause = "line >= ? AND line < ?" |
|
314 | lineclause = "line >= ? AND line < ?" | |
315 | params = (session, start, stop) |
|
315 | params = (session, start, stop) | |
316 | else: |
|
316 | else: | |
317 | lineclause = "line>=?" |
|
317 | lineclause = "line>=?" | |
318 | params = (session, start) |
|
318 | params = (session, start) | |
319 |
|
319 | |||
320 | return self._run_sql("WHERE session==? AND %s""" % lineclause, |
|
320 | return self._run_sql("WHERE session==? AND %s""" % lineclause, | |
321 | params, raw=raw, output=output) |
|
321 | params, raw=raw, output=output) | |
322 |
|
322 | |||
323 | def get_range_by_str(self, rangestr, raw=True, output=False): |
|
323 | def get_range_by_str(self, rangestr, raw=True, output=False): | |
324 | """Get lines of history from a string of ranges, as used by magic |
|
324 | """Get lines of history from a string of ranges, as used by magic | |
325 | commands %hist, %save, %macro, etc. |
|
325 | commands %hist, %save, %macro, etc. | |
326 |
|
326 | |||
327 | Parameters |
|
327 | Parameters | |
328 | ---------- |
|
328 | ---------- | |
329 | rangestr : str |
|
329 | rangestr : str | |
330 | A string specifying ranges, e.g. "5 ~2/1-4". See |
|
330 | A string specifying ranges, e.g. "5 ~2/1-4". See | |
331 | :func:`magic_history` for full details. |
|
331 | :func:`magic_history` for full details. | |
332 | raw, output : bool |
|
332 | raw, output : bool | |
333 | As :meth:`get_range` |
|
333 | As :meth:`get_range` | |
334 |
|
334 | |||
335 | Returns |
|
335 | Returns | |
336 | ------- |
|
336 | ------- | |
337 | Tuples as :meth:`get_range` |
|
337 | Tuples as :meth:`get_range` | |
338 | """ |
|
338 | """ | |
339 | for sess, s, e in extract_hist_ranges(rangestr): |
|
339 | for sess, s, e in extract_hist_ranges(rangestr): | |
340 | for line in self.get_range(sess, s, e, raw=raw, output=output): |
|
340 | for line in self.get_range(sess, s, e, raw=raw, output=output): | |
341 | yield line |
|
341 | yield line | |
342 |
|
342 | |||
343 |
|
343 | |||
344 | class HistoryManager(HistoryAccessor): |
|
344 | class HistoryManager(HistoryAccessor): | |
345 | """A class to organize all history-related functionality in one place. |
|
345 | """A class to organize all history-related functionality in one place. | |
346 | """ |
|
346 | """ | |
347 | # Public interface |
|
347 | # Public interface | |
348 |
|
348 | |||
349 | # An instance of the IPython shell we are attached to |
|
349 | # An instance of the IPython shell we are attached to | |
350 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
350 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
351 | # Lists to hold processed and raw history. These start with a blank entry |
|
351 | # Lists to hold processed and raw history. These start with a blank entry | |
352 | # so that we can index them starting from 1 |
|
352 | # so that we can index them starting from 1 | |
353 | input_hist_parsed = List([""]) |
|
353 | input_hist_parsed = List([""]) | |
354 | input_hist_raw = List([""]) |
|
354 | input_hist_raw = List([""]) | |
355 | # A list of directories visited during session |
|
355 | # A list of directories visited during session | |
356 | dir_hist = List() |
|
356 | dir_hist = List() | |
357 | def _dir_hist_default(self): |
|
357 | def _dir_hist_default(self): | |
358 | try: |
|
358 | try: | |
359 | return [os.getcwdu()] |
|
359 | return [os.getcwdu()] | |
360 | except OSError: |
|
360 | except OSError: | |
361 | return [] |
|
361 | return [] | |
362 |
|
362 | |||
363 | # A dict of output history, keyed with ints from the shell's |
|
363 | # A dict of output history, keyed with ints from the shell's | |
364 | # execution count. |
|
364 | # execution count. | |
365 | output_hist = Dict() |
|
365 | output_hist = Dict() | |
366 | # The text/plain repr of outputs. |
|
366 | # The text/plain repr of outputs. | |
367 | output_hist_reprs = Dict() |
|
367 | output_hist_reprs = Dict() | |
368 |
|
368 | |||
369 | # The number of the current session in the history database |
|
369 | # The number of the current session in the history database | |
370 | session_number = Integer() |
|
370 | session_number = Integer() | |
371 | # Should we log output to the database? (default no) |
|
371 | # Should we log output to the database? (default no) | |
372 | db_log_output = Bool(False, config=True) |
|
372 | db_log_output = Bool(False, config=True) | |
373 | # Write to database every x commands (higher values save disk access & power) |
|
373 | # Write to database every x commands (higher values save disk access & power) | |
374 | # Values of 1 or less effectively disable caching. |
|
374 | # Values of 1 or less effectively disable caching. | |
375 | db_cache_size = Integer(0, config=True) |
|
375 | db_cache_size = Integer(0, config=True) | |
376 | # The input and output caches |
|
376 | # The input and output caches | |
377 | db_input_cache = List() |
|
377 | db_input_cache = List() | |
378 | db_output_cache = List() |
|
378 | db_output_cache = List() | |
379 |
|
379 | |||
380 | # History saving in separate thread |
|
380 | # History saving in separate thread | |
381 | save_thread = Instance('IPython.core.history.HistorySavingThread') |
|
381 | save_thread = Instance('IPython.core.history.HistorySavingThread') | |
382 | try: # Event is a function returning an instance of _Event... |
|
382 | try: # Event is a function returning an instance of _Event... | |
383 | save_flag = Instance(threading._Event) |
|
383 | save_flag = Instance(threading._Event) | |
384 | except AttributeError: # ...until Python 3.3, when it's a class. |
|
384 | except AttributeError: # ...until Python 3.3, when it's a class. | |
385 | save_flag = Instance(threading.Event) |
|
385 | save_flag = Instance(threading.Event) | |
386 |
|
386 | |||
387 | # Private interface |
|
387 | # Private interface | |
388 | # Variables used to store the three last inputs from the user. On each new |
|
388 | # Variables used to store the three last inputs from the user. On each new | |
389 | # history update, we populate the user's namespace with these, shifted as |
|
389 | # history update, we populate the user's namespace with these, shifted as | |
390 | # necessary. |
|
390 | # necessary. | |
391 | _i00 = Unicode(u'') |
|
391 | _i00 = Unicode(u'') | |
392 | _i = Unicode(u'') |
|
392 | _i = Unicode(u'') | |
393 | _ii = Unicode(u'') |
|
393 | _ii = Unicode(u'') | |
394 | _iii = Unicode(u'') |
|
394 | _iii = Unicode(u'') | |
395 |
|
395 | |||
396 | # A regex matching all forms of the exit command, so that we don't store |
|
396 | # A regex matching all forms of the exit command, so that we don't store | |
397 | # them in the history (it's annoying to rewind the first entry and land on |
|
397 | # them in the history (it's annoying to rewind the first entry and land on | |
398 | # an exit call). |
|
398 | # an exit call). | |
399 | _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$") |
|
399 | _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$") | |
400 |
|
400 | |||
401 | def __init__(self, shell=None, config=None, **traits): |
|
401 | def __init__(self, shell=None, config=None, **traits): | |
402 | """Create a new history manager associated with a shell instance. |
|
402 | """Create a new history manager associated with a shell instance. | |
403 | """ |
|
403 | """ | |
404 | # We need a pointer back to the shell for various tasks. |
|
404 | # We need a pointer back to the shell for various tasks. | |
405 | super(HistoryManager, self).__init__(shell=shell, config=config, |
|
405 | super(HistoryManager, self).__init__(shell=shell, config=config, | |
406 | **traits) |
|
406 | **traits) | |
407 | self.save_flag = threading.Event() |
|
407 | self.save_flag = threading.Event() | |
408 | self.db_input_cache_lock = threading.Lock() |
|
408 | self.db_input_cache_lock = threading.Lock() | |
409 | self.db_output_cache_lock = threading.Lock() |
|
409 | self.db_output_cache_lock = threading.Lock() | |
410 | if self.hist_file != ':memory:': |
|
410 | if self.hist_file != ':memory:': | |
411 | self.save_thread = HistorySavingThread(self) |
|
411 | self.save_thread = HistorySavingThread(self) | |
412 | self.save_thread.start() |
|
412 | self.save_thread.start() | |
413 |
|
413 | |||
414 | self.new_session() |
|
414 | self.new_session() | |
415 |
|
415 | |||
416 | def _get_hist_file_name(self, profile=None): |
|
416 | def _get_hist_file_name(self, profile=None): | |
417 | """Get default history file name based on the Shell's profile. |
|
417 | """Get default history file name based on the Shell's profile. | |
418 |
|
418 | |||
419 | The profile parameter is ignored, but must exist for compatibility with |
|
419 | The profile parameter is ignored, but must exist for compatibility with | |
420 | the parent class.""" |
|
420 | the parent class.""" | |
421 | profile_dir = self.shell.profile_dir.location |
|
421 | profile_dir = self.shell.profile_dir.location | |
422 | return os.path.join(profile_dir, 'history.sqlite') |
|
422 | return os.path.join(profile_dir, 'history.sqlite') | |
423 |
|
423 | |||
424 | @needs_sqlite |
|
424 | @needs_sqlite | |
425 | def new_session(self, conn=None): |
|
425 | def new_session(self, conn=None): | |
426 | """Get a new session number.""" |
|
426 | """Get a new session number.""" | |
427 | if conn is None: |
|
427 | if conn is None: | |
428 | conn = self.db |
|
428 | conn = self.db | |
429 |
|
429 | |||
430 | with conn: |
|
430 | with conn: | |
431 | cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL, |
|
431 | cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL, | |
432 | NULL, "") """, (datetime.datetime.now(),)) |
|
432 | NULL, "") """, (datetime.datetime.now(),)) | |
433 | self.session_number = cur.lastrowid |
|
433 | self.session_number = cur.lastrowid | |
434 |
|
434 | |||
435 | def end_session(self): |
|
435 | def end_session(self): | |
436 | """Close the database session, filling in the end time and line count.""" |
|
436 | """Close the database session, filling in the end time and line count.""" | |
437 | self.writeout_cache() |
|
437 | self.writeout_cache() | |
438 | with self.db: |
|
438 | with self.db: | |
439 | self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE |
|
439 | self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE | |
440 | session==?""", (datetime.datetime.now(), |
|
440 | session==?""", (datetime.datetime.now(), | |
441 | len(self.input_hist_parsed)-1, self.session_number)) |
|
441 | len(self.input_hist_parsed)-1, self.session_number)) | |
442 | self.session_number = 0 |
|
442 | self.session_number = 0 | |
443 |
|
443 | |||
444 | def name_session(self, name): |
|
444 | def name_session(self, name): | |
445 | """Give the current session a name in the history database.""" |
|
445 | """Give the current session a name in the history database.""" | |
446 | with self.db: |
|
446 | with self.db: | |
447 | self.db.execute("UPDATE sessions SET remark=? WHERE session==?", |
|
447 | self.db.execute("UPDATE sessions SET remark=? WHERE session==?", | |
448 | (name, self.session_number)) |
|
448 | (name, self.session_number)) | |
449 |
|
449 | |||
450 | def reset(self, new_session=True): |
|
450 | def reset(self, new_session=True): | |
451 | """Clear the session history, releasing all object references, and |
|
451 | """Clear the session history, releasing all object references, and | |
452 | optionally open a new session.""" |
|
452 | optionally open a new session.""" | |
453 | self.output_hist.clear() |
|
453 | self.output_hist.clear() | |
454 | # The directory history can't be completely empty |
|
454 | # The directory history can't be completely empty | |
455 | self.dir_hist[:] = [os.getcwdu()] |
|
455 | self.dir_hist[:] = [os.getcwdu()] | |
456 |
|
456 | |||
457 | if new_session: |
|
457 | if new_session: | |
458 | if self.session_number: |
|
458 | if self.session_number: | |
459 | self.end_session() |
|
459 | self.end_session() | |
460 | self.input_hist_parsed[:] = [""] |
|
460 | self.input_hist_parsed[:] = [""] | |
461 | self.input_hist_raw[:] = [""] |
|
461 | self.input_hist_raw[:] = [""] | |
462 | self.new_session() |
|
462 | self.new_session() | |
463 |
|
463 | |||
464 | # ------------------------------ |
|
464 | # ------------------------------ | |
465 | # Methods for retrieving history |
|
465 | # Methods for retrieving history | |
466 | # ------------------------------ |
|
466 | # ------------------------------ | |
467 | def _get_range_session(self, start=1, stop=None, raw=True, output=False): |
|
467 | def _get_range_session(self, start=1, stop=None, raw=True, output=False): | |
468 | """Get input and output history from the current session. Called by |
|
468 | """Get input and output history from the current session. Called by | |
469 | get_range, and takes similar parameters.""" |
|
469 | get_range, and takes similar parameters.""" | |
470 | input_hist = self.input_hist_raw if raw else self.input_hist_parsed |
|
470 | input_hist = self.input_hist_raw if raw else self.input_hist_parsed | |
471 |
|
471 | |||
472 | n = len(input_hist) |
|
472 | n = len(input_hist) | |
473 | if start < 0: |
|
473 | if start < 0: | |
474 | start += n |
|
474 | start += n | |
475 | if not stop or (stop > n): |
|
475 | if not stop or (stop > n): | |
476 | stop = n |
|
476 | stop = n | |
477 | elif stop < 0: |
|
477 | elif stop < 0: | |
478 | stop += n |
|
478 | stop += n | |
479 |
|
479 | |||
480 | for i in range(start, stop): |
|
480 | for i in range(start, stop): | |
481 | if output: |
|
481 | if output: | |
482 | line = (input_hist[i], self.output_hist_reprs.get(i)) |
|
482 | line = (input_hist[i], self.output_hist_reprs.get(i)) | |
483 | else: |
|
483 | else: | |
484 | line = input_hist[i] |
|
484 | line = input_hist[i] | |
485 | yield (0, i, line) |
|
485 | yield (0, i, line) | |
486 |
|
486 | |||
487 | def get_range(self, session=0, start=1, stop=None, raw=True,output=False): |
|
487 | def get_range(self, session=0, start=1, stop=None, raw=True,output=False): | |
488 | """Retrieve input by session. |
|
488 | """Retrieve input by session. | |
489 |
|
489 | |||
490 | Parameters |
|
490 | Parameters | |
491 | ---------- |
|
491 | ---------- | |
492 | session : int |
|
492 | session : int | |
493 | Session number to retrieve. The current session is 0, and negative |
|
493 | Session number to retrieve. The current session is 0, and negative | |
494 | numbers count back from current session, so -1 is previous session. |
|
494 | numbers count back from current session, so -1 is previous session. | |
495 | start : int |
|
495 | start : int | |
496 | First line to retrieve. |
|
496 | First line to retrieve. | |
497 | stop : int |
|
497 | stop : int | |
498 | End of line range (excluded from output itself). If None, retrieve |
|
498 | End of line range (excluded from output itself). If None, retrieve | |
499 | to the end of the session. |
|
499 | to the end of the session. | |
500 | raw : bool |
|
500 | raw : bool | |
501 | If True, return untranslated input |
|
501 | If True, return untranslated input | |
502 | output : bool |
|
502 | output : bool | |
503 | If True, attempt to include output. This will be 'real' Python |
|
503 | If True, attempt to include output. This will be 'real' Python | |
504 | objects for the current session, or text reprs from previous |
|
504 | objects for the current session, or text reprs from previous | |
505 | sessions if db_log_output was enabled at the time. Where no output |
|
505 | sessions if db_log_output was enabled at the time. Where no output | |
506 | is found, None is used. |
|
506 | is found, None is used. | |
507 |
|
507 | |||
508 | Returns |
|
508 | Returns | |
509 | ------- |
|
509 | ------- | |
510 | An iterator over the desired lines. Each line is a 3-tuple, either |
|
510 | An iterator over the desired lines. Each line is a 3-tuple, either | |
511 | (session, line, input) if output is False, or |
|
511 | (session, line, input) if output is False, or | |
512 | (session, line, (input, output)) if output is True. |
|
512 | (session, line, (input, output)) if output is True. | |
513 | """ |
|
513 | """ | |
514 | if session <= 0: |
|
514 | if session <= 0: | |
515 | session += self.session_number |
|
515 | session += self.session_number | |
516 | if session==self.session_number: # Current session |
|
516 | if session==self.session_number: # Current session | |
517 | return self._get_range_session(start, stop, raw, output) |
|
517 | return self._get_range_session(start, stop, raw, output) | |
518 | return super(HistoryManager, self).get_range(session, start, stop, raw, |
|
518 | return super(HistoryManager, self).get_range(session, start, stop, raw, | |
519 | output) |
|
519 | output) | |
520 |
|
520 | |||
521 | ## ---------------------------- |
|
521 | ## ---------------------------- | |
522 | ## Methods for storing history: |
|
522 | ## Methods for storing history: | |
523 | ## ---------------------------- |
|
523 | ## ---------------------------- | |
524 | def store_inputs(self, line_num, source, source_raw=None): |
|
524 | def store_inputs(self, line_num, source, source_raw=None): | |
525 | """Store source and raw input in history and create input cache |
|
525 | """Store source and raw input in history and create input cache | |
526 | variables _i*. |
|
526 | variables _i*. | |
527 |
|
527 | |||
528 | Parameters |
|
528 | Parameters | |
529 | ---------- |
|
529 | ---------- | |
530 | line_num : int |
|
530 | line_num : int | |
531 | The prompt number of this input. |
|
531 | The prompt number of this input. | |
532 |
|
532 | |||
533 | source : str |
|
533 | source : str | |
534 | Python input. |
|
534 | Python input. | |
535 |
|
535 | |||
536 | source_raw : str, optional |
|
536 | source_raw : str, optional | |
537 | If given, this is the raw input without any IPython transformations |
|
537 | If given, this is the raw input without any IPython transformations | |
538 | applied to it. If not given, ``source`` is used. |
|
538 | applied to it. If not given, ``source`` is used. | |
539 | """ |
|
539 | """ | |
540 | if source_raw is None: |
|
540 | if source_raw is None: | |
541 | source_raw = source |
|
541 | source_raw = source | |
542 | source = source.rstrip('\n') |
|
542 | source = source.rstrip('\n') | |
543 | source_raw = source_raw.rstrip('\n') |
|
543 | source_raw = source_raw.rstrip('\n') | |
544 |
|
544 | |||
545 | # do not store exit/quit commands |
|
545 | # do not store exit/quit commands | |
546 | if self._exit_re.match(source_raw.strip()): |
|
546 | if self._exit_re.match(source_raw.strip()): | |
547 | return |
|
547 | return | |
548 |
|
548 | |||
549 | self.input_hist_parsed.append(source) |
|
549 | self.input_hist_parsed.append(source) | |
550 | self.input_hist_raw.append(source_raw) |
|
550 | self.input_hist_raw.append(source_raw) | |
551 |
|
551 | |||
552 | with self.db_input_cache_lock: |
|
552 | with self.db_input_cache_lock: | |
553 | self.db_input_cache.append((line_num, source, source_raw)) |
|
553 | self.db_input_cache.append((line_num, source, source_raw)) | |
554 | # Trigger to flush cache and write to DB. |
|
554 | # Trigger to flush cache and write to DB. | |
555 | if len(self.db_input_cache) >= self.db_cache_size: |
|
555 | if len(self.db_input_cache) >= self.db_cache_size: | |
556 | self.save_flag.set() |
|
556 | self.save_flag.set() | |
557 |
|
557 | |||
558 | # update the auto _i variables |
|
558 | # update the auto _i variables | |
559 | self._iii = self._ii |
|
559 | self._iii = self._ii | |
560 | self._ii = self._i |
|
560 | self._ii = self._i | |
561 | self._i = self._i00 |
|
561 | self._i = self._i00 | |
562 | self._i00 = source_raw |
|
562 | self._i00 = source_raw | |
563 |
|
563 | |||
564 | # hackish access to user namespace to create _i1,_i2... dynamically |
|
564 | # hackish access to user namespace to create _i1,_i2... dynamically | |
565 | new_i = '_i%s' % line_num |
|
565 | new_i = '_i%s' % line_num | |
566 | to_main = {'_i': self._i, |
|
566 | to_main = {'_i': self._i, | |
567 | '_ii': self._ii, |
|
567 | '_ii': self._ii, | |
568 | '_iii': self._iii, |
|
568 | '_iii': self._iii, | |
569 | new_i : self._i00 } |
|
569 | new_i : self._i00 } | |
570 |
|
570 | |||
571 | self.shell.push(to_main, interactive=False) |
|
571 | self.shell.push(to_main, interactive=False) | |
572 |
|
572 | |||
573 | def store_output(self, line_num): |
|
573 | def store_output(self, line_num): | |
574 | """If database output logging is enabled, this saves all the |
|
574 | """If database output logging is enabled, this saves all the | |
575 | outputs from the indicated prompt number to the database. It's |
|
575 | outputs from the indicated prompt number to the database. It's | |
576 | called by run_cell after code has been executed. |
|
576 | called by run_cell after code has been executed. | |
577 |
|
577 | |||
578 | Parameters |
|
578 | Parameters | |
579 | ---------- |
|
579 | ---------- | |
580 | line_num : int |
|
580 | line_num : int | |
581 | The line number from which to save outputs |
|
581 | The line number from which to save outputs | |
582 | """ |
|
582 | """ | |
583 | if (not self.db_log_output) or (line_num not in self.output_hist_reprs): |
|
583 | if (not self.db_log_output) or (line_num not in self.output_hist_reprs): | |
584 | return |
|
584 | return | |
585 | output = self.output_hist_reprs[line_num] |
|
585 | output = self.output_hist_reprs[line_num] | |
586 |
|
586 | |||
587 | with self.db_output_cache_lock: |
|
587 | with self.db_output_cache_lock: | |
588 | self.db_output_cache.append((line_num, output)) |
|
588 | self.db_output_cache.append((line_num, output)) | |
589 | if self.db_cache_size <= 1: |
|
589 | if self.db_cache_size <= 1: | |
590 | self.save_flag.set() |
|
590 | self.save_flag.set() | |
591 |
|
591 | |||
592 | def _writeout_input_cache(self, conn): |
|
592 | def _writeout_input_cache(self, conn): | |
593 | with conn: |
|
593 | with conn: | |
594 | for line in self.db_input_cache: |
|
594 | for line in self.db_input_cache: | |
595 | conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)", |
|
595 | conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)", | |
596 | (self.session_number,)+line) |
|
596 | (self.session_number,)+line) | |
597 |
|
597 | |||
598 | def _writeout_output_cache(self, conn): |
|
598 | def _writeout_output_cache(self, conn): | |
599 | with conn: |
|
599 | with conn: | |
600 | for line in self.db_output_cache: |
|
600 | for line in self.db_output_cache: | |
601 | conn.execute("INSERT INTO output_history VALUES (?, ?, ?)", |
|
601 | conn.execute("INSERT INTO output_history VALUES (?, ?, ?)", | |
602 | (self.session_number,)+line) |
|
602 | (self.session_number,)+line) | |
603 |
|
603 | |||
604 | @needs_sqlite |
|
604 | @needs_sqlite | |
605 | def writeout_cache(self, conn=None): |
|
605 | def writeout_cache(self, conn=None): | |
606 | """Write any entries in the cache to the database.""" |
|
606 | """Write any entries in the cache to the database.""" | |
607 | if conn is None: |
|
607 | if conn is None: | |
608 | conn = self.db |
|
608 | conn = self.db | |
609 |
|
609 | |||
610 | with self.db_input_cache_lock: |
|
610 | with self.db_input_cache_lock: | |
611 | try: |
|
611 | try: | |
612 | self._writeout_input_cache(conn) |
|
612 | self._writeout_input_cache(conn) | |
613 | except sqlite3.IntegrityError: |
|
613 | except sqlite3.IntegrityError: | |
614 | self.new_session(conn) |
|
614 | self.new_session(conn) | |
615 | print("ERROR! Session/line number was not unique in", |
|
615 | print("ERROR! Session/line number was not unique in", | |
616 | "database. History logging moved to new session", |
|
616 | "database. History logging moved to new session", | |
617 | self.session_number) |
|
617 | self.session_number) | |
618 | try: |
|
618 | try: | |
619 | # Try writing to the new session. If this fails, don't |
|
619 | # Try writing to the new session. If this fails, don't | |
620 | # recurse |
|
620 | # recurse | |
621 | self._writeout_input_cache(conn) |
|
621 | self._writeout_input_cache(conn) | |
622 | except sqlite3.IntegrityError: |
|
622 | except sqlite3.IntegrityError: | |
623 | pass |
|
623 | pass | |
624 | finally: |
|
624 | finally: | |
625 | self.db_input_cache = [] |
|
625 | self.db_input_cache = [] | |
626 |
|
626 | |||
627 | with self.db_output_cache_lock: |
|
627 | with self.db_output_cache_lock: | |
628 | try: |
|
628 | try: | |
629 | self._writeout_output_cache(conn) |
|
629 | self._writeout_output_cache(conn) | |
630 | except sqlite3.IntegrityError: |
|
630 | except sqlite3.IntegrityError: | |
631 | print("!! Session/line number for output was not unique", |
|
631 | print("!! Session/line number for output was not unique", | |
632 | "in database. Output will not be stored.") |
|
632 | "in database. Output will not be stored.") | |
633 | finally: |
|
633 | finally: | |
634 | self.db_output_cache = [] |
|
634 | self.db_output_cache = [] | |
635 |
|
635 | |||
636 |
|
636 | |||
637 | class HistorySavingThread(threading.Thread): |
|
637 | class HistorySavingThread(threading.Thread): | |
638 | """This thread takes care of writing history to the database, so that |
|
638 | """This thread takes care of writing history to the database, so that | |
639 | the UI isn't held up while that happens. |
|
639 | the UI isn't held up while that happens. | |
640 |
|
640 | |||
641 | It waits for the HistoryManager's save_flag to be set, then writes out |
|
641 | It waits for the HistoryManager's save_flag to be set, then writes out | |
642 | the history cache. The main thread is responsible for setting the flag when |
|
642 | the history cache. The main thread is responsible for setting the flag when | |
643 | the cache size reaches a defined threshold.""" |
|
643 | the cache size reaches a defined threshold.""" | |
644 | daemon = True |
|
644 | daemon = True | |
645 | stop_now = False |
|
645 | stop_now = False | |
646 | def __init__(self, history_manager): |
|
646 | def __init__(self, history_manager): | |
647 | super(HistorySavingThread, self).__init__() |
|
647 | super(HistorySavingThread, self).__init__() | |
648 | self.history_manager = history_manager |
|
648 | self.history_manager = history_manager | |
649 | atexit.register(self.stop) |
|
649 | atexit.register(self.stop) | |
650 |
|
650 | |||
651 | @needs_sqlite |
|
651 | @needs_sqlite | |
652 | def run(self): |
|
652 | def run(self): | |
653 | # We need a separate db connection per thread: |
|
653 | # We need a separate db connection per thread: | |
654 | try: |
|
654 | try: | |
655 | self.db = sqlite3.connect(self.history_manager.hist_file) |
|
655 | self.db = sqlite3.connect(self.history_manager.hist_file) | |
656 | while True: |
|
656 | while True: | |
657 | self.history_manager.save_flag.wait() |
|
657 | self.history_manager.save_flag.wait() | |
658 | if self.stop_now: |
|
658 | if self.stop_now: | |
659 | return |
|
659 | return | |
660 | self.history_manager.save_flag.clear() |
|
660 | self.history_manager.save_flag.clear() | |
661 | self.history_manager.writeout_cache(self.db) |
|
661 | self.history_manager.writeout_cache(self.db) | |
662 | except Exception as e: |
|
662 | except Exception as e: | |
663 | print(("The history saving thread hit an unexpected error (%s)." |
|
663 | print(("The history saving thread hit an unexpected error (%s)." | |
664 | "History will not be written to the database.") % repr(e)) |
|
664 | "History will not be written to the database.") % repr(e)) | |
665 |
|
665 | |||
666 | def stop(self): |
|
666 | def stop(self): | |
667 | """This can be called from the main thread to safely stop this thread. |
|
667 | """This can be called from the main thread to safely stop this thread. | |
668 |
|
668 | |||
669 | Note that it does not attempt to write out remaining history before |
|
669 | Note that it does not attempt to write out remaining history before | |
670 | exiting. That should be done by calling the HistoryManager's |
|
670 | exiting. That should be done by calling the HistoryManager's | |
671 | end_session method.""" |
|
671 | end_session method.""" | |
672 | self.stop_now = True |
|
672 | self.stop_now = True | |
673 | self.history_manager.save_flag.set() |
|
673 | self.history_manager.save_flag.set() | |
674 | self.join() |
|
674 | self.join() | |
675 |
|
675 | |||
676 |
|
676 | |||
677 | # To match, e.g. ~5/8-~2/3 |
|
677 | # To match, e.g. ~5/8-~2/3 | |
678 | range_re = re.compile(r""" |
|
678 | range_re = re.compile(r""" | |
679 | ((?P<startsess>~?\d+)/)? |
|
679 | ((?P<startsess>~?\d+)/)? | |
680 | (?P<start>\d+) # Only the start line num is compulsory |
|
680 | (?P<start>\d+) # Only the start line num is compulsory | |
681 | ((?P<sep>[\-:]) |
|
681 | ((?P<sep>[\-:]) | |
682 | ((?P<endsess>~?\d+)/)? |
|
682 | ((?P<endsess>~?\d+)/)? | |
683 | (?P<end>\d+))? |
|
683 | (?P<end>\d+))? | |
684 | $""", re.VERBOSE) |
|
684 | $""", re.VERBOSE) | |
685 |
|
685 | |||
686 |
|
686 | |||
687 | def extract_hist_ranges(ranges_str): |
|
687 | def extract_hist_ranges(ranges_str): | |
688 | """Turn a string of history ranges into 3-tuples of (session, start, stop). |
|
688 | """Turn a string of history ranges into 3-tuples of (session, start, stop). | |
689 |
|
689 | |||
690 | Examples |
|
690 | Examples | |
691 | -------- |
|
691 | -------- | |
692 | list(extract_input_ranges("~8/5-~7/4 2")) |
|
692 | list(extract_input_ranges("~8/5-~7/4 2")) | |
693 | [(-8, 5, None), (-7, 1, 4), (0, 2, 3)] |
|
693 | [(-8, 5, None), (-7, 1, 4), (0, 2, 3)] | |
694 | """ |
|
694 | """ | |
695 | for range_str in ranges_str.split(): |
|
695 | for range_str in ranges_str.split(): | |
696 | rmatch = range_re.match(range_str) |
|
696 | rmatch = range_re.match(range_str) | |
697 | if not rmatch: |
|
697 | if not rmatch: | |
698 | continue |
|
698 | continue | |
699 | start = int(rmatch.group("start")) |
|
699 | start = int(rmatch.group("start")) | |
700 | end = rmatch.group("end") |
|
700 | end = rmatch.group("end") | |
701 | end = int(end) if end else start+1 # If no end specified, get (a, a+1) |
|
701 | end = int(end) if end else start+1 # If no end specified, get (a, a+1) | |
702 | if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3] |
|
702 | if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3] | |
703 | end += 1 |
|
703 | end += 1 | |
704 | startsess = rmatch.group("startsess") or "0" |
|
704 | startsess = rmatch.group("startsess") or "0" | |
705 | endsess = rmatch.group("endsess") or startsess |
|
705 | endsess = rmatch.group("endsess") or startsess | |
706 | startsess = int(startsess.replace("~","-")) |
|
706 | startsess = int(startsess.replace("~","-")) | |
707 | endsess = int(endsess.replace("~","-")) |
|
707 | endsess = int(endsess.replace("~","-")) | |
708 | assert endsess >= startsess |
|
708 | assert endsess >= startsess | |
709 |
|
709 | |||
710 | if endsess == startsess: |
|
710 | if endsess == startsess: | |
711 | yield (startsess, start, end) |
|
711 | yield (startsess, start, end) | |
712 | continue |
|
712 | continue | |
713 | # Multiple sessions in one range: |
|
713 | # Multiple sessions in one range: | |
714 | yield (startsess, start, None) |
|
714 | yield (startsess, start, None) | |
715 | for sess in range(startsess+1, endsess): |
|
715 | for sess in range(startsess+1, endsess): | |
716 | yield (sess, 1, None) |
|
716 | yield (sess, 1, None) | |
717 | yield (endsess, 1, end) |
|
717 | yield (endsess, 1, end) | |
718 |
|
718 | |||
719 |
|
719 | |||
720 | def _format_lineno(session, line): |
|
720 | def _format_lineno(session, line): | |
721 | """Helper function to format line numbers properly.""" |
|
721 | """Helper function to format line numbers properly.""" | |
722 | if session == 0: |
|
722 | if session == 0: | |
723 | return str(line) |
|
723 | return str(line) | |
724 | return "%s#%s" % (session, line) |
|
724 | return "%s#%s" % (session, line) | |
725 |
|
725 | |||
726 |
|
726 | |||
727 | @register_magics |
|
727 | @register_magics | |
728 | class HistoryMagics(Magics): |
|
728 | class HistoryMagics(Magics): | |
729 |
|
729 | |||
730 | @skip_doctest |
|
730 | @skip_doctest | |
731 | @line_magic |
|
731 | @line_magic | |
732 | def history(self, parameter_s = ''): |
|
732 | def history(self, parameter_s = ''): | |
733 | """Print input history (_i<n> variables), with most recent last. |
|
733 | """Print input history (_i<n> variables), with most recent last. | |
734 |
|
734 | |||
735 | %history [-o -p -t -n] [-f filename] [range | -g pattern | -l number] |
|
735 | %history [-o -p -t -n] [-f filename] [range | -g pattern | -l number] | |
736 |
|
736 | |||
737 | By default, input history is printed without line numbers so it can be |
|
737 | By default, input history is printed without line numbers so it can be | |
738 | directly pasted into an editor. Use -n to show them. |
|
738 | directly pasted into an editor. Use -n to show them. | |
739 |
|
739 | |||
740 | By default, all input history from the current session is displayed. |
|
740 | By default, all input history from the current session is displayed. | |
741 | Ranges of history can be indicated using the syntax: |
|
741 | Ranges of history can be indicated using the syntax: | |
742 | 4 : Line 4, current session |
|
742 | 4 : Line 4, current session | |
743 | 4-6 : Lines 4-6, current session |
|
743 | 4-6 : Lines 4-6, current session | |
744 | 243/1-5: Lines 1-5, session 243 |
|
744 | 243/1-5: Lines 1-5, session 243 | |
745 | ~2/7 : Line 7, session 2 before current |
|
745 | ~2/7 : Line 7, session 2 before current | |
746 | ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line |
|
746 | ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line | |
747 | of 6 sessions ago. |
|
747 | of 6 sessions ago. | |
748 | Multiple ranges can be entered, separated by spaces |
|
748 | Multiple ranges can be entered, separated by spaces | |
749 |
|
749 | |||
750 | The same syntax is used by %macro, %save, %edit, %rerun |
|
750 | The same syntax is used by %macro, %save, %edit, %rerun | |
751 |
|
751 | |||
752 | Options: |
|
752 | Options: | |
753 |
|
753 | |||
754 | -n: print line numbers for each input. |
|
754 | -n: print line numbers for each input. | |
755 | This feature is only available if numbered prompts are in use. |
|
755 | This feature is only available if numbered prompts are in use. | |
756 |
|
756 | |||
757 | -o: also print outputs for each input. |
|
757 | -o: also print outputs for each input. | |
758 |
|
758 | |||
759 | -p: print classic '>>>' python prompts before each input. This is |
|
759 | -p: print classic '>>>' python prompts before each input. This is | |
760 | useful for making documentation, and in conjunction with -o, for |
|
760 | useful for making documentation, and in conjunction with -o, for | |
761 | producing doctest-ready output. |
|
761 | producing doctest-ready output. | |
762 |
|
762 | |||
763 | -r: (default) print the 'raw' history, i.e. the actual commands you |
|
763 | -r: (default) print the 'raw' history, i.e. the actual commands you | |
764 | typed. |
|
764 | typed. | |
765 |
|
765 | |||
766 | -t: print the 'translated' history, as IPython understands it. |
|
766 | -t: print the 'translated' history, as IPython understands it. | |
767 | IPython filters your input and converts it all into valid Python |
|
767 | IPython filters your input and converts it all into valid Python | |
768 | source before executing it (things like magics or aliases are turned |
|
768 | source before executing it (things like magics or aliases are turned | |
769 | into function calls, for example). With this option, you'll see the |
|
769 | into function calls, for example). With this option, you'll see the | |
770 | native history instead of the user-entered version: '%cd /' will be |
|
770 | native history instead of the user-entered version: '%cd /' will be | |
771 | seen as 'get_ipython().magic("%cd /")' instead of '%cd /'. |
|
771 | seen as 'get_ipython().magic("%cd /")' instead of '%cd /'. | |
772 |
|
772 | |||
773 | -g: treat the arg as a pattern to grep for in (full) history. |
|
773 | -g: treat the arg as a pattern to grep for in (full) history. | |
774 | This includes the saved history (almost all commands ever written). |
|
774 | This includes the saved history (almost all commands ever written). | |
775 | Use '%hist -g' to show full saved history (may be very long). |
|
775 | Use '%hist -g' to show full saved history (may be very long). | |
776 |
|
776 | |||
777 | -l: get the last n lines from all sessions. Specify n as a single |
|
777 | -l: get the last n lines from all sessions. Specify n as a single | |
778 | arg, or the default is the last 10 lines. |
|
778 | arg, or the default is the last 10 lines. | |
779 |
|
779 | |||
780 | -f FILENAME: instead of printing the output to the screen, redirect |
|
780 | -f FILENAME: instead of printing the output to the screen, redirect | |
781 | it to the given file. The file is always overwritten, though *when |
|
781 | it to the given file. The file is always overwritten, though *when | |
782 | it can*, IPython asks for confirmation first. In particular, running |
|
782 | it can*, IPython asks for confirmation first. In particular, running | |
783 | the command 'history -f FILENAME' from the IPython Notebook |
|
783 | the command 'history -f FILENAME' from the IPython Notebook | |
784 | interface will replace FILENAME even if it already exists *without* |
|
784 | interface will replace FILENAME even if it already exists *without* | |
785 | confirmation. |
|
785 | confirmation. | |
786 |
|
786 | |||
787 | Examples |
|
787 | Examples | |
788 | -------- |
|
788 | -------- | |
789 | :: |
|
789 | :: | |
790 |
|
790 | |||
791 | In [6]: %hist -n 4-6 |
|
791 | In [6]: %hist -n 4-6 | |
792 | 4:a = 12 |
|
792 | 4:a = 12 | |
793 | 5:print a**2 |
|
793 | 5:print a**2 | |
794 | 6:%hist -n 4-6 |
|
794 | 6:%hist -n 4-6 | |
795 |
|
795 | |||
796 | """ |
|
796 | """ | |
797 |
|
797 | |||
798 | if not self.shell.displayhook.do_full_cache: |
|
798 | if not self.shell.displayhook.do_full_cache: | |
799 | print('This feature is only available if numbered prompts ' |
|
799 | print('This feature is only available if numbered prompts ' | |
800 | 'are in use.') |
|
800 | 'are in use.') | |
801 | return |
|
801 | return | |
802 | opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string') |
|
802 | opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string') | |
803 |
|
803 | |||
804 | # For brevity |
|
804 | # For brevity | |
805 | history_manager = self.shell.history_manager |
|
805 | history_manager = self.shell.history_manager | |
806 |
|
806 | |||
807 | def _format_lineno(session, line): |
|
807 | def _format_lineno(session, line): | |
808 | """Helper function to format line numbers properly.""" |
|
808 | """Helper function to format line numbers properly.""" | |
809 | if session in (0, history_manager.session_number): |
|
809 | if session in (0, history_manager.session_number): | |
810 | return str(line) |
|
810 | return str(line) | |
811 | return "%s/%s" % (session, line) |
|
811 | return "%s/%s" % (session, line) | |
812 |
|
812 | |||
813 | # Check if output to specific file was requested. |
|
813 | # Check if output to specific file was requested. | |
814 | try: |
|
814 | try: | |
815 | outfname = opts['f'] |
|
815 | outfname = opts['f'] | |
816 | except KeyError: |
|
816 | except KeyError: | |
817 | outfile = io.stdout # default |
|
817 | outfile = io.stdout # default | |
818 | # We don't want to close stdout at the end! |
|
818 | # We don't want to close stdout at the end! | |
819 | close_at_end = False |
|
819 | close_at_end = False | |
820 | else: |
|
820 | else: | |
821 | if os.path.exists(outfname): |
|
821 | if os.path.exists(outfname): | |
822 | try: |
|
822 | try: | |
823 | ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname) |
|
823 | ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname) | |
824 | except StdinNotImplementedError: |
|
824 | except StdinNotImplementedError: | |
825 | ans = True |
|
825 | ans = True | |
826 | if not ans: |
|
826 | if not ans: | |
827 | print('Aborting.') |
|
827 | print('Aborting.') | |
828 | return |
|
828 | return | |
829 | print("Overwriting file.") |
|
829 | print("Overwriting file.") | |
830 | outfile = io_open(outfname, 'w', encoding='utf-8') |
|
830 | outfile = io_open(outfname, 'w', encoding='utf-8') | |
831 | close_at_end = True |
|
831 | close_at_end = True | |
832 |
|
832 | |||
833 | print_nums = 'n' in opts |
|
833 | print_nums = 'n' in opts | |
834 | get_output = 'o' in opts |
|
834 | get_output = 'o' in opts | |
835 | pyprompts = 'p' in opts |
|
835 | pyprompts = 'p' in opts | |
836 | # Raw history is the default |
|
836 | # Raw history is the default | |
837 | raw = not('t' in opts) |
|
837 | raw = not('t' in opts) | |
838 |
|
838 | |||
839 | pattern = None |
|
839 | pattern = None | |
840 |
|
840 | |||
841 | if 'g' in opts: # Glob search |
|
841 | if 'g' in opts: # Glob search | |
842 | pattern = "*" + args + "*" if args else "*" |
|
842 | pattern = "*" + args + "*" if args else "*" | |
843 | hist = history_manager.search(pattern, raw=raw, output=get_output) |
|
843 | hist = history_manager.search(pattern, raw=raw, output=get_output) | |
844 | print_nums = True |
|
844 | print_nums = True | |
845 | elif 'l' in opts: # Get 'tail' |
|
845 | elif 'l' in opts: # Get 'tail' | |
846 | try: |
|
846 | try: | |
847 | n = int(args) |
|
847 | n = int(args) | |
848 | except (ValueError, IndexError): |
|
848 | except (ValueError, IndexError): | |
849 | n = 10 |
|
849 | n = 10 | |
850 | hist = history_manager.get_tail(n, raw=raw, output=get_output) |
|
850 | hist = history_manager.get_tail(n, raw=raw, output=get_output) | |
851 | else: |
|
851 | else: | |
852 | if args: # Get history by ranges |
|
852 | if args: # Get history by ranges | |
853 | hist = history_manager.get_range_by_str(args, raw, get_output) |
|
853 | hist = history_manager.get_range_by_str(args, raw, get_output) | |
854 | else: # Just get history for the current session |
|
854 | else: # Just get history for the current session | |
855 | hist = history_manager.get_range(raw=raw, output=get_output) |
|
855 | hist = history_manager.get_range(raw=raw, output=get_output) | |
856 |
|
856 | |||
857 | # We could be displaying the entire history, so let's not try to pull |
|
857 | # We could be displaying the entire history, so let's not try to pull | |
858 | # it into a list in memory. Anything that needs more space will just |
|
858 | # it into a list in memory. Anything that needs more space will just | |
859 | # misalign. |
|
859 | # misalign. | |
860 | width = 4 |
|
860 | width = 4 | |
861 |
|
861 | |||
862 | for session, lineno, inline in hist: |
|
862 | for session, lineno, inline in hist: | |
863 | # Print user history with tabs expanded to 4 spaces. The GUI |
|
863 | # Print user history with tabs expanded to 4 spaces. The GUI | |
864 | # clients use hard tabs for easier usability in auto-indented code, |
|
864 | # clients use hard tabs for easier usability in auto-indented code, | |
865 | # but we want to produce PEP-8 compliant history for safe pasting |
|
865 | # but we want to produce PEP-8 compliant history for safe pasting | |
866 | # into an editor. |
|
866 | # into an editor. | |
867 | if get_output: |
|
867 | if get_output: | |
868 | inline, output = inline |
|
868 | inline, output = inline | |
869 | inline = inline.expandtabs(4).rstrip() |
|
869 | inline = inline.expandtabs(4).rstrip() | |
870 |
|
870 | |||
871 | multiline = "\n" in inline |
|
871 | multiline = "\n" in inline | |
872 | line_sep = '\n' if multiline else ' ' |
|
872 | line_sep = '\n' if multiline else ' ' | |
873 | if print_nums: |
|
873 | if print_nums: | |
874 | print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width), |
|
874 | print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width), | |
875 | line_sep), file=outfile, end=u'') |
|
875 | line_sep), file=outfile, end=u'') | |
876 | if pyprompts: |
|
876 | if pyprompts: | |
877 | print(u">>> ", end=u"", file=outfile) |
|
877 | print(u">>> ", end=u"", file=outfile) | |
878 | if multiline: |
|
878 | if multiline: | |
879 | inline = "\n... ".join(inline.splitlines()) + "\n..." |
|
879 | inline = "\n... ".join(inline.splitlines()) + "\n..." | |
880 | print(inline, file=outfile) |
|
880 | print(inline, file=outfile) | |
881 | if get_output and output: |
|
881 | if get_output and output: | |
882 | print(output, file=outfile) |
|
882 | print(output, file=outfile) | |
883 |
|
883 | |||
884 | if close_at_end: |
|
884 | if close_at_end: | |
885 | outfile.close() |
|
885 | outfile.close() | |
886 |
|
886 | |||
|
887 | # For a long time we've had %hist as well as %history | |||
|
888 | @line_magic | |||
|
889 | def hist(self, arg): | |||
|
890 | return self.history(arg) | |||
|
891 | ||||
|
892 | hist.__doc__ = history.__doc__ | |||
|
893 | ||||
887 | @line_magic |
|
894 | @line_magic | |
888 | def rep(self, arg): |
|
895 | def rep(self, arg): | |
889 | r"""Repeat a command, or get command to input line for editing. |
|
896 | r"""Repeat a command, or get command to input line for editing. | |
890 |
|
897 | |||
891 | %recall and %rep are equivalent. |
|
898 | %recall and %rep are equivalent. | |
892 |
|
899 | |||
893 | - %recall (no arguments): |
|
900 | - %recall (no arguments): | |
894 |
|
901 | |||
895 | Place a string version of last computation result (stored in the |
|
902 | Place a string version of last computation result (stored in the | |
896 | special '_' variable) to the next input prompt. Allows you to create |
|
903 | special '_' variable) to the next input prompt. Allows you to create | |
897 | elaborate command lines without using copy-paste:: |
|
904 | elaborate command lines without using copy-paste:: | |
898 |
|
905 | |||
899 | In[1]: l = ["hei", "vaan"] |
|
906 | In[1]: l = ["hei", "vaan"] | |
900 | In[2]: "".join(l) |
|
907 | In[2]: "".join(l) | |
901 | Out[2]: heivaan |
|
908 | Out[2]: heivaan | |
902 | In[3]: %rep |
|
909 | In[3]: %rep | |
903 | In[4]: heivaan_ <== cursor blinking |
|
910 | In[4]: heivaan_ <== cursor blinking | |
904 |
|
911 | |||
905 | %recall 45 |
|
912 | %recall 45 | |
906 |
|
913 | |||
907 | Place history line 45 on the next input prompt. Use %hist to find |
|
914 | Place history line 45 on the next input prompt. Use %hist to find | |
908 | out the number. |
|
915 | out the number. | |
909 |
|
916 | |||
910 | %recall 1-4 |
|
917 | %recall 1-4 | |
911 |
|
918 | |||
912 | Combine the specified lines into one cell, and place it on the next |
|
919 | Combine the specified lines into one cell, and place it on the next | |
913 | input prompt. See %history for the slice syntax. |
|
920 | input prompt. See %history for the slice syntax. | |
914 |
|
921 | |||
915 | %recall foo+bar |
|
922 | %recall foo+bar | |
916 |
|
923 | |||
917 | If foo+bar can be evaluated in the user namespace, the result is |
|
924 | If foo+bar can be evaluated in the user namespace, the result is | |
918 | placed at the next input prompt. Otherwise, the history is searched |
|
925 | placed at the next input prompt. Otherwise, the history is searched | |
919 | for lines which contain that substring, and the most recent one is |
|
926 | for lines which contain that substring, and the most recent one is | |
920 | placed at the next input prompt. |
|
927 | placed at the next input prompt. | |
921 | """ |
|
928 | """ | |
922 | if not arg: # Last output |
|
929 | if not arg: # Last output | |
923 | self.shell.set_next_input(str(self.shell.user_ns["_"])) |
|
930 | self.shell.set_next_input(str(self.shell.user_ns["_"])) | |
924 | return |
|
931 | return | |
925 | # Get history range |
|
932 | # Get history range | |
926 | histlines = self.shell.history_manager.get_range_by_str(arg) |
|
933 | histlines = self.shell.history_manager.get_range_by_str(arg) | |
927 | cmd = "\n".join(x[2] for x in histlines) |
|
934 | cmd = "\n".join(x[2] for x in histlines) | |
928 | if cmd: |
|
935 | if cmd: | |
929 | self.shell.set_next_input(cmd.rstrip()) |
|
936 | self.shell.set_next_input(cmd.rstrip()) | |
930 | return |
|
937 | return | |
931 |
|
938 | |||
932 | try: # Variable in user namespace |
|
939 | try: # Variable in user namespace | |
933 | cmd = str(eval(arg, self.shell.user_ns)) |
|
940 | cmd = str(eval(arg, self.shell.user_ns)) | |
934 | except Exception: # Search for term in history |
|
941 | except Exception: # Search for term in history | |
935 | histlines = self.shell.history_manager.search("*"+arg+"*") |
|
942 | histlines = self.shell.history_manager.search("*"+arg+"*") | |
936 | for h in reversed([x[2] for x in histlines]): |
|
943 | for h in reversed([x[2] for x in histlines]): | |
937 | if 'rep' in h: |
|
944 | if 'rep' in h: | |
938 | continue |
|
945 | continue | |
939 | self.shell.set_next_input(h.rstrip()) |
|
946 | self.shell.set_next_input(h.rstrip()) | |
940 | return |
|
947 | return | |
941 | else: |
|
948 | else: | |
942 | self.shell.set_next_input(cmd.rstrip()) |
|
949 | self.shell.set_next_input(cmd.rstrip()) | |
943 | print("Couldn't evaluate or find in history:", arg) |
|
950 | print("Couldn't evaluate or find in history:", arg) | |
944 |
|
951 | |||
945 | @line_magic |
|
952 | @line_magic | |
946 | def rerun(self, parameter_s=''): |
|
953 | def rerun(self, parameter_s=''): | |
947 | """Re-run previous input |
|
954 | """Re-run previous input | |
948 |
|
955 | |||
949 | By default, you can specify ranges of input history to be repeated |
|
956 | By default, you can specify ranges of input history to be repeated | |
950 | (as with %history). With no arguments, it will repeat the last line. |
|
957 | (as with %history). With no arguments, it will repeat the last line. | |
951 |
|
958 | |||
952 | Options: |
|
959 | Options: | |
953 |
|
960 | |||
954 | -l <n> : Repeat the last n lines of input, not including the |
|
961 | -l <n> : Repeat the last n lines of input, not including the | |
955 | current command. |
|
962 | current command. | |
956 |
|
963 | |||
957 | -g foo : Repeat the most recent line which contains foo |
|
964 | -g foo : Repeat the most recent line which contains foo | |
958 | """ |
|
965 | """ | |
959 | opts, args = self.parse_options(parameter_s, 'l:g:', mode='string') |
|
966 | opts, args = self.parse_options(parameter_s, 'l:g:', mode='string') | |
960 | if "l" in opts: # Last n lines |
|
967 | if "l" in opts: # Last n lines | |
961 | n = int(opts['l']) |
|
968 | n = int(opts['l']) | |
962 | hist = self.shell.history_manager.get_tail(n) |
|
969 | hist = self.shell.history_manager.get_tail(n) | |
963 | elif "g" in opts: # Search |
|
970 | elif "g" in opts: # Search | |
964 | p = "*"+opts['g']+"*" |
|
971 | p = "*"+opts['g']+"*" | |
965 | hist = list(self.shell.history_manager.search(p)) |
|
972 | hist = list(self.shell.history_manager.search(p)) | |
966 | for l in reversed(hist): |
|
973 | for l in reversed(hist): | |
967 | if "rerun" not in l[2]: |
|
974 | if "rerun" not in l[2]: | |
968 | hist = [l] # The last match which isn't a %rerun |
|
975 | hist = [l] # The last match which isn't a %rerun | |
969 | break |
|
976 | break | |
970 | else: |
|
977 | else: | |
971 | hist = [] # No matches except %rerun |
|
978 | hist = [] # No matches except %rerun | |
972 | elif args: # Specify history ranges |
|
979 | elif args: # Specify history ranges | |
973 | hist = self.shell.history_manager.get_range_by_str(args) |
|
980 | hist = self.shell.history_manager.get_range_by_str(args) | |
974 | else: # Last line |
|
981 | else: # Last line | |
975 | hist = self.shell.history_manager.get_tail(1) |
|
982 | hist = self.shell.history_manager.get_tail(1) | |
976 | hist = [x[2] for x in hist] |
|
983 | hist = [x[2] for x in hist] | |
977 | if not hist: |
|
984 | if not hist: | |
978 | print("No lines in history match specification") |
|
985 | print("No lines in history match specification") | |
979 | return |
|
986 | return | |
980 | histlines = "\n".join(hist) |
|
987 | histlines = "\n".join(hist) | |
981 | print("=== Executing: ===") |
|
988 | print("=== Executing: ===") | |
982 | print(histlines) |
|
989 | print(histlines) | |
983 | print("=== Output: ===") |
|
990 | print("=== Output: ===") | |
984 | self.shell.run_cell("\n".join(hist), store_history=False) |
|
991 | self.shell.run_cell("\n".join(hist), store_history=False) | |
985 |
|
992 | |||
986 |
|
993 | |||
987 | def init_ipython(ip): |
|
994 | def init_ipython(ip): | |
988 | ip.register_magics(HistoryMagics) |
|
995 | ip.register_magics(HistoryMagics) | |
989 | # XXX - ipy_completers are in quarantine, need to be updated to new apis |
|
996 | # XXX - ipy_completers are in quarantine, need to be updated to new apis | |
990 | #import ipy_completers |
|
997 | #import ipy_completers | |
991 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
|
998 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
@@ -1,374 +1,372 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008 The IPython Development Team |
|
8 | # Copyright (C) 2008 The IPython Development Team | |
9 |
|
9 | |||
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | # Stdlib |
|
17 | # Stdlib | |
18 | import os |
|
18 | import os | |
19 | import re |
|
19 | import re | |
20 | import sys |
|
20 | import sys | |
21 | import types |
|
21 | import types | |
22 | from getopt import getopt, GetoptError |
|
22 | from getopt import getopt, GetoptError | |
23 |
|
23 | |||
24 | # Our own |
|
24 | # Our own | |
25 | from IPython.config.configurable import Configurable |
|
25 | from IPython.config.configurable import Configurable | |
26 | from IPython.core import oinspect |
|
26 | from IPython.core import oinspect | |
27 | from IPython.core.error import UsageError |
|
27 | from IPython.core.error import UsageError | |
28 | from IPython.core.prefilter import ESC_MAGIC |
|
28 | from IPython.core.prefilter import ESC_MAGIC | |
29 | from IPython.external.decorator import decorator |
|
29 | from IPython.external.decorator import decorator | |
30 | from IPython.utils.ipstruct import Struct |
|
30 | from IPython.utils.ipstruct import Struct | |
31 | from IPython.utils.process import arg_split |
|
31 | from IPython.utils.process import arg_split | |
32 | from IPython.utils.traitlets import Bool, Dict, Instance |
|
32 | from IPython.utils.traitlets import Bool, Dict, Instance | |
33 | from IPython.utils.warn import error, warn |
|
33 | from IPython.utils.warn import error, warn | |
34 |
|
34 | |||
35 | #----------------------------------------------------------------------------- |
|
35 | #----------------------------------------------------------------------------- | |
36 | # Globals |
|
36 | # Globals | |
37 | #----------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
38 |
|
38 | |||
39 | # A dict we'll use for each class that has magics, used as temporary storage to |
|
39 | # A dict we'll use for each class that has magics, used as temporary storage to | |
40 | # pass information between the @line/cell_magic method decorators and the |
|
40 | # pass information between the @line/cell_magic method decorators and the | |
41 | # @register_magics class decorator, because the method decorators have no |
|
41 | # @register_magics class decorator, because the method decorators have no | |
42 | # access to the class when they run. See for more details: |
|
42 | # access to the class when they run. See for more details: | |
43 | # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class |
|
43 | # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class | |
44 |
|
44 | |||
45 | magics = dict(line={}, cell={}) |
|
45 | magics = dict(line={}, cell={}) | |
46 |
|
46 | |||
47 | magic_types = ('line', 'cell') |
|
47 | magic_types = ('line', 'cell') | |
48 |
|
48 | |||
49 | #----------------------------------------------------------------------------- |
|
49 | #----------------------------------------------------------------------------- | |
50 | # Utility classes and functions |
|
50 | # Utility classes and functions | |
51 | #----------------------------------------------------------------------------- |
|
51 | #----------------------------------------------------------------------------- | |
52 |
|
52 | |||
53 | class Bunch: pass |
|
53 | class Bunch: pass | |
54 |
|
54 | |||
55 |
|
55 | |||
56 | def on_off(tag): |
|
56 | def on_off(tag): | |
57 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
57 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
58 | return ['OFF','ON'][tag] |
|
58 | return ['OFF','ON'][tag] | |
59 |
|
59 | |||
60 |
|
60 | |||
61 | def compress_dhist(dh): |
|
61 | def compress_dhist(dh): | |
62 | head, tail = dh[:-10], dh[-10:] |
|
62 | head, tail = dh[:-10], dh[-10:] | |
63 |
|
63 | |||
64 | newhead = [] |
|
64 | newhead = [] | |
65 | done = set() |
|
65 | done = set() | |
66 | for h in head: |
|
66 | for h in head: | |
67 | if h in done: |
|
67 | if h in done: | |
68 | continue |
|
68 | continue | |
69 | newhead.append(h) |
|
69 | newhead.append(h) | |
70 | done.add(h) |
|
70 | done.add(h) | |
71 |
|
71 | |||
72 | return newhead + tail |
|
72 | return newhead + tail | |
73 |
|
73 | |||
74 |
|
74 | |||
75 | def needs_local_scope(func): |
|
75 | def needs_local_scope(func): | |
76 | """Decorator to mark magic functions which need to local scope to run.""" |
|
76 | """Decorator to mark magic functions which need to local scope to run.""" | |
77 | func.needs_local_scope = True |
|
77 | func.needs_local_scope = True | |
78 | return func |
|
78 | return func | |
79 |
|
79 | |||
80 | #----------------------------------------------------------------------------- |
|
80 | #----------------------------------------------------------------------------- | |
81 | # Class and method decorators for registering magics |
|
81 | # Class and method decorators for registering magics | |
82 | #----------------------------------------------------------------------------- |
|
82 | #----------------------------------------------------------------------------- | |
83 |
|
83 | |||
84 | def register_magics(cls): |
|
84 | def register_magics(cls): | |
85 | cls.registered = True |
|
85 | cls.registered = True | |
86 | cls.magics = dict(line = magics['line'], |
|
86 | cls.magics = dict(line = magics['line'], | |
87 | cell = magics['cell']) |
|
87 | cell = magics['cell']) | |
88 | magics['line'] = {} |
|
88 | magics['line'] = {} | |
89 | magics['cell'] = {} |
|
89 | magics['cell'] = {} | |
90 | return cls |
|
90 | return cls | |
91 |
|
91 | |||
92 | def _record_magic(dct, mtype, mname, func): |
|
92 | def _record_magic(dct, mtype, mname, func): | |
93 | if mtype == 'line_cell': |
|
93 | if mtype == 'line_cell': | |
94 | dct['line'][mname] = dct['cell'][mname] = func |
|
94 | dct['line'][mname] = dct['cell'][mname] = func | |
95 | else: |
|
95 | else: | |
96 | dct[mtype][mname] = func |
|
96 | dct[mtype][mname] = func | |
97 |
|
97 | |||
98 | def validate_type(magic_type): |
|
98 | def validate_type(magic_type): | |
99 | if magic_type not in magic_types: |
|
99 | if magic_type not in magic_types: | |
100 | raise ValueError('magic_type must be one of %s, %s given' % |
|
100 | raise ValueError('magic_type must be one of %s, %s given' % | |
101 | magic_types, magic_type) |
|
101 | magic_types, magic_type) | |
102 |
|
102 | |||
103 |
|
103 | |||
104 | def _magic_marker(magic_type): |
|
104 | def _magic_marker(magic_type): | |
105 | validate_type(magic_type) |
|
105 | validate_type(magic_type) | |
106 |
|
106 | |||
107 | # This is a closure to capture the magic_type. We could also use a class, |
|
107 | # This is a closure to capture the magic_type. We could also use a class, | |
108 | # but it's overkill for just that one bit of state. |
|
108 | # but it's overkill for just that one bit of state. | |
109 | def magic_deco(arg): |
|
109 | def magic_deco(arg): | |
110 | call = lambda f, *a, **k: f(*a, **k) |
|
110 | call = lambda f, *a, **k: f(*a, **k) | |
111 |
|
111 | |||
112 | if callable(arg): |
|
112 | if callable(arg): | |
113 | # "Naked" decorator call (just @foo, no args) |
|
113 | # "Naked" decorator call (just @foo, no args) | |
114 | func = arg |
|
114 | func = arg | |
115 | name = func.func_name |
|
115 | name = func.func_name | |
116 | func.magic_name = name |
|
116 | func.magic_name = name | |
117 | retval = decorator(call, func) |
|
117 | retval = decorator(call, func) | |
118 | magics[magic_type][name] = name |
|
118 | magics[magic_type][name] = name | |
119 | elif isinstance(arg, basestring): |
|
119 | elif isinstance(arg, basestring): | |
120 | # Decorator called with arguments (@foo('bar')) |
|
120 | # Decorator called with arguments (@foo('bar')) | |
121 | name = arg |
|
121 | name = arg | |
122 | def mark(func, *a, **kw): |
|
122 | def mark(func, *a, **kw): | |
123 | func.magic_name = name |
|
123 | func.magic_name = name | |
124 | magics[magic_type][name] = func.func_name |
|
124 | magics[magic_type][name] = func.func_name | |
125 | return decorator(call, func) |
|
125 | return decorator(call, func) | |
126 | retval = mark |
|
126 | retval = mark | |
127 | else: |
|
127 | else: | |
128 | raise ValueError("Decorator can only be called with " |
|
128 | raise ValueError("Decorator can only be called with " | |
129 | "string or function") |
|
129 | "string or function") | |
130 |
|
130 | |||
131 | return retval |
|
131 | return retval | |
132 |
|
132 | |||
133 | return magic_deco |
|
133 | return magic_deco | |
134 |
|
134 | |||
135 |
|
135 | |||
136 | line_magic = _magic_marker('line') |
|
136 | line_magic = _magic_marker('line') | |
137 | cell_magic = _magic_marker('cell') |
|
137 | cell_magic = _magic_marker('cell') | |
138 |
|
138 | |||
139 | #----------------------------------------------------------------------------- |
|
139 | #----------------------------------------------------------------------------- | |
140 | # Core Magic classes |
|
140 | # Core Magic classes | |
141 | #----------------------------------------------------------------------------- |
|
141 | #----------------------------------------------------------------------------- | |
142 |
|
142 | |||
143 | class MagicsManager(Configurable): |
|
143 | class MagicsManager(Configurable): | |
144 | """Object that handles all magic-related functionality for IPython. |
|
144 | """Object that handles all magic-related functionality for IPython. | |
145 | """ |
|
145 | """ | |
146 | # Non-configurable class attributes |
|
146 | # Non-configurable class attributes | |
147 | magics = Dict |
|
147 | magics = Dict | |
148 |
|
148 | |||
149 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
149 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
150 |
|
150 | |||
151 | auto_magic = Bool |
|
151 | auto_magic = Bool | |
152 |
|
152 | |||
153 | _auto_status = [ |
|
153 | _auto_status = [ | |
154 | 'Automagic is OFF, % prefix IS needed for magic functions.', |
|
154 | 'Automagic is OFF, % prefix IS needed for magic functions.', | |
155 | 'Automagic is ON, % prefix IS NOT needed for magic functions.'] |
|
155 | 'Automagic is ON, % prefix IS NOT needed for magic functions.'] | |
156 |
|
156 | |||
157 | user_magics = Instance('IPython.core.magic_functions.UserMagics') |
|
157 | user_magics = Instance('IPython.core.magic_functions.UserMagics') | |
158 |
|
158 | |||
159 | def __init__(self, shell=None, config=None, user_magics=None, **traits): |
|
159 | def __init__(self, shell=None, config=None, user_magics=None, **traits): | |
160 |
|
160 | |||
161 | super(MagicsManager, self).__init__(shell=shell, config=config, |
|
161 | super(MagicsManager, self).__init__(shell=shell, config=config, | |
162 | user_magics=user_magics, **traits) |
|
162 | user_magics=user_magics, **traits) | |
163 | self.magics = dict(line={}, cell={}) |
|
163 | self.magics = dict(line={}, cell={}) | |
164 |
|
164 | |||
165 | def auto_status(self): |
|
165 | def auto_status(self): | |
166 | """Return descriptive string with automagic status.""" |
|
166 | """Return descriptive string with automagic status.""" | |
167 | return self._auto_status[self.auto_magic] |
|
167 | return self._auto_status[self.auto_magic] | |
168 |
|
168 | |||
169 | def lsmagic(self): |
|
169 | def lsmagic(self): | |
170 | """Return a dict of currently available magic functions. |
|
170 | """Return a dict of currently available magic functions. | |
171 |
|
171 | |||
172 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
172 | The return dict has the keys 'line' and 'cell', corresponding to the | |
173 | two types of magics we support. Each value is a list of names. |
|
173 | two types of magics we support. Each value is a list of names. | |
174 | """ |
|
174 | """ | |
175 | return self.magics |
|
175 | return self.magics | |
176 |
|
176 | |||
177 | def register(self, *magic_objects): |
|
177 | def register(self, *magic_objects): | |
178 | """Register one or more instances of Magics. |
|
178 | """Register one or more instances of Magics. | |
179 | """ |
|
179 | """ | |
180 | # Start by validating them to ensure they have all had their magic |
|
180 | # Start by validating them to ensure they have all had their magic | |
181 | # methods registered at the instance level |
|
181 | # methods registered at the instance level | |
182 | for m in magic_objects: |
|
182 | for m in magic_objects: | |
183 | if not m.registered: |
|
183 | if not m.registered: | |
184 | raise ValueError("Class of magics %r was constructed without " |
|
184 | raise ValueError("Class of magics %r was constructed without " | |
185 | "the @register_macics class decorator") |
|
185 | "the @register_macics class decorator") | |
186 | if type(m) is type: |
|
186 | if type(m) is type: | |
187 | # If we're given an uninstantiated class |
|
187 | # If we're given an uninstantiated class | |
188 | m = m(self.shell) |
|
188 | m = m(self.shell) | |
189 |
|
189 | |||
190 | for mtype in magic_types: |
|
190 | for mtype in magic_types: | |
191 | self.magics[mtype].update(m.magics[mtype]) |
|
191 | self.magics[mtype].update(m.magics[mtype]) | |
192 |
|
192 | |||
193 | def function_as_magic(self, func, magic_type='line', magic_name=None): |
|
193 | def function_as_magic(self, func, magic_type='line', magic_name=None): | |
194 | """Expose a standalone function as magic function for ipython. |
|
194 | """Expose a standalone function as magic function for ipython. | |
195 | """ |
|
195 | """ | |
196 |
|
196 | |||
197 | # Create the new method in the user_magics and register it in the |
|
197 | # Create the new method in the user_magics and register it in the | |
198 | # global table |
|
198 | # global table | |
199 | validate_type(magic_type) |
|
199 | validate_type(magic_type) | |
200 | magic_name = func.func_name if magic_name is None else magic_name |
|
200 | magic_name = func.func_name if magic_name is None else magic_name | |
201 | setattr(self.user_magics, magic_name, func) |
|
201 | setattr(self.user_magics, magic_name, func) | |
202 |
|
|
202 | _record_magic(self.magics, magic_type, magic_name, func) | |
203 | _record_magic(self.magics, magic_type, name, newm) |
|
|||
204 |
|
||||
205 |
|
203 | |||
206 | def _define_magic(self, name, func): |
|
204 | def _define_magic(self, name, func): | |
207 | """Support for deprecated API. |
|
205 | """Support for deprecated API. | |
208 |
|
206 | |||
209 | This method exists only to support the old-style definition of magics. |
|
207 | This method exists only to support the old-style definition of magics. | |
210 | It will eventually be removed. Deliberately not documented further. |
|
208 | It will eventually be removed. Deliberately not documented further. | |
211 | """ |
|
209 | """ | |
212 | warn('Deprecated API, use function_as_magic or register_magics: %s\n' % |
|
210 | warn('Deprecated API, use function_as_magic or register_magics: %s\n' % | |
213 | name) |
|
211 | name) | |
214 | meth = types.MethodType(func, self.user_magics) |
|
212 | meth = types.MethodType(func, self.user_magics) | |
215 | setattr(self.user_magics, name, meth) |
|
213 | setattr(self.user_magics, name, meth) | |
216 | _record_magic(self.magics, 'line', name, meth) |
|
214 | _record_magic(self.magics, 'line', name, meth) | |
217 |
|
215 | |||
218 | # Key base class that provides the central functionality for magics. |
|
216 | # Key base class that provides the central functionality for magics. | |
219 |
|
217 | |||
220 | class Magics(object): |
|
218 | class Magics(object): | |
221 | """Base class for implementing magic functions. |
|
219 | """Base class for implementing magic functions. | |
222 |
|
220 | |||
223 | Shell functions which can be reached as %function_name. All magic |
|
221 | Shell functions which can be reached as %function_name. All magic | |
224 | functions should accept a string, which they can parse for their own |
|
222 | functions should accept a string, which they can parse for their own | |
225 | needs. This can make some functions easier to type, eg `%cd ../` |
|
223 | needs. This can make some functions easier to type, eg `%cd ../` | |
226 | vs. `%cd("../")` |
|
224 | vs. `%cd("../")` | |
227 |
|
225 | |||
228 | Classes providing magic functions need to subclass this class, and they |
|
226 | Classes providing magic functions need to subclass this class, and they | |
229 | MUST: |
|
227 | MUST: | |
230 |
|
228 | |||
231 | - Use the method decorators `@line_magic` and `@cell_magic` to decorate |
|
229 | - Use the method decorators `@line_magic` and `@cell_magic` to decorate | |
232 | individual methods as magic functions, AND |
|
230 | individual methods as magic functions, AND | |
233 |
|
231 | |||
234 | - Use the class decorator `@register_magics` to ensure that the magic |
|
232 | - Use the class decorator `@register_magics` to ensure that the magic | |
235 | methods are properly registered at the instance level upon instance |
|
233 | methods are properly registered at the instance level upon instance | |
236 | initialization. |
|
234 | initialization. | |
237 |
|
235 | |||
238 | See :mod:`magic_functions` for examples of actual implementation classes. |
|
236 | See :mod:`magic_functions` for examples of actual implementation classes. | |
239 | """ |
|
237 | """ | |
240 | # Dict holding all command-line options for each magic. |
|
238 | # Dict holding all command-line options for each magic. | |
241 | options_table = None |
|
239 | options_table = None | |
242 | # Dict for the mapping of magic names to methods, set by class decorator |
|
240 | # Dict for the mapping of magic names to methods, set by class decorator | |
243 | magics = None |
|
241 | magics = None | |
244 | # Flag to check that the class decorator was properly applied |
|
242 | # Flag to check that the class decorator was properly applied | |
245 | registered = False |
|
243 | registered = False | |
246 | # Instance of IPython shell |
|
244 | # Instance of IPython shell | |
247 | shell = None |
|
245 | shell = None | |
248 |
|
246 | |||
249 | def __init__(self, shell): |
|
247 | def __init__(self, shell): | |
250 | if not(self.__class__.registered): |
|
248 | if not(self.__class__.registered): | |
251 | raise ValueError('Magics subclass without registration - ' |
|
249 | raise ValueError('Magics subclass without registration - ' | |
252 | 'did you forget to apply @register_magics?') |
|
250 | 'did you forget to apply @register_magics?') | |
253 | self.shell = shell |
|
251 | self.shell = shell | |
254 | self.options_table = {} |
|
252 | self.options_table = {} | |
255 | # The method decorators are run when the instance doesn't exist yet, so |
|
253 | # The method decorators are run when the instance doesn't exist yet, so | |
256 | # they can only record the names of the methods they are supposed to |
|
254 | # they can only record the names of the methods they are supposed to | |
257 | # grab. Only now, that the instance exists, can we create the proper |
|
255 | # grab. Only now, that the instance exists, can we create the proper | |
258 | # mapping to bound methods. So we read the info off the original names |
|
256 | # mapping to bound methods. So we read the info off the original names | |
259 | # table and replace each method name by the actual bound method. |
|
257 | # table and replace each method name by the actual bound method. | |
260 | for mtype in magic_types: |
|
258 | for mtype in magic_types: | |
261 | tab = self.magics[mtype] |
|
259 | tab = self.magics[mtype] | |
262 | # must explicitly use keys, as we're mutating this puppy |
|
260 | # must explicitly use keys, as we're mutating this puppy | |
263 | for magic_name in tab.keys(): |
|
261 | for magic_name in tab.keys(): | |
264 | meth_name = tab[magic_name] |
|
262 | meth_name = tab[magic_name] | |
265 | if isinstance(meth_name, basestring): |
|
263 | if isinstance(meth_name, basestring): | |
266 | tab[magic_name] = getattr(self, meth_name) |
|
264 | tab[magic_name] = getattr(self, meth_name) | |
267 |
|
265 | |||
268 | def arg_err(self,func): |
|
266 | def arg_err(self,func): | |
269 | """Print docstring if incorrect arguments were passed""" |
|
267 | """Print docstring if incorrect arguments were passed""" | |
270 | print 'Error in arguments:' |
|
268 | print 'Error in arguments:' | |
271 | print oinspect.getdoc(func) |
|
269 | print oinspect.getdoc(func) | |
272 |
|
270 | |||
273 | def format_latex(self, strng): |
|
271 | def format_latex(self, strng): | |
274 | """Format a string for latex inclusion.""" |
|
272 | """Format a string for latex inclusion.""" | |
275 |
|
273 | |||
276 | # Characters that need to be escaped for latex: |
|
274 | # Characters that need to be escaped for latex: | |
277 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
275 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
278 | # Magic command names as headers: |
|
276 | # Magic command names as headers: | |
279 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
277 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
280 | re.MULTILINE) |
|
278 | re.MULTILINE) | |
281 | # Magic commands |
|
279 | # Magic commands | |
282 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
280 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
283 | re.MULTILINE) |
|
281 | re.MULTILINE) | |
284 | # Paragraph continue |
|
282 | # Paragraph continue | |
285 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
283 | par_re = re.compile(r'\\$',re.MULTILINE) | |
286 |
|
284 | |||
287 | # The "\n" symbol |
|
285 | # The "\n" symbol | |
288 | newline_re = re.compile(r'\\n') |
|
286 | newline_re = re.compile(r'\\n') | |
289 |
|
287 | |||
290 | # Now build the string for output: |
|
288 | # Now build the string for output: | |
291 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
289 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
292 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
290 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
293 | strng) |
|
291 | strng) | |
294 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
292 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
295 | strng = par_re.sub(r'\\\\',strng) |
|
293 | strng = par_re.sub(r'\\\\',strng) | |
296 | strng = escape_re.sub(r'\\\1',strng) |
|
294 | strng = escape_re.sub(r'\\\1',strng) | |
297 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
295 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
298 | return strng |
|
296 | return strng | |
299 |
|
297 | |||
300 | def parse_options(self, arg_str, opt_str, *long_opts, **kw): |
|
298 | def parse_options(self, arg_str, opt_str, *long_opts, **kw): | |
301 | """Parse options passed to an argument string. |
|
299 | """Parse options passed to an argument string. | |
302 |
|
300 | |||
303 | The interface is similar to that of getopt(), but it returns back a |
|
301 | The interface is similar to that of getopt(), but it returns back a | |
304 | Struct with the options as keys and the stripped argument string still |
|
302 | Struct with the options as keys and the stripped argument string still | |
305 | as a string. |
|
303 | as a string. | |
306 |
|
304 | |||
307 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
305 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
308 | This allows us to easily expand variables, glob files, quote |
|
306 | This allows us to easily expand variables, glob files, quote | |
309 | arguments, etc. |
|
307 | arguments, etc. | |
310 |
|
308 | |||
311 | Options: |
|
309 | Options: | |
312 | -mode: default 'string'. If given as 'list', the argument string is |
|
310 | -mode: default 'string'. If given as 'list', the argument string is | |
313 | returned as a list (split on whitespace) instead of a string. |
|
311 | returned as a list (split on whitespace) instead of a string. | |
314 |
|
312 | |||
315 | -list_all: put all option values in lists. Normally only options |
|
313 | -list_all: put all option values in lists. Normally only options | |
316 | appearing more than once are put in a list. |
|
314 | appearing more than once are put in a list. | |
317 |
|
315 | |||
318 | -posix (True): whether to split the input line in POSIX mode or not, |
|
316 | -posix (True): whether to split the input line in POSIX mode or not, | |
319 | as per the conventions outlined in the shlex module from the |
|
317 | as per the conventions outlined in the shlex module from the | |
320 | standard library.""" |
|
318 | standard library.""" | |
321 |
|
319 | |||
322 | # inject default options at the beginning of the input line |
|
320 | # inject default options at the beginning of the input line | |
323 | caller = sys._getframe(1).f_code.co_name |
|
321 | caller = sys._getframe(1).f_code.co_name | |
324 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
322 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
325 |
|
323 | |||
326 | mode = kw.get('mode','string') |
|
324 | mode = kw.get('mode','string') | |
327 | if mode not in ['string','list']: |
|
325 | if mode not in ['string','list']: | |
328 | raise ValueError,'incorrect mode given: %s' % mode |
|
326 | raise ValueError,'incorrect mode given: %s' % mode | |
329 | # Get options |
|
327 | # Get options | |
330 | list_all = kw.get('list_all',0) |
|
328 | list_all = kw.get('list_all',0) | |
331 | posix = kw.get('posix', os.name == 'posix') |
|
329 | posix = kw.get('posix', os.name == 'posix') | |
332 | strict = kw.get('strict', True) |
|
330 | strict = kw.get('strict', True) | |
333 |
|
331 | |||
334 | # Check if we have more than one argument to warrant extra processing: |
|
332 | # Check if we have more than one argument to warrant extra processing: | |
335 | odict = {} # Dictionary with options |
|
333 | odict = {} # Dictionary with options | |
336 | args = arg_str.split() |
|
334 | args = arg_str.split() | |
337 | if len(args) >= 1: |
|
335 | if len(args) >= 1: | |
338 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
336 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
339 | # need to look for options |
|
337 | # need to look for options | |
340 | argv = arg_split(arg_str, posix, strict) |
|
338 | argv = arg_split(arg_str, posix, strict) | |
341 | # Do regular option processing |
|
339 | # Do regular option processing | |
342 | try: |
|
340 | try: | |
343 | opts,args = getopt(argv,opt_str,*long_opts) |
|
341 | opts,args = getopt(argv,opt_str,*long_opts) | |
344 | except GetoptError,e: |
|
342 | except GetoptError,e: | |
345 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
343 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
346 | " ".join(long_opts))) |
|
344 | " ".join(long_opts))) | |
347 | for o,a in opts: |
|
345 | for o,a in opts: | |
348 | if o.startswith('--'): |
|
346 | if o.startswith('--'): | |
349 | o = o[2:] |
|
347 | o = o[2:] | |
350 | else: |
|
348 | else: | |
351 | o = o[1:] |
|
349 | o = o[1:] | |
352 | try: |
|
350 | try: | |
353 | odict[o].append(a) |
|
351 | odict[o].append(a) | |
354 | except AttributeError: |
|
352 | except AttributeError: | |
355 | odict[o] = [odict[o],a] |
|
353 | odict[o] = [odict[o],a] | |
356 | except KeyError: |
|
354 | except KeyError: | |
357 | if list_all: |
|
355 | if list_all: | |
358 | odict[o] = [a] |
|
356 | odict[o] = [a] | |
359 | else: |
|
357 | else: | |
360 | odict[o] = a |
|
358 | odict[o] = a | |
361 |
|
359 | |||
362 | # Prepare opts,args for return |
|
360 | # Prepare opts,args for return | |
363 | opts = Struct(odict) |
|
361 | opts = Struct(odict) | |
364 | if mode == 'string': |
|
362 | if mode == 'string': | |
365 | args = ' '.join(args) |
|
363 | args = ' '.join(args) | |
366 |
|
364 | |||
367 | return opts,args |
|
365 | return opts,args | |
368 |
|
366 | |||
369 | def default_option(self, fn, optstr): |
|
367 | def default_option(self, fn, optstr): | |
370 | """Make an entry in the options_table for fn, with value optstr""" |
|
368 | """Make an entry in the options_table for fn, with value optstr""" | |
371 |
|
369 | |||
372 | if fn not in self.lsmagic(): |
|
370 | if fn not in self.lsmagic(): | |
373 | error("%s is not a magic function" % fn) |
|
371 | error("%s is not a magic function" % fn) | |
374 | self.options_table[fn] = optstr |
|
372 | self.options_table[fn] = optstr |
@@ -1,3730 +1,3730 b'' | |||||
1 | """Magic functions for InteractiveShell. |
|
1 | """Magic functions for InteractiveShell. | |
2 | """ |
|
2 | """ | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
6 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> | |
7 | # Copyright (C) 2008 The IPython Development Team |
|
7 | # Copyright (C) 2008 The IPython Development Team | |
8 |
|
8 | |||
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Imports |
|
13 | # Imports | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | import __builtin__ as builtin_mod |
|
16 | import __builtin__ as builtin_mod | |
17 | import bdb |
|
17 | import bdb | |
18 | import gc |
|
18 | import gc | |
19 | import inspect |
|
19 | import inspect | |
20 | import io |
|
20 | import io | |
21 | import json |
|
21 | import json | |
22 | import os |
|
22 | import os | |
23 | import re |
|
23 | import re | |
24 | import sys |
|
24 | import sys | |
25 | import time |
|
25 | import time | |
26 | from StringIO import StringIO |
|
26 | from StringIO import StringIO | |
27 | from pprint import pformat |
|
27 | from pprint import pformat | |
28 | from urllib2 import urlopen |
|
28 | from urllib2 import urlopen | |
29 |
|
29 | |||
30 | # cProfile was added in Python2.5 |
|
30 | # cProfile was added in Python2.5 | |
31 | try: |
|
31 | try: | |
32 | import cProfile as profile |
|
32 | import cProfile as profile | |
33 | import pstats |
|
33 | import pstats | |
34 | except ImportError: |
|
34 | except ImportError: | |
35 | # profile isn't bundled by default in Debian for license reasons |
|
35 | # profile isn't bundled by default in Debian for license reasons | |
36 | try: |
|
36 | try: | |
37 | import profile, pstats |
|
37 | import profile, pstats | |
38 | except ImportError: |
|
38 | except ImportError: | |
39 | profile = pstats = None |
|
39 | profile = pstats = None | |
40 |
|
40 | |||
41 | from IPython.config.application import Application |
|
41 | from IPython.config.application import Application | |
42 | from IPython.core import debugger, oinspect |
|
42 | from IPython.core import debugger, oinspect | |
43 | from IPython.core import magic_arguments, page |
|
43 | from IPython.core import magic_arguments, page | |
44 | from IPython.core.error import UsageError, StdinNotImplementedError, TryNext |
|
44 | from IPython.core.error import UsageError, StdinNotImplementedError, TryNext | |
45 | from IPython.core.macro import Macro |
|
45 | from IPython.core.macro import Macro | |
46 | from IPython.core.magic import (Bunch, Magics, compress_dhist, |
|
46 | from IPython.core.magic import (Bunch, Magics, compress_dhist, | |
47 | on_off, needs_local_scope, |
|
47 | on_off, needs_local_scope, | |
48 | register_magics, line_magic, cell_magic) |
|
48 | register_magics, line_magic, cell_magic) | |
49 | from IPython.core.prefilter import ESC_MAGIC |
|
49 | from IPython.core.prefilter import ESC_MAGIC | |
50 | from IPython.testing.skipdoctest import skip_doctest |
|
50 | from IPython.testing.skipdoctest import skip_doctest | |
51 | from IPython.utils import openpy |
|
51 | from IPython.utils import openpy | |
52 | from IPython.utils import py3compat |
|
52 | from IPython.utils import py3compat | |
53 | from IPython.utils.encoding import DEFAULT_ENCODING |
|
53 | from IPython.utils.encoding import DEFAULT_ENCODING | |
54 | from IPython.utils.io import file_read, nlprint |
|
54 | from IPython.utils.io import file_read, nlprint | |
55 | from IPython.utils.ipstruct import Struct |
|
55 | from IPython.utils.ipstruct import Struct | |
56 | from IPython.utils.module_paths import find_mod |
|
56 | from IPython.utils.module_paths import find_mod | |
57 | from IPython.utils.path import get_py_filename, unquote_filename |
|
57 | from IPython.utils.path import get_py_filename, unquote_filename | |
58 | from IPython.utils.process import abbrev_cwd |
|
58 | from IPython.utils.process import abbrev_cwd | |
59 | from IPython.utils.terminal import set_term_title |
|
59 | from IPython.utils.terminal import set_term_title | |
60 | from IPython.utils.text import format_screen |
|
60 | from IPython.utils.text import format_screen | |
61 | from IPython.utils.timing import clock, clock2 |
|
61 | from IPython.utils.timing import clock, clock2 | |
62 | from IPython.utils.warn import warn, error |
|
62 | from IPython.utils.warn import warn, error | |
63 |
|
63 | |||
64 | #----------------------------------------------------------------------------- |
|
64 | #----------------------------------------------------------------------------- | |
65 | # Magic implementation classes |
|
65 | # Magic implementation classes | |
66 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
67 |
|
67 | |||
68 | @register_magics |
|
68 | @register_magics | |
69 | class UserMagics(Magics): |
|
69 | class UserMagics(Magics): | |
70 | """Placeholder for user-defined magics to be added at runtime. |
|
70 | """Placeholder for user-defined magics to be added at runtime. | |
71 |
|
71 | |||
72 | All magics are eventually merged into a single namespace at runtime, but we |
|
72 | All magics are eventually merged into a single namespace at runtime, but we | |
73 | use this class to isolate the magics defined dynamically by the user into |
|
73 | use this class to isolate the magics defined dynamically by the user into | |
74 | their own class. |
|
74 | their own class. | |
75 | """ |
|
75 | """ | |
76 |
|
76 | |||
77 |
|
77 | |||
78 | @register_magics |
|
78 | @register_magics | |
79 | class BasicMagics(Magics): |
|
79 | class BasicMagics(Magics): | |
80 | """Magics that provide central IPython functionality. |
|
80 | """Magics that provide central IPython functionality. | |
81 |
|
81 | |||
82 | These are various magics that don't fit into specific categories but that |
|
82 | These are various magics that don't fit into specific categories but that | |
83 | are all part of the base 'IPython experience'.""" |
|
83 | are all part of the base 'IPython experience'.""" | |
84 |
|
84 | |||
85 | def _lsmagic(self): |
|
85 | def _lsmagic(self): | |
86 | mesc = ESC_MAGIC |
|
86 | mesc = ESC_MAGIC | |
87 | cesc = mesc*2 |
|
87 | cesc = mesc*2 | |
88 | mman = self.shell.magics_manager |
|
88 | mman = self.shell.magics_manager | |
89 | magics = mman.lsmagic() |
|
89 | magics = mman.lsmagic() | |
90 | out = ['Available line magics:', |
|
90 | out = ['Available line magics:', | |
91 | mesc + (' '+mesc).join(magics['line']), |
|
91 | mesc + (' '+mesc).join(magics['line']), | |
92 | '', |
|
92 | '', | |
93 | 'Available cell magics:', |
|
93 | 'Available cell magics:', | |
94 | cesc + (' '+cesc).join(magics['cell']), |
|
94 | cesc + (' '+cesc).join(magics['cell']), | |
95 | '', |
|
95 | '', | |
96 | mman.auto_status()] |
|
96 | mman.auto_status()] | |
97 | return '\n'.join(out) |
|
97 | return '\n'.join(out) | |
98 |
|
98 | |||
99 | @line_magic |
|
99 | @line_magic | |
100 | def lsmagic(self, parameter_s=''): |
|
100 | def lsmagic(self, parameter_s=''): | |
101 | """List currently available magic functions.""" |
|
101 | """List currently available magic functions.""" | |
102 | print self._lsmagic() |
|
102 | print self._lsmagic() | |
103 |
|
103 | |||
104 | @line_magic |
|
104 | @line_magic | |
105 | def magic(self, parameter_s=''): |
|
105 | def magic(self, parameter_s=''): | |
106 | """Print information about the magic function system. |
|
106 | """Print information about the magic function system. | |
107 |
|
107 | |||
108 | Supported formats: -latex, -brief, -rest |
|
108 | Supported formats: -latex, -brief, -rest | |
109 | """ |
|
109 | """ | |
110 |
|
110 | |||
111 | mode = '' |
|
111 | mode = '' | |
112 | try: |
|
112 | try: | |
113 | mode = parameter_s.split()[0][1:] |
|
113 | mode = parameter_s.split()[0][1:] | |
114 | if mode == 'rest': |
|
114 | if mode == 'rest': | |
115 | rest_docs = [] |
|
115 | rest_docs = [] | |
116 | except: |
|
116 | except: | |
117 | pass |
|
117 | pass | |
118 |
|
118 | |||
119 | magic_docs = [] |
|
119 | magic_docs = [] | |
120 | escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC*2) |
|
120 | escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC*2) | |
121 | magics = self.shell.magics_manager.magics |
|
121 | magics = self.shell.magics_manager.magics | |
122 |
|
122 | |||
123 | for mtype in ('line', 'cell'): |
|
123 | for mtype in ('line', 'cell'): | |
124 | escape = escapes[mtype] |
|
124 | escape = escapes[mtype] | |
125 | for fname, fn in magics[mtype].iteritems(): |
|
125 | for fname, fn in magics[mtype].iteritems(): | |
126 |
|
126 | |||
127 | if mode == 'brief': |
|
127 | if mode == 'brief': | |
128 | # only first line |
|
128 | # only first line | |
129 | if fn.__doc__: |
|
129 | if fn.__doc__: | |
130 | fndoc = fn.__doc__.split('\n',1)[0] |
|
130 | fndoc = fn.__doc__.split('\n',1)[0] | |
131 | else: |
|
131 | else: | |
132 | fndoc = 'No documentation' |
|
132 | fndoc = 'No documentation' | |
133 | else: |
|
133 | else: | |
134 | if fn.__doc__: |
|
134 | if fn.__doc__: | |
135 | fndoc = fn.__doc__.rstrip() |
|
135 | fndoc = fn.__doc__.rstrip() | |
136 | else: |
|
136 | else: | |
137 | fndoc = 'No documentation' |
|
137 | fndoc = 'No documentation' | |
138 |
|
138 | |||
139 | if mode == 'rest': |
|
139 | if mode == 'rest': | |
140 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' % |
|
140 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' % | |
141 | (escape, fname, fndoc)) |
|
141 | (escape, fname, fndoc)) | |
142 | else: |
|
142 | else: | |
143 | magic_docs.append('%s%s:\n\t%s\n' % |
|
143 | magic_docs.append('%s%s:\n\t%s\n' % | |
144 | (escape, fname, fndoc)) |
|
144 | (escape, fname, fndoc)) | |
145 |
|
145 | |||
146 | magic_docs = ''.join(magic_docs) |
|
146 | magic_docs = ''.join(magic_docs) | |
147 |
|
147 | |||
148 | if mode == 'rest': |
|
148 | if mode == 'rest': | |
149 | return "".join(rest_docs) |
|
149 | return "".join(rest_docs) | |
150 |
|
150 | |||
151 | if mode == 'latex': |
|
151 | if mode == 'latex': | |
152 | print self.format_latex(magic_docs) |
|
152 | print self.format_latex(magic_docs) | |
153 | return |
|
153 | return | |
154 | else: |
|
154 | else: | |
155 | magic_docs = format_screen(magic_docs) |
|
155 | magic_docs = format_screen(magic_docs) | |
156 | if mode == 'brief': |
|
156 | if mode == 'brief': | |
157 | return magic_docs |
|
157 | return magic_docs | |
158 |
|
158 | |||
159 | out = [""" |
|
159 | out = [""" | |
160 | IPython's 'magic' functions |
|
160 | IPython's 'magic' functions | |
161 | =========================== |
|
161 | =========================== | |
162 |
|
162 | |||
163 | The magic function system provides a series of functions which allow you to |
|
163 | The magic function system provides a series of functions which allow you to | |
164 | control the behavior of IPython itself, plus a lot of system-type |
|
164 | control the behavior of IPython itself, plus a lot of system-type | |
165 | features. All these functions are prefixed with a % character, but parameters |
|
165 | features. All these functions are prefixed with a % character, but parameters | |
166 | are given without parentheses or quotes. |
|
166 | are given without parentheses or quotes. | |
167 |
|
167 | |||
168 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
168 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
169 | %automagic function), you don't need to type in the % explicitly. By default, |
|
169 | %automagic function), you don't need to type in the % explicitly. By default, | |
170 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
170 | IPython ships with automagic on, so you should only rarely need the % escape. | |
171 |
|
171 | |||
172 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
172 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
173 | to 'mydir', if it exists. |
|
173 | to 'mydir', if it exists. | |
174 |
|
174 | |||
175 | For a list of the available magic functions, use %lsmagic. For a description |
|
175 | For a list of the available magic functions, use %lsmagic. For a description | |
176 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
176 | of any of them, type %magic_name?, e.g. '%cd?'. | |
177 |
|
177 | |||
178 | Currently the magic system has the following functions:""", |
|
178 | Currently the magic system has the following functions:""", | |
179 | magic_docs, |
|
179 | magic_docs, | |
180 | "Summary of magic functions (from %slsmagic):", |
|
180 | "Summary of magic functions (from %slsmagic):", | |
181 | self._lsmagic(), |
|
181 | self._lsmagic(), | |
182 | ] |
|
182 | ] | |
183 | page.page('\n'.join(out)) |
|
183 | page.page('\n'.join(out)) | |
184 |
|
184 | |||
185 |
|
185 | |||
186 | @line_magic |
|
186 | @line_magic | |
187 | def page(self, parameter_s=''): |
|
187 | def page(self, parameter_s=''): | |
188 | """Pretty print the object and display it through a pager. |
|
188 | """Pretty print the object and display it through a pager. | |
189 |
|
189 | |||
190 | %page [options] OBJECT |
|
190 | %page [options] OBJECT | |
191 |
|
191 | |||
192 | If no object is given, use _ (last output). |
|
192 | If no object is given, use _ (last output). | |
193 |
|
193 | |||
194 | Options: |
|
194 | Options: | |
195 |
|
195 | |||
196 | -r: page str(object), don't pretty-print it.""" |
|
196 | -r: page str(object), don't pretty-print it.""" | |
197 |
|
197 | |||
198 | # After a function contributed by Olivier Aubert, slightly modified. |
|
198 | # After a function contributed by Olivier Aubert, slightly modified. | |
199 |
|
199 | |||
200 | # Process options/args |
|
200 | # Process options/args | |
201 | opts, args = self.parse_options(parameter_s, 'r') |
|
201 | opts, args = self.parse_options(parameter_s, 'r') | |
202 | raw = 'r' in opts |
|
202 | raw = 'r' in opts | |
203 |
|
203 | |||
204 | oname = args and args or '_' |
|
204 | oname = args and args or '_' | |
205 | info = self._ofind(oname) |
|
205 | info = self._ofind(oname) | |
206 | if info['found']: |
|
206 | if info['found']: | |
207 | txt = (raw and str or pformat)( info['obj'] ) |
|
207 | txt = (raw and str or pformat)( info['obj'] ) | |
208 | page.page(txt) |
|
208 | page.page(txt) | |
209 | else: |
|
209 | else: | |
210 | print 'Object `%s` not found' % oname |
|
210 | print 'Object `%s` not found' % oname | |
211 |
|
211 | |||
212 | @line_magic |
|
212 | @line_magic | |
213 | def profile(self, parameter_s=''): |
|
213 | def profile(self, parameter_s=''): | |
214 | """Print your currently active IPython profile.""" |
|
214 | """Print your currently active IPython profile.""" | |
215 | from IPython.core.application import BaseIPythonApplication |
|
215 | from IPython.core.application import BaseIPythonApplication | |
216 | if BaseIPythonApplication.initialized(): |
|
216 | if BaseIPythonApplication.initialized(): | |
217 | print BaseIPythonApplication.instance().profile |
|
217 | print BaseIPythonApplication.instance().profile | |
218 | else: |
|
218 | else: | |
219 | error("profile is an application-level value, but you don't appear to be in an IPython application") |
|
219 | error("profile is an application-level value, but you don't appear to be in an IPython application") | |
220 |
|
220 | |||
221 | @line_magic |
|
221 | @line_magic | |
222 | def pprint(self, parameter_s=''): |
|
222 | def pprint(self, parameter_s=''): | |
223 | """Toggle pretty printing on/off.""" |
|
223 | """Toggle pretty printing on/off.""" | |
224 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
224 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
225 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
225 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
226 | print 'Pretty printing has been turned', \ |
|
226 | print 'Pretty printing has been turned', \ | |
227 | ['OFF','ON'][ptformatter.pprint] |
|
227 | ['OFF','ON'][ptformatter.pprint] | |
228 |
|
228 | |||
229 | @line_magic |
|
229 | @line_magic | |
230 | def colors(self, parameter_s=''): |
|
230 | def colors(self, parameter_s=''): | |
231 | """Switch color scheme for prompts, info system and exception handlers. |
|
231 | """Switch color scheme for prompts, info system and exception handlers. | |
232 |
|
232 | |||
233 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
233 | Currently implemented schemes: NoColor, Linux, LightBG. | |
234 |
|
234 | |||
235 | Color scheme names are not case-sensitive. |
|
235 | Color scheme names are not case-sensitive. | |
236 |
|
236 | |||
237 | Examples |
|
237 | Examples | |
238 | -------- |
|
238 | -------- | |
239 | To get a plain black and white terminal:: |
|
239 | To get a plain black and white terminal:: | |
240 |
|
240 | |||
241 | %colors nocolor |
|
241 | %colors nocolor | |
242 | """ |
|
242 | """ | |
243 | def color_switch_err(name): |
|
243 | def color_switch_err(name): | |
244 | warn('Error changing %s color schemes.\n%s' % |
|
244 | warn('Error changing %s color schemes.\n%s' % | |
245 | (name,sys.exc_info()[1])) |
|
245 | (name,sys.exc_info()[1])) | |
246 |
|
246 | |||
247 |
|
247 | |||
248 | new_scheme = parameter_s.strip() |
|
248 | new_scheme = parameter_s.strip() | |
249 | if not new_scheme: |
|
249 | if not new_scheme: | |
250 | raise UsageError( |
|
250 | raise UsageError( | |
251 | "%colors: you must specify a color scheme. See '%colors?'") |
|
251 | "%colors: you must specify a color scheme. See '%colors?'") | |
252 | return |
|
252 | return | |
253 | # local shortcut |
|
253 | # local shortcut | |
254 | shell = self.shell |
|
254 | shell = self.shell | |
255 |
|
255 | |||
256 | import IPython.utils.rlineimpl as readline |
|
256 | import IPython.utils.rlineimpl as readline | |
257 |
|
257 | |||
258 | if not shell.colors_force and \ |
|
258 | if not shell.colors_force and \ | |
259 | not readline.have_readline and sys.platform == "win32": |
|
259 | not readline.have_readline and sys.platform == "win32": | |
260 | msg = """\ |
|
260 | msg = """\ | |
261 | Proper color support under MS Windows requires the pyreadline library. |
|
261 | Proper color support under MS Windows requires the pyreadline library. | |
262 | You can find it at: |
|
262 | You can find it at: | |
263 | http://ipython.org/pyreadline.html |
|
263 | http://ipython.org/pyreadline.html | |
264 | Gary's readline needs the ctypes module, from: |
|
264 | Gary's readline needs the ctypes module, from: | |
265 | http://starship.python.net/crew/theller/ctypes |
|
265 | http://starship.python.net/crew/theller/ctypes | |
266 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
266 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
267 |
|
267 | |||
268 | Defaulting color scheme to 'NoColor'""" |
|
268 | Defaulting color scheme to 'NoColor'""" | |
269 | new_scheme = 'NoColor' |
|
269 | new_scheme = 'NoColor' | |
270 | warn(msg) |
|
270 | warn(msg) | |
271 |
|
271 | |||
272 | # readline option is 0 |
|
272 | # readline option is 0 | |
273 | if not shell.colors_force and not shell.has_readline: |
|
273 | if not shell.colors_force and not shell.has_readline: | |
274 | new_scheme = 'NoColor' |
|
274 | new_scheme = 'NoColor' | |
275 |
|
275 | |||
276 | # Set prompt colors |
|
276 | # Set prompt colors | |
277 | try: |
|
277 | try: | |
278 | shell.prompt_manager.color_scheme = new_scheme |
|
278 | shell.prompt_manager.color_scheme = new_scheme | |
279 | except: |
|
279 | except: | |
280 | color_switch_err('prompt') |
|
280 | color_switch_err('prompt') | |
281 | else: |
|
281 | else: | |
282 | shell.colors = \ |
|
282 | shell.colors = \ | |
283 | shell.prompt_manager.color_scheme_table.active_scheme_name |
|
283 | shell.prompt_manager.color_scheme_table.active_scheme_name | |
284 | # Set exception colors |
|
284 | # Set exception colors | |
285 | try: |
|
285 | try: | |
286 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
286 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
287 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
287 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
288 | except: |
|
288 | except: | |
289 | color_switch_err('exception') |
|
289 | color_switch_err('exception') | |
290 |
|
290 | |||
291 | # Set info (for 'object?') colors |
|
291 | # Set info (for 'object?') colors | |
292 | if shell.color_info: |
|
292 | if shell.color_info: | |
293 | try: |
|
293 | try: | |
294 | shell.inspector.set_active_scheme(new_scheme) |
|
294 | shell.inspector.set_active_scheme(new_scheme) | |
295 | except: |
|
295 | except: | |
296 | color_switch_err('object inspector') |
|
296 | color_switch_err('object inspector') | |
297 | else: |
|
297 | else: | |
298 | shell.inspector.set_active_scheme('NoColor') |
|
298 | shell.inspector.set_active_scheme('NoColor') | |
299 |
|
299 | |||
300 | @line_magic |
|
300 | @line_magic | |
301 | def xmode(self, parameter_s=''): |
|
301 | def xmode(self, parameter_s=''): | |
302 | """Switch modes for the exception handlers. |
|
302 | """Switch modes for the exception handlers. | |
303 |
|
303 | |||
304 | Valid modes: Plain, Context and Verbose. |
|
304 | Valid modes: Plain, Context and Verbose. | |
305 |
|
305 | |||
306 | If called without arguments, acts as a toggle.""" |
|
306 | If called without arguments, acts as a toggle.""" | |
307 |
|
307 | |||
308 | def xmode_switch_err(name): |
|
308 | def xmode_switch_err(name): | |
309 | warn('Error changing %s exception modes.\n%s' % |
|
309 | warn('Error changing %s exception modes.\n%s' % | |
310 | (name,sys.exc_info()[1])) |
|
310 | (name,sys.exc_info()[1])) | |
311 |
|
311 | |||
312 | shell = self.shell |
|
312 | shell = self.shell | |
313 | new_mode = parameter_s.strip().capitalize() |
|
313 | new_mode = parameter_s.strip().capitalize() | |
314 | try: |
|
314 | try: | |
315 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
315 | shell.InteractiveTB.set_mode(mode=new_mode) | |
316 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
316 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
317 | except: |
|
317 | except: | |
318 | xmode_switch_err('user') |
|
318 | xmode_switch_err('user') | |
319 |
|
319 | |||
320 | @line_magic |
|
320 | @line_magic | |
321 | def quickref(self,arg): |
|
321 | def quickref(self,arg): | |
322 | """ Show a quick reference sheet """ |
|
322 | """ Show a quick reference sheet """ | |
323 |
|
|
323 | from IPython.core.usage import quick_reference | |
324 |
qr = |
|
324 | qr = quick_reference + self.magic('-brief') | |
325 | page.page(qr) |
|
325 | page.page(qr) | |
326 |
|
326 | |||
327 | @line_magic |
|
327 | @line_magic | |
328 | def doctest_mode(self, parameter_s=''): |
|
328 | def doctest_mode(self, parameter_s=''): | |
329 | """Toggle doctest mode on and off. |
|
329 | """Toggle doctest mode on and off. | |
330 |
|
330 | |||
331 | This mode is intended to make IPython behave as much as possible like a |
|
331 | This mode is intended to make IPython behave as much as possible like a | |
332 | plain Python shell, from the perspective of how its prompts, exceptions |
|
332 | plain Python shell, from the perspective of how its prompts, exceptions | |
333 | and output look. This makes it easy to copy and paste parts of a |
|
333 | and output look. This makes it easy to copy and paste parts of a | |
334 | session into doctests. It does so by: |
|
334 | session into doctests. It does so by: | |
335 |
|
335 | |||
336 | - Changing the prompts to the classic ``>>>`` ones. |
|
336 | - Changing the prompts to the classic ``>>>`` ones. | |
337 | - Changing the exception reporting mode to 'Plain'. |
|
337 | - Changing the exception reporting mode to 'Plain'. | |
338 | - Disabling pretty-printing of output. |
|
338 | - Disabling pretty-printing of output. | |
339 |
|
339 | |||
340 | Note that IPython also supports the pasting of code snippets that have |
|
340 | Note that IPython also supports the pasting of code snippets that have | |
341 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
341 | leading '>>>' and '...' prompts in them. This means that you can paste | |
342 | doctests from files or docstrings (even if they have leading |
|
342 | doctests from files or docstrings (even if they have leading | |
343 | whitespace), and the code will execute correctly. You can then use |
|
343 | whitespace), and the code will execute correctly. You can then use | |
344 | '%history -t' to see the translated history; this will give you the |
|
344 | '%history -t' to see the translated history; this will give you the | |
345 | input after removal of all the leading prompts and whitespace, which |
|
345 | input after removal of all the leading prompts and whitespace, which | |
346 | can be pasted back into an editor. |
|
346 | can be pasted back into an editor. | |
347 |
|
347 | |||
348 | With these features, you can switch into this mode easily whenever you |
|
348 | With these features, you can switch into this mode easily whenever you | |
349 | need to do testing and changes to doctests, without having to leave |
|
349 | need to do testing and changes to doctests, without having to leave | |
350 | your existing IPython session. |
|
350 | your existing IPython session. | |
351 | """ |
|
351 | """ | |
352 |
|
352 | |||
353 | # Shorthands |
|
353 | # Shorthands | |
354 | shell = self.shell |
|
354 | shell = self.shell | |
355 | pm = shell.prompt_manager |
|
355 | pm = shell.prompt_manager | |
356 | meta = shell.meta |
|
356 | meta = shell.meta | |
357 | disp_formatter = self.shell.display_formatter |
|
357 | disp_formatter = self.shell.display_formatter | |
358 | ptformatter = disp_formatter.formatters['text/plain'] |
|
358 | ptformatter = disp_formatter.formatters['text/plain'] | |
359 | # dstore is a data store kept in the instance metadata bag to track any |
|
359 | # dstore is a data store kept in the instance metadata bag to track any | |
360 | # changes we make, so we can undo them later. |
|
360 | # changes we make, so we can undo them later. | |
361 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
361 | dstore = meta.setdefault('doctest_mode',Struct()) | |
362 | save_dstore = dstore.setdefault |
|
362 | save_dstore = dstore.setdefault | |
363 |
|
363 | |||
364 | # save a few values we'll need to recover later |
|
364 | # save a few values we'll need to recover later | |
365 | mode = save_dstore('mode',False) |
|
365 | mode = save_dstore('mode',False) | |
366 | save_dstore('rc_pprint',ptformatter.pprint) |
|
366 | save_dstore('rc_pprint',ptformatter.pprint) | |
367 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
367 | save_dstore('xmode',shell.InteractiveTB.mode) | |
368 | save_dstore('rc_separate_out',shell.separate_out) |
|
368 | save_dstore('rc_separate_out',shell.separate_out) | |
369 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
369 | save_dstore('rc_separate_out2',shell.separate_out2) | |
370 | save_dstore('rc_prompts_pad_left',pm.justify) |
|
370 | save_dstore('rc_prompts_pad_left',pm.justify) | |
371 | save_dstore('rc_separate_in',shell.separate_in) |
|
371 | save_dstore('rc_separate_in',shell.separate_in) | |
372 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
372 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
373 | save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template)) |
|
373 | save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template)) | |
374 |
|
374 | |||
375 | if mode == False: |
|
375 | if mode == False: | |
376 | # turn on |
|
376 | # turn on | |
377 | pm.in_template = '>>> ' |
|
377 | pm.in_template = '>>> ' | |
378 | pm.in2_template = '... ' |
|
378 | pm.in2_template = '... ' | |
379 | pm.out_template = '' |
|
379 | pm.out_template = '' | |
380 |
|
380 | |||
381 | # Prompt separators like plain python |
|
381 | # Prompt separators like plain python | |
382 | shell.separate_in = '' |
|
382 | shell.separate_in = '' | |
383 | shell.separate_out = '' |
|
383 | shell.separate_out = '' | |
384 | shell.separate_out2 = '' |
|
384 | shell.separate_out2 = '' | |
385 |
|
385 | |||
386 | pm.justify = False |
|
386 | pm.justify = False | |
387 |
|
387 | |||
388 | ptformatter.pprint = False |
|
388 | ptformatter.pprint = False | |
389 | disp_formatter.plain_text_only = True |
|
389 | disp_formatter.plain_text_only = True | |
390 |
|
390 | |||
391 | shell.magic('xmode Plain') |
|
391 | shell.magic('xmode Plain') | |
392 | else: |
|
392 | else: | |
393 | # turn off |
|
393 | # turn off | |
394 | pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates |
|
394 | pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates | |
395 |
|
395 | |||
396 | shell.separate_in = dstore.rc_separate_in |
|
396 | shell.separate_in = dstore.rc_separate_in | |
397 |
|
397 | |||
398 | shell.separate_out = dstore.rc_separate_out |
|
398 | shell.separate_out = dstore.rc_separate_out | |
399 | shell.separate_out2 = dstore.rc_separate_out2 |
|
399 | shell.separate_out2 = dstore.rc_separate_out2 | |
400 |
|
400 | |||
401 | pm.justify = dstore.rc_prompts_pad_left |
|
401 | pm.justify = dstore.rc_prompts_pad_left | |
402 |
|
402 | |||
403 | ptformatter.pprint = dstore.rc_pprint |
|
403 | ptformatter.pprint = dstore.rc_pprint | |
404 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
404 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
405 |
|
405 | |||
406 | shell.magic('xmode ' + dstore.xmode) |
|
406 | shell.magic('xmode ' + dstore.xmode) | |
407 |
|
407 | |||
408 | # Store new mode and inform |
|
408 | # Store new mode and inform | |
409 | dstore.mode = bool(1-int(mode)) |
|
409 | dstore.mode = bool(1-int(mode)) | |
410 | mode_label = ['OFF','ON'][dstore.mode] |
|
410 | mode_label = ['OFF','ON'][dstore.mode] | |
411 | print 'Doctest mode is:', mode_label |
|
411 | print 'Doctest mode is:', mode_label | |
412 |
|
412 | |||
413 | @line_magic |
|
413 | @line_magic | |
414 | def gui(self, parameter_s=''): |
|
414 | def gui(self, parameter_s=''): | |
415 | """Enable or disable IPython GUI event loop integration. |
|
415 | """Enable or disable IPython GUI event loop integration. | |
416 |
|
416 | |||
417 | %gui [GUINAME] |
|
417 | %gui [GUINAME] | |
418 |
|
418 | |||
419 | This magic replaces IPython's threaded shells that were activated |
|
419 | This magic replaces IPython's threaded shells that were activated | |
420 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
420 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
421 | can now be enabled at runtime and keyboard |
|
421 | can now be enabled at runtime and keyboard | |
422 | interrupts should work without any problems. The following toolkits |
|
422 | interrupts should work without any problems. The following toolkits | |
423 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: |
|
423 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: | |
424 |
|
424 | |||
425 | %gui wx # enable wxPython event loop integration |
|
425 | %gui wx # enable wxPython event loop integration | |
426 | %gui qt4|qt # enable PyQt4 event loop integration |
|
426 | %gui qt4|qt # enable PyQt4 event loop integration | |
427 | %gui gtk # enable PyGTK event loop integration |
|
427 | %gui gtk # enable PyGTK event loop integration | |
428 | %gui gtk3 # enable Gtk3 event loop integration |
|
428 | %gui gtk3 # enable Gtk3 event loop integration | |
429 | %gui tk # enable Tk event loop integration |
|
429 | %gui tk # enable Tk event loop integration | |
430 | %gui OSX # enable Cocoa event loop integration |
|
430 | %gui OSX # enable Cocoa event loop integration | |
431 | # (requires %matplotlib 1.1) |
|
431 | # (requires %matplotlib 1.1) | |
432 | %gui # disable all event loop integration |
|
432 | %gui # disable all event loop integration | |
433 |
|
433 | |||
434 | WARNING: after any of these has been called you can simply create |
|
434 | WARNING: after any of these has been called you can simply create | |
435 | an application object, but DO NOT start the event loop yourself, as |
|
435 | an application object, but DO NOT start the event loop yourself, as | |
436 | we have already handled that. |
|
436 | we have already handled that. | |
437 | """ |
|
437 | """ | |
438 | opts, arg = self.parse_options(parameter_s, '') |
|
438 | opts, arg = self.parse_options(parameter_s, '') | |
439 | if arg=='': arg = None |
|
439 | if arg=='': arg = None | |
440 | try: |
|
440 | try: | |
441 | return self.enable_gui(arg) |
|
441 | return self.enable_gui(arg) | |
442 | except Exception as e: |
|
442 | except Exception as e: | |
443 | # print simple error message, rather than traceback if we can't |
|
443 | # print simple error message, rather than traceback if we can't | |
444 | # hook up the GUI |
|
444 | # hook up the GUI | |
445 | error(str(e)) |
|
445 | error(str(e)) | |
446 |
|
446 | |||
447 | @skip_doctest |
|
447 | @skip_doctest | |
448 | @line_magic |
|
448 | @line_magic | |
449 | def precision(self, s=''): |
|
449 | def precision(self, s=''): | |
450 | """Set floating point precision for pretty printing. |
|
450 | """Set floating point precision for pretty printing. | |
451 |
|
451 | |||
452 | Can set either integer precision or a format string. |
|
452 | Can set either integer precision or a format string. | |
453 |
|
453 | |||
454 | If numpy has been imported and precision is an int, |
|
454 | If numpy has been imported and precision is an int, | |
455 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
455 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
456 |
|
456 | |||
457 | If no argument is given, defaults will be restored. |
|
457 | If no argument is given, defaults will be restored. | |
458 |
|
458 | |||
459 | Examples |
|
459 | Examples | |
460 | -------- |
|
460 | -------- | |
461 | :: |
|
461 | :: | |
462 |
|
462 | |||
463 | In [1]: from math import pi |
|
463 | In [1]: from math import pi | |
464 |
|
464 | |||
465 | In [2]: %precision 3 |
|
465 | In [2]: %precision 3 | |
466 | Out[2]: u'%.3f' |
|
466 | Out[2]: u'%.3f' | |
467 |
|
467 | |||
468 | In [3]: pi |
|
468 | In [3]: pi | |
469 | Out[3]: 3.142 |
|
469 | Out[3]: 3.142 | |
470 |
|
470 | |||
471 | In [4]: %precision %i |
|
471 | In [4]: %precision %i | |
472 | Out[4]: u'%i' |
|
472 | Out[4]: u'%i' | |
473 |
|
473 | |||
474 | In [5]: pi |
|
474 | In [5]: pi | |
475 | Out[5]: 3 |
|
475 | Out[5]: 3 | |
476 |
|
476 | |||
477 | In [6]: %precision %e |
|
477 | In [6]: %precision %e | |
478 | Out[6]: u'%e' |
|
478 | Out[6]: u'%e' | |
479 |
|
479 | |||
480 | In [7]: pi**10 |
|
480 | In [7]: pi**10 | |
481 | Out[7]: 9.364805e+04 |
|
481 | Out[7]: 9.364805e+04 | |
482 |
|
482 | |||
483 | In [8]: %precision |
|
483 | In [8]: %precision | |
484 | Out[8]: u'%r' |
|
484 | Out[8]: u'%r' | |
485 |
|
485 | |||
486 | In [9]: pi**10 |
|
486 | In [9]: pi**10 | |
487 | Out[9]: 93648.047476082982 |
|
487 | Out[9]: 93648.047476082982 | |
488 | """ |
|
488 | """ | |
489 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
489 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
490 | ptformatter.float_precision = s |
|
490 | ptformatter.float_precision = s | |
491 | return ptformatter.float_format |
|
491 | return ptformatter.float_format | |
492 |
|
492 | |||
493 | @magic_arguments.magic_arguments() |
|
493 | @magic_arguments.magic_arguments() | |
494 | @magic_arguments.argument( |
|
494 | @magic_arguments.argument( | |
495 | '-e', '--export', action='store_true', default=False, |
|
495 | '-e', '--export', action='store_true', default=False, | |
496 | help='Export IPython history as a notebook. The filename argument ' |
|
496 | help='Export IPython history as a notebook. The filename argument ' | |
497 | 'is used to specify the notebook name and format. For example ' |
|
497 | 'is used to specify the notebook name and format. For example ' | |
498 | 'a filename of notebook.ipynb will result in a notebook name ' |
|
498 | 'a filename of notebook.ipynb will result in a notebook name ' | |
499 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' |
|
499 | 'of "notebook" and a format of "xml". Likewise using a ".json" ' | |
500 | 'or ".py" file extension will write the notebook in the json ' |
|
500 | 'or ".py" file extension will write the notebook in the json ' | |
501 | 'or py formats.' |
|
501 | 'or py formats.' | |
502 | ) |
|
502 | ) | |
503 | @magic_arguments.argument( |
|
503 | @magic_arguments.argument( | |
504 | '-f', '--format', |
|
504 | '-f', '--format', | |
505 | help='Convert an existing IPython notebook to a new format. This option ' |
|
505 | help='Convert an existing IPython notebook to a new format. This option ' | |
506 | 'specifies the new format and can have the values: xml, json, py. ' |
|
506 | 'specifies the new format and can have the values: xml, json, py. ' | |
507 | 'The target filename is chosen automatically based on the new ' |
|
507 | 'The target filename is chosen automatically based on the new ' | |
508 | 'format. The filename argument gives the name of the source file.' |
|
508 | 'format. The filename argument gives the name of the source file.' | |
509 | ) |
|
509 | ) | |
510 | @magic_arguments.argument( |
|
510 | @magic_arguments.argument( | |
511 | 'filename', type=unicode, |
|
511 | 'filename', type=unicode, | |
512 | help='Notebook name or filename' |
|
512 | help='Notebook name or filename' | |
513 | ) |
|
513 | ) | |
514 | @line_magic |
|
514 | @line_magic | |
515 | def notebook(self, s): |
|
515 | def notebook(self, s): | |
516 | """Export and convert IPython notebooks. |
|
516 | """Export and convert IPython notebooks. | |
517 |
|
517 | |||
518 | This function can export the current IPython history to a notebook file |
|
518 | This function can export the current IPython history to a notebook file | |
519 | or can convert an existing notebook file into a different format. For |
|
519 | or can convert an existing notebook file into a different format. For | |
520 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". |
|
520 | example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". | |
521 | To export the history to "foo.py" do "%notebook -e foo.py". To convert |
|
521 | To export the history to "foo.py" do "%notebook -e foo.py". To convert | |
522 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible |
|
522 | "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible | |
523 | formats include (json/ipynb, py). |
|
523 | formats include (json/ipynb, py). | |
524 | """ |
|
524 | """ | |
525 |
args = magic_arguments.parse_argstring(self. |
|
525 | args = magic_arguments.parse_argstring(self.notebook, s) | |
526 |
|
526 | |||
527 | from IPython.nbformat import current |
|
527 | from IPython.nbformat import current | |
528 | args.filename = unquote_filename(args.filename) |
|
528 | args.filename = unquote_filename(args.filename) | |
529 | if args.export: |
|
529 | if args.export: | |
530 | fname, name, format = current.parse_filename(args.filename) |
|
530 | fname, name, format = current.parse_filename(args.filename) | |
531 | cells = [] |
|
531 | cells = [] | |
532 | hist = list(self.shell.history_manager.get_range()) |
|
532 | hist = list(self.shell.history_manager.get_range()) | |
533 | for session, prompt_number, input in hist[:-1]: |
|
533 | for session, prompt_number, input in hist[:-1]: | |
534 | cells.append(current.new_code_cell(prompt_number=prompt_number, |
|
534 | cells.append(current.new_code_cell(prompt_number=prompt_number, | |
535 | input=input)) |
|
535 | input=input)) | |
536 | worksheet = current.new_worksheet(cells=cells) |
|
536 | worksheet = current.new_worksheet(cells=cells) | |
537 | nb = current.new_notebook(name=name,worksheets=[worksheet]) |
|
537 | nb = current.new_notebook(name=name,worksheets=[worksheet]) | |
538 | with io.open(fname, 'w', encoding='utf-8') as f: |
|
538 | with io.open(fname, 'w', encoding='utf-8') as f: | |
539 | current.write(nb, f, format); |
|
539 | current.write(nb, f, format); | |
540 | elif args.format is not None: |
|
540 | elif args.format is not None: | |
541 | old_fname, old_name, old_format = current.parse_filename(args.filename) |
|
541 | old_fname, old_name, old_format = current.parse_filename(args.filename) | |
542 | new_format = args.format |
|
542 | new_format = args.format | |
543 | if new_format == u'xml': |
|
543 | if new_format == u'xml': | |
544 | raise ValueError('Notebooks cannot be written as xml.') |
|
544 | raise ValueError('Notebooks cannot be written as xml.') | |
545 | elif new_format == u'ipynb' or new_format == u'json': |
|
545 | elif new_format == u'ipynb' or new_format == u'json': | |
546 | new_fname = old_name + u'.ipynb' |
|
546 | new_fname = old_name + u'.ipynb' | |
547 | new_format = u'json' |
|
547 | new_format = u'json' | |
548 | elif new_format == u'py': |
|
548 | elif new_format == u'py': | |
549 | new_fname = old_name + u'.py' |
|
549 | new_fname = old_name + u'.py' | |
550 | else: |
|
550 | else: | |
551 | raise ValueError('Invalid notebook format: %s' % new_format) |
|
551 | raise ValueError('Invalid notebook format: %s' % new_format) | |
552 | with io.open(old_fname, 'r', encoding='utf-8') as f: |
|
552 | with io.open(old_fname, 'r', encoding='utf-8') as f: | |
553 | nb = current.read(f, old_format) |
|
553 | nb = current.read(f, old_format) | |
554 | with io.open(new_fname, 'w', encoding='utf-8') as f: |
|
554 | with io.open(new_fname, 'w', encoding='utf-8') as f: | |
555 | current.write(nb, f, new_format) |
|
555 | current.write(nb, f, new_format) | |
556 |
|
556 | |||
557 |
|
557 | |||
558 | # Used for exception handling in magic_edit |
|
558 | # Used for exception handling in magic_edit | |
559 | class MacroToEdit(ValueError): pass |
|
559 | class MacroToEdit(ValueError): pass | |
560 |
|
560 | |||
561 |
|
561 | |||
562 | @register_magics |
|
562 | @register_magics | |
563 | class CodeMagics(Magics): |
|
563 | class CodeMagics(Magics): | |
564 | """Magics related to code management (loading, saving, editing, ...).""" |
|
564 | """Magics related to code management (loading, saving, editing, ...).""" | |
565 |
|
565 | |||
566 | @line_magic |
|
566 | @line_magic | |
567 | def save(self, parameter_s=''): |
|
567 | def save(self, parameter_s=''): | |
568 | """Save a set of lines or a macro to a given filename. |
|
568 | """Save a set of lines or a macro to a given filename. | |
569 |
|
569 | |||
570 | Usage:\\ |
|
570 | Usage:\\ | |
571 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
571 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
572 |
|
572 | |||
573 | Options: |
|
573 | Options: | |
574 |
|
574 | |||
575 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
575 | -r: use 'raw' input. By default, the 'processed' history is used, | |
576 | so that magics are loaded in their transformed version to valid |
|
576 | so that magics are loaded in their transformed version to valid | |
577 | Python. If this option is given, the raw input as typed as the |
|
577 | Python. If this option is given, the raw input as typed as the | |
578 | command line is used instead. |
|
578 | command line is used instead. | |
579 |
|
579 | |||
580 | This function uses the same syntax as %history for input ranges, |
|
580 | This function uses the same syntax as %history for input ranges, | |
581 | then saves the lines to the filename you specify. |
|
581 | then saves the lines to the filename you specify. | |
582 |
|
582 | |||
583 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
583 | It adds a '.py' extension to the file if you don't do so yourself, and | |
584 | it asks for confirmation before overwriting existing files.""" |
|
584 | it asks for confirmation before overwriting existing files.""" | |
585 |
|
585 | |||
586 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
586 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
587 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) |
|
587 | fname, codefrom = unquote_filename(args[0]), " ".join(args[1:]) | |
588 | if not fname.endswith('.py'): |
|
588 | if not fname.endswith('.py'): | |
589 | fname += '.py' |
|
589 | fname += '.py' | |
590 | if os.path.isfile(fname): |
|
590 | if os.path.isfile(fname): | |
591 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
591 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
592 | if ans.lower() not in ['y','yes']: |
|
592 | if ans.lower() not in ['y','yes']: | |
593 | print 'Operation cancelled.' |
|
593 | print 'Operation cancelled.' | |
594 | return |
|
594 | return | |
595 | try: |
|
595 | try: | |
596 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) |
|
596 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) | |
597 | except (TypeError, ValueError) as e: |
|
597 | except (TypeError, ValueError) as e: | |
598 | print e.args[0] |
|
598 | print e.args[0] | |
599 | return |
|
599 | return | |
600 | with io.open(fname,'w', encoding="utf-8") as f: |
|
600 | with io.open(fname,'w', encoding="utf-8") as f: | |
601 | f.write(u"# coding: utf-8\n") |
|
601 | f.write(u"# coding: utf-8\n") | |
602 | f.write(py3compat.cast_unicode(cmds)) |
|
602 | f.write(py3compat.cast_unicode(cmds)) | |
603 | print 'The following commands were written to file `%s`:' % fname |
|
603 | print 'The following commands were written to file `%s`:' % fname | |
604 | print cmds |
|
604 | print cmds | |
605 |
|
605 | |||
606 | @line_magic |
|
606 | @line_magic | |
607 | def pastebin(self, parameter_s=''): |
|
607 | def pastebin(self, parameter_s=''): | |
608 | """Upload code to Github's Gist paste bin, returning the URL. |
|
608 | """Upload code to Github's Gist paste bin, returning the URL. | |
609 |
|
609 | |||
610 | Usage:\\ |
|
610 | Usage:\\ | |
611 | %pastebin [-d "Custom description"] 1-7 |
|
611 | %pastebin [-d "Custom description"] 1-7 | |
612 |
|
612 | |||
613 | The argument can be an input history range, a filename, or the name of a |
|
613 | The argument can be an input history range, a filename, or the name of a | |
614 | string or macro. |
|
614 | string or macro. | |
615 |
|
615 | |||
616 | Options: |
|
616 | Options: | |
617 |
|
617 | |||
618 | -d: Pass a custom description for the gist. The default will say |
|
618 | -d: Pass a custom description for the gist. The default will say | |
619 | "Pasted from IPython". |
|
619 | "Pasted from IPython". | |
620 | """ |
|
620 | """ | |
621 | opts, args = self.parse_options(parameter_s, 'd:') |
|
621 | opts, args = self.parse_options(parameter_s, 'd:') | |
622 |
|
622 | |||
623 | try: |
|
623 | try: | |
624 | code = self.shell.find_user_code(args) |
|
624 | code = self.shell.find_user_code(args) | |
625 | except (ValueError, TypeError) as e: |
|
625 | except (ValueError, TypeError) as e: | |
626 | print e.args[0] |
|
626 | print e.args[0] | |
627 | return |
|
627 | return | |
628 |
|
628 | |||
629 | post_data = json.dumps({ |
|
629 | post_data = json.dumps({ | |
630 | "description": opts.get('d', "Pasted from IPython"), |
|
630 | "description": opts.get('d', "Pasted from IPython"), | |
631 | "public": True, |
|
631 | "public": True, | |
632 | "files": { |
|
632 | "files": { | |
633 | "file1.py": { |
|
633 | "file1.py": { | |
634 | "content": code |
|
634 | "content": code | |
635 | } |
|
635 | } | |
636 | } |
|
636 | } | |
637 | }).encode('utf-8') |
|
637 | }).encode('utf-8') | |
638 |
|
638 | |||
639 | response = urlopen("https://api.github.com/gists", post_data) |
|
639 | response = urlopen("https://api.github.com/gists", post_data) | |
640 | response_data = json.loads(response.read().decode('utf-8')) |
|
640 | response_data = json.loads(response.read().decode('utf-8')) | |
641 | return response_data['html_url'] |
|
641 | return response_data['html_url'] | |
642 |
|
642 | |||
643 | @line_magic |
|
643 | @line_magic | |
644 | def loadpy(self, arg_s): |
|
644 | def loadpy(self, arg_s): | |
645 | """Load a .py python script into the GUI console. |
|
645 | """Load a .py python script into the GUI console. | |
646 |
|
646 | |||
647 | This magic command can either take a local filename or a url:: |
|
647 | This magic command can either take a local filename or a url:: | |
648 |
|
648 | |||
649 | %loadpy myscript.py |
|
649 | %loadpy myscript.py | |
650 | %loadpy http://www.example.com/myscript.py |
|
650 | %loadpy http://www.example.com/myscript.py | |
651 | """ |
|
651 | """ | |
652 | arg_s = unquote_filename(arg_s) |
|
652 | arg_s = unquote_filename(arg_s) | |
653 | remote_url = arg_s.startswith(('http://', 'https://')) |
|
653 | remote_url = arg_s.startswith(('http://', 'https://')) | |
654 | local_url = not remote_url |
|
654 | local_url = not remote_url | |
655 | if local_url and not arg_s.endswith('.py'): |
|
655 | if local_url and not arg_s.endswith('.py'): | |
656 | # Local files must be .py; for remote URLs it's possible that the |
|
656 | # Local files must be .py; for remote URLs it's possible that the | |
657 | # fetch URL doesn't have a .py in it (many servers have an opaque |
|
657 | # fetch URL doesn't have a .py in it (many servers have an opaque | |
658 | # URL, such as scipy-central.org). |
|
658 | # URL, such as scipy-central.org). | |
659 | raise ValueError('%%loadpy only works with .py files: %s' % arg_s) |
|
659 | raise ValueError('%%loadpy only works with .py files: %s' % arg_s) | |
660 |
|
660 | |||
661 | # openpy takes care of finding the source encoding (per PEP 263) |
|
661 | # openpy takes care of finding the source encoding (per PEP 263) | |
662 | if remote_url: |
|
662 | if remote_url: | |
663 | contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True) |
|
663 | contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True) | |
664 | else: |
|
664 | else: | |
665 | contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True) |
|
665 | contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True) | |
666 |
|
666 | |||
667 | self.set_next_input(contents) |
|
667 | self.set_next_input(contents) | |
668 |
|
668 | |||
669 | def _find_edit_target(self, args, opts, last_call): |
|
669 | def _find_edit_target(self, args, opts, last_call): | |
670 | """Utility method used by magic_edit to find what to edit.""" |
|
670 | """Utility method used by magic_edit to find what to edit.""" | |
671 |
|
671 | |||
672 | def make_filename(arg): |
|
672 | def make_filename(arg): | |
673 | "Make a filename from the given args" |
|
673 | "Make a filename from the given args" | |
674 | arg = unquote_filename(arg) |
|
674 | arg = unquote_filename(arg) | |
675 | try: |
|
675 | try: | |
676 | filename = get_py_filename(arg) |
|
676 | filename = get_py_filename(arg) | |
677 | except IOError: |
|
677 | except IOError: | |
678 | # If it ends with .py but doesn't already exist, assume we want |
|
678 | # If it ends with .py but doesn't already exist, assume we want | |
679 | # a new file. |
|
679 | # a new file. | |
680 | if arg.endswith('.py'): |
|
680 | if arg.endswith('.py'): | |
681 | filename = arg |
|
681 | filename = arg | |
682 | else: |
|
682 | else: | |
683 | filename = None |
|
683 | filename = None | |
684 | return filename |
|
684 | return filename | |
685 |
|
685 | |||
686 | # Set a few locals from the options for convenience: |
|
686 | # Set a few locals from the options for convenience: | |
687 | opts_prev = 'p' in opts |
|
687 | opts_prev = 'p' in opts | |
688 | opts_raw = 'r' in opts |
|
688 | opts_raw = 'r' in opts | |
689 |
|
689 | |||
690 | # custom exceptions |
|
690 | # custom exceptions | |
691 | class DataIsObject(Exception): pass |
|
691 | class DataIsObject(Exception): pass | |
692 |
|
692 | |||
693 | # Default line number value |
|
693 | # Default line number value | |
694 | lineno = opts.get('n',None) |
|
694 | lineno = opts.get('n',None) | |
695 |
|
695 | |||
696 | if opts_prev: |
|
696 | if opts_prev: | |
697 | args = '_%s' % last_call[0] |
|
697 | args = '_%s' % last_call[0] | |
698 | if not self.shell.user_ns.has_key(args): |
|
698 | if not self.shell.user_ns.has_key(args): | |
699 | args = last_call[1] |
|
699 | args = last_call[1] | |
700 |
|
700 | |||
701 | # use last_call to remember the state of the previous call, but don't |
|
701 | # use last_call to remember the state of the previous call, but don't | |
702 | # let it be clobbered by successive '-p' calls. |
|
702 | # let it be clobbered by successive '-p' calls. | |
703 | try: |
|
703 | try: | |
704 | last_call[0] = self.shell.displayhook.prompt_count |
|
704 | last_call[0] = self.shell.displayhook.prompt_count | |
705 | if not opts_prev: |
|
705 | if not opts_prev: | |
706 | last_call[1] = args |
|
706 | last_call[1] = args | |
707 | except: |
|
707 | except: | |
708 | pass |
|
708 | pass | |
709 |
|
709 | |||
710 | # by default this is done with temp files, except when the given |
|
710 | # by default this is done with temp files, except when the given | |
711 | # arg is a filename |
|
711 | # arg is a filename | |
712 | use_temp = True |
|
712 | use_temp = True | |
713 |
|
713 | |||
714 | data = '' |
|
714 | data = '' | |
715 |
|
715 | |||
716 | # First, see if the arguments should be a filename. |
|
716 | # First, see if the arguments should be a filename. | |
717 | filename = make_filename(args) |
|
717 | filename = make_filename(args) | |
718 | if filename: |
|
718 | if filename: | |
719 | use_temp = False |
|
719 | use_temp = False | |
720 | elif args: |
|
720 | elif args: | |
721 | # Mode where user specifies ranges of lines, like in %macro. |
|
721 | # Mode where user specifies ranges of lines, like in %macro. | |
722 | data = self.shell.extract_input_lines(args, opts_raw) |
|
722 | data = self.shell.extract_input_lines(args, opts_raw) | |
723 | if not data: |
|
723 | if not data: | |
724 | try: |
|
724 | try: | |
725 | # Load the parameter given as a variable. If not a string, |
|
725 | # Load the parameter given as a variable. If not a string, | |
726 | # process it as an object instead (below) |
|
726 | # process it as an object instead (below) | |
727 |
|
727 | |||
728 | #print '*** args',args,'type',type(args) # dbg |
|
728 | #print '*** args',args,'type',type(args) # dbg | |
729 | data = eval(args, self.shell.user_ns) |
|
729 | data = eval(args, self.shell.user_ns) | |
730 | if not isinstance(data, basestring): |
|
730 | if not isinstance(data, basestring): | |
731 | raise DataIsObject |
|
731 | raise DataIsObject | |
732 |
|
732 | |||
733 | except (NameError,SyntaxError): |
|
733 | except (NameError,SyntaxError): | |
734 | # given argument is not a variable, try as a filename |
|
734 | # given argument is not a variable, try as a filename | |
735 | filename = make_filename(args) |
|
735 | filename = make_filename(args) | |
736 | if filename is None: |
|
736 | if filename is None: | |
737 | warn("Argument given (%s) can't be found as a variable " |
|
737 | warn("Argument given (%s) can't be found as a variable " | |
738 | "or as a filename." % args) |
|
738 | "or as a filename." % args) | |
739 | return |
|
739 | return | |
740 | use_temp = False |
|
740 | use_temp = False | |
741 |
|
741 | |||
742 | except DataIsObject: |
|
742 | except DataIsObject: | |
743 | # macros have a special edit function |
|
743 | # macros have a special edit function | |
744 | if isinstance(data, Macro): |
|
744 | if isinstance(data, Macro): | |
745 | raise MacroToEdit(data) |
|
745 | raise MacroToEdit(data) | |
746 |
|
746 | |||
747 | # For objects, try to edit the file where they are defined |
|
747 | # For objects, try to edit the file where they are defined | |
748 | try: |
|
748 | try: | |
749 | filename = inspect.getabsfile(data) |
|
749 | filename = inspect.getabsfile(data) | |
750 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
750 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
751 | # class created by %edit? Try to find source |
|
751 | # class created by %edit? Try to find source | |
752 | # by looking for method definitions instead, the |
|
752 | # by looking for method definitions instead, the | |
753 | # __module__ in those classes is FakeModule. |
|
753 | # __module__ in those classes is FakeModule. | |
754 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
754 | attrs = [getattr(data, aname) for aname in dir(data)] | |
755 | for attr in attrs: |
|
755 | for attr in attrs: | |
756 | if not inspect.ismethod(attr): |
|
756 | if not inspect.ismethod(attr): | |
757 | continue |
|
757 | continue | |
758 | filename = inspect.getabsfile(attr) |
|
758 | filename = inspect.getabsfile(attr) | |
759 | if filename and 'fakemodule' not in filename.lower(): |
|
759 | if filename and 'fakemodule' not in filename.lower(): | |
760 | # change the attribute to be the edit target instead |
|
760 | # change the attribute to be the edit target instead | |
761 | data = attr |
|
761 | data = attr | |
762 | break |
|
762 | break | |
763 |
|
763 | |||
764 | datafile = 1 |
|
764 | datafile = 1 | |
765 | except TypeError: |
|
765 | except TypeError: | |
766 | filename = make_filename(args) |
|
766 | filename = make_filename(args) | |
767 | datafile = 1 |
|
767 | datafile = 1 | |
768 | warn('Could not find file where `%s` is defined.\n' |
|
768 | warn('Could not find file where `%s` is defined.\n' | |
769 | 'Opening a file named `%s`' % (args,filename)) |
|
769 | 'Opening a file named `%s`' % (args,filename)) | |
770 | # Now, make sure we can actually read the source (if it was in |
|
770 | # Now, make sure we can actually read the source (if it was in | |
771 | # a temp file it's gone by now). |
|
771 | # a temp file it's gone by now). | |
772 | if datafile: |
|
772 | if datafile: | |
773 | try: |
|
773 | try: | |
774 | if lineno is None: |
|
774 | if lineno is None: | |
775 | lineno = inspect.getsourcelines(data)[1] |
|
775 | lineno = inspect.getsourcelines(data)[1] | |
776 | except IOError: |
|
776 | except IOError: | |
777 | filename = make_filename(args) |
|
777 | filename = make_filename(args) | |
778 | if filename is None: |
|
778 | if filename is None: | |
779 | warn('The file `%s` where `%s` was defined cannot ' |
|
779 | warn('The file `%s` where `%s` was defined cannot ' | |
780 | 'be read.' % (filename,data)) |
|
780 | 'be read.' % (filename,data)) | |
781 | return |
|
781 | return | |
782 | use_temp = False |
|
782 | use_temp = False | |
783 |
|
783 | |||
784 | if use_temp: |
|
784 | if use_temp: | |
785 | filename = self.shell.mktempfile(data) |
|
785 | filename = self.shell.mktempfile(data) | |
786 | print 'IPython will make a temporary file named:',filename |
|
786 | print 'IPython will make a temporary file named:',filename | |
787 |
|
787 | |||
788 | return filename, lineno, use_temp |
|
788 | return filename, lineno, use_temp | |
789 |
|
789 | |||
790 | def _edit_macro(self,mname,macro): |
|
790 | def _edit_macro(self,mname,macro): | |
791 | """open an editor with the macro data in a file""" |
|
791 | """open an editor with the macro data in a file""" | |
792 | filename = self.shell.mktempfile(macro.value) |
|
792 | filename = self.shell.mktempfile(macro.value) | |
793 | self.shell.hooks.editor(filename) |
|
793 | self.shell.hooks.editor(filename) | |
794 |
|
794 | |||
795 | # and make a new macro object, to replace the old one |
|
795 | # and make a new macro object, to replace the old one | |
796 | mfile = open(filename) |
|
796 | mfile = open(filename) | |
797 | mvalue = mfile.read() |
|
797 | mvalue = mfile.read() | |
798 | mfile.close() |
|
798 | mfile.close() | |
799 | self.shell.user_ns[mname] = Macro(mvalue) |
|
799 | self.shell.user_ns[mname] = Macro(mvalue) | |
800 |
|
800 | |||
801 | @line_magic |
|
801 | @line_magic | |
802 | def ed(self, parameter_s=''): |
|
802 | def ed(self, parameter_s=''): | |
803 | """Alias to %edit.""" |
|
803 | """Alias to %edit.""" | |
804 | return self.magic_edit(parameter_s) |
|
804 | return self.magic_edit(parameter_s) | |
805 |
|
805 | |||
806 | @skip_doctest |
|
806 | @skip_doctest | |
807 | @line_magic |
|
807 | @line_magic | |
808 | def edit(self, parameter_s='',last_call=['','']): |
|
808 | def edit(self, parameter_s='',last_call=['','']): | |
809 | """Bring up an editor and execute the resulting code. |
|
809 | """Bring up an editor and execute the resulting code. | |
810 |
|
810 | |||
811 | Usage: |
|
811 | Usage: | |
812 | %edit [options] [args] |
|
812 | %edit [options] [args] | |
813 |
|
813 | |||
814 | %edit runs IPython's editor hook. The default version of this hook is |
|
814 | %edit runs IPython's editor hook. The default version of this hook is | |
815 | set to call the editor specified by your $EDITOR environment variable. |
|
815 | set to call the editor specified by your $EDITOR environment variable. | |
816 | If this isn't found, it will default to vi under Linux/Unix and to |
|
816 | If this isn't found, it will default to vi under Linux/Unix and to | |
817 | notepad under Windows. See the end of this docstring for how to change |
|
817 | notepad under Windows. See the end of this docstring for how to change | |
818 | the editor hook. |
|
818 | the editor hook. | |
819 |
|
819 | |||
820 | You can also set the value of this editor via the |
|
820 | You can also set the value of this editor via the | |
821 | ``TerminalInteractiveShell.editor`` option in your configuration file. |
|
821 | ``TerminalInteractiveShell.editor`` option in your configuration file. | |
822 | This is useful if you wish to use a different editor from your typical |
|
822 | This is useful if you wish to use a different editor from your typical | |
823 | default with IPython (and for Windows users who typically don't set |
|
823 | default with IPython (and for Windows users who typically don't set | |
824 | environment variables). |
|
824 | environment variables). | |
825 |
|
825 | |||
826 | This command allows you to conveniently edit multi-line code right in |
|
826 | This command allows you to conveniently edit multi-line code right in | |
827 | your IPython session. |
|
827 | your IPython session. | |
828 |
|
828 | |||
829 | If called without arguments, %edit opens up an empty editor with a |
|
829 | If called without arguments, %edit opens up an empty editor with a | |
830 | temporary file and will execute the contents of this file when you |
|
830 | temporary file and will execute the contents of this file when you | |
831 | close it (don't forget to save it!). |
|
831 | close it (don't forget to save it!). | |
832 |
|
832 | |||
833 |
|
833 | |||
834 | Options: |
|
834 | Options: | |
835 |
|
835 | |||
836 | -n <number>: open the editor at a specified line number. By default, |
|
836 | -n <number>: open the editor at a specified line number. By default, | |
837 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
837 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
838 | you can configure this by providing your own modified hook if your |
|
838 | you can configure this by providing your own modified hook if your | |
839 | favorite editor supports line-number specifications with a different |
|
839 | favorite editor supports line-number specifications with a different | |
840 | syntax. |
|
840 | syntax. | |
841 |
|
841 | |||
842 | -p: this will call the editor with the same data as the previous time |
|
842 | -p: this will call the editor with the same data as the previous time | |
843 | it was used, regardless of how long ago (in your current session) it |
|
843 | it was used, regardless of how long ago (in your current session) it | |
844 | was. |
|
844 | was. | |
845 |
|
845 | |||
846 | -r: use 'raw' input. This option only applies to input taken from the |
|
846 | -r: use 'raw' input. This option only applies to input taken from the | |
847 | user's history. By default, the 'processed' history is used, so that |
|
847 | user's history. By default, the 'processed' history is used, so that | |
848 | magics are loaded in their transformed version to valid Python. If |
|
848 | magics are loaded in their transformed version to valid Python. If | |
849 | this option is given, the raw input as typed as the command line is |
|
849 | this option is given, the raw input as typed as the command line is | |
850 | used instead. When you exit the editor, it will be executed by |
|
850 | used instead. When you exit the editor, it will be executed by | |
851 | IPython's own processor. |
|
851 | IPython's own processor. | |
852 |
|
852 | |||
853 | -x: do not execute the edited code immediately upon exit. This is |
|
853 | -x: do not execute the edited code immediately upon exit. This is | |
854 | mainly useful if you are editing programs which need to be called with |
|
854 | mainly useful if you are editing programs which need to be called with | |
855 | command line arguments, which you can then do using %run. |
|
855 | command line arguments, which you can then do using %run. | |
856 |
|
856 | |||
857 |
|
857 | |||
858 | Arguments: |
|
858 | Arguments: | |
859 |
|
859 | |||
860 | If arguments are given, the following possibilities exist: |
|
860 | If arguments are given, the following possibilities exist: | |
861 |
|
861 | |||
862 | - If the argument is a filename, IPython will load that into the |
|
862 | - If the argument is a filename, IPython will load that into the | |
863 | editor. It will execute its contents with execfile() when you exit, |
|
863 | editor. It will execute its contents with execfile() when you exit, | |
864 | loading any code in the file into your interactive namespace. |
|
864 | loading any code in the file into your interactive namespace. | |
865 |
|
865 | |||
866 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
866 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". | |
867 | The syntax is the same as in the %history magic. |
|
867 | The syntax is the same as in the %history magic. | |
868 |
|
868 | |||
869 | - If the argument is a string variable, its contents are loaded |
|
869 | - If the argument is a string variable, its contents are loaded | |
870 | into the editor. You can thus edit any string which contains |
|
870 | into the editor. You can thus edit any string which contains | |
871 | python code (including the result of previous edits). |
|
871 | python code (including the result of previous edits). | |
872 |
|
872 | |||
873 | - If the argument is the name of an object (other than a string), |
|
873 | - If the argument is the name of an object (other than a string), | |
874 | IPython will try to locate the file where it was defined and open the |
|
874 | IPython will try to locate the file where it was defined and open the | |
875 | editor at the point where it is defined. You can use `%edit function` |
|
875 | editor at the point where it is defined. You can use `%edit function` | |
876 | to load an editor exactly at the point where 'function' is defined, |
|
876 | to load an editor exactly at the point where 'function' is defined, | |
877 | edit it and have the file be executed automatically. |
|
877 | edit it and have the file be executed automatically. | |
878 |
|
878 | |||
879 | - If the object is a macro (see %macro for details), this opens up your |
|
879 | - If the object is a macro (see %macro for details), this opens up your | |
880 | specified editor with a temporary file containing the macro's data. |
|
880 | specified editor with a temporary file containing the macro's data. | |
881 | Upon exit, the macro is reloaded with the contents of the file. |
|
881 | Upon exit, the macro is reloaded with the contents of the file. | |
882 |
|
882 | |||
883 | Note: opening at an exact line is only supported under Unix, and some |
|
883 | Note: opening at an exact line is only supported under Unix, and some | |
884 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
884 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
885 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
885 | '+NUMBER' parameter necessary for this feature. Good editors like | |
886 | (X)Emacs, vi, jed, pico and joe all do. |
|
886 | (X)Emacs, vi, jed, pico and joe all do. | |
887 |
|
887 | |||
888 | After executing your code, %edit will return as output the code you |
|
888 | After executing your code, %edit will return as output the code you | |
889 | typed in the editor (except when it was an existing file). This way |
|
889 | typed in the editor (except when it was an existing file). This way | |
890 | you can reload the code in further invocations of %edit as a variable, |
|
890 | you can reload the code in further invocations of %edit as a variable, | |
891 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
891 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
892 | the output. |
|
892 | the output. | |
893 |
|
893 | |||
894 | Note that %edit is also available through the alias %ed. |
|
894 | Note that %edit is also available through the alias %ed. | |
895 |
|
895 | |||
896 | This is an example of creating a simple function inside the editor and |
|
896 | This is an example of creating a simple function inside the editor and | |
897 | then modifying it. First, start up the editor:: |
|
897 | then modifying it. First, start up the editor:: | |
898 |
|
898 | |||
899 | In [1]: ed |
|
899 | In [1]: ed | |
900 | Editing... done. Executing edited code... |
|
900 | Editing... done. Executing edited code... | |
901 | Out[1]: 'def foo():\\n print "foo() was defined in an editing |
|
901 | Out[1]: 'def foo():\\n print "foo() was defined in an editing | |
902 | session"\\n' |
|
902 | session"\\n' | |
903 |
|
903 | |||
904 | We can then call the function foo():: |
|
904 | We can then call the function foo():: | |
905 |
|
905 | |||
906 | In [2]: foo() |
|
906 | In [2]: foo() | |
907 | foo() was defined in an editing session |
|
907 | foo() was defined in an editing session | |
908 |
|
908 | |||
909 | Now we edit foo. IPython automatically loads the editor with the |
|
909 | Now we edit foo. IPython automatically loads the editor with the | |
910 | (temporary) file where foo() was previously defined:: |
|
910 | (temporary) file where foo() was previously defined:: | |
911 |
|
911 | |||
912 | In [3]: ed foo |
|
912 | In [3]: ed foo | |
913 | Editing... done. Executing edited code... |
|
913 | Editing... done. Executing edited code... | |
914 |
|
914 | |||
915 | And if we call foo() again we get the modified version:: |
|
915 | And if we call foo() again we get the modified version:: | |
916 |
|
916 | |||
917 | In [4]: foo() |
|
917 | In [4]: foo() | |
918 | foo() has now been changed! |
|
918 | foo() has now been changed! | |
919 |
|
919 | |||
920 | Here is an example of how to edit a code snippet successive |
|
920 | Here is an example of how to edit a code snippet successive | |
921 | times. First we call the editor:: |
|
921 | times. First we call the editor:: | |
922 |
|
922 | |||
923 | In [5]: ed |
|
923 | In [5]: ed | |
924 | Editing... done. Executing edited code... |
|
924 | Editing... done. Executing edited code... | |
925 | hello |
|
925 | hello | |
926 | Out[5]: "print 'hello'\\n" |
|
926 | Out[5]: "print 'hello'\\n" | |
927 |
|
927 | |||
928 | Now we call it again with the previous output (stored in _):: |
|
928 | Now we call it again with the previous output (stored in _):: | |
929 |
|
929 | |||
930 | In [6]: ed _ |
|
930 | In [6]: ed _ | |
931 | Editing... done. Executing edited code... |
|
931 | Editing... done. Executing edited code... | |
932 | hello world |
|
932 | hello world | |
933 | Out[6]: "print 'hello world'\\n" |
|
933 | Out[6]: "print 'hello world'\\n" | |
934 |
|
934 | |||
935 | Now we call it with the output #8 (stored in _8, also as Out[8]):: |
|
935 | Now we call it with the output #8 (stored in _8, also as Out[8]):: | |
936 |
|
936 | |||
937 | In [7]: ed _8 |
|
937 | In [7]: ed _8 | |
938 | Editing... done. Executing edited code... |
|
938 | Editing... done. Executing edited code... | |
939 | hello again |
|
939 | hello again | |
940 | Out[7]: "print 'hello again'\\n" |
|
940 | Out[7]: "print 'hello again'\\n" | |
941 |
|
941 | |||
942 |
|
942 | |||
943 | Changing the default editor hook: |
|
943 | Changing the default editor hook: | |
944 |
|
944 | |||
945 | If you wish to write your own editor hook, you can put it in a |
|
945 | If you wish to write your own editor hook, you can put it in a | |
946 | configuration file which you load at startup time. The default hook |
|
946 | configuration file which you load at startup time. The default hook | |
947 | is defined in the IPython.core.hooks module, and you can use that as a |
|
947 | is defined in the IPython.core.hooks module, and you can use that as a | |
948 | starting example for further modifications. That file also has |
|
948 | starting example for further modifications. That file also has | |
949 | general instructions on how to set a new hook for use once you've |
|
949 | general instructions on how to set a new hook for use once you've | |
950 | defined it.""" |
|
950 | defined it.""" | |
951 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
951 | opts,args = self.parse_options(parameter_s,'prxn:') | |
952 |
|
952 | |||
953 | try: |
|
953 | try: | |
954 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) |
|
954 | filename, lineno, is_temp = self._find_edit_target(args, opts, last_call) | |
955 | except MacroToEdit as e: |
|
955 | except MacroToEdit as e: | |
956 | self._edit_macro(args, e.args[0]) |
|
956 | self._edit_macro(args, e.args[0]) | |
957 | return |
|
957 | return | |
958 |
|
958 | |||
959 | # do actual editing here |
|
959 | # do actual editing here | |
960 | print 'Editing...', |
|
960 | print 'Editing...', | |
961 | sys.stdout.flush() |
|
961 | sys.stdout.flush() | |
962 | try: |
|
962 | try: | |
963 | # Quote filenames that may have spaces in them |
|
963 | # Quote filenames that may have spaces in them | |
964 | if ' ' in filename: |
|
964 | if ' ' in filename: | |
965 | filename = "'%s'" % filename |
|
965 | filename = "'%s'" % filename | |
966 | self.shell.hooks.editor(filename,lineno) |
|
966 | self.shell.hooks.editor(filename,lineno) | |
967 | except TryNext: |
|
967 | except TryNext: | |
968 | warn('Could not open editor') |
|
968 | warn('Could not open editor') | |
969 | return |
|
969 | return | |
970 |
|
970 | |||
971 | # XXX TODO: should this be generalized for all string vars? |
|
971 | # XXX TODO: should this be generalized for all string vars? | |
972 | # For now, this is special-cased to blocks created by cpaste |
|
972 | # For now, this is special-cased to blocks created by cpaste | |
973 | if args.strip() == 'pasted_block': |
|
973 | if args.strip() == 'pasted_block': | |
974 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
974 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
975 |
|
975 | |||
976 | if 'x' in opts: # -x prevents actual execution |
|
976 | if 'x' in opts: # -x prevents actual execution | |
977 |
|
977 | |||
978 | else: |
|
978 | else: | |
979 | print 'done. Executing edited code...' |
|
979 | print 'done. Executing edited code...' | |
980 | if 'r' in opts: # Untranslated IPython code |
|
980 | if 'r' in opts: # Untranslated IPython code | |
981 | self.shell.run_cell(file_read(filename), |
|
981 | self.shell.run_cell(file_read(filename), | |
982 | store_history=False) |
|
982 | store_history=False) | |
983 | else: |
|
983 | else: | |
984 | self.shell.safe_execfile(filename, self.shell.user_ns, |
|
984 | self.shell.safe_execfile(filename, self.shell.user_ns, | |
985 | self.shell.user_ns) |
|
985 | self.shell.user_ns) | |
986 |
|
986 | |||
987 | if is_temp: |
|
987 | if is_temp: | |
988 | try: |
|
988 | try: | |
989 | return open(filename).read() |
|
989 | return open(filename).read() | |
990 | except IOError,msg: |
|
990 | except IOError,msg: | |
991 | if msg.filename == filename: |
|
991 | if msg.filename == filename: | |
992 | warn('File not found. Did you forget to save?') |
|
992 | warn('File not found. Did you forget to save?') | |
993 | return |
|
993 | return | |
994 | else: |
|
994 | else: | |
995 | self.shell.showtraceback() |
|
995 | self.shell.showtraceback() | |
996 |
|
996 | |||
997 |
|
997 | |||
998 | @register_magics |
|
998 | @register_magics | |
999 | class ConfigMagics(Magics): |
|
999 | class ConfigMagics(Magics): | |
1000 |
|
1000 | |||
1001 | def __init__(self, shell): |
|
1001 | def __init__(self, shell): | |
1002 | super(ConfigMagics, self).__init__(shell) |
|
1002 | super(ConfigMagics, self).__init__(shell) | |
1003 | self.configurables = [] |
|
1003 | self.configurables = [] | |
1004 |
|
1004 | |||
1005 | @line_magic |
|
1005 | @line_magic | |
1006 | def config(self, s): |
|
1006 | def config(self, s): | |
1007 | """configure IPython |
|
1007 | """configure IPython | |
1008 |
|
1008 | |||
1009 | %config Class[.trait=value] |
|
1009 | %config Class[.trait=value] | |
1010 |
|
1010 | |||
1011 | This magic exposes most of the IPython config system. Any |
|
1011 | This magic exposes most of the IPython config system. Any | |
1012 | Configurable class should be able to be configured with the simple |
|
1012 | Configurable class should be able to be configured with the simple | |
1013 | line:: |
|
1013 | line:: | |
1014 |
|
1014 | |||
1015 | %config Class.trait=value |
|
1015 | %config Class.trait=value | |
1016 |
|
1016 | |||
1017 | Where `value` will be resolved in the user's namespace, if it is an |
|
1017 | Where `value` will be resolved in the user's namespace, if it is an | |
1018 | expression or variable name. |
|
1018 | expression or variable name. | |
1019 |
|
1019 | |||
1020 | Examples |
|
1020 | Examples | |
1021 | -------- |
|
1021 | -------- | |
1022 |
|
1022 | |||
1023 | To see what classes are available for config, pass no arguments:: |
|
1023 | To see what classes are available for config, pass no arguments:: | |
1024 |
|
1024 | |||
1025 | In [1]: %config |
|
1025 | In [1]: %config | |
1026 | Available objects for config: |
|
1026 | Available objects for config: | |
1027 | TerminalInteractiveShell |
|
1027 | TerminalInteractiveShell | |
1028 | HistoryManager |
|
1028 | HistoryManager | |
1029 | PrefilterManager |
|
1029 | PrefilterManager | |
1030 | AliasManager |
|
1030 | AliasManager | |
1031 | IPCompleter |
|
1031 | IPCompleter | |
1032 | PromptManager |
|
1032 | PromptManager | |
1033 | DisplayFormatter |
|
1033 | DisplayFormatter | |
1034 |
|
1034 | |||
1035 | To view what is configurable on a given class, just pass the class |
|
1035 | To view what is configurable on a given class, just pass the class | |
1036 | name:: |
|
1036 | name:: | |
1037 |
|
1037 | |||
1038 | In [2]: %config IPCompleter |
|
1038 | In [2]: %config IPCompleter | |
1039 | IPCompleter options |
|
1039 | IPCompleter options | |
1040 | ----------------- |
|
1040 | ----------------- | |
1041 | IPCompleter.omit__names=<Enum> |
|
1041 | IPCompleter.omit__names=<Enum> | |
1042 | Current: 2 |
|
1042 | Current: 2 | |
1043 | Choices: (0, 1, 2) |
|
1043 | Choices: (0, 1, 2) | |
1044 | Instruct the completer to omit private method names |
|
1044 | Instruct the completer to omit private method names | |
1045 | Specifically, when completing on ``object.<tab>``. |
|
1045 | Specifically, when completing on ``object.<tab>``. | |
1046 | When 2 [default]: all names that start with '_' will be excluded. |
|
1046 | When 2 [default]: all names that start with '_' will be excluded. | |
1047 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
1047 | When 1: all 'magic' names (``__foo__``) will be excluded. | |
1048 | When 0: nothing will be excluded. |
|
1048 | When 0: nothing will be excluded. | |
1049 | IPCompleter.merge_completions=<CBool> |
|
1049 | IPCompleter.merge_completions=<CBool> | |
1050 | Current: True |
|
1050 | Current: True | |
1051 | Whether to merge completion results into a single list |
|
1051 | Whether to merge completion results into a single list | |
1052 | If False, only the completion results from the first non-empty completer |
|
1052 | If False, only the completion results from the first non-empty completer | |
1053 | will be returned. |
|
1053 | will be returned. | |
1054 | IPCompleter.limit_to__all__=<CBool> |
|
1054 | IPCompleter.limit_to__all__=<CBool> | |
1055 | Current: False |
|
1055 | Current: False | |
1056 | Instruct the completer to use __all__ for the completion |
|
1056 | Instruct the completer to use __all__ for the completion | |
1057 | Specifically, when completing on ``object.<tab>``. |
|
1057 | Specifically, when completing on ``object.<tab>``. | |
1058 | When True: only those names in obj.__all__ will be included. |
|
1058 | When True: only those names in obj.__all__ will be included. | |
1059 | When False [default]: the __all__ attribute is ignored |
|
1059 | When False [default]: the __all__ attribute is ignored | |
1060 | IPCompleter.greedy=<CBool> |
|
1060 | IPCompleter.greedy=<CBool> | |
1061 | Current: False |
|
1061 | Current: False | |
1062 | Activate greedy completion |
|
1062 | Activate greedy completion | |
1063 | This will enable completion on elements of lists, results of function calls, |
|
1063 | This will enable completion on elements of lists, results of function calls, | |
1064 | etc., but can be unsafe because the code is actually evaluated on TAB. |
|
1064 | etc., but can be unsafe because the code is actually evaluated on TAB. | |
1065 |
|
1065 | |||
1066 | but the real use is in setting values:: |
|
1066 | but the real use is in setting values:: | |
1067 |
|
1067 | |||
1068 | In [3]: %config IPCompleter.greedy = True |
|
1068 | In [3]: %config IPCompleter.greedy = True | |
1069 |
|
1069 | |||
1070 | and these values are read from the user_ns if they are variables:: |
|
1070 | and these values are read from the user_ns if they are variables:: | |
1071 |
|
1071 | |||
1072 | In [4]: feeling_greedy=False |
|
1072 | In [4]: feeling_greedy=False | |
1073 |
|
1073 | |||
1074 | In [5]: %config IPCompleter.greedy = feeling_greedy |
|
1074 | In [5]: %config IPCompleter.greedy = feeling_greedy | |
1075 |
|
1075 | |||
1076 | """ |
|
1076 | """ | |
1077 | from IPython.config.loader import Config |
|
1077 | from IPython.config.loader import Config | |
1078 | # some IPython objects are Configurable, but do not yet have |
|
1078 | # some IPython objects are Configurable, but do not yet have | |
1079 | # any configurable traits. Exclude them from the effects of |
|
1079 | # any configurable traits. Exclude them from the effects of | |
1080 | # this magic, as their presence is just noise: |
|
1080 | # this magic, as their presence is just noise: | |
1081 | configurables = [ c for c in self.shell.configurables |
|
1081 | configurables = [ c for c in self.shell.configurables | |
1082 | if c.__class__.class_traits(config=True) ] |
|
1082 | if c.__class__.class_traits(config=True) ] | |
1083 | classnames = [ c.__class__.__name__ for c in configurables ] |
|
1083 | classnames = [ c.__class__.__name__ for c in configurables ] | |
1084 |
|
1084 | |||
1085 | line = s.strip() |
|
1085 | line = s.strip() | |
1086 | if not line: |
|
1086 | if not line: | |
1087 | # print available configurable names |
|
1087 | # print available configurable names | |
1088 | print "Available objects for config:" |
|
1088 | print "Available objects for config:" | |
1089 | for name in classnames: |
|
1089 | for name in classnames: | |
1090 | print " ", name |
|
1090 | print " ", name | |
1091 | return |
|
1091 | return | |
1092 | elif line in classnames: |
|
1092 | elif line in classnames: | |
1093 | # `%config TerminalInteractiveShell` will print trait info for |
|
1093 | # `%config TerminalInteractiveShell` will print trait info for | |
1094 | # TerminalInteractiveShell |
|
1094 | # TerminalInteractiveShell | |
1095 | c = configurables[classnames.index(line)] |
|
1095 | c = configurables[classnames.index(line)] | |
1096 | cls = c.__class__ |
|
1096 | cls = c.__class__ | |
1097 | help = cls.class_get_help(c) |
|
1097 | help = cls.class_get_help(c) | |
1098 | # strip leading '--' from cl-args: |
|
1098 | # strip leading '--' from cl-args: | |
1099 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) |
|
1099 | help = re.sub(re.compile(r'^--', re.MULTILINE), '', help) | |
1100 | print help |
|
1100 | print help | |
1101 | return |
|
1101 | return | |
1102 | elif '=' not in line: |
|
1102 | elif '=' not in line: | |
1103 | raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line) |
|
1103 | raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line) | |
1104 |
|
1104 | |||
1105 |
|
1105 | |||
1106 | # otherwise, assume we are setting configurables. |
|
1106 | # otherwise, assume we are setting configurables. | |
1107 | # leave quotes on args when splitting, because we want |
|
1107 | # leave quotes on args when splitting, because we want | |
1108 | # unquoted args to eval in user_ns |
|
1108 | # unquoted args to eval in user_ns | |
1109 | cfg = Config() |
|
1109 | cfg = Config() | |
1110 | exec "cfg."+line in locals(), self.shell.user_ns |
|
1110 | exec "cfg."+line in locals(), self.shell.user_ns | |
1111 |
|
1111 | |||
1112 | for configurable in configurables: |
|
1112 | for configurable in configurables: | |
1113 | try: |
|
1113 | try: | |
1114 | configurable.update_config(cfg) |
|
1114 | configurable.update_config(cfg) | |
1115 | except Exception as e: |
|
1115 | except Exception as e: | |
1116 | error(e) |
|
1116 | error(e) | |
1117 |
|
1117 | |||
1118 |
|
1118 | |||
1119 | @register_magics |
|
1119 | @register_magics | |
1120 | class NamespaceMagics(Magics): |
|
1120 | class NamespaceMagics(Magics): | |
1121 | """Magics to manage various aspects of the user's namespace. |
|
1121 | """Magics to manage various aspects of the user's namespace. | |
1122 |
|
1122 | |||
1123 | These include listing variables, introspecting into them, etc. |
|
1123 | These include listing variables, introspecting into them, etc. | |
1124 | """ |
|
1124 | """ | |
1125 |
|
1125 | |||
1126 | @line_magic |
|
1126 | @line_magic | |
1127 | def pinfo(self, parameter_s='', namespaces=None): |
|
1127 | def pinfo(self, parameter_s='', namespaces=None): | |
1128 | """Provide detailed information about an object. |
|
1128 | """Provide detailed information about an object. | |
1129 |
|
1129 | |||
1130 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
1130 | '%pinfo object' is just a synonym for object? or ?object.""" | |
1131 |
|
1131 | |||
1132 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
1132 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
1133 |
|
1133 | |||
1134 |
|
1134 | |||
1135 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
1135 | # detail_level: 0 -> obj? , 1 -> obj?? | |
1136 | detail_level = 0 |
|
1136 | detail_level = 0 | |
1137 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
1137 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
1138 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
1138 | # happen if the user types 'pinfo foo?' at the cmd line. | |
1139 | pinfo,qmark1,oname,qmark2 = \ |
|
1139 | pinfo,qmark1,oname,qmark2 = \ | |
1140 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
1140 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
1141 | if pinfo or qmark1 or qmark2: |
|
1141 | if pinfo or qmark1 or qmark2: | |
1142 | detail_level = 1 |
|
1142 | detail_level = 1 | |
1143 | if "*" in oname: |
|
1143 | if "*" in oname: | |
1144 | self.psearch(oname) |
|
1144 | self.psearch(oname) | |
1145 | else: |
|
1145 | else: | |
1146 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
1146 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
1147 | namespaces=namespaces) |
|
1147 | namespaces=namespaces) | |
1148 |
|
1148 | |||
1149 | @line_magic |
|
1149 | @line_magic | |
1150 | def pinfo2(self, parameter_s='', namespaces=None): |
|
1150 | def pinfo2(self, parameter_s='', namespaces=None): | |
1151 | """Provide extra detailed information about an object. |
|
1151 | """Provide extra detailed information about an object. | |
1152 |
|
1152 | |||
1153 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
1153 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
1154 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
1154 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
1155 | namespaces=namespaces) |
|
1155 | namespaces=namespaces) | |
1156 |
|
1156 | |||
1157 | @skip_doctest |
|
1157 | @skip_doctest | |
1158 | @line_magic |
|
1158 | @line_magic | |
1159 | def pdef(self, parameter_s='', namespaces=None): |
|
1159 | def pdef(self, parameter_s='', namespaces=None): | |
1160 | """Print the definition header for any callable object. |
|
1160 | """Print the definition header for any callable object. | |
1161 |
|
1161 | |||
1162 | If the object is a class, print the constructor information. |
|
1162 | If the object is a class, print the constructor information. | |
1163 |
|
1163 | |||
1164 | Examples |
|
1164 | Examples | |
1165 | -------- |
|
1165 | -------- | |
1166 | :: |
|
1166 | :: | |
1167 |
|
1167 | |||
1168 | In [3]: %pdef urllib.urlopen |
|
1168 | In [3]: %pdef urllib.urlopen | |
1169 | urllib.urlopen(url, data=None, proxies=None) |
|
1169 | urllib.urlopen(url, data=None, proxies=None) | |
1170 | """ |
|
1170 | """ | |
1171 | self._inspect('pdef',parameter_s, namespaces) |
|
1171 | self._inspect('pdef',parameter_s, namespaces) | |
1172 |
|
1172 | |||
1173 | @line_magic |
|
1173 | @line_magic | |
1174 | def pdoc(self, parameter_s='', namespaces=None): |
|
1174 | def pdoc(self, parameter_s='', namespaces=None): | |
1175 | """Print the docstring for an object. |
|
1175 | """Print the docstring for an object. | |
1176 |
|
1176 | |||
1177 | If the given object is a class, it will print both the class and the |
|
1177 | If the given object is a class, it will print both the class and the | |
1178 | constructor docstrings.""" |
|
1178 | constructor docstrings.""" | |
1179 | self._inspect('pdoc',parameter_s, namespaces) |
|
1179 | self._inspect('pdoc',parameter_s, namespaces) | |
1180 |
|
1180 | |||
1181 | @line_magic |
|
1181 | @line_magic | |
1182 | def psource(self, parameter_s='', namespaces=None): |
|
1182 | def psource(self, parameter_s='', namespaces=None): | |
1183 | """Print (or run through pager) the source code for an object.""" |
|
1183 | """Print (or run through pager) the source code for an object.""" | |
1184 | self._inspect('psource',parameter_s, namespaces) |
|
1184 | self._inspect('psource',parameter_s, namespaces) | |
1185 |
|
1185 | |||
1186 | @line_magic |
|
1186 | @line_magic | |
1187 | def pfile(self, parameter_s=''): |
|
1187 | def pfile(self, parameter_s=''): | |
1188 | """Print (or run through pager) the file where an object is defined. |
|
1188 | """Print (or run through pager) the file where an object is defined. | |
1189 |
|
1189 | |||
1190 | The file opens at the line where the object definition begins. IPython |
|
1190 | The file opens at the line where the object definition begins. IPython | |
1191 | will honor the environment variable PAGER if set, and otherwise will |
|
1191 | will honor the environment variable PAGER if set, and otherwise will | |
1192 | do its best to print the file in a convenient form. |
|
1192 | do its best to print the file in a convenient form. | |
1193 |
|
1193 | |||
1194 | If the given argument is not an object currently defined, IPython will |
|
1194 | If the given argument is not an object currently defined, IPython will | |
1195 | try to interpret it as a filename (automatically adding a .py extension |
|
1195 | try to interpret it as a filename (automatically adding a .py extension | |
1196 | if needed). You can thus use %pfile as a syntax highlighting code |
|
1196 | if needed). You can thus use %pfile as a syntax highlighting code | |
1197 | viewer.""" |
|
1197 | viewer.""" | |
1198 |
|
1198 | |||
1199 | # first interpret argument as an object name |
|
1199 | # first interpret argument as an object name | |
1200 | out = self._inspect('pfile',parameter_s) |
|
1200 | out = self._inspect('pfile',parameter_s) | |
1201 | # if not, try the input as a filename |
|
1201 | # if not, try the input as a filename | |
1202 | if out == 'not found': |
|
1202 | if out == 'not found': | |
1203 | try: |
|
1203 | try: | |
1204 | filename = get_py_filename(parameter_s) |
|
1204 | filename = get_py_filename(parameter_s) | |
1205 | except IOError,msg: |
|
1205 | except IOError,msg: | |
1206 | print msg |
|
1206 | print msg | |
1207 | return |
|
1207 | return | |
1208 | page.page(self.shell.inspector.format(open(filename).read())) |
|
1208 | page.page(self.shell.inspector.format(open(filename).read())) | |
1209 |
|
1209 | |||
1210 | @line_magic |
|
1210 | @line_magic | |
1211 | def psearch(self, parameter_s=''): |
|
1211 | def psearch(self, parameter_s=''): | |
1212 | """Search for object in namespaces by wildcard. |
|
1212 | """Search for object in namespaces by wildcard. | |
1213 |
|
1213 | |||
1214 | %psearch [options] PATTERN [OBJECT TYPE] |
|
1214 | %psearch [options] PATTERN [OBJECT TYPE] | |
1215 |
|
1215 | |||
1216 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
1216 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
1217 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
1217 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
1218 | rest of the command line must be unchanged (options come first), so |
|
1218 | rest of the command line must be unchanged (options come first), so | |
1219 | for example the following forms are equivalent |
|
1219 | for example the following forms are equivalent | |
1220 |
|
1220 | |||
1221 | %psearch -i a* function |
|
1221 | %psearch -i a* function | |
1222 | -i a* function? |
|
1222 | -i a* function? | |
1223 | ?-i a* function |
|
1223 | ?-i a* function | |
1224 |
|
1224 | |||
1225 | Arguments: |
|
1225 | Arguments: | |
1226 |
|
1226 | |||
1227 | PATTERN |
|
1227 | PATTERN | |
1228 |
|
1228 | |||
1229 | where PATTERN is a string containing * as a wildcard similar to its |
|
1229 | where PATTERN is a string containing * as a wildcard similar to its | |
1230 | use in a shell. The pattern is matched in all namespaces on the |
|
1230 | use in a shell. The pattern is matched in all namespaces on the | |
1231 | search path. By default objects starting with a single _ are not |
|
1231 | search path. By default objects starting with a single _ are not | |
1232 | matched, many IPython generated objects have a single |
|
1232 | matched, many IPython generated objects have a single | |
1233 | underscore. The default is case insensitive matching. Matching is |
|
1233 | underscore. The default is case insensitive matching. Matching is | |
1234 | also done on the attributes of objects and not only on the objects |
|
1234 | also done on the attributes of objects and not only on the objects | |
1235 | in a module. |
|
1235 | in a module. | |
1236 |
|
1236 | |||
1237 | [OBJECT TYPE] |
|
1237 | [OBJECT TYPE] | |
1238 |
|
1238 | |||
1239 | Is the name of a python type from the types module. The name is |
|
1239 | Is the name of a python type from the types module. The name is | |
1240 | given in lowercase without the ending type, ex. StringType is |
|
1240 | given in lowercase without the ending type, ex. StringType is | |
1241 | written string. By adding a type here only objects matching the |
|
1241 | written string. By adding a type here only objects matching the | |
1242 | given type are matched. Using all here makes the pattern match all |
|
1242 | given type are matched. Using all here makes the pattern match all | |
1243 | types (this is the default). |
|
1243 | types (this is the default). | |
1244 |
|
1244 | |||
1245 | Options: |
|
1245 | Options: | |
1246 |
|
1246 | |||
1247 | -a: makes the pattern match even objects whose names start with a |
|
1247 | -a: makes the pattern match even objects whose names start with a | |
1248 | single underscore. These names are normally omitted from the |
|
1248 | single underscore. These names are normally omitted from the | |
1249 | search. |
|
1249 | search. | |
1250 |
|
1250 | |||
1251 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
1251 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
1252 | these options are given, the default is read from your configuration |
|
1252 | these options are given, the default is read from your configuration | |
1253 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. |
|
1253 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. | |
1254 | If this option is not specified in your configuration file, IPython's |
|
1254 | If this option is not specified in your configuration file, IPython's | |
1255 | internal default is to do a case sensitive search. |
|
1255 | internal default is to do a case sensitive search. | |
1256 |
|
1256 | |||
1257 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
1257 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
1258 | specify can be searched in any of the following namespaces: |
|
1258 | specify can be searched in any of the following namespaces: | |
1259 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
1259 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
1260 | 'builtin' and 'user' are the search defaults. Note that you should |
|
1260 | 'builtin' and 'user' are the search defaults. Note that you should | |
1261 | not use quotes when specifying namespaces. |
|
1261 | not use quotes when specifying namespaces. | |
1262 |
|
1262 | |||
1263 | 'Builtin' contains the python module builtin, 'user' contains all |
|
1263 | 'Builtin' contains the python module builtin, 'user' contains all | |
1264 | user data, 'alias' only contain the shell aliases and no python |
|
1264 | user data, 'alias' only contain the shell aliases and no python | |
1265 | objects, 'internal' contains objects used by IPython. The |
|
1265 | objects, 'internal' contains objects used by IPython. The | |
1266 | 'user_global' namespace is only used by embedded IPython instances, |
|
1266 | 'user_global' namespace is only used by embedded IPython instances, | |
1267 | and it contains module-level globals. You can add namespaces to the |
|
1267 | and it contains module-level globals. You can add namespaces to the | |
1268 | search with -s or exclude them with -e (these options can be given |
|
1268 | search with -s or exclude them with -e (these options can be given | |
1269 | more than once). |
|
1269 | more than once). | |
1270 |
|
1270 | |||
1271 | Examples |
|
1271 | Examples | |
1272 | -------- |
|
1272 | -------- | |
1273 | :: |
|
1273 | :: | |
1274 |
|
1274 | |||
1275 | %psearch a* -> objects beginning with an a |
|
1275 | %psearch a* -> objects beginning with an a | |
1276 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
1276 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
1277 | %psearch a* function -> all functions beginning with an a |
|
1277 | %psearch a* function -> all functions beginning with an a | |
1278 | %psearch re.e* -> objects beginning with an e in module re |
|
1278 | %psearch re.e* -> objects beginning with an e in module re | |
1279 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
1279 | %psearch r*.e* -> objects that start with e in modules starting in r | |
1280 | %psearch r*.* string -> all strings in modules beginning with r |
|
1280 | %psearch r*.* string -> all strings in modules beginning with r | |
1281 |
|
1281 | |||
1282 | Case sensitive search:: |
|
1282 | Case sensitive search:: | |
1283 |
|
1283 | |||
1284 | %psearch -c a* list all object beginning with lower case a |
|
1284 | %psearch -c a* list all object beginning with lower case a | |
1285 |
|
1285 | |||
1286 | Show objects beginning with a single _:: |
|
1286 | Show objects beginning with a single _:: | |
1287 |
|
1287 | |||
1288 | %psearch -a _* list objects beginning with a single underscore""" |
|
1288 | %psearch -a _* list objects beginning with a single underscore""" | |
1289 | try: |
|
1289 | try: | |
1290 | parameter_s.encode('ascii') |
|
1290 | parameter_s.encode('ascii') | |
1291 | except UnicodeEncodeError: |
|
1291 | except UnicodeEncodeError: | |
1292 | print 'Python identifiers can only contain ascii characters.' |
|
1292 | print 'Python identifiers can only contain ascii characters.' | |
1293 | return |
|
1293 | return | |
1294 |
|
1294 | |||
1295 | # default namespaces to be searched |
|
1295 | # default namespaces to be searched | |
1296 | def_search = ['user_local', 'user_global', 'builtin'] |
|
1296 | def_search = ['user_local', 'user_global', 'builtin'] | |
1297 |
|
1297 | |||
1298 | # Process options/args |
|
1298 | # Process options/args | |
1299 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
1299 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
1300 | opt = opts.get |
|
1300 | opt = opts.get | |
1301 | shell = self.shell |
|
1301 | shell = self.shell | |
1302 | psearch = shell.inspector.psearch |
|
1302 | psearch = shell.inspector.psearch | |
1303 |
|
1303 | |||
1304 | # select case options |
|
1304 | # select case options | |
1305 | if opts.has_key('i'): |
|
1305 | if opts.has_key('i'): | |
1306 | ignore_case = True |
|
1306 | ignore_case = True | |
1307 | elif opts.has_key('c'): |
|
1307 | elif opts.has_key('c'): | |
1308 | ignore_case = False |
|
1308 | ignore_case = False | |
1309 | else: |
|
1309 | else: | |
1310 | ignore_case = not shell.wildcards_case_sensitive |
|
1310 | ignore_case = not shell.wildcards_case_sensitive | |
1311 |
|
1311 | |||
1312 | # Build list of namespaces to search from user options |
|
1312 | # Build list of namespaces to search from user options | |
1313 | def_search.extend(opt('s',[])) |
|
1313 | def_search.extend(opt('s',[])) | |
1314 | ns_exclude = ns_exclude=opt('e',[]) |
|
1314 | ns_exclude = ns_exclude=opt('e',[]) | |
1315 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
1315 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
1316 |
|
1316 | |||
1317 | # Call the actual search |
|
1317 | # Call the actual search | |
1318 | try: |
|
1318 | try: | |
1319 | psearch(args,shell.ns_table,ns_search, |
|
1319 | psearch(args,shell.ns_table,ns_search, | |
1320 | show_all=opt('a'),ignore_case=ignore_case) |
|
1320 | show_all=opt('a'),ignore_case=ignore_case) | |
1321 | except: |
|
1321 | except: | |
1322 | shell.showtraceback() |
|
1322 | shell.showtraceback() | |
1323 |
|
1323 | |||
1324 | @skip_doctest |
|
1324 | @skip_doctest | |
1325 | @line_magic |
|
1325 | @line_magic | |
1326 | def who_ls(self, parameter_s=''): |
|
1326 | def who_ls(self, parameter_s=''): | |
1327 | """Return a sorted list of all interactive variables. |
|
1327 | """Return a sorted list of all interactive variables. | |
1328 |
|
1328 | |||
1329 | If arguments are given, only variables of types matching these |
|
1329 | If arguments are given, only variables of types matching these | |
1330 | arguments are returned. |
|
1330 | arguments are returned. | |
1331 |
|
1331 | |||
1332 | Examples |
|
1332 | Examples | |
1333 | -------- |
|
1333 | -------- | |
1334 |
|
1334 | |||
1335 | Define two variables and list them with who_ls:: |
|
1335 | Define two variables and list them with who_ls:: | |
1336 |
|
1336 | |||
1337 | In [1]: alpha = 123 |
|
1337 | In [1]: alpha = 123 | |
1338 |
|
1338 | |||
1339 | In [2]: beta = 'test' |
|
1339 | In [2]: beta = 'test' | |
1340 |
|
1340 | |||
1341 | In [3]: %who_ls |
|
1341 | In [3]: %who_ls | |
1342 | Out[3]: ['alpha', 'beta'] |
|
1342 | Out[3]: ['alpha', 'beta'] | |
1343 |
|
1343 | |||
1344 | In [4]: %who_ls int |
|
1344 | In [4]: %who_ls int | |
1345 | Out[4]: ['alpha'] |
|
1345 | Out[4]: ['alpha'] | |
1346 |
|
1346 | |||
1347 | In [5]: %who_ls str |
|
1347 | In [5]: %who_ls str | |
1348 | Out[5]: ['beta'] |
|
1348 | Out[5]: ['beta'] | |
1349 | """ |
|
1349 | """ | |
1350 |
|
1350 | |||
1351 | user_ns = self.shell.user_ns |
|
1351 | user_ns = self.shell.user_ns | |
1352 | user_ns_hidden = self.shell.user_ns_hidden |
|
1352 | user_ns_hidden = self.shell.user_ns_hidden | |
1353 | out = [ i for i in user_ns |
|
1353 | out = [ i for i in user_ns | |
1354 | if not i.startswith('_') \ |
|
1354 | if not i.startswith('_') \ | |
1355 | and not i in user_ns_hidden ] |
|
1355 | and not i in user_ns_hidden ] | |
1356 |
|
1356 | |||
1357 | typelist = parameter_s.split() |
|
1357 | typelist = parameter_s.split() | |
1358 | if typelist: |
|
1358 | if typelist: | |
1359 | typeset = set(typelist) |
|
1359 | typeset = set(typelist) | |
1360 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
1360 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
1361 |
|
1361 | |||
1362 | out.sort() |
|
1362 | out.sort() | |
1363 | return out |
|
1363 | return out | |
1364 |
|
1364 | |||
1365 | @skip_doctest |
|
1365 | @skip_doctest | |
1366 | @line_magic |
|
1366 | @line_magic | |
1367 | def who(self, parameter_s=''): |
|
1367 | def who(self, parameter_s=''): | |
1368 | """Print all interactive variables, with some minimal formatting. |
|
1368 | """Print all interactive variables, with some minimal formatting. | |
1369 |
|
1369 | |||
1370 | If any arguments are given, only variables whose type matches one of |
|
1370 | If any arguments are given, only variables whose type matches one of | |
1371 | these are printed. For example:: |
|
1371 | these are printed. For example:: | |
1372 |
|
1372 | |||
1373 | %who function str |
|
1373 | %who function str | |
1374 |
|
1374 | |||
1375 | will only list functions and strings, excluding all other types of |
|
1375 | will only list functions and strings, excluding all other types of | |
1376 | variables. To find the proper type names, simply use type(var) at a |
|
1376 | variables. To find the proper type names, simply use type(var) at a | |
1377 | command line to see how python prints type names. For example: |
|
1377 | command line to see how python prints type names. For example: | |
1378 |
|
1378 | |||
1379 | :: |
|
1379 | :: | |
1380 |
|
1380 | |||
1381 | In [1]: type('hello')\\ |
|
1381 | In [1]: type('hello')\\ | |
1382 | Out[1]: <type 'str'> |
|
1382 | Out[1]: <type 'str'> | |
1383 |
|
1383 | |||
1384 | indicates that the type name for strings is 'str'. |
|
1384 | indicates that the type name for strings is 'str'. | |
1385 |
|
1385 | |||
1386 | ``%who`` always excludes executed names loaded through your configuration |
|
1386 | ``%who`` always excludes executed names loaded through your configuration | |
1387 | file and things which are internal to IPython. |
|
1387 | file and things which are internal to IPython. | |
1388 |
|
1388 | |||
1389 | This is deliberate, as typically you may load many modules and the |
|
1389 | This is deliberate, as typically you may load many modules and the | |
1390 | purpose of %who is to show you only what you've manually defined. |
|
1390 | purpose of %who is to show you only what you've manually defined. | |
1391 |
|
1391 | |||
1392 | Examples |
|
1392 | Examples | |
1393 | -------- |
|
1393 | -------- | |
1394 |
|
1394 | |||
1395 | Define two variables and list them with who:: |
|
1395 | Define two variables and list them with who:: | |
1396 |
|
1396 | |||
1397 | In [1]: alpha = 123 |
|
1397 | In [1]: alpha = 123 | |
1398 |
|
1398 | |||
1399 | In [2]: beta = 'test' |
|
1399 | In [2]: beta = 'test' | |
1400 |
|
1400 | |||
1401 | In [3]: %who |
|
1401 | In [3]: %who | |
1402 | alpha beta |
|
1402 | alpha beta | |
1403 |
|
1403 | |||
1404 | In [4]: %who int |
|
1404 | In [4]: %who int | |
1405 | alpha |
|
1405 | alpha | |
1406 |
|
1406 | |||
1407 | In [5]: %who str |
|
1407 | In [5]: %who str | |
1408 | beta |
|
1408 | beta | |
1409 | """ |
|
1409 | """ | |
1410 |
|
1410 | |||
1411 |
varlist = self. |
|
1411 | varlist = self.who_ls(parameter_s) | |
1412 | if not varlist: |
|
1412 | if not varlist: | |
1413 | if parameter_s: |
|
1413 | if parameter_s: | |
1414 | print 'No variables match your requested type.' |
|
1414 | print 'No variables match your requested type.' | |
1415 | else: |
|
1415 | else: | |
1416 | print 'Interactive namespace is empty.' |
|
1416 | print 'Interactive namespace is empty.' | |
1417 | return |
|
1417 | return | |
1418 |
|
1418 | |||
1419 | # if we have variables, move on... |
|
1419 | # if we have variables, move on... | |
1420 | count = 0 |
|
1420 | count = 0 | |
1421 | for i in varlist: |
|
1421 | for i in varlist: | |
1422 | print i+'\t', |
|
1422 | print i+'\t', | |
1423 | count += 1 |
|
1423 | count += 1 | |
1424 | if count > 8: |
|
1424 | if count > 8: | |
1425 | count = 0 |
|
1425 | count = 0 | |
1426 |
|
1426 | |||
1427 |
|
1427 | |||
1428 |
|
1428 | |||
1429 | @skip_doctest |
|
1429 | @skip_doctest | |
1430 | @line_magic |
|
1430 | @line_magic | |
1431 | def whos(self, parameter_s=''): |
|
1431 | def whos(self, parameter_s=''): | |
1432 | """Like %who, but gives some extra information about each variable. |
|
1432 | """Like %who, but gives some extra information about each variable. | |
1433 |
|
1433 | |||
1434 | The same type filtering of %who can be applied here. |
|
1434 | The same type filtering of %who can be applied here. | |
1435 |
|
1435 | |||
1436 | For all variables, the type is printed. Additionally it prints: |
|
1436 | For all variables, the type is printed. Additionally it prints: | |
1437 |
|
1437 | |||
1438 | - For {},[],(): their length. |
|
1438 | - For {},[],(): their length. | |
1439 |
|
1439 | |||
1440 | - For numpy arrays, a summary with shape, number of |
|
1440 | - For numpy arrays, a summary with shape, number of | |
1441 | elements, typecode and size in memory. |
|
1441 | elements, typecode and size in memory. | |
1442 |
|
1442 | |||
1443 | - Everything else: a string representation, snipping their middle if |
|
1443 | - Everything else: a string representation, snipping their middle if | |
1444 | too long. |
|
1444 | too long. | |
1445 |
|
1445 | |||
1446 | Examples |
|
1446 | Examples | |
1447 | -------- |
|
1447 | -------- | |
1448 |
|
1448 | |||
1449 | Define two variables and list them with whos:: |
|
1449 | Define two variables and list them with whos:: | |
1450 |
|
1450 | |||
1451 | In [1]: alpha = 123 |
|
1451 | In [1]: alpha = 123 | |
1452 |
|
1452 | |||
1453 | In [2]: beta = 'test' |
|
1453 | In [2]: beta = 'test' | |
1454 |
|
1454 | |||
1455 | In [3]: %whos |
|
1455 | In [3]: %whos | |
1456 | Variable Type Data/Info |
|
1456 | Variable Type Data/Info | |
1457 | -------------------------------- |
|
1457 | -------------------------------- | |
1458 | alpha int 123 |
|
1458 | alpha int 123 | |
1459 | beta str test |
|
1459 | beta str test | |
1460 | """ |
|
1460 | """ | |
1461 |
|
1461 | |||
1462 |
varnames = self. |
|
1462 | varnames = self.who_ls(parameter_s) | |
1463 | if not varnames: |
|
1463 | if not varnames: | |
1464 | if parameter_s: |
|
1464 | if parameter_s: | |
1465 | print 'No variables match your requested type.' |
|
1465 | print 'No variables match your requested type.' | |
1466 | else: |
|
1466 | else: | |
1467 | print 'Interactive namespace is empty.' |
|
1467 | print 'Interactive namespace is empty.' | |
1468 | return |
|
1468 | return | |
1469 |
|
1469 | |||
1470 | # if we have variables, move on... |
|
1470 | # if we have variables, move on... | |
1471 |
|
1471 | |||
1472 | # for these types, show len() instead of data: |
|
1472 | # for these types, show len() instead of data: | |
1473 | seq_types = ['dict', 'list', 'tuple'] |
|
1473 | seq_types = ['dict', 'list', 'tuple'] | |
1474 |
|
1474 | |||
1475 | # for numpy arrays, display summary info |
|
1475 | # for numpy arrays, display summary info | |
1476 | ndarray_type = None |
|
1476 | ndarray_type = None | |
1477 | if 'numpy' in sys.modules: |
|
1477 | if 'numpy' in sys.modules: | |
1478 | try: |
|
1478 | try: | |
1479 | from numpy import ndarray |
|
1479 | from numpy import ndarray | |
1480 | except ImportError: |
|
1480 | except ImportError: | |
1481 | pass |
|
1481 | pass | |
1482 | else: |
|
1482 | else: | |
1483 | ndarray_type = ndarray.__name__ |
|
1483 | ndarray_type = ndarray.__name__ | |
1484 |
|
1484 | |||
1485 | # Find all variable names and types so we can figure out column sizes |
|
1485 | # Find all variable names and types so we can figure out column sizes | |
1486 | def get_vars(i): |
|
1486 | def get_vars(i): | |
1487 | return self.shell.user_ns[i] |
|
1487 | return self.shell.user_ns[i] | |
1488 |
|
1488 | |||
1489 | # some types are well known and can be shorter |
|
1489 | # some types are well known and can be shorter | |
1490 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
1490 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
1491 | def type_name(v): |
|
1491 | def type_name(v): | |
1492 | tn = type(v).__name__ |
|
1492 | tn = type(v).__name__ | |
1493 | return abbrevs.get(tn,tn) |
|
1493 | return abbrevs.get(tn,tn) | |
1494 |
|
1494 | |||
1495 | varlist = map(get_vars,varnames) |
|
1495 | varlist = map(get_vars,varnames) | |
1496 |
|
1496 | |||
1497 | typelist = [] |
|
1497 | typelist = [] | |
1498 | for vv in varlist: |
|
1498 | for vv in varlist: | |
1499 | tt = type_name(vv) |
|
1499 | tt = type_name(vv) | |
1500 |
|
1500 | |||
1501 | if tt=='instance': |
|
1501 | if tt=='instance': | |
1502 | typelist.append( abbrevs.get(str(vv.__class__), |
|
1502 | typelist.append( abbrevs.get(str(vv.__class__), | |
1503 | str(vv.__class__))) |
|
1503 | str(vv.__class__))) | |
1504 | else: |
|
1504 | else: | |
1505 | typelist.append(tt) |
|
1505 | typelist.append(tt) | |
1506 |
|
1506 | |||
1507 | # column labels and # of spaces as separator |
|
1507 | # column labels and # of spaces as separator | |
1508 | varlabel = 'Variable' |
|
1508 | varlabel = 'Variable' | |
1509 | typelabel = 'Type' |
|
1509 | typelabel = 'Type' | |
1510 | datalabel = 'Data/Info' |
|
1510 | datalabel = 'Data/Info' | |
1511 | colsep = 3 |
|
1511 | colsep = 3 | |
1512 | # variable format strings |
|
1512 | # variable format strings | |
1513 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
1513 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" | |
1514 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
1514 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
1515 | # find the size of the columns to format the output nicely |
|
1515 | # find the size of the columns to format the output nicely | |
1516 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
1516 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
1517 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
1517 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
1518 | # table header |
|
1518 | # table header | |
1519 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
1519 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
1520 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
1520 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
1521 | # and the table itself |
|
1521 | # and the table itself | |
1522 | kb = 1024 |
|
1522 | kb = 1024 | |
1523 | Mb = 1048576 # kb**2 |
|
1523 | Mb = 1048576 # kb**2 | |
1524 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
1524 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
1525 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), |
|
1525 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), | |
1526 | if vtype in seq_types: |
|
1526 | if vtype in seq_types: | |
1527 | print "n="+str(len(var)) |
|
1527 | print "n="+str(len(var)) | |
1528 | elif vtype == ndarray_type: |
|
1528 | elif vtype == ndarray_type: | |
1529 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
1529 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
1530 | if vtype==ndarray_type: |
|
1530 | if vtype==ndarray_type: | |
1531 | # numpy |
|
1531 | # numpy | |
1532 | vsize = var.size |
|
1532 | vsize = var.size | |
1533 | vbytes = vsize*var.itemsize |
|
1533 | vbytes = vsize*var.itemsize | |
1534 | vdtype = var.dtype |
|
1534 | vdtype = var.dtype | |
1535 |
|
1535 | |||
1536 | if vbytes < 100000: |
|
1536 | if vbytes < 100000: | |
1537 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1537 | print aformat % (vshape,vsize,vdtype,vbytes) | |
1538 | else: |
|
1538 | else: | |
1539 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1539 | print aformat % (vshape,vsize,vdtype,vbytes), | |
1540 | if vbytes < Mb: |
|
1540 | if vbytes < Mb: | |
1541 | print '(%s kb)' % (vbytes/kb,) |
|
1541 | print '(%s kb)' % (vbytes/kb,) | |
1542 | else: |
|
1542 | else: | |
1543 | print '(%s Mb)' % (vbytes/Mb,) |
|
1543 | print '(%s Mb)' % (vbytes/Mb,) | |
1544 | else: |
|
1544 | else: | |
1545 | try: |
|
1545 | try: | |
1546 | vstr = str(var) |
|
1546 | vstr = str(var) | |
1547 | except UnicodeEncodeError: |
|
1547 | except UnicodeEncodeError: | |
1548 | vstr = unicode(var).encode(DEFAULT_ENCODING, |
|
1548 | vstr = unicode(var).encode(DEFAULT_ENCODING, | |
1549 | 'backslashreplace') |
|
1549 | 'backslashreplace') | |
1550 | except: |
|
1550 | except: | |
1551 | vstr = "<object with id %d (str() failed)>" % id(var) |
|
1551 | vstr = "<object with id %d (str() failed)>" % id(var) | |
1552 | vstr = vstr.replace('\n','\\n') |
|
1552 | vstr = vstr.replace('\n','\\n') | |
1553 | if len(vstr) < 50: |
|
1553 | if len(vstr) < 50: | |
1554 | print vstr |
|
1554 | print vstr | |
1555 | else: |
|
1555 | else: | |
1556 | print vstr[:25] + "<...>" + vstr[-25:] |
|
1556 | print vstr[:25] + "<...>" + vstr[-25:] | |
1557 |
|
1557 | |||
1558 | @line_magic |
|
1558 | @line_magic | |
1559 | def reset(self, parameter_s=''): |
|
1559 | def reset(self, parameter_s=''): | |
1560 | """Resets the namespace by removing all names defined by the user, if |
|
1560 | """Resets the namespace by removing all names defined by the user, if | |
1561 | called without arguments, or by removing some types of objects, such |
|
1561 | called without arguments, or by removing some types of objects, such | |
1562 | as everything currently in IPython's In[] and Out[] containers (see |
|
1562 | as everything currently in IPython's In[] and Out[] containers (see | |
1563 | the parameters for details). |
|
1563 | the parameters for details). | |
1564 |
|
1564 | |||
1565 | Parameters |
|
1565 | Parameters | |
1566 | ---------- |
|
1566 | ---------- | |
1567 | -f : force reset without asking for confirmation. |
|
1567 | -f : force reset without asking for confirmation. | |
1568 |
|
1568 | |||
1569 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
1569 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. | |
1570 | References to objects may be kept. By default (without this option), |
|
1570 | References to objects may be kept. By default (without this option), | |
1571 | we do a 'hard' reset, giving you a new session and removing all |
|
1571 | we do a 'hard' reset, giving you a new session and removing all | |
1572 | references to objects from the current session. |
|
1572 | references to objects from the current session. | |
1573 |
|
1573 | |||
1574 | in : reset input history |
|
1574 | in : reset input history | |
1575 |
|
1575 | |||
1576 | out : reset output history |
|
1576 | out : reset output history | |
1577 |
|
1577 | |||
1578 | dhist : reset directory history |
|
1578 | dhist : reset directory history | |
1579 |
|
1579 | |||
1580 | array : reset only variables that are NumPy arrays |
|
1580 | array : reset only variables that are NumPy arrays | |
1581 |
|
1581 | |||
1582 | See Also |
|
1582 | See Also | |
1583 | -------- |
|
1583 | -------- | |
1584 | magic_reset_selective : invoked as ``%reset_selective`` |
|
1584 | magic_reset_selective : invoked as ``%reset_selective`` | |
1585 |
|
1585 | |||
1586 | Examples |
|
1586 | Examples | |
1587 | -------- |
|
1587 | -------- | |
1588 | :: |
|
1588 | :: | |
1589 |
|
1589 | |||
1590 | In [6]: a = 1 |
|
1590 | In [6]: a = 1 | |
1591 |
|
1591 | |||
1592 | In [7]: a |
|
1592 | In [7]: a | |
1593 | Out[7]: 1 |
|
1593 | Out[7]: 1 | |
1594 |
|
1594 | |||
1595 | In [8]: 'a' in _ip.user_ns |
|
1595 | In [8]: 'a' in _ip.user_ns | |
1596 | Out[8]: True |
|
1596 | Out[8]: True | |
1597 |
|
1597 | |||
1598 | In [9]: %reset -f |
|
1598 | In [9]: %reset -f | |
1599 |
|
1599 | |||
1600 | In [1]: 'a' in _ip.user_ns |
|
1600 | In [1]: 'a' in _ip.user_ns | |
1601 | Out[1]: False |
|
1601 | Out[1]: False | |
1602 |
|
1602 | |||
1603 | In [2]: %reset -f in |
|
1603 | In [2]: %reset -f in | |
1604 | Flushing input history |
|
1604 | Flushing input history | |
1605 |
|
1605 | |||
1606 | In [3]: %reset -f dhist in |
|
1606 | In [3]: %reset -f dhist in | |
1607 | Flushing directory history |
|
1607 | Flushing directory history | |
1608 | Flushing input history |
|
1608 | Flushing input history | |
1609 |
|
1609 | |||
1610 | Notes |
|
1610 | Notes | |
1611 | ----- |
|
1611 | ----- | |
1612 | Calling this magic from clients that do not implement standard input, |
|
1612 | Calling this magic from clients that do not implement standard input, | |
1613 | such as the ipython notebook interface, will reset the namespace |
|
1613 | such as the ipython notebook interface, will reset the namespace | |
1614 | without confirmation. |
|
1614 | without confirmation. | |
1615 | """ |
|
1615 | """ | |
1616 | opts, args = self.parse_options(parameter_s,'sf', mode='list') |
|
1616 | opts, args = self.parse_options(parameter_s,'sf', mode='list') | |
1617 | if 'f' in opts: |
|
1617 | if 'f' in opts: | |
1618 | ans = True |
|
1618 | ans = True | |
1619 | else: |
|
1619 | else: | |
1620 | try: |
|
1620 | try: | |
1621 | ans = self.shell.ask_yes_no( |
|
1621 | ans = self.shell.ask_yes_no( | |
1622 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n') |
|
1622 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n') | |
1623 | except StdinNotImplementedError: |
|
1623 | except StdinNotImplementedError: | |
1624 | ans = True |
|
1624 | ans = True | |
1625 | if not ans: |
|
1625 | if not ans: | |
1626 | print 'Nothing done.' |
|
1626 | print 'Nothing done.' | |
1627 | return |
|
1627 | return | |
1628 |
|
1628 | |||
1629 | if 's' in opts: # Soft reset |
|
1629 | if 's' in opts: # Soft reset | |
1630 | user_ns = self.shell.user_ns |
|
1630 | user_ns = self.shell.user_ns | |
1631 | for i in self.magic_who_ls(): |
|
1631 | for i in self.magic_who_ls(): | |
1632 | del(user_ns[i]) |
|
1632 | del(user_ns[i]) | |
1633 | elif len(args) == 0: # Hard reset |
|
1633 | elif len(args) == 0: # Hard reset | |
1634 | self.shell.reset(new_session = False) |
|
1634 | self.shell.reset(new_session = False) | |
1635 |
|
1635 | |||
1636 | # reset in/out/dhist/array: previously extensinions/clearcmd.py |
|
1636 | # reset in/out/dhist/array: previously extensinions/clearcmd.py | |
1637 | ip = self.shell |
|
1637 | ip = self.shell | |
1638 | user_ns = self.shell.user_ns # local lookup, heavily used |
|
1638 | user_ns = self.shell.user_ns # local lookup, heavily used | |
1639 |
|
1639 | |||
1640 | for target in args: |
|
1640 | for target in args: | |
1641 | target = target.lower() # make matches case insensitive |
|
1641 | target = target.lower() # make matches case insensitive | |
1642 | if target == 'out': |
|
1642 | if target == 'out': | |
1643 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) |
|
1643 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) | |
1644 | self.shell.displayhook.flush() |
|
1644 | self.shell.displayhook.flush() | |
1645 |
|
1645 | |||
1646 | elif target == 'in': |
|
1646 | elif target == 'in': | |
1647 | print "Flushing input history" |
|
1647 | print "Flushing input history" | |
1648 | pc = self.shell.displayhook.prompt_count + 1 |
|
1648 | pc = self.shell.displayhook.prompt_count + 1 | |
1649 | for n in range(1, pc): |
|
1649 | for n in range(1, pc): | |
1650 | key = '_i'+repr(n) |
|
1650 | key = '_i'+repr(n) | |
1651 | user_ns.pop(key,None) |
|
1651 | user_ns.pop(key,None) | |
1652 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) |
|
1652 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) | |
1653 | hm = ip.history_manager |
|
1653 | hm = ip.history_manager | |
1654 | # don't delete these, as %save and %macro depending on the length |
|
1654 | # don't delete these, as %save and %macro depending on the length | |
1655 | # of these lists to be preserved |
|
1655 | # of these lists to be preserved | |
1656 | hm.input_hist_parsed[:] = [''] * pc |
|
1656 | hm.input_hist_parsed[:] = [''] * pc | |
1657 | hm.input_hist_raw[:] = [''] * pc |
|
1657 | hm.input_hist_raw[:] = [''] * pc | |
1658 | # hm has internal machinery for _i,_ii,_iii, clear it out |
|
1658 | # hm has internal machinery for _i,_ii,_iii, clear it out | |
1659 | hm._i = hm._ii = hm._iii = hm._i00 = u'' |
|
1659 | hm._i = hm._ii = hm._iii = hm._i00 = u'' | |
1660 |
|
1660 | |||
1661 | elif target == 'array': |
|
1661 | elif target == 'array': | |
1662 | # Support cleaning up numpy arrays |
|
1662 | # Support cleaning up numpy arrays | |
1663 | try: |
|
1663 | try: | |
1664 | from numpy import ndarray |
|
1664 | from numpy import ndarray | |
1665 | # This must be done with items and not iteritems because we're |
|
1665 | # This must be done with items and not iteritems because we're | |
1666 | # going to modify the dict in-place. |
|
1666 | # going to modify the dict in-place. | |
1667 | for x,val in user_ns.items(): |
|
1667 | for x,val in user_ns.items(): | |
1668 | if isinstance(val,ndarray): |
|
1668 | if isinstance(val,ndarray): | |
1669 | del user_ns[x] |
|
1669 | del user_ns[x] | |
1670 | except ImportError: |
|
1670 | except ImportError: | |
1671 | print "reset array only works if Numpy is available." |
|
1671 | print "reset array only works if Numpy is available." | |
1672 |
|
1672 | |||
1673 | elif target == 'dhist': |
|
1673 | elif target == 'dhist': | |
1674 | print "Flushing directory history" |
|
1674 | print "Flushing directory history" | |
1675 | del user_ns['_dh'][:] |
|
1675 | del user_ns['_dh'][:] | |
1676 |
|
1676 | |||
1677 | else: |
|
1677 | else: | |
1678 | print "Don't know how to reset ", |
|
1678 | print "Don't know how to reset ", | |
1679 | print target + ", please run `%reset?` for details" |
|
1679 | print target + ", please run `%reset?` for details" | |
1680 |
|
1680 | |||
1681 | gc.collect() |
|
1681 | gc.collect() | |
1682 |
|
1682 | |||
1683 | @line_magic |
|
1683 | @line_magic | |
1684 | def reset_selective(self, parameter_s=''): |
|
1684 | def reset_selective(self, parameter_s=''): | |
1685 | """Resets the namespace by removing names defined by the user. |
|
1685 | """Resets the namespace by removing names defined by the user. | |
1686 |
|
1686 | |||
1687 | Input/Output history are left around in case you need them. |
|
1687 | Input/Output history are left around in case you need them. | |
1688 |
|
1688 | |||
1689 | %reset_selective [-f] regex |
|
1689 | %reset_selective [-f] regex | |
1690 |
|
1690 | |||
1691 | No action is taken if regex is not included |
|
1691 | No action is taken if regex is not included | |
1692 |
|
1692 | |||
1693 | Options |
|
1693 | Options | |
1694 | -f : force reset without asking for confirmation. |
|
1694 | -f : force reset without asking for confirmation. | |
1695 |
|
1695 | |||
1696 | See Also |
|
1696 | See Also | |
1697 | -------- |
|
1697 | -------- | |
1698 | magic_reset : invoked as ``%reset`` |
|
1698 | magic_reset : invoked as ``%reset`` | |
1699 |
|
1699 | |||
1700 | Examples |
|
1700 | Examples | |
1701 | -------- |
|
1701 | -------- | |
1702 |
|
1702 | |||
1703 | We first fully reset the namespace so your output looks identical to |
|
1703 | We first fully reset the namespace so your output looks identical to | |
1704 | this example for pedagogical reasons; in practice you do not need a |
|
1704 | this example for pedagogical reasons; in practice you do not need a | |
1705 | full reset:: |
|
1705 | full reset:: | |
1706 |
|
1706 | |||
1707 | In [1]: %reset -f |
|
1707 | In [1]: %reset -f | |
1708 |
|
1708 | |||
1709 | Now, with a clean namespace we can make a few variables and use |
|
1709 | Now, with a clean namespace we can make a few variables and use | |
1710 | ``%reset_selective`` to only delete names that match our regexp:: |
|
1710 | ``%reset_selective`` to only delete names that match our regexp:: | |
1711 |
|
1711 | |||
1712 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1712 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
1713 |
|
1713 | |||
1714 | In [3]: who_ls |
|
1714 | In [3]: who_ls | |
1715 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1715 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
1716 |
|
1716 | |||
1717 | In [4]: %reset_selective -f b[2-3]m |
|
1717 | In [4]: %reset_selective -f b[2-3]m | |
1718 |
|
1718 | |||
1719 | In [5]: who_ls |
|
1719 | In [5]: who_ls | |
1720 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1720 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1721 |
|
1721 | |||
1722 | In [6]: %reset_selective -f d |
|
1722 | In [6]: %reset_selective -f d | |
1723 |
|
1723 | |||
1724 | In [7]: who_ls |
|
1724 | In [7]: who_ls | |
1725 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1725 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1726 |
|
1726 | |||
1727 | In [8]: %reset_selective -f c |
|
1727 | In [8]: %reset_selective -f c | |
1728 |
|
1728 | |||
1729 | In [9]: who_ls |
|
1729 | In [9]: who_ls | |
1730 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1730 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1731 |
|
1731 | |||
1732 | In [10]: %reset_selective -f b |
|
1732 | In [10]: %reset_selective -f b | |
1733 |
|
1733 | |||
1734 | In [11]: who_ls |
|
1734 | In [11]: who_ls | |
1735 | Out[11]: ['a'] |
|
1735 | Out[11]: ['a'] | |
1736 |
|
1736 | |||
1737 | Notes |
|
1737 | Notes | |
1738 | ----- |
|
1738 | ----- | |
1739 | Calling this magic from clients that do not implement standard input, |
|
1739 | Calling this magic from clients that do not implement standard input, | |
1740 | such as the ipython notebook interface, will reset the namespace |
|
1740 | such as the ipython notebook interface, will reset the namespace | |
1741 | without confirmation. |
|
1741 | without confirmation. | |
1742 | """ |
|
1742 | """ | |
1743 |
|
1743 | |||
1744 | opts, regex = self.parse_options(parameter_s,'f') |
|
1744 | opts, regex = self.parse_options(parameter_s,'f') | |
1745 |
|
1745 | |||
1746 | if opts.has_key('f'): |
|
1746 | if opts.has_key('f'): | |
1747 | ans = True |
|
1747 | ans = True | |
1748 | else: |
|
1748 | else: | |
1749 | try: |
|
1749 | try: | |
1750 | ans = self.shell.ask_yes_no( |
|
1750 | ans = self.shell.ask_yes_no( | |
1751 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", |
|
1751 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", | |
1752 | default='n') |
|
1752 | default='n') | |
1753 | except StdinNotImplementedError: |
|
1753 | except StdinNotImplementedError: | |
1754 | ans = True |
|
1754 | ans = True | |
1755 | if not ans: |
|
1755 | if not ans: | |
1756 | print 'Nothing done.' |
|
1756 | print 'Nothing done.' | |
1757 | return |
|
1757 | return | |
1758 | user_ns = self.shell.user_ns |
|
1758 | user_ns = self.shell.user_ns | |
1759 | if not regex: |
|
1759 | if not regex: | |
1760 | print 'No regex pattern specified. Nothing done.' |
|
1760 | print 'No regex pattern specified. Nothing done.' | |
1761 | return |
|
1761 | return | |
1762 | else: |
|
1762 | else: | |
1763 | try: |
|
1763 | try: | |
1764 | m = re.compile(regex) |
|
1764 | m = re.compile(regex) | |
1765 | except TypeError: |
|
1765 | except TypeError: | |
1766 | raise TypeError('regex must be a string or compiled pattern') |
|
1766 | raise TypeError('regex must be a string or compiled pattern') | |
1767 | for i in self.magic_who_ls(): |
|
1767 | for i in self.magic_who_ls(): | |
1768 | if m.search(i): |
|
1768 | if m.search(i): | |
1769 | del(user_ns[i]) |
|
1769 | del(user_ns[i]) | |
1770 |
|
1770 | |||
1771 | @line_magic |
|
1771 | @line_magic | |
1772 | def xdel(self, parameter_s=''): |
|
1772 | def xdel(self, parameter_s=''): | |
1773 | """Delete a variable, trying to clear it from anywhere that |
|
1773 | """Delete a variable, trying to clear it from anywhere that | |
1774 | IPython's machinery has references to it. By default, this uses |
|
1774 | IPython's machinery has references to it. By default, this uses | |
1775 | the identity of the named object in the user namespace to remove |
|
1775 | the identity of the named object in the user namespace to remove | |
1776 | references held under other names. The object is also removed |
|
1776 | references held under other names. The object is also removed | |
1777 | from the output history. |
|
1777 | from the output history. | |
1778 |
|
1778 | |||
1779 | Options |
|
1779 | Options | |
1780 | -n : Delete the specified name from all namespaces, without |
|
1780 | -n : Delete the specified name from all namespaces, without | |
1781 | checking their identity. |
|
1781 | checking their identity. | |
1782 | """ |
|
1782 | """ | |
1783 | opts, varname = self.parse_options(parameter_s,'n') |
|
1783 | opts, varname = self.parse_options(parameter_s,'n') | |
1784 | try: |
|
1784 | try: | |
1785 | self.shell.del_var(varname, ('n' in opts)) |
|
1785 | self.shell.del_var(varname, ('n' in opts)) | |
1786 | except (NameError, ValueError) as e: |
|
1786 | except (NameError, ValueError) as e: | |
1787 | print type(e).__name__ +": "+ str(e) |
|
1787 | print type(e).__name__ +": "+ str(e) | |
1788 |
|
1788 | |||
1789 |
|
1789 | |||
1790 | @register_magics |
|
1790 | @register_magics | |
1791 | class ExecutionMagics(Magics): |
|
1791 | class ExecutionMagics(Magics): | |
1792 | """Magics related to code execution, debugging, profiling, etc. |
|
1792 | """Magics related to code execution, debugging, profiling, etc. | |
1793 |
|
1793 | |||
1794 | """ |
|
1794 | """ | |
1795 |
|
1795 | |||
1796 | def __init__(self, shell): |
|
1796 | def __init__(self, shell): | |
1797 | super(ExecutionMagics, self).__init__(shell) |
|
1797 | super(ExecutionMagics, self).__init__(shell) | |
1798 | if profile is None: |
|
1798 | if profile is None: | |
1799 | self.prun = self.profile_missing_notice |
|
1799 | self.prun = self.profile_missing_notice | |
1800 | # Default execution function used to actually run user code. |
|
1800 | # Default execution function used to actually run user code. | |
1801 | self.default_runner = None |
|
1801 | self.default_runner = None | |
1802 |
|
1802 | |||
1803 | def profile_missing_notice(self, *args, **kwargs): |
|
1803 | def profile_missing_notice(self, *args, **kwargs): | |
1804 | error("""\ |
|
1804 | error("""\ | |
1805 | The profile module could not be found. It has been removed from the standard |
|
1805 | The profile module could not be found. It has been removed from the standard | |
1806 | python packages because of its non-free license. To use profiling, install the |
|
1806 | python packages because of its non-free license. To use profiling, install the | |
1807 | python-profiler package from non-free.""") |
|
1807 | python-profiler package from non-free.""") | |
1808 |
|
1808 | |||
1809 | @skip_doctest |
|
1809 | @skip_doctest | |
1810 | @line_magic |
|
1810 | @line_magic | |
1811 | def prun(self, parameter_s='',user_mode=1, |
|
1811 | def prun(self, parameter_s='',user_mode=1, | |
1812 | opts=None,arg_lst=None,prog_ns=None): |
|
1812 | opts=None,arg_lst=None,prog_ns=None): | |
1813 |
|
1813 | |||
1814 | """Run a statement through the python code profiler. |
|
1814 | """Run a statement through the python code profiler. | |
1815 |
|
1815 | |||
1816 | Usage: |
|
1816 | Usage: | |
1817 | %prun [options] statement |
|
1817 | %prun [options] statement | |
1818 |
|
1818 | |||
1819 | The given statement (which doesn't require quote marks) is run via the |
|
1819 | The given statement (which doesn't require quote marks) is run via the | |
1820 | python profiler in a manner similar to the profile.run() function. |
|
1820 | python profiler in a manner similar to the profile.run() function. | |
1821 | Namespaces are internally managed to work correctly; profile.run |
|
1821 | Namespaces are internally managed to work correctly; profile.run | |
1822 | cannot be used in IPython because it makes certain assumptions about |
|
1822 | cannot be used in IPython because it makes certain assumptions about | |
1823 | namespaces which do not hold under IPython. |
|
1823 | namespaces which do not hold under IPython. | |
1824 |
|
1824 | |||
1825 | Options: |
|
1825 | Options: | |
1826 |
|
1826 | |||
1827 | -l <limit>: you can place restrictions on what or how much of the |
|
1827 | -l <limit>: you can place restrictions on what or how much of the | |
1828 | profile gets printed. The limit value can be: |
|
1828 | profile gets printed. The limit value can be: | |
1829 |
|
1829 | |||
1830 | * A string: only information for function names containing this string |
|
1830 | * A string: only information for function names containing this string | |
1831 | is printed. |
|
1831 | is printed. | |
1832 |
|
1832 | |||
1833 | * An integer: only these many lines are printed. |
|
1833 | * An integer: only these many lines are printed. | |
1834 |
|
1834 | |||
1835 | * A float (between 0 and 1): this fraction of the report is printed |
|
1835 | * A float (between 0 and 1): this fraction of the report is printed | |
1836 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1836 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1837 |
|
1837 | |||
1838 | You can combine several limits with repeated use of the option. For |
|
1838 | You can combine several limits with repeated use of the option. For | |
1839 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1839 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1840 | information about class constructors. |
|
1840 | information about class constructors. | |
1841 |
|
1841 | |||
1842 | -r: return the pstats.Stats object generated by the profiling. This |
|
1842 | -r: return the pstats.Stats object generated by the profiling. This | |
1843 | object has all the information about the profile in it, and you can |
|
1843 | object has all the information about the profile in it, and you can | |
1844 | later use it for further analysis or in other functions. |
|
1844 | later use it for further analysis or in other functions. | |
1845 |
|
1845 | |||
1846 | -s <key>: sort profile by given key. You can provide more than one key |
|
1846 | -s <key>: sort profile by given key. You can provide more than one key | |
1847 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1847 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1848 | default sorting key is 'time'. |
|
1848 | default sorting key is 'time'. | |
1849 |
|
1849 | |||
1850 | The following is copied verbatim from the profile documentation |
|
1850 | The following is copied verbatim from the profile documentation | |
1851 | referenced below: |
|
1851 | referenced below: | |
1852 |
|
1852 | |||
1853 | When more than one key is provided, additional keys are used as |
|
1853 | When more than one key is provided, additional keys are used as | |
1854 | secondary criteria when the there is equality in all keys selected |
|
1854 | secondary criteria when the there is equality in all keys selected | |
1855 | before them. |
|
1855 | before them. | |
1856 |
|
1856 | |||
1857 | Abbreviations can be used for any key names, as long as the |
|
1857 | Abbreviations can be used for any key names, as long as the | |
1858 | abbreviation is unambiguous. The following are the keys currently |
|
1858 | abbreviation is unambiguous. The following are the keys currently | |
1859 | defined: |
|
1859 | defined: | |
1860 |
|
1860 | |||
1861 | Valid Arg Meaning |
|
1861 | Valid Arg Meaning | |
1862 | "calls" call count |
|
1862 | "calls" call count | |
1863 | "cumulative" cumulative time |
|
1863 | "cumulative" cumulative time | |
1864 | "file" file name |
|
1864 | "file" file name | |
1865 | "module" file name |
|
1865 | "module" file name | |
1866 | "pcalls" primitive call count |
|
1866 | "pcalls" primitive call count | |
1867 | "line" line number |
|
1867 | "line" line number | |
1868 | "name" function name |
|
1868 | "name" function name | |
1869 | "nfl" name/file/line |
|
1869 | "nfl" name/file/line | |
1870 | "stdname" standard name |
|
1870 | "stdname" standard name | |
1871 | "time" internal time |
|
1871 | "time" internal time | |
1872 |
|
1872 | |||
1873 | Note that all sorts on statistics are in descending order (placing |
|
1873 | Note that all sorts on statistics are in descending order (placing | |
1874 | most time consuming items first), where as name, file, and line number |
|
1874 | most time consuming items first), where as name, file, and line number | |
1875 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1875 | searches are in ascending order (i.e., alphabetical). The subtle | |
1876 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1876 | distinction between "nfl" and "stdname" is that the standard name is a | |
1877 | sort of the name as printed, which means that the embedded line |
|
1877 | sort of the name as printed, which means that the embedded line | |
1878 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1878 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1879 | would (if the file names were the same) appear in the string order |
|
1879 | would (if the file names were the same) appear in the string order | |
1880 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1880 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1881 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1881 | line numbers. In fact, sort_stats("nfl") is the same as | |
1882 | sort_stats("name", "file", "line"). |
|
1882 | sort_stats("name", "file", "line"). | |
1883 |
|
1883 | |||
1884 | -T <filename>: save profile results as shown on screen to a text |
|
1884 | -T <filename>: save profile results as shown on screen to a text | |
1885 | file. The profile is still shown on screen. |
|
1885 | file. The profile is still shown on screen. | |
1886 |
|
1886 | |||
1887 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1887 | -D <filename>: save (via dump_stats) profile statistics to given | |
1888 | filename. This data is in a format understood by the pstats module, and |
|
1888 | filename. This data is in a format understood by the pstats module, and | |
1889 | is generated by a call to the dump_stats() method of profile |
|
1889 | is generated by a call to the dump_stats() method of profile | |
1890 | objects. The profile is still shown on screen. |
|
1890 | objects. The profile is still shown on screen. | |
1891 |
|
1891 | |||
1892 | -q: suppress output to the pager. Best used with -T and/or -D above. |
|
1892 | -q: suppress output to the pager. Best used with -T and/or -D above. | |
1893 |
|
1893 | |||
1894 | If you want to run complete programs under the profiler's control, use |
|
1894 | If you want to run complete programs under the profiler's control, use | |
1895 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1895 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1896 | contains profiler specific options as described here. |
|
1896 | contains profiler specific options as described here. | |
1897 |
|
1897 | |||
1898 | You can read the complete documentation for the profile module with:: |
|
1898 | You can read the complete documentation for the profile module with:: | |
1899 |
|
1899 | |||
1900 | In [1]: import profile; profile.help() |
|
1900 | In [1]: import profile; profile.help() | |
1901 | """ |
|
1901 | """ | |
1902 |
|
1902 | |||
1903 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1903 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1904 |
|
1904 | |||
1905 | if user_mode: # regular user call |
|
1905 | if user_mode: # regular user call | |
1906 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q', |
|
1906 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q', | |
1907 | list_all=1, posix=False) |
|
1907 | list_all=1, posix=False) | |
1908 | namespace = self.shell.user_ns |
|
1908 | namespace = self.shell.user_ns | |
1909 | else: # called to run a program by %run -p |
|
1909 | else: # called to run a program by %run -p | |
1910 | try: |
|
1910 | try: | |
1911 | filename = get_py_filename(arg_lst[0]) |
|
1911 | filename = get_py_filename(arg_lst[0]) | |
1912 | except IOError as e: |
|
1912 | except IOError as e: | |
1913 | try: |
|
1913 | try: | |
1914 | msg = str(e) |
|
1914 | msg = str(e) | |
1915 | except UnicodeError: |
|
1915 | except UnicodeError: | |
1916 | msg = e.message |
|
1916 | msg = e.message | |
1917 | error(msg) |
|
1917 | error(msg) | |
1918 | return |
|
1918 | return | |
1919 |
|
1919 | |||
1920 | arg_str = 'execfile(filename,prog_ns)' |
|
1920 | arg_str = 'execfile(filename,prog_ns)' | |
1921 | namespace = { |
|
1921 | namespace = { | |
1922 | 'execfile': self.shell.safe_execfile, |
|
1922 | 'execfile': self.shell.safe_execfile, | |
1923 | 'prog_ns': prog_ns, |
|
1923 | 'prog_ns': prog_ns, | |
1924 | 'filename': filename |
|
1924 | 'filename': filename | |
1925 | } |
|
1925 | } | |
1926 |
|
1926 | |||
1927 | opts.merge(opts_def) |
|
1927 | opts.merge(opts_def) | |
1928 |
|
1928 | |||
1929 | prof = profile.Profile() |
|
1929 | prof = profile.Profile() | |
1930 | try: |
|
1930 | try: | |
1931 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1931 | prof = prof.runctx(arg_str,namespace,namespace) | |
1932 | sys_exit = '' |
|
1932 | sys_exit = '' | |
1933 | except SystemExit: |
|
1933 | except SystemExit: | |
1934 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1934 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1935 |
|
1935 | |||
1936 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1936 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1937 |
|
1937 | |||
1938 | lims = opts.l |
|
1938 | lims = opts.l | |
1939 | if lims: |
|
1939 | if lims: | |
1940 | lims = [] # rebuild lims with ints/floats/strings |
|
1940 | lims = [] # rebuild lims with ints/floats/strings | |
1941 | for lim in opts.l: |
|
1941 | for lim in opts.l: | |
1942 | try: |
|
1942 | try: | |
1943 | lims.append(int(lim)) |
|
1943 | lims.append(int(lim)) | |
1944 | except ValueError: |
|
1944 | except ValueError: | |
1945 | try: |
|
1945 | try: | |
1946 | lims.append(float(lim)) |
|
1946 | lims.append(float(lim)) | |
1947 | except ValueError: |
|
1947 | except ValueError: | |
1948 | lims.append(lim) |
|
1948 | lims.append(lim) | |
1949 |
|
1949 | |||
1950 | # Trap output. |
|
1950 | # Trap output. | |
1951 | stdout_trap = StringIO() |
|
1951 | stdout_trap = StringIO() | |
1952 |
|
1952 | |||
1953 | if hasattr(stats,'stream'): |
|
1953 | if hasattr(stats,'stream'): | |
1954 | # In newer versions of python, the stats object has a 'stream' |
|
1954 | # In newer versions of python, the stats object has a 'stream' | |
1955 | # attribute to write into. |
|
1955 | # attribute to write into. | |
1956 | stats.stream = stdout_trap |
|
1956 | stats.stream = stdout_trap | |
1957 | stats.print_stats(*lims) |
|
1957 | stats.print_stats(*lims) | |
1958 | else: |
|
1958 | else: | |
1959 | # For older versions, we manually redirect stdout during printing |
|
1959 | # For older versions, we manually redirect stdout during printing | |
1960 | sys_stdout = sys.stdout |
|
1960 | sys_stdout = sys.stdout | |
1961 | try: |
|
1961 | try: | |
1962 | sys.stdout = stdout_trap |
|
1962 | sys.stdout = stdout_trap | |
1963 | stats.print_stats(*lims) |
|
1963 | stats.print_stats(*lims) | |
1964 | finally: |
|
1964 | finally: | |
1965 | sys.stdout = sys_stdout |
|
1965 | sys.stdout = sys_stdout | |
1966 |
|
1966 | |||
1967 | output = stdout_trap.getvalue() |
|
1967 | output = stdout_trap.getvalue() | |
1968 | output = output.rstrip() |
|
1968 | output = output.rstrip() | |
1969 |
|
1969 | |||
1970 | if 'q' not in opts: |
|
1970 | if 'q' not in opts: | |
1971 | page.page(output) |
|
1971 | page.page(output) | |
1972 | print sys_exit, |
|
1972 | print sys_exit, | |
1973 |
|
1973 | |||
1974 | dump_file = opts.D[0] |
|
1974 | dump_file = opts.D[0] | |
1975 | text_file = opts.T[0] |
|
1975 | text_file = opts.T[0] | |
1976 | if dump_file: |
|
1976 | if dump_file: | |
1977 | dump_file = unquote_filename(dump_file) |
|
1977 | dump_file = unquote_filename(dump_file) | |
1978 | prof.dump_stats(dump_file) |
|
1978 | prof.dump_stats(dump_file) | |
1979 | print '\n*** Profile stats marshalled to file',\ |
|
1979 | print '\n*** Profile stats marshalled to file',\ | |
1980 | `dump_file`+'.',sys_exit |
|
1980 | `dump_file`+'.',sys_exit | |
1981 | if text_file: |
|
1981 | if text_file: | |
1982 | text_file = unquote_filename(text_file) |
|
1982 | text_file = unquote_filename(text_file) | |
1983 | pfile = open(text_file,'w') |
|
1983 | pfile = open(text_file,'w') | |
1984 | pfile.write(output) |
|
1984 | pfile.write(output) | |
1985 | pfile.close() |
|
1985 | pfile.close() | |
1986 | print '\n*** Profile printout saved to text file',\ |
|
1986 | print '\n*** Profile printout saved to text file',\ | |
1987 | `text_file`+'.',sys_exit |
|
1987 | `text_file`+'.',sys_exit | |
1988 |
|
1988 | |||
1989 | if opts.has_key('r'): |
|
1989 | if opts.has_key('r'): | |
1990 | return stats |
|
1990 | return stats | |
1991 | else: |
|
1991 | else: | |
1992 | return None |
|
1992 | return None | |
1993 |
|
1993 | |||
1994 | @line_magic |
|
1994 | @line_magic | |
1995 | def pdb(self, parameter_s=''): |
|
1995 | def pdb(self, parameter_s=''): | |
1996 | """Control the automatic calling of the pdb interactive debugger. |
|
1996 | """Control the automatic calling of the pdb interactive debugger. | |
1997 |
|
1997 | |||
1998 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1998 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1999 | argument it works as a toggle. |
|
1999 | argument it works as a toggle. | |
2000 |
|
2000 | |||
2001 | When an exception is triggered, IPython can optionally call the |
|
2001 | When an exception is triggered, IPython can optionally call the | |
2002 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
2002 | interactive pdb debugger after the traceback printout. %pdb toggles | |
2003 | this feature on and off. |
|
2003 | this feature on and off. | |
2004 |
|
2004 | |||
2005 | The initial state of this feature is set in your configuration |
|
2005 | The initial state of this feature is set in your configuration | |
2006 | file (the option is ``InteractiveShell.pdb``). |
|
2006 | file (the option is ``InteractiveShell.pdb``). | |
2007 |
|
2007 | |||
2008 | If you want to just activate the debugger AFTER an exception has fired, |
|
2008 | If you want to just activate the debugger AFTER an exception has fired, | |
2009 | without having to type '%pdb on' and rerunning your code, you can use |
|
2009 | without having to type '%pdb on' and rerunning your code, you can use | |
2010 | the %debug magic.""" |
|
2010 | the %debug magic.""" | |
2011 |
|
2011 | |||
2012 | par = parameter_s.strip().lower() |
|
2012 | par = parameter_s.strip().lower() | |
2013 |
|
2013 | |||
2014 | if par: |
|
2014 | if par: | |
2015 | try: |
|
2015 | try: | |
2016 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
2016 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
2017 | except KeyError: |
|
2017 | except KeyError: | |
2018 | print ('Incorrect argument. Use on/1, off/0, ' |
|
2018 | print ('Incorrect argument. Use on/1, off/0, ' | |
2019 | 'or nothing for a toggle.') |
|
2019 | 'or nothing for a toggle.') | |
2020 | return |
|
2020 | return | |
2021 | else: |
|
2021 | else: | |
2022 | # toggle |
|
2022 | # toggle | |
2023 | new_pdb = not self.shell.call_pdb |
|
2023 | new_pdb = not self.shell.call_pdb | |
2024 |
|
2024 | |||
2025 | # set on the shell |
|
2025 | # set on the shell | |
2026 | self.shell.call_pdb = new_pdb |
|
2026 | self.shell.call_pdb = new_pdb | |
2027 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
2027 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
2028 |
|
2028 | |||
2029 | @line_magic |
|
2029 | @line_magic | |
2030 | def debug(self, parameter_s=''): |
|
2030 | def debug(self, parameter_s=''): | |
2031 | """Activate the interactive debugger in post-mortem mode. |
|
2031 | """Activate the interactive debugger in post-mortem mode. | |
2032 |
|
2032 | |||
2033 | If an exception has just occurred, this lets you inspect its stack |
|
2033 | If an exception has just occurred, this lets you inspect its stack | |
2034 | frames interactively. Note that this will always work only on the last |
|
2034 | frames interactively. Note that this will always work only on the last | |
2035 | traceback that occurred, so you must call this quickly after an |
|
2035 | traceback that occurred, so you must call this quickly after an | |
2036 | exception that you wish to inspect has fired, because if another one |
|
2036 | exception that you wish to inspect has fired, because if another one | |
2037 | occurs, it clobbers the previous one. |
|
2037 | occurs, it clobbers the previous one. | |
2038 |
|
2038 | |||
2039 | If you want IPython to automatically do this on every exception, see |
|
2039 | If you want IPython to automatically do this on every exception, see | |
2040 | the %pdb magic for more details. |
|
2040 | the %pdb magic for more details. | |
2041 | """ |
|
2041 | """ | |
2042 | self.shell.debugger(force=True) |
|
2042 | self.shell.debugger(force=True) | |
2043 |
|
2043 | |||
2044 | @line_magic |
|
2044 | @line_magic | |
2045 | def tb(self, s): |
|
2045 | def tb(self, s): | |
2046 | """Print the last traceback with the currently active exception mode. |
|
2046 | """Print the last traceback with the currently active exception mode. | |
2047 |
|
2047 | |||
2048 | See %xmode for changing exception reporting modes.""" |
|
2048 | See %xmode for changing exception reporting modes.""" | |
2049 | self.shell.showtraceback() |
|
2049 | self.shell.showtraceback() | |
2050 |
|
2050 | |||
2051 | @skip_doctest |
|
2051 | @skip_doctest | |
2052 | @line_magic |
|
2052 | @line_magic | |
2053 | def run(self, parameter_s='', runner=None, |
|
2053 | def run(self, parameter_s='', runner=None, | |
2054 | file_finder=get_py_filename): |
|
2054 | file_finder=get_py_filename): | |
2055 | """Run the named file inside IPython as a program. |
|
2055 | """Run the named file inside IPython as a program. | |
2056 |
|
2056 | |||
2057 | Usage:\\ |
|
2057 | Usage:\\ | |
2058 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
2058 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
2059 |
|
2059 | |||
2060 | Parameters after the filename are passed as command-line arguments to |
|
2060 | Parameters after the filename are passed as command-line arguments to | |
2061 | the program (put in sys.argv). Then, control returns to IPython's |
|
2061 | the program (put in sys.argv). Then, control returns to IPython's | |
2062 | prompt. |
|
2062 | prompt. | |
2063 |
|
2063 | |||
2064 | This is similar to running at a system prompt:\\ |
|
2064 | This is similar to running at a system prompt:\\ | |
2065 | $ python file args\\ |
|
2065 | $ python file args\\ | |
2066 | but with the advantage of giving you IPython's tracebacks, and of |
|
2066 | but with the advantage of giving you IPython's tracebacks, and of | |
2067 | loading all variables into your interactive namespace for further use |
|
2067 | loading all variables into your interactive namespace for further use | |
2068 | (unless -p is used, see below). |
|
2068 | (unless -p is used, see below). | |
2069 |
|
2069 | |||
2070 | The file is executed in a namespace initially consisting only of |
|
2070 | The file is executed in a namespace initially consisting only of | |
2071 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
2071 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
2072 | sees its environment as if it were being run as a stand-alone program |
|
2072 | sees its environment as if it were being run as a stand-alone program | |
2073 | (except for sharing global objects such as previously imported |
|
2073 | (except for sharing global objects such as previously imported | |
2074 | modules). But after execution, the IPython interactive namespace gets |
|
2074 | modules). But after execution, the IPython interactive namespace gets | |
2075 | updated with all variables defined in the program (except for __name__ |
|
2075 | updated with all variables defined in the program (except for __name__ | |
2076 | and sys.argv). This allows for very convenient loading of code for |
|
2076 | and sys.argv). This allows for very convenient loading of code for | |
2077 | interactive work, while giving each program a 'clean sheet' to run in. |
|
2077 | interactive work, while giving each program a 'clean sheet' to run in. | |
2078 |
|
2078 | |||
2079 | Options: |
|
2079 | Options: | |
2080 |
|
2080 | |||
2081 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
2081 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
2082 | without extension (as python does under import). This allows running |
|
2082 | without extension (as python does under import). This allows running | |
2083 | scripts and reloading the definitions in them without calling code |
|
2083 | scripts and reloading the definitions in them without calling code | |
2084 | protected by an ' if __name__ == "__main__" ' clause. |
|
2084 | protected by an ' if __name__ == "__main__" ' clause. | |
2085 |
|
2085 | |||
2086 | -i: run the file in IPython's namespace instead of an empty one. This |
|
2086 | -i: run the file in IPython's namespace instead of an empty one. This | |
2087 | is useful if you are experimenting with code written in a text editor |
|
2087 | is useful if you are experimenting with code written in a text editor | |
2088 | which depends on variables defined interactively. |
|
2088 | which depends on variables defined interactively. | |
2089 |
|
2089 | |||
2090 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
2090 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
2091 | being run. This is particularly useful if IPython is being used to |
|
2091 | being run. This is particularly useful if IPython is being used to | |
2092 | run unittests, which always exit with a sys.exit() call. In such |
|
2092 | run unittests, which always exit with a sys.exit() call. In such | |
2093 | cases you are interested in the output of the test results, not in |
|
2093 | cases you are interested in the output of the test results, not in | |
2094 | seeing a traceback of the unittest module. |
|
2094 | seeing a traceback of the unittest module. | |
2095 |
|
2095 | |||
2096 | -t: print timing information at the end of the run. IPython will give |
|
2096 | -t: print timing information at the end of the run. IPython will give | |
2097 | you an estimated CPU time consumption for your script, which under |
|
2097 | you an estimated CPU time consumption for your script, which under | |
2098 | Unix uses the resource module to avoid the wraparound problems of |
|
2098 | Unix uses the resource module to avoid the wraparound problems of | |
2099 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
2099 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
2100 | is also given (for Windows platforms this is reported as 0.0). |
|
2100 | is also given (for Windows platforms this is reported as 0.0). | |
2101 |
|
2101 | |||
2102 | If -t is given, an additional -N<N> option can be given, where <N> |
|
2102 | If -t is given, an additional -N<N> option can be given, where <N> | |
2103 | must be an integer indicating how many times you want the script to |
|
2103 | must be an integer indicating how many times you want the script to | |
2104 | run. The final timing report will include total and per run results. |
|
2104 | run. The final timing report will include total and per run results. | |
2105 |
|
2105 | |||
2106 | For example (testing the script uniq_stable.py):: |
|
2106 | For example (testing the script uniq_stable.py):: | |
2107 |
|
2107 | |||
2108 | In [1]: run -t uniq_stable |
|
2108 | In [1]: run -t uniq_stable | |
2109 |
|
2109 | |||
2110 | IPython CPU timings (estimated):\\ |
|
2110 | IPython CPU timings (estimated):\\ | |
2111 | User : 0.19597 s.\\ |
|
2111 | User : 0.19597 s.\\ | |
2112 | System: 0.0 s.\\ |
|
2112 | System: 0.0 s.\\ | |
2113 |
|
2113 | |||
2114 | In [2]: run -t -N5 uniq_stable |
|
2114 | In [2]: run -t -N5 uniq_stable | |
2115 |
|
2115 | |||
2116 | IPython CPU timings (estimated):\\ |
|
2116 | IPython CPU timings (estimated):\\ | |
2117 | Total runs performed: 5\\ |
|
2117 | Total runs performed: 5\\ | |
2118 | Times : Total Per run\\ |
|
2118 | Times : Total Per run\\ | |
2119 | User : 0.910862 s, 0.1821724 s.\\ |
|
2119 | User : 0.910862 s, 0.1821724 s.\\ | |
2120 | System: 0.0 s, 0.0 s. |
|
2120 | System: 0.0 s, 0.0 s. | |
2121 |
|
2121 | |||
2122 | -d: run your program under the control of pdb, the Python debugger. |
|
2122 | -d: run your program under the control of pdb, the Python debugger. | |
2123 | This allows you to execute your program step by step, watch variables, |
|
2123 | This allows you to execute your program step by step, watch variables, | |
2124 | etc. Internally, what IPython does is similar to calling: |
|
2124 | etc. Internally, what IPython does is similar to calling: | |
2125 |
|
2125 | |||
2126 | pdb.run('execfile("YOURFILENAME")') |
|
2126 | pdb.run('execfile("YOURFILENAME")') | |
2127 |
|
2127 | |||
2128 | with a breakpoint set on line 1 of your file. You can change the line |
|
2128 | with a breakpoint set on line 1 of your file. You can change the line | |
2129 | number for this automatic breakpoint to be <N> by using the -bN option |
|
2129 | number for this automatic breakpoint to be <N> by using the -bN option | |
2130 | (where N must be an integer). For example:: |
|
2130 | (where N must be an integer). For example:: | |
2131 |
|
2131 | |||
2132 | %run -d -b40 myscript |
|
2132 | %run -d -b40 myscript | |
2133 |
|
2133 | |||
2134 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
2134 | will set the first breakpoint at line 40 in myscript.py. Note that | |
2135 | the first breakpoint must be set on a line which actually does |
|
2135 | the first breakpoint must be set on a line which actually does | |
2136 | something (not a comment or docstring) for it to stop execution. |
|
2136 | something (not a comment or docstring) for it to stop execution. | |
2137 |
|
2137 | |||
2138 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
2138 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
2139 | first enter 'c' (without quotes) to start execution up to the first |
|
2139 | first enter 'c' (without quotes) to start execution up to the first | |
2140 | breakpoint. |
|
2140 | breakpoint. | |
2141 |
|
2141 | |||
2142 | Entering 'help' gives information about the use of the debugger. You |
|
2142 | Entering 'help' gives information about the use of the debugger. You | |
2143 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
2143 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
2144 | at a prompt. |
|
2144 | at a prompt. | |
2145 |
|
2145 | |||
2146 | -p: run program under the control of the Python profiler module (which |
|
2146 | -p: run program under the control of the Python profiler module (which | |
2147 | prints a detailed report of execution times, function calls, etc). |
|
2147 | prints a detailed report of execution times, function calls, etc). | |
2148 |
|
2148 | |||
2149 | You can pass other options after -p which affect the behavior of the |
|
2149 | You can pass other options after -p which affect the behavior of the | |
2150 | profiler itself. See the docs for %prun for details. |
|
2150 | profiler itself. See the docs for %prun for details. | |
2151 |
|
2151 | |||
2152 | In this mode, the program's variables do NOT propagate back to the |
|
2152 | In this mode, the program's variables do NOT propagate back to the | |
2153 | IPython interactive namespace (because they remain in the namespace |
|
2153 | IPython interactive namespace (because they remain in the namespace | |
2154 | where the profiler executes them). |
|
2154 | where the profiler executes them). | |
2155 |
|
2155 | |||
2156 | Internally this triggers a call to %prun, see its documentation for |
|
2156 | Internally this triggers a call to %prun, see its documentation for | |
2157 | details on the options available specifically for profiling. |
|
2157 | details on the options available specifically for profiling. | |
2158 |
|
2158 | |||
2159 | There is one special usage for which the text above doesn't apply: |
|
2159 | There is one special usage for which the text above doesn't apply: | |
2160 | if the filename ends with .ipy, the file is run as ipython script, |
|
2160 | if the filename ends with .ipy, the file is run as ipython script, | |
2161 | just as if the commands were written on IPython prompt. |
|
2161 | just as if the commands were written on IPython prompt. | |
2162 |
|
2162 | |||
2163 | -m: specify module name to load instead of script path. Similar to |
|
2163 | -m: specify module name to load instead of script path. Similar to | |
2164 | the -m option for the python interpreter. Use this option last if you |
|
2164 | the -m option for the python interpreter. Use this option last if you | |
2165 | want to combine with other %run options. Unlike the python interpreter |
|
2165 | want to combine with other %run options. Unlike the python interpreter | |
2166 | only source modules are allowed no .pyc or .pyo files. |
|
2166 | only source modules are allowed no .pyc or .pyo files. | |
2167 | For example:: |
|
2167 | For example:: | |
2168 |
|
2168 | |||
2169 | %run -m example |
|
2169 | %run -m example | |
2170 |
|
2170 | |||
2171 | will run the example module. |
|
2171 | will run the example module. | |
2172 |
|
2172 | |||
2173 | """ |
|
2173 | """ | |
2174 |
|
2174 | |||
2175 | # get arguments and set sys.argv for program to be run. |
|
2175 | # get arguments and set sys.argv for program to be run. | |
2176 | opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:', |
|
2176 | opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:', | |
2177 | mode='list', list_all=1) |
|
2177 | mode='list', list_all=1) | |
2178 | if "m" in opts: |
|
2178 | if "m" in opts: | |
2179 | modulename = opts["m"][0] |
|
2179 | modulename = opts["m"][0] | |
2180 | modpath = find_mod(modulename) |
|
2180 | modpath = find_mod(modulename) | |
2181 | if modpath is None: |
|
2181 | if modpath is None: | |
2182 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
2182 | warn('%r is not a valid modulename on sys.path'%modulename) | |
2183 | return |
|
2183 | return | |
2184 | arg_lst = [modpath] + arg_lst |
|
2184 | arg_lst = [modpath] + arg_lst | |
2185 | try: |
|
2185 | try: | |
2186 | filename = file_finder(arg_lst[0]) |
|
2186 | filename = file_finder(arg_lst[0]) | |
2187 | except IndexError: |
|
2187 | except IndexError: | |
2188 | warn('you must provide at least a filename.') |
|
2188 | warn('you must provide at least a filename.') | |
2189 | print '\n%run:\n', oinspect.getdoc(self.magic_run) |
|
2189 | print '\n%run:\n', oinspect.getdoc(self.magic_run) | |
2190 | return |
|
2190 | return | |
2191 | except IOError as e: |
|
2191 | except IOError as e: | |
2192 | try: |
|
2192 | try: | |
2193 | msg = str(e) |
|
2193 | msg = str(e) | |
2194 | except UnicodeError: |
|
2194 | except UnicodeError: | |
2195 | msg = e.message |
|
2195 | msg = e.message | |
2196 | error(msg) |
|
2196 | error(msg) | |
2197 | return |
|
2197 | return | |
2198 |
|
2198 | |||
2199 | if filename.lower().endswith('.ipy'): |
|
2199 | if filename.lower().endswith('.ipy'): | |
2200 | self.shell.safe_execfile_ipy(filename) |
|
2200 | self.shell.safe_execfile_ipy(filename) | |
2201 | return |
|
2201 | return | |
2202 |
|
2202 | |||
2203 | # Control the response to exit() calls made by the script being run |
|
2203 | # Control the response to exit() calls made by the script being run | |
2204 | exit_ignore = 'e' in opts |
|
2204 | exit_ignore = 'e' in opts | |
2205 |
|
2205 | |||
2206 | # Make sure that the running script gets a proper sys.argv as if it |
|
2206 | # Make sure that the running script gets a proper sys.argv as if it | |
2207 | # were run from a system shell. |
|
2207 | # were run from a system shell. | |
2208 | save_argv = sys.argv # save it for later restoring |
|
2208 | save_argv = sys.argv # save it for later restoring | |
2209 |
|
2209 | |||
2210 | # simulate shell expansion on arguments, at least tilde expansion |
|
2210 | # simulate shell expansion on arguments, at least tilde expansion | |
2211 | args = [ os.path.expanduser(a) for a in arg_lst[1:] ] |
|
2211 | args = [ os.path.expanduser(a) for a in arg_lst[1:] ] | |
2212 |
|
2212 | |||
2213 | sys.argv = [filename] + args # put in the proper filename |
|
2213 | sys.argv = [filename] + args # put in the proper filename | |
2214 | # protect sys.argv from potential unicode strings on Python 2: |
|
2214 | # protect sys.argv from potential unicode strings on Python 2: | |
2215 | if not py3compat.PY3: |
|
2215 | if not py3compat.PY3: | |
2216 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] |
|
2216 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] | |
2217 |
|
2217 | |||
2218 | if 'i' in opts: |
|
2218 | if 'i' in opts: | |
2219 | # Run in user's interactive namespace |
|
2219 | # Run in user's interactive namespace | |
2220 | prog_ns = self.shell.user_ns |
|
2220 | prog_ns = self.shell.user_ns | |
2221 | __name__save = self.shell.user_ns['__name__'] |
|
2221 | __name__save = self.shell.user_ns['__name__'] | |
2222 | prog_ns['__name__'] = '__main__' |
|
2222 | prog_ns['__name__'] = '__main__' | |
2223 | main_mod = self.shell.new_main_mod(prog_ns) |
|
2223 | main_mod = self.shell.new_main_mod(prog_ns) | |
2224 | else: |
|
2224 | else: | |
2225 | # Run in a fresh, empty namespace |
|
2225 | # Run in a fresh, empty namespace | |
2226 | if 'n' in opts: |
|
2226 | if 'n' in opts: | |
2227 | name = os.path.splitext(os.path.basename(filename))[0] |
|
2227 | name = os.path.splitext(os.path.basename(filename))[0] | |
2228 | else: |
|
2228 | else: | |
2229 | name = '__main__' |
|
2229 | name = '__main__' | |
2230 |
|
2230 | |||
2231 | main_mod = self.shell.new_main_mod() |
|
2231 | main_mod = self.shell.new_main_mod() | |
2232 | prog_ns = main_mod.__dict__ |
|
2232 | prog_ns = main_mod.__dict__ | |
2233 | prog_ns['__name__'] = name |
|
2233 | prog_ns['__name__'] = name | |
2234 |
|
2234 | |||
2235 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
2235 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
2236 | # set the __file__ global in the script's namespace |
|
2236 | # set the __file__ global in the script's namespace | |
2237 | prog_ns['__file__'] = filename |
|
2237 | prog_ns['__file__'] = filename | |
2238 |
|
2238 | |||
2239 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
2239 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
2240 | # that, if we overwrite __main__, we replace it at the end |
|
2240 | # that, if we overwrite __main__, we replace it at the end | |
2241 | main_mod_name = prog_ns['__name__'] |
|
2241 | main_mod_name = prog_ns['__name__'] | |
2242 |
|
2242 | |||
2243 | if main_mod_name == '__main__': |
|
2243 | if main_mod_name == '__main__': | |
2244 | restore_main = sys.modules['__main__'] |
|
2244 | restore_main = sys.modules['__main__'] | |
2245 | else: |
|
2245 | else: | |
2246 | restore_main = False |
|
2246 | restore_main = False | |
2247 |
|
2247 | |||
2248 | # This needs to be undone at the end to prevent holding references to |
|
2248 | # This needs to be undone at the end to prevent holding references to | |
2249 | # every single object ever created. |
|
2249 | # every single object ever created. | |
2250 | sys.modules[main_mod_name] = main_mod |
|
2250 | sys.modules[main_mod_name] = main_mod | |
2251 |
|
2251 | |||
2252 | try: |
|
2252 | try: | |
2253 | stats = None |
|
2253 | stats = None | |
2254 | with self.shell.readline_no_record: |
|
2254 | with self.shell.readline_no_record: | |
2255 | if 'p' in opts: |
|
2255 | if 'p' in opts: | |
2256 | stats = self.prun('', 0, opts, arg_lst, prog_ns) |
|
2256 | stats = self.prun('', 0, opts, arg_lst, prog_ns) | |
2257 | else: |
|
2257 | else: | |
2258 | if 'd' in opts: |
|
2258 | if 'd' in opts: | |
2259 | deb = debugger.Pdb(self.shell.colors) |
|
2259 | deb = debugger.Pdb(self.shell.colors) | |
2260 | # reset Breakpoint state, which is moronically kept |
|
2260 | # reset Breakpoint state, which is moronically kept | |
2261 | # in a class |
|
2261 | # in a class | |
2262 | bdb.Breakpoint.next = 1 |
|
2262 | bdb.Breakpoint.next = 1 | |
2263 | bdb.Breakpoint.bplist = {} |
|
2263 | bdb.Breakpoint.bplist = {} | |
2264 | bdb.Breakpoint.bpbynumber = [None] |
|
2264 | bdb.Breakpoint.bpbynumber = [None] | |
2265 | # Set an initial breakpoint to stop execution |
|
2265 | # Set an initial breakpoint to stop execution | |
2266 | maxtries = 10 |
|
2266 | maxtries = 10 | |
2267 | bp = int(opts.get('b', [1])[0]) |
|
2267 | bp = int(opts.get('b', [1])[0]) | |
2268 | checkline = deb.checkline(filename, bp) |
|
2268 | checkline = deb.checkline(filename, bp) | |
2269 | if not checkline: |
|
2269 | if not checkline: | |
2270 | for bp in range(bp + 1, bp + maxtries + 1): |
|
2270 | for bp in range(bp + 1, bp + maxtries + 1): | |
2271 | if deb.checkline(filename, bp): |
|
2271 | if deb.checkline(filename, bp): | |
2272 | break |
|
2272 | break | |
2273 | else: |
|
2273 | else: | |
2274 | msg = ("\nI failed to find a valid line to set " |
|
2274 | msg = ("\nI failed to find a valid line to set " | |
2275 | "a breakpoint\n" |
|
2275 | "a breakpoint\n" | |
2276 | "after trying up to line: %s.\n" |
|
2276 | "after trying up to line: %s.\n" | |
2277 | "Please set a valid breakpoint manually " |
|
2277 | "Please set a valid breakpoint manually " | |
2278 | "with the -b option." % bp) |
|
2278 | "with the -b option." % bp) | |
2279 | error(msg) |
|
2279 | error(msg) | |
2280 | return |
|
2280 | return | |
2281 | # if we find a good linenumber, set the breakpoint |
|
2281 | # if we find a good linenumber, set the breakpoint | |
2282 | deb.do_break('%s:%s' % (filename, bp)) |
|
2282 | deb.do_break('%s:%s' % (filename, bp)) | |
2283 | # Start file run |
|
2283 | # Start file run | |
2284 | print "NOTE: Enter 'c' at the", |
|
2284 | print "NOTE: Enter 'c' at the", | |
2285 | print "%s prompt to start your script." % deb.prompt |
|
2285 | print "%s prompt to start your script." % deb.prompt | |
2286 | ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns} |
|
2286 | ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns} | |
2287 | try: |
|
2287 | try: | |
2288 | deb.run('execfile("%s", prog_ns)' % filename, ns) |
|
2288 | deb.run('execfile("%s", prog_ns)' % filename, ns) | |
2289 |
|
2289 | |||
2290 | except: |
|
2290 | except: | |
2291 | etype, value, tb = sys.exc_info() |
|
2291 | etype, value, tb = sys.exc_info() | |
2292 | # Skip three frames in the traceback: the %run one, |
|
2292 | # Skip three frames in the traceback: the %run one, | |
2293 | # one inside bdb.py, and the command-line typed by the |
|
2293 | # one inside bdb.py, and the command-line typed by the | |
2294 | # user (run by exec in pdb itself). |
|
2294 | # user (run by exec in pdb itself). | |
2295 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
2295 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) | |
2296 | else: |
|
2296 | else: | |
2297 | if runner is None: |
|
2297 | if runner is None: | |
2298 | runner = self.default_runner |
|
2298 | runner = self.default_runner | |
2299 | if runner is None: |
|
2299 | if runner is None: | |
2300 | runner = self.shell.safe_execfile |
|
2300 | runner = self.shell.safe_execfile | |
2301 | if 't' in opts: |
|
2301 | if 't' in opts: | |
2302 | # timed execution |
|
2302 | # timed execution | |
2303 | try: |
|
2303 | try: | |
2304 | nruns = int(opts['N'][0]) |
|
2304 | nruns = int(opts['N'][0]) | |
2305 | if nruns < 1: |
|
2305 | if nruns < 1: | |
2306 | error('Number of runs must be >=1') |
|
2306 | error('Number of runs must be >=1') | |
2307 | return |
|
2307 | return | |
2308 | except (KeyError): |
|
2308 | except (KeyError): | |
2309 | nruns = 1 |
|
2309 | nruns = 1 | |
2310 | twall0 = time.time() |
|
2310 | twall0 = time.time() | |
2311 | if nruns == 1: |
|
2311 | if nruns == 1: | |
2312 | t0 = clock2() |
|
2312 | t0 = clock2() | |
2313 | runner(filename, prog_ns, prog_ns, |
|
2313 | runner(filename, prog_ns, prog_ns, | |
2314 | exit_ignore=exit_ignore) |
|
2314 | exit_ignore=exit_ignore) | |
2315 | t1 = clock2() |
|
2315 | t1 = clock2() | |
2316 | t_usr = t1[0] - t0[0] |
|
2316 | t_usr = t1[0] - t0[0] | |
2317 | t_sys = t1[1] - t0[1] |
|
2317 | t_sys = t1[1] - t0[1] | |
2318 | print "\nIPython CPU timings (estimated):" |
|
2318 | print "\nIPython CPU timings (estimated):" | |
2319 | print " User : %10.2f s." % t_usr |
|
2319 | print " User : %10.2f s." % t_usr | |
2320 | print " System : %10.2f s." % t_sys |
|
2320 | print " System : %10.2f s." % t_sys | |
2321 | else: |
|
2321 | else: | |
2322 | runs = range(nruns) |
|
2322 | runs = range(nruns) | |
2323 | t0 = clock2() |
|
2323 | t0 = clock2() | |
2324 | for nr in runs: |
|
2324 | for nr in runs: | |
2325 | runner(filename, prog_ns, prog_ns, |
|
2325 | runner(filename, prog_ns, prog_ns, | |
2326 | exit_ignore=exit_ignore) |
|
2326 | exit_ignore=exit_ignore) | |
2327 | t1 = clock2() |
|
2327 | t1 = clock2() | |
2328 | t_usr = t1[0] - t0[0] |
|
2328 | t_usr = t1[0] - t0[0] | |
2329 | t_sys = t1[1] - t0[1] |
|
2329 | t_sys = t1[1] - t0[1] | |
2330 | print "\nIPython CPU timings (estimated):" |
|
2330 | print "\nIPython CPU timings (estimated):" | |
2331 | print "Total runs performed:", nruns |
|
2331 | print "Total runs performed:", nruns | |
2332 | print " Times : %10.2f %10.2f" % ('Total', 'Per run') |
|
2332 | print " Times : %10.2f %10.2f" % ('Total', 'Per run') | |
2333 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) |
|
2333 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) | |
2334 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) |
|
2334 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) | |
2335 | twall1 = time.time() |
|
2335 | twall1 = time.time() | |
2336 | print "Wall time: %10.2f s." % (twall1 - twall0) |
|
2336 | print "Wall time: %10.2f s." % (twall1 - twall0) | |
2337 |
|
2337 | |||
2338 | else: |
|
2338 | else: | |
2339 | # regular execution |
|
2339 | # regular execution | |
2340 | runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) |
|
2340 | runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore) | |
2341 |
|
2341 | |||
2342 | if 'i' in opts: |
|
2342 | if 'i' in opts: | |
2343 | self.shell.user_ns['__name__'] = __name__save |
|
2343 | self.shell.user_ns['__name__'] = __name__save | |
2344 | else: |
|
2344 | else: | |
2345 | # The shell MUST hold a reference to prog_ns so after %run |
|
2345 | # The shell MUST hold a reference to prog_ns so after %run | |
2346 | # exits, the python deletion mechanism doesn't zero it out |
|
2346 | # exits, the python deletion mechanism doesn't zero it out | |
2347 | # (leaving dangling references). |
|
2347 | # (leaving dangling references). | |
2348 | self.shell.cache_main_mod(prog_ns, filename) |
|
2348 | self.shell.cache_main_mod(prog_ns, filename) | |
2349 | # update IPython interactive namespace |
|
2349 | # update IPython interactive namespace | |
2350 |
|
2350 | |||
2351 | # Some forms of read errors on the file may mean the |
|
2351 | # Some forms of read errors on the file may mean the | |
2352 | # __name__ key was never set; using pop we don't have to |
|
2352 | # __name__ key was never set; using pop we don't have to | |
2353 | # worry about a possible KeyError. |
|
2353 | # worry about a possible KeyError. | |
2354 | prog_ns.pop('__name__', None) |
|
2354 | prog_ns.pop('__name__', None) | |
2355 |
|
2355 | |||
2356 | self.shell.user_ns.update(prog_ns) |
|
2356 | self.shell.user_ns.update(prog_ns) | |
2357 | finally: |
|
2357 | finally: | |
2358 | # It's a bit of a mystery why, but __builtins__ can change from |
|
2358 | # It's a bit of a mystery why, but __builtins__ can change from | |
2359 | # being a module to becoming a dict missing some key data after |
|
2359 | # being a module to becoming a dict missing some key data after | |
2360 | # %run. As best I can see, this is NOT something IPython is doing |
|
2360 | # %run. As best I can see, this is NOT something IPython is doing | |
2361 | # at all, and similar problems have been reported before: |
|
2361 | # at all, and similar problems have been reported before: | |
2362 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
2362 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
2363 | # Since this seems to be done by the interpreter itself, the best |
|
2363 | # Since this seems to be done by the interpreter itself, the best | |
2364 | # we can do is to at least restore __builtins__ for the user on |
|
2364 | # we can do is to at least restore __builtins__ for the user on | |
2365 | # exit. |
|
2365 | # exit. | |
2366 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
2366 | self.shell.user_ns['__builtins__'] = builtin_mod | |
2367 |
|
2367 | |||
2368 | # Ensure key global structures are restored |
|
2368 | # Ensure key global structures are restored | |
2369 | sys.argv = save_argv |
|
2369 | sys.argv = save_argv | |
2370 | if restore_main: |
|
2370 | if restore_main: | |
2371 | sys.modules['__main__'] = restore_main |
|
2371 | sys.modules['__main__'] = restore_main | |
2372 | else: |
|
2372 | else: | |
2373 | # Remove from sys.modules the reference to main_mod we'd |
|
2373 | # Remove from sys.modules the reference to main_mod we'd | |
2374 | # added. Otherwise it will trap references to objects |
|
2374 | # added. Otherwise it will trap references to objects | |
2375 | # contained therein. |
|
2375 | # contained therein. | |
2376 | del sys.modules[main_mod_name] |
|
2376 | del sys.modules[main_mod_name] | |
2377 |
|
2377 | |||
2378 | return stats |
|
2378 | return stats | |
2379 |
|
2379 | |||
2380 | @skip_doctest |
|
2380 | @skip_doctest | |
2381 | @line_magic |
|
2381 | @line_magic | |
2382 | def timeit(self, parameter_s=''): |
|
2382 | def timeit(self, parameter_s=''): | |
2383 | """Time execution of a Python statement or expression |
|
2383 | """Time execution of a Python statement or expression | |
2384 |
|
2384 | |||
2385 | Usage:\\ |
|
2385 | Usage:\\ | |
2386 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
2386 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
2387 |
|
2387 | |||
2388 | Time execution of a Python statement or expression using the timeit |
|
2388 | Time execution of a Python statement or expression using the timeit | |
2389 | module. |
|
2389 | module. | |
2390 |
|
2390 | |||
2391 | Options: |
|
2391 | Options: | |
2392 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
2392 | -n<N>: execute the given statement <N> times in a loop. If this value | |
2393 | is not given, a fitting value is chosen. |
|
2393 | is not given, a fitting value is chosen. | |
2394 |
|
2394 | |||
2395 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
2395 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
2396 | Default: 3 |
|
2396 | Default: 3 | |
2397 |
|
2397 | |||
2398 | -t: use time.time to measure the time, which is the default on Unix. |
|
2398 | -t: use time.time to measure the time, which is the default on Unix. | |
2399 | This function measures wall time. |
|
2399 | This function measures wall time. | |
2400 |
|
2400 | |||
2401 | -c: use time.clock to measure the time, which is the default on |
|
2401 | -c: use time.clock to measure the time, which is the default on | |
2402 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
2402 | Windows and measures wall time. On Unix, resource.getrusage is used | |
2403 | instead and returns the CPU user time. |
|
2403 | instead and returns the CPU user time. | |
2404 |
|
2404 | |||
2405 | -p<P>: use a precision of <P> digits to display the timing result. |
|
2405 | -p<P>: use a precision of <P> digits to display the timing result. | |
2406 | Default: 3 |
|
2406 | Default: 3 | |
2407 |
|
2407 | |||
2408 |
|
2408 | |||
2409 | Examples |
|
2409 | Examples | |
2410 | -------- |
|
2410 | -------- | |
2411 | :: |
|
2411 | :: | |
2412 |
|
2412 | |||
2413 | In [1]: %timeit pass |
|
2413 | In [1]: %timeit pass | |
2414 | 10000000 loops, best of 3: 53.3 ns per loop |
|
2414 | 10000000 loops, best of 3: 53.3 ns per loop | |
2415 |
|
2415 | |||
2416 | In [2]: u = None |
|
2416 | In [2]: u = None | |
2417 |
|
2417 | |||
2418 | In [3]: %timeit u is None |
|
2418 | In [3]: %timeit u is None | |
2419 | 10000000 loops, best of 3: 184 ns per loop |
|
2419 | 10000000 loops, best of 3: 184 ns per loop | |
2420 |
|
2420 | |||
2421 | In [4]: %timeit -r 4 u == None |
|
2421 | In [4]: %timeit -r 4 u == None | |
2422 | 1000000 loops, best of 4: 242 ns per loop |
|
2422 | 1000000 loops, best of 4: 242 ns per loop | |
2423 |
|
2423 | |||
2424 | In [5]: import time |
|
2424 | In [5]: import time | |
2425 |
|
2425 | |||
2426 | In [6]: %timeit -n1 time.sleep(2) |
|
2426 | In [6]: %timeit -n1 time.sleep(2) | |
2427 | 1 loops, best of 3: 2 s per loop |
|
2427 | 1 loops, best of 3: 2 s per loop | |
2428 |
|
2428 | |||
2429 |
|
2429 | |||
2430 | The times reported by %timeit will be slightly higher than those |
|
2430 | The times reported by %timeit will be slightly higher than those | |
2431 | reported by the timeit.py script when variables are accessed. This is |
|
2431 | reported by the timeit.py script when variables are accessed. This is | |
2432 | due to the fact that %timeit executes the statement in the namespace |
|
2432 | due to the fact that %timeit executes the statement in the namespace | |
2433 | of the shell, compared with timeit.py, which uses a single setup |
|
2433 | of the shell, compared with timeit.py, which uses a single setup | |
2434 | statement to import function or create variables. Generally, the bias |
|
2434 | statement to import function or create variables. Generally, the bias | |
2435 | does not matter as long as results from timeit.py are not mixed with |
|
2435 | does not matter as long as results from timeit.py are not mixed with | |
2436 | those from %timeit.""" |
|
2436 | those from %timeit.""" | |
2437 |
|
2437 | |||
2438 | import timeit |
|
2438 | import timeit | |
2439 | import math |
|
2439 | import math | |
2440 |
|
2440 | |||
2441 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
2441 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
2442 | # certain terminals. Until we figure out a robust way of |
|
2442 | # certain terminals. Until we figure out a robust way of | |
2443 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
2443 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
2444 | # microseconds. I am really NOT happy about disabling the proper |
|
2444 | # microseconds. I am really NOT happy about disabling the proper | |
2445 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
2445 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
2446 | # right solution for this is, I'm all ears... |
|
2446 | # right solution for this is, I'm all ears... | |
2447 | # |
|
2447 | # | |
2448 | # Note: using |
|
2448 | # Note: using | |
2449 | # |
|
2449 | # | |
2450 | # s = u'\xb5' |
|
2450 | # s = u'\xb5' | |
2451 | # s.encode(sys.getdefaultencoding()) |
|
2451 | # s.encode(sys.getdefaultencoding()) | |
2452 | # |
|
2452 | # | |
2453 | # is not sufficient, as I've seen terminals where that fails but |
|
2453 | # is not sufficient, as I've seen terminals where that fails but | |
2454 | # print s |
|
2454 | # print s | |
2455 | # |
|
2455 | # | |
2456 | # succeeds |
|
2456 | # succeeds | |
2457 | # |
|
2457 | # | |
2458 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
2458 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
2459 |
|
2459 | |||
2460 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
2460 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
2461 | units = [u"s", u"ms",u'us',"ns"] |
|
2461 | units = [u"s", u"ms",u'us',"ns"] | |
2462 |
|
2462 | |||
2463 | scaling = [1, 1e3, 1e6, 1e9] |
|
2463 | scaling = [1, 1e3, 1e6, 1e9] | |
2464 |
|
2464 | |||
2465 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
2465 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
2466 | posix=False, strict=False) |
|
2466 | posix=False, strict=False) | |
2467 | if stmt == "": |
|
2467 | if stmt == "": | |
2468 | return |
|
2468 | return | |
2469 | timefunc = timeit.default_timer |
|
2469 | timefunc = timeit.default_timer | |
2470 | number = int(getattr(opts, "n", 0)) |
|
2470 | number = int(getattr(opts, "n", 0)) | |
2471 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
2471 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
2472 | precision = int(getattr(opts, "p", 3)) |
|
2472 | precision = int(getattr(opts, "p", 3)) | |
2473 | if hasattr(opts, "t"): |
|
2473 | if hasattr(opts, "t"): | |
2474 | timefunc = time.time |
|
2474 | timefunc = time.time | |
2475 | if hasattr(opts, "c"): |
|
2475 | if hasattr(opts, "c"): | |
2476 | timefunc = clock |
|
2476 | timefunc = clock | |
2477 |
|
2477 | |||
2478 | timer = timeit.Timer(timer=timefunc) |
|
2478 | timer = timeit.Timer(timer=timefunc) | |
2479 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
2479 | # this code has tight coupling to the inner workings of timeit.Timer, | |
2480 | # but is there a better way to achieve that the code stmt has access |
|
2480 | # but is there a better way to achieve that the code stmt has access | |
2481 | # to the shell namespace? |
|
2481 | # to the shell namespace? | |
2482 |
|
2482 | |||
2483 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
2483 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
2484 | 'setup': "pass"} |
|
2484 | 'setup': "pass"} | |
2485 | # Track compilation time so it can be reported if too long |
|
2485 | # Track compilation time so it can be reported if too long | |
2486 | # Minimum time above which compilation time will be reported |
|
2486 | # Minimum time above which compilation time will be reported | |
2487 | tc_min = 0.1 |
|
2487 | tc_min = 0.1 | |
2488 |
|
2488 | |||
2489 | t0 = clock() |
|
2489 | t0 = clock() | |
2490 | code = compile(src, "<magic-timeit>", "exec") |
|
2490 | code = compile(src, "<magic-timeit>", "exec") | |
2491 | tc = clock()-t0 |
|
2491 | tc = clock()-t0 | |
2492 |
|
2492 | |||
2493 | ns = {} |
|
2493 | ns = {} | |
2494 | exec code in self.shell.user_ns, ns |
|
2494 | exec code in self.shell.user_ns, ns | |
2495 | timer.inner = ns["inner"] |
|
2495 | timer.inner = ns["inner"] | |
2496 |
|
2496 | |||
2497 | if number == 0: |
|
2497 | if number == 0: | |
2498 | # determine number so that 0.2 <= total time < 2.0 |
|
2498 | # determine number so that 0.2 <= total time < 2.0 | |
2499 | number = 1 |
|
2499 | number = 1 | |
2500 | for i in range(1, 10): |
|
2500 | for i in range(1, 10): | |
2501 | if timer.timeit(number) >= 0.2: |
|
2501 | if timer.timeit(number) >= 0.2: | |
2502 | break |
|
2502 | break | |
2503 | number *= 10 |
|
2503 | number *= 10 | |
2504 |
|
2504 | |||
2505 | best = min(timer.repeat(repeat, number)) / number |
|
2505 | best = min(timer.repeat(repeat, number)) / number | |
2506 |
|
2506 | |||
2507 | if best > 0.0 and best < 1000.0: |
|
2507 | if best > 0.0 and best < 1000.0: | |
2508 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
2508 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
2509 | elif best >= 1000.0: |
|
2509 | elif best >= 1000.0: | |
2510 | order = 0 |
|
2510 | order = 0 | |
2511 | else: |
|
2511 | else: | |
2512 | order = 3 |
|
2512 | order = 3 | |
2513 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
2513 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
2514 | precision, |
|
2514 | precision, | |
2515 | best * scaling[order], |
|
2515 | best * scaling[order], | |
2516 | units[order]) |
|
2516 | units[order]) | |
2517 | if tc > tc_min: |
|
2517 | if tc > tc_min: | |
2518 | print "Compiler time: %.2f s" % tc |
|
2518 | print "Compiler time: %.2f s" % tc | |
2519 |
|
2519 | |||
2520 | @cell_magic('timeit') |
|
2520 | @cell_magic('timeit') | |
2521 | def cell_timeit(self, line, cell): |
|
2521 | def cell_timeit(self, line, cell): | |
2522 | """Time execution of a Python cell.""" |
|
2522 | """Time execution of a Python cell.""" | |
2523 | raise NotImplementedError |
|
2523 | raise NotImplementedError | |
2524 |
|
2524 | |||
2525 | @skip_doctest |
|
2525 | @skip_doctest | |
2526 | @needs_local_scope |
|
2526 | @needs_local_scope | |
2527 | @line_magic |
|
2527 | @line_magic | |
2528 | def time(self,parameter_s, user_locals): |
|
2528 | def time(self,parameter_s, user_locals): | |
2529 | """Time execution of a Python statement or expression. |
|
2529 | """Time execution of a Python statement or expression. | |
2530 |
|
2530 | |||
2531 | The CPU and wall clock times are printed, and the value of the |
|
2531 | The CPU and wall clock times are printed, and the value of the | |
2532 | expression (if any) is returned. Note that under Win32, system time |
|
2532 | expression (if any) is returned. Note that under Win32, system time | |
2533 | is always reported as 0, since it can not be measured. |
|
2533 | is always reported as 0, since it can not be measured. | |
2534 |
|
2534 | |||
2535 | This function provides very basic timing functionality. In Python |
|
2535 | This function provides very basic timing functionality. In Python | |
2536 | 2.3, the timeit module offers more control and sophistication, so this |
|
2536 | 2.3, the timeit module offers more control and sophistication, so this | |
2537 | could be rewritten to use it (patches welcome). |
|
2537 | could be rewritten to use it (patches welcome). | |
2538 |
|
2538 | |||
2539 | Examples |
|
2539 | Examples | |
2540 | -------- |
|
2540 | -------- | |
2541 | :: |
|
2541 | :: | |
2542 |
|
2542 | |||
2543 | In [1]: time 2**128 |
|
2543 | In [1]: time 2**128 | |
2544 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2544 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2545 | Wall time: 0.00 |
|
2545 | Wall time: 0.00 | |
2546 | Out[1]: 340282366920938463463374607431768211456L |
|
2546 | Out[1]: 340282366920938463463374607431768211456L | |
2547 |
|
2547 | |||
2548 | In [2]: n = 1000000 |
|
2548 | In [2]: n = 1000000 | |
2549 |
|
2549 | |||
2550 | In [3]: time sum(range(n)) |
|
2550 | In [3]: time sum(range(n)) | |
2551 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
2551 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
2552 | Wall time: 1.37 |
|
2552 | Wall time: 1.37 | |
2553 | Out[3]: 499999500000L |
|
2553 | Out[3]: 499999500000L | |
2554 |
|
2554 | |||
2555 | In [4]: time print 'hello world' |
|
2555 | In [4]: time print 'hello world' | |
2556 | hello world |
|
2556 | hello world | |
2557 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2557 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2558 | Wall time: 0.00 |
|
2558 | Wall time: 0.00 | |
2559 |
|
2559 | |||
2560 | Note that the time needed by Python to compile the given expression |
|
2560 | Note that the time needed by Python to compile the given expression | |
2561 | will be reported if it is more than 0.1s. In this example, the |
|
2561 | will be reported if it is more than 0.1s. In this example, the | |
2562 | actual exponentiation is done by Python at compilation time, so while |
|
2562 | actual exponentiation is done by Python at compilation time, so while | |
2563 | the expression can take a noticeable amount of time to compute, that |
|
2563 | the expression can take a noticeable amount of time to compute, that | |
2564 | time is purely due to the compilation: |
|
2564 | time is purely due to the compilation: | |
2565 |
|
2565 | |||
2566 | In [5]: time 3**9999; |
|
2566 | In [5]: time 3**9999; | |
2567 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2567 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2568 | Wall time: 0.00 s |
|
2568 | Wall time: 0.00 s | |
2569 |
|
2569 | |||
2570 | In [6]: time 3**999999; |
|
2570 | In [6]: time 3**999999; | |
2571 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
2571 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
2572 | Wall time: 0.00 s |
|
2572 | Wall time: 0.00 s | |
2573 | Compiler : 0.78 s |
|
2573 | Compiler : 0.78 s | |
2574 | """ |
|
2574 | """ | |
2575 |
|
2575 | |||
2576 | # fail immediately if the given expression can't be compiled |
|
2576 | # fail immediately if the given expression can't be compiled | |
2577 |
|
2577 | |||
2578 | expr = self.shell.prefilter(parameter_s,False) |
|
2578 | expr = self.shell.prefilter(parameter_s,False) | |
2579 |
|
2579 | |||
2580 | # Minimum time above which compilation time will be reported |
|
2580 | # Minimum time above which compilation time will be reported | |
2581 | tc_min = 0.1 |
|
2581 | tc_min = 0.1 | |
2582 |
|
2582 | |||
2583 | try: |
|
2583 | try: | |
2584 | mode = 'eval' |
|
2584 | mode = 'eval' | |
2585 | t0 = clock() |
|
2585 | t0 = clock() | |
2586 | code = compile(expr,'<timed eval>',mode) |
|
2586 | code = compile(expr,'<timed eval>',mode) | |
2587 | tc = clock()-t0 |
|
2587 | tc = clock()-t0 | |
2588 | except SyntaxError: |
|
2588 | except SyntaxError: | |
2589 | mode = 'exec' |
|
2589 | mode = 'exec' | |
2590 | t0 = clock() |
|
2590 | t0 = clock() | |
2591 | code = compile(expr,'<timed exec>',mode) |
|
2591 | code = compile(expr,'<timed exec>',mode) | |
2592 | tc = clock()-t0 |
|
2592 | tc = clock()-t0 | |
2593 | # skew measurement as little as possible |
|
2593 | # skew measurement as little as possible | |
2594 | glob = self.shell.user_ns |
|
2594 | glob = self.shell.user_ns | |
2595 | wtime = time.time |
|
2595 | wtime = time.time | |
2596 | # time execution |
|
2596 | # time execution | |
2597 | wall_st = wtime() |
|
2597 | wall_st = wtime() | |
2598 | if mode=='eval': |
|
2598 | if mode=='eval': | |
2599 | st = clock2() |
|
2599 | st = clock2() | |
2600 | out = eval(code, glob, user_locals) |
|
2600 | out = eval(code, glob, user_locals) | |
2601 | end = clock2() |
|
2601 | end = clock2() | |
2602 | else: |
|
2602 | else: | |
2603 | st = clock2() |
|
2603 | st = clock2() | |
2604 | exec code in glob, user_locals |
|
2604 | exec code in glob, user_locals | |
2605 | end = clock2() |
|
2605 | end = clock2() | |
2606 | out = None |
|
2606 | out = None | |
2607 | wall_end = wtime() |
|
2607 | wall_end = wtime() | |
2608 | # Compute actual times and report |
|
2608 | # Compute actual times and report | |
2609 | wall_time = wall_end-wall_st |
|
2609 | wall_time = wall_end-wall_st | |
2610 | cpu_user = end[0]-st[0] |
|
2610 | cpu_user = end[0]-st[0] | |
2611 | cpu_sys = end[1]-st[1] |
|
2611 | cpu_sys = end[1]-st[1] | |
2612 | cpu_tot = cpu_user+cpu_sys |
|
2612 | cpu_tot = cpu_user+cpu_sys | |
2613 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
2613 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
2614 | (cpu_user,cpu_sys,cpu_tot) |
|
2614 | (cpu_user,cpu_sys,cpu_tot) | |
2615 | print "Wall time: %.2f s" % wall_time |
|
2615 | print "Wall time: %.2f s" % wall_time | |
2616 | if tc > tc_min: |
|
2616 | if tc > tc_min: | |
2617 | print "Compiler : %.2f s" % tc |
|
2617 | print "Compiler : %.2f s" % tc | |
2618 | return out |
|
2618 | return out | |
2619 |
|
2619 | |||
2620 | @skip_doctest |
|
2620 | @skip_doctest | |
2621 | @line_magic |
|
2621 | @line_magic | |
2622 | def macro(self, parameter_s=''): |
|
2622 | def macro(self, parameter_s=''): | |
2623 | """Define a macro for future re-execution. It accepts ranges of history, |
|
2623 | """Define a macro for future re-execution. It accepts ranges of history, | |
2624 | filenames or string objects. |
|
2624 | filenames or string objects. | |
2625 |
|
2625 | |||
2626 | Usage:\\ |
|
2626 | Usage:\\ | |
2627 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
2627 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
2628 |
|
2628 | |||
2629 | Options: |
|
2629 | Options: | |
2630 |
|
2630 | |||
2631 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2631 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2632 | so that magics are loaded in their transformed version to valid |
|
2632 | so that magics are loaded in their transformed version to valid | |
2633 | Python. If this option is given, the raw input as typed as the |
|
2633 | Python. If this option is given, the raw input as typed as the | |
2634 | command line is used instead. |
|
2634 | command line is used instead. | |
2635 |
|
2635 | |||
2636 | This will define a global variable called `name` which is a string |
|
2636 | This will define a global variable called `name` which is a string | |
2637 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
2637 | made of joining the slices and lines you specify (n1,n2,... numbers | |
2638 | above) from your input history into a single string. This variable |
|
2638 | above) from your input history into a single string. This variable | |
2639 | acts like an automatic function which re-executes those lines as if |
|
2639 | acts like an automatic function which re-executes those lines as if | |
2640 | you had typed them. You just type 'name' at the prompt and the code |
|
2640 | you had typed them. You just type 'name' at the prompt and the code | |
2641 | executes. |
|
2641 | executes. | |
2642 |
|
2642 | |||
2643 | The syntax for indicating input ranges is described in %history. |
|
2643 | The syntax for indicating input ranges is described in %history. | |
2644 |
|
2644 | |||
2645 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
2645 | Note: as a 'hidden' feature, you can also use traditional python slice | |
2646 | notation, where N:M means numbers N through M-1. |
|
2646 | notation, where N:M means numbers N through M-1. | |
2647 |
|
2647 | |||
2648 | For example, if your history contains (%hist prints it):: |
|
2648 | For example, if your history contains (%hist prints it):: | |
2649 |
|
2649 | |||
2650 | 44: x=1 |
|
2650 | 44: x=1 | |
2651 | 45: y=3 |
|
2651 | 45: y=3 | |
2652 | 46: z=x+y |
|
2652 | 46: z=x+y | |
2653 | 47: print x |
|
2653 | 47: print x | |
2654 | 48: a=5 |
|
2654 | 48: a=5 | |
2655 | 49: print 'x',x,'y',y |
|
2655 | 49: print 'x',x,'y',y | |
2656 |
|
2656 | |||
2657 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2657 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2658 | called my_macro with:: |
|
2658 | called my_macro with:: | |
2659 |
|
2659 | |||
2660 | In [55]: %macro my_macro 44-47 49 |
|
2660 | In [55]: %macro my_macro 44-47 49 | |
2661 |
|
2661 | |||
2662 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2662 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2663 | in one pass. |
|
2663 | in one pass. | |
2664 |
|
2664 | |||
2665 | You don't need to give the line-numbers in order, and any given line |
|
2665 | You don't need to give the line-numbers in order, and any given line | |
2666 | number can appear multiple times. You can assemble macros with any |
|
2666 | number can appear multiple times. You can assemble macros with any | |
2667 | lines from your input history in any order. |
|
2667 | lines from your input history in any order. | |
2668 |
|
2668 | |||
2669 | The macro is a simple object which holds its value in an attribute, |
|
2669 | The macro is a simple object which holds its value in an attribute, | |
2670 | but IPython's display system checks for macros and executes them as |
|
2670 | but IPython's display system checks for macros and executes them as | |
2671 | code instead of printing them when you type their name. |
|
2671 | code instead of printing them when you type their name. | |
2672 |
|
2672 | |||
2673 | You can view a macro's contents by explicitly printing it with:: |
|
2673 | You can view a macro's contents by explicitly printing it with:: | |
2674 |
|
2674 | |||
2675 | print macro_name |
|
2675 | print macro_name | |
2676 |
|
2676 | |||
2677 | """ |
|
2677 | """ | |
2678 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2678 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2679 | if not args: # List existing macros |
|
2679 | if not args: # List existing macros | |
2680 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ |
|
2680 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ | |
2681 | isinstance(v, Macro)) |
|
2681 | isinstance(v, Macro)) | |
2682 | if len(args) == 1: |
|
2682 | if len(args) == 1: | |
2683 | raise UsageError( |
|
2683 | raise UsageError( | |
2684 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2684 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2685 | name, codefrom = args[0], " ".join(args[1:]) |
|
2685 | name, codefrom = args[0], " ".join(args[1:]) | |
2686 |
|
2686 | |||
2687 | #print 'rng',ranges # dbg |
|
2687 | #print 'rng',ranges # dbg | |
2688 | try: |
|
2688 | try: | |
2689 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2689 | lines = self.shell.find_user_code(codefrom, 'r' in opts) | |
2690 | except (ValueError, TypeError) as e: |
|
2690 | except (ValueError, TypeError) as e: | |
2691 | print e.args[0] |
|
2691 | print e.args[0] | |
2692 | return |
|
2692 | return | |
2693 | macro = Macro(lines) |
|
2693 | macro = Macro(lines) | |
2694 | self.shell.define_macro(name, macro) |
|
2694 | self.shell.define_macro(name, macro) | |
2695 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2695 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2696 | print '=== Macro contents: ===' |
|
2696 | print '=== Macro contents: ===' | |
2697 | print macro, |
|
2697 | print macro, | |
2698 |
|
2698 | |||
2699 |
|
2699 | |||
2700 | @register_magics |
|
2700 | @register_magics | |
2701 | class AutoMagics(Magics): |
|
2701 | class AutoMagics(Magics): | |
2702 | """Magics that control various autoX behaviors.""" |
|
2702 | """Magics that control various autoX behaviors.""" | |
2703 |
|
2703 | |||
2704 | def __init__(self, shell): |
|
2704 | def __init__(self, shell): | |
2705 | super(AutoMagics, self).__init__(shell) |
|
2705 | super(AutoMagics, self).__init__(shell) | |
2706 | # namespace for holding state we may need |
|
2706 | # namespace for holding state we may need | |
2707 | self._magic_state = Bunch() |
|
2707 | self._magic_state = Bunch() | |
2708 |
|
2708 | |||
2709 | @line_magic |
|
2709 | @line_magic | |
2710 | def automagic(self, parameter_s=''): |
|
2710 | def automagic(self, parameter_s=''): | |
2711 | """Make magic functions callable without having to type the initial %. |
|
2711 | """Make magic functions callable without having to type the initial %. | |
2712 |
|
2712 | |||
2713 | Without argumentsl toggles on/off (when off, you must call it as |
|
2713 | Without argumentsl toggles on/off (when off, you must call it as | |
2714 | %automagic, of course). With arguments it sets the value, and you can |
|
2714 | %automagic, of course). With arguments it sets the value, and you can | |
2715 | use any of (case insensitive): |
|
2715 | use any of (case insensitive): | |
2716 |
|
2716 | |||
2717 | - on, 1, True: to activate |
|
2717 | - on, 1, True: to activate | |
2718 |
|
2718 | |||
2719 | - off, 0, False: to deactivate. |
|
2719 | - off, 0, False: to deactivate. | |
2720 |
|
2720 | |||
2721 | Note that magic functions have lowest priority, so if there's a |
|
2721 | Note that magic functions have lowest priority, so if there's a | |
2722 | variable whose name collides with that of a magic fn, automagic won't |
|
2722 | variable whose name collides with that of a magic fn, automagic won't | |
2723 | work for that function (you get the variable instead). However, if you |
|
2723 | work for that function (you get the variable instead). However, if you | |
2724 | delete the variable (del var), the previously shadowed magic function |
|
2724 | delete the variable (del var), the previously shadowed magic function | |
2725 | becomes visible to automagic again.""" |
|
2725 | becomes visible to automagic again.""" | |
2726 |
|
2726 | |||
2727 | arg = parameter_s.lower() |
|
2727 | arg = parameter_s.lower() | |
2728 | mman = self.shell.magics_manager |
|
2728 | mman = self.shell.magics_manager | |
2729 | if arg in ('on', '1', 'true'): |
|
2729 | if arg in ('on', '1', 'true'): | |
2730 | val = True |
|
2730 | val = True | |
2731 | elif arg in ('off', '0', 'false'): |
|
2731 | elif arg in ('off', '0', 'false'): | |
2732 | val = False |
|
2732 | val = False | |
2733 | else: |
|
2733 | else: | |
2734 | val = not mman.auto_magic |
|
2734 | val = not mman.auto_magic | |
2735 | mman.auto_magic = val |
|
2735 | mman.auto_magic = val | |
2736 | print '\n' + self.shell.magics_manager.auto_status() |
|
2736 | print '\n' + self.shell.magics_manager.auto_status() | |
2737 |
|
2737 | |||
2738 | @skip_doctest |
|
2738 | @skip_doctest | |
2739 | @line_magic |
|
2739 | @line_magic | |
2740 | def autocall(self, parameter_s=''): |
|
2740 | def autocall(self, parameter_s=''): | |
2741 | """Make functions callable without having to type parentheses. |
|
2741 | """Make functions callable without having to type parentheses. | |
2742 |
|
2742 | |||
2743 | Usage: |
|
2743 | Usage: | |
2744 |
|
2744 | |||
2745 | %autocall [mode] |
|
2745 | %autocall [mode] | |
2746 |
|
2746 | |||
2747 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
2747 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
2748 | value is toggled on and off (remembering the previous state). |
|
2748 | value is toggled on and off (remembering the previous state). | |
2749 |
|
2749 | |||
2750 | In more detail, these values mean: |
|
2750 | In more detail, these values mean: | |
2751 |
|
2751 | |||
2752 | 0 -> fully disabled |
|
2752 | 0 -> fully disabled | |
2753 |
|
2753 | |||
2754 | 1 -> active, but do not apply if there are no arguments on the line. |
|
2754 | 1 -> active, but do not apply if there are no arguments on the line. | |
2755 |
|
2755 | |||
2756 | In this mode, you get:: |
|
2756 | In this mode, you get:: | |
2757 |
|
2757 | |||
2758 | In [1]: callable |
|
2758 | In [1]: callable | |
2759 | Out[1]: <built-in function callable> |
|
2759 | Out[1]: <built-in function callable> | |
2760 |
|
2760 | |||
2761 | In [2]: callable 'hello' |
|
2761 | In [2]: callable 'hello' | |
2762 | ------> callable('hello') |
|
2762 | ------> callable('hello') | |
2763 | Out[2]: False |
|
2763 | Out[2]: False | |
2764 |
|
2764 | |||
2765 | 2 -> Active always. Even if no arguments are present, the callable |
|
2765 | 2 -> Active always. Even if no arguments are present, the callable | |
2766 | object is called:: |
|
2766 | object is called:: | |
2767 |
|
2767 | |||
2768 | In [2]: float |
|
2768 | In [2]: float | |
2769 | ------> float() |
|
2769 | ------> float() | |
2770 | Out[2]: 0.0 |
|
2770 | Out[2]: 0.0 | |
2771 |
|
2771 | |||
2772 | Note that even with autocall off, you can still use '/' at the start of |
|
2772 | Note that even with autocall off, you can still use '/' at the start of | |
2773 | a line to treat the first argument on the command line as a function |
|
2773 | a line to treat the first argument on the command line as a function | |
2774 | and add parentheses to it:: |
|
2774 | and add parentheses to it:: | |
2775 |
|
2775 | |||
2776 | In [8]: /str 43 |
|
2776 | In [8]: /str 43 | |
2777 | ------> str(43) |
|
2777 | ------> str(43) | |
2778 | Out[8]: '43' |
|
2778 | Out[8]: '43' | |
2779 |
|
2779 | |||
2780 | # all-random (note for auto-testing) |
|
2780 | # all-random (note for auto-testing) | |
2781 | """ |
|
2781 | """ | |
2782 |
|
2782 | |||
2783 | if parameter_s: |
|
2783 | if parameter_s: | |
2784 | arg = int(parameter_s) |
|
2784 | arg = int(parameter_s) | |
2785 | else: |
|
2785 | else: | |
2786 | arg = 'toggle' |
|
2786 | arg = 'toggle' | |
2787 |
|
2787 | |||
2788 | if not arg in (0, 1, 2,'toggle'): |
|
2788 | if not arg in (0, 1, 2,'toggle'): | |
2789 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
2789 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
2790 | return |
|
2790 | return | |
2791 |
|
2791 | |||
2792 | if arg in (0, 1, 2): |
|
2792 | if arg in (0, 1, 2): | |
2793 | self.shell.autocall = arg |
|
2793 | self.shell.autocall = arg | |
2794 | else: # toggle |
|
2794 | else: # toggle | |
2795 | if self.shell.autocall: |
|
2795 | if self.shell.autocall: | |
2796 | self._magic_state.autocall_save = self.shell.autocall |
|
2796 | self._magic_state.autocall_save = self.shell.autocall | |
2797 | self.shell.autocall = 0 |
|
2797 | self.shell.autocall = 0 | |
2798 | else: |
|
2798 | else: | |
2799 | try: |
|
2799 | try: | |
2800 | self.shell.autocall = self._magic_state.autocall_save |
|
2800 | self.shell.autocall = self._magic_state.autocall_save | |
2801 | except AttributeError: |
|
2801 | except AttributeError: | |
2802 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
2802 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
2803 |
|
2803 | |||
2804 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
2804 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
2805 |
|
2805 | |||
2806 |
|
2806 | |||
2807 | @register_magics |
|
2807 | @register_magics | |
2808 | class OSMagics(Magics): |
|
2808 | class OSMagics(Magics): | |
2809 | """Magics to interact with the underlying OS (shell-type functionality). |
|
2809 | """Magics to interact with the underlying OS (shell-type functionality). | |
2810 | """ |
|
2810 | """ | |
2811 |
|
2811 | |||
2812 | @skip_doctest |
|
2812 | @skip_doctest | |
2813 | @line_magic |
|
2813 | @line_magic | |
2814 | def alias(self, parameter_s=''): |
|
2814 | def alias(self, parameter_s=''): | |
2815 | """Define an alias for a system command. |
|
2815 | """Define an alias for a system command. | |
2816 |
|
2816 | |||
2817 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2817 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2818 |
|
2818 | |||
2819 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2819 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2820 | params' (from your underlying operating system). |
|
2820 | params' (from your underlying operating system). | |
2821 |
|
2821 | |||
2822 | Aliases have lower precedence than magic functions and Python normal |
|
2822 | Aliases have lower precedence than magic functions and Python normal | |
2823 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2823 | variables, so if 'foo' is both a Python variable and an alias, the | |
2824 | alias can not be executed until 'del foo' removes the Python variable. |
|
2824 | alias can not be executed until 'del foo' removes the Python variable. | |
2825 |
|
2825 | |||
2826 | You can use the %l specifier in an alias definition to represent the |
|
2826 | You can use the %l specifier in an alias definition to represent the | |
2827 | whole line when the alias is called. For example:: |
|
2827 | whole line when the alias is called. For example:: | |
2828 |
|
2828 | |||
2829 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2829 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2830 | In [3]: bracket hello world |
|
2830 | In [3]: bracket hello world | |
2831 | Input in brackets: <hello world> |
|
2831 | Input in brackets: <hello world> | |
2832 |
|
2832 | |||
2833 | You can also define aliases with parameters using %s specifiers (one |
|
2833 | You can also define aliases with parameters using %s specifiers (one | |
2834 | per parameter):: |
|
2834 | per parameter):: | |
2835 |
|
2835 | |||
2836 | In [1]: alias parts echo first %s second %s |
|
2836 | In [1]: alias parts echo first %s second %s | |
2837 | In [2]: %parts A B |
|
2837 | In [2]: %parts A B | |
2838 | first A second B |
|
2838 | first A second B | |
2839 | In [3]: %parts A |
|
2839 | In [3]: %parts A | |
2840 | Incorrect number of arguments: 2 expected. |
|
2840 | Incorrect number of arguments: 2 expected. | |
2841 | parts is an alias to: 'echo first %s second %s' |
|
2841 | parts is an alias to: 'echo first %s second %s' | |
2842 |
|
2842 | |||
2843 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2843 | Note that %l and %s are mutually exclusive. You can only use one or | |
2844 | the other in your aliases. |
|
2844 | the other in your aliases. | |
2845 |
|
2845 | |||
2846 | Aliases expand Python variables just like system calls using ! or !! |
|
2846 | Aliases expand Python variables just like system calls using ! or !! | |
2847 | do: all expressions prefixed with '$' get expanded. For details of |
|
2847 | do: all expressions prefixed with '$' get expanded. For details of | |
2848 | the semantic rules, see PEP-215: |
|
2848 | the semantic rules, see PEP-215: | |
2849 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2849 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2850 | IPython for variable expansion. If you want to access a true shell |
|
2850 | IPython for variable expansion. If you want to access a true shell | |
2851 | variable, an extra $ is necessary to prevent its expansion by |
|
2851 | variable, an extra $ is necessary to prevent its expansion by | |
2852 | IPython:: |
|
2852 | IPython:: | |
2853 |
|
2853 | |||
2854 | In [6]: alias show echo |
|
2854 | In [6]: alias show echo | |
2855 | In [7]: PATH='A Python string' |
|
2855 | In [7]: PATH='A Python string' | |
2856 | In [8]: show $PATH |
|
2856 | In [8]: show $PATH | |
2857 | A Python string |
|
2857 | A Python string | |
2858 | In [9]: show $$PATH |
|
2858 | In [9]: show $$PATH | |
2859 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2859 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2860 |
|
2860 | |||
2861 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2861 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2862 | and %rehashx functions, which automatically create aliases for the |
|
2862 | and %rehashx functions, which automatically create aliases for the | |
2863 | contents of your $PATH. |
|
2863 | contents of your $PATH. | |
2864 |
|
2864 | |||
2865 | If called with no parameters, %alias prints the current alias table.""" |
|
2865 | If called with no parameters, %alias prints the current alias table.""" | |
2866 |
|
2866 | |||
2867 | par = parameter_s.strip() |
|
2867 | par = parameter_s.strip() | |
2868 | if not par: |
|
2868 | if not par: | |
2869 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2869 | aliases = sorted(self.shell.alias_manager.aliases) | |
2870 | # stored = self.shell.db.get('stored_aliases', {} ) |
|
2870 | # stored = self.shell.db.get('stored_aliases', {} ) | |
2871 | # for k, v in stored: |
|
2871 | # for k, v in stored: | |
2872 | # atab.append(k, v[0]) |
|
2872 | # atab.append(k, v[0]) | |
2873 |
|
2873 | |||
2874 | print "Total number of aliases:", len(aliases) |
|
2874 | print "Total number of aliases:", len(aliases) | |
2875 | sys.stdout.flush() |
|
2875 | sys.stdout.flush() | |
2876 | return aliases |
|
2876 | return aliases | |
2877 |
|
2877 | |||
2878 | # Now try to define a new one |
|
2878 | # Now try to define a new one | |
2879 | try: |
|
2879 | try: | |
2880 | alias,cmd = par.split(None, 1) |
|
2880 | alias,cmd = par.split(None, 1) | |
2881 | except: |
|
2881 | except: | |
2882 | print oinspect.getdoc(self.magic_alias) |
|
2882 | print oinspect.getdoc(self.magic_alias) | |
2883 | else: |
|
2883 | else: | |
2884 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2884 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2885 | # end magic_alias |
|
2885 | # end magic_alias | |
2886 |
|
2886 | |||
2887 | @line_magic |
|
2887 | @line_magic | |
2888 | def unalias(self, parameter_s=''): |
|
2888 | def unalias(self, parameter_s=''): | |
2889 | """Remove an alias""" |
|
2889 | """Remove an alias""" | |
2890 |
|
2890 | |||
2891 | aname = parameter_s.strip() |
|
2891 | aname = parameter_s.strip() | |
2892 | self.shell.alias_manager.undefine_alias(aname) |
|
2892 | self.shell.alias_manager.undefine_alias(aname) | |
2893 | stored = self.shell.db.get('stored_aliases', {} ) |
|
2893 | stored = self.shell.db.get('stored_aliases', {} ) | |
2894 | if aname in stored: |
|
2894 | if aname in stored: | |
2895 | print "Removing %stored alias",aname |
|
2895 | print "Removing %stored alias",aname | |
2896 | del stored[aname] |
|
2896 | del stored[aname] | |
2897 | self.shell.db['stored_aliases'] = stored |
|
2897 | self.shell.db['stored_aliases'] = stored | |
2898 |
|
2898 | |||
2899 | @line_magic |
|
2899 | @line_magic | |
2900 | def rehashx(self, parameter_s=''): |
|
2900 | def rehashx(self, parameter_s=''): | |
2901 | """Update the alias table with all executable files in $PATH. |
|
2901 | """Update the alias table with all executable files in $PATH. | |
2902 |
|
2902 | |||
2903 | This version explicitly checks that every entry in $PATH is a file |
|
2903 | This version explicitly checks that every entry in $PATH is a file | |
2904 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2904 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2905 |
|
2905 | |||
2906 | Under Windows, it checks executability as a match against a |
|
2906 | Under Windows, it checks executability as a match against a | |
2907 | '|'-separated string of extensions, stored in the IPython config |
|
2907 | '|'-separated string of extensions, stored in the IPython config | |
2908 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2908 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2909 |
|
2909 | |||
2910 | This function also resets the root module cache of module completer, |
|
2910 | This function also resets the root module cache of module completer, | |
2911 | used on slow filesystems. |
|
2911 | used on slow filesystems. | |
2912 | """ |
|
2912 | """ | |
2913 | from IPython.core.alias import InvalidAliasError |
|
2913 | from IPython.core.alias import InvalidAliasError | |
2914 |
|
2914 | |||
2915 | # for the benefit of module completer in ipy_completers.py |
|
2915 | # for the benefit of module completer in ipy_completers.py | |
2916 | del self.shell.db['rootmodules'] |
|
2916 | del self.shell.db['rootmodules'] | |
2917 |
|
2917 | |||
2918 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2918 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2919 | os.environ.get('PATH','').split(os.pathsep)] |
|
2919 | os.environ.get('PATH','').split(os.pathsep)] | |
2920 | path = filter(os.path.isdir,path) |
|
2920 | path = filter(os.path.isdir,path) | |
2921 |
|
2921 | |||
2922 | syscmdlist = [] |
|
2922 | syscmdlist = [] | |
2923 | # Now define isexec in a cross platform manner. |
|
2923 | # Now define isexec in a cross platform manner. | |
2924 | if os.name == 'posix': |
|
2924 | if os.name == 'posix': | |
2925 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2925 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2926 | os.access(fname,os.X_OK) |
|
2926 | os.access(fname,os.X_OK) | |
2927 | else: |
|
2927 | else: | |
2928 | try: |
|
2928 | try: | |
2929 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2929 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2930 | except KeyError: |
|
2930 | except KeyError: | |
2931 | winext = 'exe|com|bat|py' |
|
2931 | winext = 'exe|com|bat|py' | |
2932 | if 'py' not in winext: |
|
2932 | if 'py' not in winext: | |
2933 | winext += '|py' |
|
2933 | winext += '|py' | |
2934 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2934 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2935 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2935 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2936 | savedir = os.getcwdu() |
|
2936 | savedir = os.getcwdu() | |
2937 |
|
2937 | |||
2938 | # Now walk the paths looking for executables to alias. |
|
2938 | # Now walk the paths looking for executables to alias. | |
2939 | try: |
|
2939 | try: | |
2940 | # write the whole loop for posix/Windows so we don't have an if in |
|
2940 | # write the whole loop for posix/Windows so we don't have an if in | |
2941 | # the innermost part |
|
2941 | # the innermost part | |
2942 | if os.name == 'posix': |
|
2942 | if os.name == 'posix': | |
2943 | for pdir in path: |
|
2943 | for pdir in path: | |
2944 | os.chdir(pdir) |
|
2944 | os.chdir(pdir) | |
2945 | for ff in os.listdir(pdir): |
|
2945 | for ff in os.listdir(pdir): | |
2946 | if isexec(ff): |
|
2946 | if isexec(ff): | |
2947 | try: |
|
2947 | try: | |
2948 | # Removes dots from the name since ipython |
|
2948 | # Removes dots from the name since ipython | |
2949 | # will assume names with dots to be python. |
|
2949 | # will assume names with dots to be python. | |
2950 | self.shell.alias_manager.define_alias( |
|
2950 | self.shell.alias_manager.define_alias( | |
2951 | ff.replace('.',''), ff) |
|
2951 | ff.replace('.',''), ff) | |
2952 | except InvalidAliasError: |
|
2952 | except InvalidAliasError: | |
2953 | pass |
|
2953 | pass | |
2954 | else: |
|
2954 | else: | |
2955 | syscmdlist.append(ff) |
|
2955 | syscmdlist.append(ff) | |
2956 | else: |
|
2956 | else: | |
2957 | no_alias = self.shell.alias_manager.no_alias |
|
2957 | no_alias = self.shell.alias_manager.no_alias | |
2958 | for pdir in path: |
|
2958 | for pdir in path: | |
2959 | os.chdir(pdir) |
|
2959 | os.chdir(pdir) | |
2960 | for ff in os.listdir(pdir): |
|
2960 | for ff in os.listdir(pdir): | |
2961 | base, ext = os.path.splitext(ff) |
|
2961 | base, ext = os.path.splitext(ff) | |
2962 | if isexec(ff) and base.lower() not in no_alias: |
|
2962 | if isexec(ff) and base.lower() not in no_alias: | |
2963 | if ext.lower() == '.exe': |
|
2963 | if ext.lower() == '.exe': | |
2964 | ff = base |
|
2964 | ff = base | |
2965 | try: |
|
2965 | try: | |
2966 | # Removes dots from the name since ipython |
|
2966 | # Removes dots from the name since ipython | |
2967 | # will assume names with dots to be python. |
|
2967 | # will assume names with dots to be python. | |
2968 | self.shell.alias_manager.define_alias( |
|
2968 | self.shell.alias_manager.define_alias( | |
2969 | base.lower().replace('.',''), ff) |
|
2969 | base.lower().replace('.',''), ff) | |
2970 | except InvalidAliasError: |
|
2970 | except InvalidAliasError: | |
2971 | pass |
|
2971 | pass | |
2972 | syscmdlist.append(ff) |
|
2972 | syscmdlist.append(ff) | |
2973 | self.shell.db['syscmdlist'] = syscmdlist |
|
2973 | self.shell.db['syscmdlist'] = syscmdlist | |
2974 | finally: |
|
2974 | finally: | |
2975 | os.chdir(savedir) |
|
2975 | os.chdir(savedir) | |
2976 |
|
2976 | |||
2977 | @skip_doctest |
|
2977 | @skip_doctest | |
2978 | @line_magic |
|
2978 | @line_magic | |
2979 | def pwd(self, parameter_s=''): |
|
2979 | def pwd(self, parameter_s=''): | |
2980 | """Return the current working directory path. |
|
2980 | """Return the current working directory path. | |
2981 |
|
2981 | |||
2982 | Examples |
|
2982 | Examples | |
2983 | -------- |
|
2983 | -------- | |
2984 | :: |
|
2984 | :: | |
2985 |
|
2985 | |||
2986 | In [9]: pwd |
|
2986 | In [9]: pwd | |
2987 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2987 | Out[9]: '/home/tsuser/sprint/ipython' | |
2988 | """ |
|
2988 | """ | |
2989 | return os.getcwdu() |
|
2989 | return os.getcwdu() | |
2990 |
|
2990 | |||
2991 | @skip_doctest |
|
2991 | @skip_doctest | |
2992 | @line_magic |
|
2992 | @line_magic | |
2993 | def cd(self, parameter_s=''): |
|
2993 | def cd(self, parameter_s=''): | |
2994 | """Change the current working directory. |
|
2994 | """Change the current working directory. | |
2995 |
|
2995 | |||
2996 | This command automatically maintains an internal list of directories |
|
2996 | This command automatically maintains an internal list of directories | |
2997 | you visit during your IPython session, in the variable _dh. The |
|
2997 | you visit during your IPython session, in the variable _dh. The | |
2998 | command %dhist shows this history nicely formatted. You can also |
|
2998 | command %dhist shows this history nicely formatted. You can also | |
2999 | do 'cd -<tab>' to see directory history conveniently. |
|
2999 | do 'cd -<tab>' to see directory history conveniently. | |
3000 |
|
3000 | |||
3001 | Usage: |
|
3001 | Usage: | |
3002 |
|
3002 | |||
3003 | cd 'dir': changes to directory 'dir'. |
|
3003 | cd 'dir': changes to directory 'dir'. | |
3004 |
|
3004 | |||
3005 | cd -: changes to the last visited directory. |
|
3005 | cd -: changes to the last visited directory. | |
3006 |
|
3006 | |||
3007 | cd -<n>: changes to the n-th directory in the directory history. |
|
3007 | cd -<n>: changes to the n-th directory in the directory history. | |
3008 |
|
3008 | |||
3009 | cd --foo: change to directory that matches 'foo' in history |
|
3009 | cd --foo: change to directory that matches 'foo' in history | |
3010 |
|
3010 | |||
3011 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
3011 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
3012 | (note: cd <bookmark_name> is enough if there is no |
|
3012 | (note: cd <bookmark_name> is enough if there is no | |
3013 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
3013 | directory <bookmark_name>, but a bookmark with the name exists.) | |
3014 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
3014 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
3015 |
|
3015 | |||
3016 | Options: |
|
3016 | Options: | |
3017 |
|
3017 | |||
3018 | -q: quiet. Do not print the working directory after the cd command is |
|
3018 | -q: quiet. Do not print the working directory after the cd command is | |
3019 | executed. By default IPython's cd command does print this directory, |
|
3019 | executed. By default IPython's cd command does print this directory, | |
3020 | since the default prompts do not display path information. |
|
3020 | since the default prompts do not display path information. | |
3021 |
|
3021 | |||
3022 | Note that !cd doesn't work for this purpose because the shell where |
|
3022 | Note that !cd doesn't work for this purpose because the shell where | |
3023 | !command runs is immediately discarded after executing 'command'. |
|
3023 | !command runs is immediately discarded after executing 'command'. | |
3024 |
|
3024 | |||
3025 | Examples |
|
3025 | Examples | |
3026 | -------- |
|
3026 | -------- | |
3027 | :: |
|
3027 | :: | |
3028 |
|
3028 | |||
3029 | In [10]: cd parent/child |
|
3029 | In [10]: cd parent/child | |
3030 | /home/tsuser/parent/child |
|
3030 | /home/tsuser/parent/child | |
3031 | """ |
|
3031 | """ | |
3032 |
|
3032 | |||
3033 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
3033 | #bkms = self.shell.persist.get("bookmarks",{}) | |
3034 |
|
3034 | |||
3035 | oldcwd = os.getcwdu() |
|
3035 | oldcwd = os.getcwdu() | |
3036 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
3036 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
3037 | # jump in directory history by number |
|
3037 | # jump in directory history by number | |
3038 | if numcd: |
|
3038 | if numcd: | |
3039 | nn = int(numcd.group(2)) |
|
3039 | nn = int(numcd.group(2)) | |
3040 | try: |
|
3040 | try: | |
3041 | ps = self.shell.user_ns['_dh'][nn] |
|
3041 | ps = self.shell.user_ns['_dh'][nn] | |
3042 | except IndexError: |
|
3042 | except IndexError: | |
3043 | print 'The requested directory does not exist in history.' |
|
3043 | print 'The requested directory does not exist in history.' | |
3044 | return |
|
3044 | return | |
3045 | else: |
|
3045 | else: | |
3046 | opts = {} |
|
3046 | opts = {} | |
3047 | elif parameter_s.startswith('--'): |
|
3047 | elif parameter_s.startswith('--'): | |
3048 | ps = None |
|
3048 | ps = None | |
3049 | fallback = None |
|
3049 | fallback = None | |
3050 | pat = parameter_s[2:] |
|
3050 | pat = parameter_s[2:] | |
3051 | dh = self.shell.user_ns['_dh'] |
|
3051 | dh = self.shell.user_ns['_dh'] | |
3052 | # first search only by basename (last component) |
|
3052 | # first search only by basename (last component) | |
3053 | for ent in reversed(dh): |
|
3053 | for ent in reversed(dh): | |
3054 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
3054 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
3055 | ps = ent |
|
3055 | ps = ent | |
3056 | break |
|
3056 | break | |
3057 |
|
3057 | |||
3058 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
3058 | if fallback is None and pat in ent and os.path.isdir(ent): | |
3059 | fallback = ent |
|
3059 | fallback = ent | |
3060 |
|
3060 | |||
3061 | # if we have no last part match, pick the first full path match |
|
3061 | # if we have no last part match, pick the first full path match | |
3062 | if ps is None: |
|
3062 | if ps is None: | |
3063 | ps = fallback |
|
3063 | ps = fallback | |
3064 |
|
3064 | |||
3065 | if ps is None: |
|
3065 | if ps is None: | |
3066 | print "No matching entry in directory history" |
|
3066 | print "No matching entry in directory history" | |
3067 | return |
|
3067 | return | |
3068 | else: |
|
3068 | else: | |
3069 | opts = {} |
|
3069 | opts = {} | |
3070 |
|
3070 | |||
3071 |
|
3071 | |||
3072 | else: |
|
3072 | else: | |
3073 | #turn all non-space-escaping backslashes to slashes, |
|
3073 | #turn all non-space-escaping backslashes to slashes, | |
3074 | # for c:\windows\directory\names\ |
|
3074 | # for c:\windows\directory\names\ | |
3075 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
3075 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
3076 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
3076 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
3077 | # jump to previous |
|
3077 | # jump to previous | |
3078 | if ps == '-': |
|
3078 | if ps == '-': | |
3079 | try: |
|
3079 | try: | |
3080 | ps = self.shell.user_ns['_dh'][-2] |
|
3080 | ps = self.shell.user_ns['_dh'][-2] | |
3081 | except IndexError: |
|
3081 | except IndexError: | |
3082 | raise UsageError('%cd -: No previous directory to change to.') |
|
3082 | raise UsageError('%cd -: No previous directory to change to.') | |
3083 | # jump to bookmark if needed |
|
3083 | # jump to bookmark if needed | |
3084 | else: |
|
3084 | else: | |
3085 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
3085 | if not os.path.isdir(ps) or opts.has_key('b'): | |
3086 | bkms = self.shell.db.get('bookmarks', {}) |
|
3086 | bkms = self.shell.db.get('bookmarks', {}) | |
3087 |
|
3087 | |||
3088 | if bkms.has_key(ps): |
|
3088 | if bkms.has_key(ps): | |
3089 | target = bkms[ps] |
|
3089 | target = bkms[ps] | |
3090 | print '(bookmark:%s) -> %s' % (ps,target) |
|
3090 | print '(bookmark:%s) -> %s' % (ps,target) | |
3091 | ps = target |
|
3091 | ps = target | |
3092 | else: |
|
3092 | else: | |
3093 | if opts.has_key('b'): |
|
3093 | if opts.has_key('b'): | |
3094 | raise UsageError("Bookmark '%s' not found. " |
|
3094 | raise UsageError("Bookmark '%s' not found. " | |
3095 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
3095 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
3096 |
|
3096 | |||
3097 | # strip extra quotes on Windows, because os.chdir doesn't like them |
|
3097 | # strip extra quotes on Windows, because os.chdir doesn't like them | |
3098 | ps = unquote_filename(ps) |
|
3098 | ps = unquote_filename(ps) | |
3099 | # at this point ps should point to the target dir |
|
3099 | # at this point ps should point to the target dir | |
3100 | if ps: |
|
3100 | if ps: | |
3101 | try: |
|
3101 | try: | |
3102 | os.chdir(os.path.expanduser(ps)) |
|
3102 | os.chdir(os.path.expanduser(ps)) | |
3103 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
3103 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
3104 | set_term_title('IPython: ' + abbrev_cwd()) |
|
3104 | set_term_title('IPython: ' + abbrev_cwd()) | |
3105 | except OSError: |
|
3105 | except OSError: | |
3106 | print sys.exc_info()[1] |
|
3106 | print sys.exc_info()[1] | |
3107 | else: |
|
3107 | else: | |
3108 | cwd = os.getcwdu() |
|
3108 | cwd = os.getcwdu() | |
3109 | dhist = self.shell.user_ns['_dh'] |
|
3109 | dhist = self.shell.user_ns['_dh'] | |
3110 | if oldcwd != cwd: |
|
3110 | if oldcwd != cwd: | |
3111 | dhist.append(cwd) |
|
3111 | dhist.append(cwd) | |
3112 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] |
|
3112 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] | |
3113 |
|
3113 | |||
3114 | else: |
|
3114 | else: | |
3115 | os.chdir(self.shell.home_dir) |
|
3115 | os.chdir(self.shell.home_dir) | |
3116 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
3116 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
3117 | set_term_title('IPython: ' + '~') |
|
3117 | set_term_title('IPython: ' + '~') | |
3118 | cwd = os.getcwdu() |
|
3118 | cwd = os.getcwdu() | |
3119 | dhist = self.shell.user_ns['_dh'] |
|
3119 | dhist = self.shell.user_ns['_dh'] | |
3120 |
|
3120 | |||
3121 | if oldcwd != cwd: |
|
3121 | if oldcwd != cwd: | |
3122 | dhist.append(cwd) |
|
3122 | dhist.append(cwd) | |
3123 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] |
|
3123 | self.shell.db['dhist'] = compress_dhist(dhist)[-100:] | |
3124 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
3124 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
3125 | print self.shell.user_ns['_dh'][-1] |
|
3125 | print self.shell.user_ns['_dh'][-1] | |
3126 |
|
3126 | |||
3127 |
|
3127 | |||
3128 | @line_magic |
|
3128 | @line_magic | |
3129 | def env(self, parameter_s=''): |
|
3129 | def env(self, parameter_s=''): | |
3130 | """List environment variables.""" |
|
3130 | """List environment variables.""" | |
3131 |
|
3131 | |||
3132 | return dict(os.environ) |
|
3132 | return dict(os.environ) | |
3133 |
|
3133 | |||
3134 | @line_magic |
|
3134 | @line_magic | |
3135 | def pushd(self, parameter_s=''): |
|
3135 | def pushd(self, parameter_s=''): | |
3136 | """Place the current dir on stack and change directory. |
|
3136 | """Place the current dir on stack and change directory. | |
3137 |
|
3137 | |||
3138 | Usage:\\ |
|
3138 | Usage:\\ | |
3139 | %pushd ['dirname'] |
|
3139 | %pushd ['dirname'] | |
3140 | """ |
|
3140 | """ | |
3141 |
|
3141 | |||
3142 | dir_s = self.shell.dir_stack |
|
3142 | dir_s = self.shell.dir_stack | |
3143 | tgt = os.path.expanduser(unquote_filename(parameter_s)) |
|
3143 | tgt = os.path.expanduser(unquote_filename(parameter_s)) | |
3144 | cwd = os.getcwdu().replace(self.shell.home_dir,'~') |
|
3144 | cwd = os.getcwdu().replace(self.shell.home_dir,'~') | |
3145 | if tgt: |
|
3145 | if tgt: | |
3146 | self.magic_cd(parameter_s) |
|
3146 | self.magic_cd(parameter_s) | |
3147 | dir_s.insert(0,cwd) |
|
3147 | dir_s.insert(0,cwd) | |
3148 | return self.shell.magic('dirs') |
|
3148 | return self.shell.magic('dirs') | |
3149 |
|
3149 | |||
3150 | @line_magic |
|
3150 | @line_magic | |
3151 | def popd(self, parameter_s=''): |
|
3151 | def popd(self, parameter_s=''): | |
3152 | """Change to directory popped off the top of the stack. |
|
3152 | """Change to directory popped off the top of the stack. | |
3153 | """ |
|
3153 | """ | |
3154 | if not self.shell.dir_stack: |
|
3154 | if not self.shell.dir_stack: | |
3155 | raise UsageError("%popd on empty stack") |
|
3155 | raise UsageError("%popd on empty stack") | |
3156 | top = self.shell.dir_stack.pop(0) |
|
3156 | top = self.shell.dir_stack.pop(0) | |
3157 | self.magic_cd(top) |
|
3157 | self.magic_cd(top) | |
3158 | print "popd ->",top |
|
3158 | print "popd ->",top | |
3159 |
|
3159 | |||
3160 | @line_magic |
|
3160 | @line_magic | |
3161 | def dirs(self, parameter_s=''): |
|
3161 | def dirs(self, parameter_s=''): | |
3162 | """Return the current directory stack.""" |
|
3162 | """Return the current directory stack.""" | |
3163 |
|
3163 | |||
3164 | return self.shell.dir_stack |
|
3164 | return self.shell.dir_stack | |
3165 |
|
3165 | |||
3166 | @line_magic |
|
3166 | @line_magic | |
3167 | def dhist(self, parameter_s=''): |
|
3167 | def dhist(self, parameter_s=''): | |
3168 | """Print your history of visited directories. |
|
3168 | """Print your history of visited directories. | |
3169 |
|
3169 | |||
3170 | %dhist -> print full history\\ |
|
3170 | %dhist -> print full history\\ | |
3171 | %dhist n -> print last n entries only\\ |
|
3171 | %dhist n -> print last n entries only\\ | |
3172 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
3172 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
3173 |
|
3173 | |||
3174 | This history is automatically maintained by the %cd command, and |
|
3174 | This history is automatically maintained by the %cd command, and | |
3175 | always available as the global list variable _dh. You can use %cd -<n> |
|
3175 | always available as the global list variable _dh. You can use %cd -<n> | |
3176 | to go to directory number <n>. |
|
3176 | to go to directory number <n>. | |
3177 |
|
3177 | |||
3178 | Note that most of time, you should view directory history by entering |
|
3178 | Note that most of time, you should view directory history by entering | |
3179 | cd -<TAB>. |
|
3179 | cd -<TAB>. | |
3180 |
|
3180 | |||
3181 | """ |
|
3181 | """ | |
3182 |
|
3182 | |||
3183 | dh = self.shell.user_ns['_dh'] |
|
3183 | dh = self.shell.user_ns['_dh'] | |
3184 | if parameter_s: |
|
3184 | if parameter_s: | |
3185 | try: |
|
3185 | try: | |
3186 | args = map(int,parameter_s.split()) |
|
3186 | args = map(int,parameter_s.split()) | |
3187 | except: |
|
3187 | except: | |
3188 | self.arg_err(self.dhist) |
|
3188 | self.arg_err(self.dhist) | |
3189 | return |
|
3189 | return | |
3190 | if len(args) == 1: |
|
3190 | if len(args) == 1: | |
3191 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
3191 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
3192 | elif len(args) == 2: |
|
3192 | elif len(args) == 2: | |
3193 | ini,fin = args |
|
3193 | ini,fin = args | |
3194 | else: |
|
3194 | else: | |
3195 | self.arg_err(self.dhist) |
|
3195 | self.arg_err(self.dhist) | |
3196 | return |
|
3196 | return | |
3197 | else: |
|
3197 | else: | |
3198 | ini,fin = 0,len(dh) |
|
3198 | ini,fin = 0,len(dh) | |
3199 | nlprint(dh, |
|
3199 | nlprint(dh, | |
3200 | header = 'Directory history (kept in _dh)', |
|
3200 | header = 'Directory history (kept in _dh)', | |
3201 | start=ini,stop=fin) |
|
3201 | start=ini,stop=fin) | |
3202 |
|
3202 | |||
3203 | @skip_doctest |
|
3203 | @skip_doctest | |
3204 | @line_magic |
|
3204 | @line_magic | |
3205 | def sc(self, parameter_s=''): |
|
3205 | def sc(self, parameter_s=''): | |
3206 | """Shell capture - execute a shell command and capture its output. |
|
3206 | """Shell capture - execute a shell command and capture its output. | |
3207 |
|
3207 | |||
3208 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
3208 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
3209 |
|
3209 | |||
3210 | You should use the form 'var = !command' instead. Example: |
|
3210 | You should use the form 'var = !command' instead. Example: | |
3211 |
|
3211 | |||
3212 | "%sc -l myfiles = ls ~" should now be written as |
|
3212 | "%sc -l myfiles = ls ~" should now be written as | |
3213 |
|
3213 | |||
3214 | "myfiles = !ls ~" |
|
3214 | "myfiles = !ls ~" | |
3215 |
|
3215 | |||
3216 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
3216 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
3217 | below. |
|
3217 | below. | |
3218 |
|
3218 | |||
3219 | -- |
|
3219 | -- | |
3220 | %sc [options] varname=command |
|
3220 | %sc [options] varname=command | |
3221 |
|
3221 | |||
3222 | IPython will run the given command using commands.getoutput(), and |
|
3222 | IPython will run the given command using commands.getoutput(), and | |
3223 | will then update the user's interactive namespace with a variable |
|
3223 | will then update the user's interactive namespace with a variable | |
3224 | called varname, containing the value of the call. Your command can |
|
3224 | called varname, containing the value of the call. Your command can | |
3225 | contain shell wildcards, pipes, etc. |
|
3225 | contain shell wildcards, pipes, etc. | |
3226 |
|
3226 | |||
3227 | The '=' sign in the syntax is mandatory, and the variable name you |
|
3227 | The '=' sign in the syntax is mandatory, and the variable name you | |
3228 | supply must follow Python's standard conventions for valid names. |
|
3228 | supply must follow Python's standard conventions for valid names. | |
3229 |
|
3229 | |||
3230 | (A special format without variable name exists for internal use) |
|
3230 | (A special format without variable name exists for internal use) | |
3231 |
|
3231 | |||
3232 | Options: |
|
3232 | Options: | |
3233 |
|
3233 | |||
3234 | -l: list output. Split the output on newlines into a list before |
|
3234 | -l: list output. Split the output on newlines into a list before | |
3235 | assigning it to the given variable. By default the output is stored |
|
3235 | assigning it to the given variable. By default the output is stored | |
3236 | as a single string. |
|
3236 | as a single string. | |
3237 |
|
3237 | |||
3238 | -v: verbose. Print the contents of the variable. |
|
3238 | -v: verbose. Print the contents of the variable. | |
3239 |
|
3239 | |||
3240 | In most cases you should not need to split as a list, because the |
|
3240 | In most cases you should not need to split as a list, because the | |
3241 | returned value is a special type of string which can automatically |
|
3241 | returned value is a special type of string which can automatically | |
3242 | provide its contents either as a list (split on newlines) or as a |
|
3242 | provide its contents either as a list (split on newlines) or as a | |
3243 | space-separated string. These are convenient, respectively, either |
|
3243 | space-separated string. These are convenient, respectively, either | |
3244 | for sequential processing or to be passed to a shell command. |
|
3244 | for sequential processing or to be passed to a shell command. | |
3245 |
|
3245 | |||
3246 | For example:: |
|
3246 | For example:: | |
3247 |
|
3247 | |||
3248 | # Capture into variable a |
|
3248 | # Capture into variable a | |
3249 | In [1]: sc a=ls *py |
|
3249 | In [1]: sc a=ls *py | |
3250 |
|
3250 | |||
3251 | # a is a string with embedded newlines |
|
3251 | # a is a string with embedded newlines | |
3252 | In [2]: a |
|
3252 | In [2]: a | |
3253 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
3253 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
3254 |
|
3254 | |||
3255 | # which can be seen as a list: |
|
3255 | # which can be seen as a list: | |
3256 | In [3]: a.l |
|
3256 | In [3]: a.l | |
3257 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
3257 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
3258 |
|
3258 | |||
3259 | # or as a whitespace-separated string: |
|
3259 | # or as a whitespace-separated string: | |
3260 | In [4]: a.s |
|
3260 | In [4]: a.s | |
3261 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
3261 | Out[4]: 'setup.py win32_manual_post_install.py' | |
3262 |
|
3262 | |||
3263 | # a.s is useful to pass as a single command line: |
|
3263 | # a.s is useful to pass as a single command line: | |
3264 | In [5]: !wc -l $a.s |
|
3264 | In [5]: !wc -l $a.s | |
3265 | 146 setup.py |
|
3265 | 146 setup.py | |
3266 | 130 win32_manual_post_install.py |
|
3266 | 130 win32_manual_post_install.py | |
3267 | 276 total |
|
3267 | 276 total | |
3268 |
|
3268 | |||
3269 | # while the list form is useful to loop over: |
|
3269 | # while the list form is useful to loop over: | |
3270 | In [6]: for f in a.l: |
|
3270 | In [6]: for f in a.l: | |
3271 | ...: !wc -l $f |
|
3271 | ...: !wc -l $f | |
3272 | ...: |
|
3272 | ...: | |
3273 | 146 setup.py |
|
3273 | 146 setup.py | |
3274 | 130 win32_manual_post_install.py |
|
3274 | 130 win32_manual_post_install.py | |
3275 |
|
3275 | |||
3276 | Similarly, the lists returned by the -l option are also special, in |
|
3276 | Similarly, the lists returned by the -l option are also special, in | |
3277 | the sense that you can equally invoke the .s attribute on them to |
|
3277 | the sense that you can equally invoke the .s attribute on them to | |
3278 | automatically get a whitespace-separated string from their contents:: |
|
3278 | automatically get a whitespace-separated string from their contents:: | |
3279 |
|
3279 | |||
3280 | In [7]: sc -l b=ls *py |
|
3280 | In [7]: sc -l b=ls *py | |
3281 |
|
3281 | |||
3282 | In [8]: b |
|
3282 | In [8]: b | |
3283 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
3283 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
3284 |
|
3284 | |||
3285 | In [9]: b.s |
|
3285 | In [9]: b.s | |
3286 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
3286 | Out[9]: 'setup.py win32_manual_post_install.py' | |
3287 |
|
3287 | |||
3288 | In summary, both the lists and strings used for output capture have |
|
3288 | In summary, both the lists and strings used for output capture have | |
3289 | the following special attributes:: |
|
3289 | the following special attributes:: | |
3290 |
|
3290 | |||
3291 | .l (or .list) : value as list. |
|
3291 | .l (or .list) : value as list. | |
3292 | .n (or .nlstr): value as newline-separated string. |
|
3292 | .n (or .nlstr): value as newline-separated string. | |
3293 | .s (or .spstr): value as space-separated string. |
|
3293 | .s (or .spstr): value as space-separated string. | |
3294 | """ |
|
3294 | """ | |
3295 |
|
3295 | |||
3296 | opts,args = self.parse_options(parameter_s,'lv') |
|
3296 | opts,args = self.parse_options(parameter_s,'lv') | |
3297 | # Try to get a variable name and command to run |
|
3297 | # Try to get a variable name and command to run | |
3298 | try: |
|
3298 | try: | |
3299 | # the variable name must be obtained from the parse_options |
|
3299 | # the variable name must be obtained from the parse_options | |
3300 | # output, which uses shlex.split to strip options out. |
|
3300 | # output, which uses shlex.split to strip options out. | |
3301 | var,_ = args.split('=',1) |
|
3301 | var,_ = args.split('=',1) | |
3302 | var = var.strip() |
|
3302 | var = var.strip() | |
3303 | # But the command has to be extracted from the original input |
|
3303 | # But the command has to be extracted from the original input | |
3304 | # parameter_s, not on what parse_options returns, to avoid the |
|
3304 | # parameter_s, not on what parse_options returns, to avoid the | |
3305 | # quote stripping which shlex.split performs on it. |
|
3305 | # quote stripping which shlex.split performs on it. | |
3306 | _,cmd = parameter_s.split('=',1) |
|
3306 | _,cmd = parameter_s.split('=',1) | |
3307 | except ValueError: |
|
3307 | except ValueError: | |
3308 | var,cmd = '','' |
|
3308 | var,cmd = '','' | |
3309 | # If all looks ok, proceed |
|
3309 | # If all looks ok, proceed | |
3310 | split = 'l' in opts |
|
3310 | split = 'l' in opts | |
3311 | out = self.shell.getoutput(cmd, split=split) |
|
3311 | out = self.shell.getoutput(cmd, split=split) | |
3312 | if opts.has_key('v'): |
|
3312 | if opts.has_key('v'): | |
3313 | print '%s ==\n%s' % (var,pformat(out)) |
|
3313 | print '%s ==\n%s' % (var,pformat(out)) | |
3314 | if var: |
|
3314 | if var: | |
3315 | self.shell.user_ns.update({var:out}) |
|
3315 | self.shell.user_ns.update({var:out}) | |
3316 | else: |
|
3316 | else: | |
3317 | return out |
|
3317 | return out | |
3318 |
|
3318 | |||
3319 | @line_magic |
|
3319 | @line_magic | |
3320 | def sx(self, parameter_s=''): |
|
3320 | def sx(self, parameter_s=''): | |
3321 | """Shell execute - run a shell command and capture its output. |
|
3321 | """Shell execute - run a shell command and capture its output. | |
3322 |
|
3322 | |||
3323 | %sx command |
|
3323 | %sx command | |
3324 |
|
3324 | |||
3325 | IPython will run the given command using commands.getoutput(), and |
|
3325 | IPython will run the given command using commands.getoutput(), and | |
3326 | return the result formatted as a list (split on '\\n'). Since the |
|
3326 | return the result formatted as a list (split on '\\n'). Since the | |
3327 | output is _returned_, it will be stored in ipython's regular output |
|
3327 | output is _returned_, it will be stored in ipython's regular output | |
3328 | cache Out[N] and in the '_N' automatic variables. |
|
3328 | cache Out[N] and in the '_N' automatic variables. | |
3329 |
|
3329 | |||
3330 | Notes: |
|
3330 | Notes: | |
3331 |
|
3331 | |||
3332 | 1) If an input line begins with '!!', then %sx is automatically |
|
3332 | 1) If an input line begins with '!!', then %sx is automatically | |
3333 | invoked. That is, while:: |
|
3333 | invoked. That is, while:: | |
3334 |
|
3334 | |||
3335 | !ls |
|
3335 | !ls | |
3336 |
|
3336 | |||
3337 | causes ipython to simply issue system('ls'), typing:: |
|
3337 | causes ipython to simply issue system('ls'), typing:: | |
3338 |
|
3338 | |||
3339 | !!ls |
|
3339 | !!ls | |
3340 |
|
3340 | |||
3341 | is a shorthand equivalent to:: |
|
3341 | is a shorthand equivalent to:: | |
3342 |
|
3342 | |||
3343 | %sx ls |
|
3343 | %sx ls | |
3344 |
|
3344 | |||
3345 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3345 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3346 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3346 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3347 | to process line-oriented shell output via further python commands. |
|
3347 | to process line-oriented shell output via further python commands. | |
3348 | %sc is meant to provide much finer control, but requires more |
|
3348 | %sc is meant to provide much finer control, but requires more | |
3349 | typing. |
|
3349 | typing. | |
3350 |
|
3350 | |||
3351 | 3) Just like %sc -l, this is a list with special attributes: |
|
3351 | 3) Just like %sc -l, this is a list with special attributes: | |
3352 | :: |
|
3352 | :: | |
3353 |
|
3353 | |||
3354 | .l (or .list) : value as list. |
|
3354 | .l (or .list) : value as list. | |
3355 | .n (or .nlstr): value as newline-separated string. |
|
3355 | .n (or .nlstr): value as newline-separated string. | |
3356 | .s (or .spstr): value as whitespace-separated string. |
|
3356 | .s (or .spstr): value as whitespace-separated string. | |
3357 |
|
3357 | |||
3358 | This is very useful when trying to use such lists as arguments to |
|
3358 | This is very useful when trying to use such lists as arguments to | |
3359 | system commands.""" |
|
3359 | system commands.""" | |
3360 |
|
3360 | |||
3361 | if parameter_s: |
|
3361 | if parameter_s: | |
3362 | return self.shell.getoutput(parameter_s) |
|
3362 | return self.shell.getoutput(parameter_s) | |
3363 |
|
3363 | |||
3364 |
|
3364 | |||
3365 | @line_magic |
|
3365 | @line_magic | |
3366 | def bookmark(self, parameter_s=''): |
|
3366 | def bookmark(self, parameter_s=''): | |
3367 | """Manage IPython's bookmark system. |
|
3367 | """Manage IPython's bookmark system. | |
3368 |
|
3368 | |||
3369 | %bookmark <name> - set bookmark to current dir |
|
3369 | %bookmark <name> - set bookmark to current dir | |
3370 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3370 | %bookmark <name> <dir> - set bookmark to <dir> | |
3371 | %bookmark -l - list all bookmarks |
|
3371 | %bookmark -l - list all bookmarks | |
3372 | %bookmark -d <name> - remove bookmark |
|
3372 | %bookmark -d <name> - remove bookmark | |
3373 | %bookmark -r - remove all bookmarks |
|
3373 | %bookmark -r - remove all bookmarks | |
3374 |
|
3374 | |||
3375 | You can later on access a bookmarked folder with:: |
|
3375 | You can later on access a bookmarked folder with:: | |
3376 |
|
3376 | |||
3377 | %cd -b <name> |
|
3377 | %cd -b <name> | |
3378 |
|
3378 | |||
3379 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3379 | or simply '%cd <name>' if there is no directory called <name> AND | |
3380 | there is such a bookmark defined. |
|
3380 | there is such a bookmark defined. | |
3381 |
|
3381 | |||
3382 | Your bookmarks persist through IPython sessions, but they are |
|
3382 | Your bookmarks persist through IPython sessions, but they are | |
3383 | associated with each profile.""" |
|
3383 | associated with each profile.""" | |
3384 |
|
3384 | |||
3385 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3385 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3386 | if len(args) > 2: |
|
3386 | if len(args) > 2: | |
3387 | raise UsageError("%bookmark: too many arguments") |
|
3387 | raise UsageError("%bookmark: too many arguments") | |
3388 |
|
3388 | |||
3389 | bkms = self.shell.db.get('bookmarks',{}) |
|
3389 | bkms = self.shell.db.get('bookmarks',{}) | |
3390 |
|
3390 | |||
3391 | if opts.has_key('d'): |
|
3391 | if opts.has_key('d'): | |
3392 | try: |
|
3392 | try: | |
3393 | todel = args[0] |
|
3393 | todel = args[0] | |
3394 | except IndexError: |
|
3394 | except IndexError: | |
3395 | raise UsageError( |
|
3395 | raise UsageError( | |
3396 | "%bookmark -d: must provide a bookmark to delete") |
|
3396 | "%bookmark -d: must provide a bookmark to delete") | |
3397 | else: |
|
3397 | else: | |
3398 | try: |
|
3398 | try: | |
3399 | del bkms[todel] |
|
3399 | del bkms[todel] | |
3400 | except KeyError: |
|
3400 | except KeyError: | |
3401 | raise UsageError( |
|
3401 | raise UsageError( | |
3402 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3402 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3403 |
|
3403 | |||
3404 | elif opts.has_key('r'): |
|
3404 | elif opts.has_key('r'): | |
3405 | bkms = {} |
|
3405 | bkms = {} | |
3406 | elif opts.has_key('l'): |
|
3406 | elif opts.has_key('l'): | |
3407 | bks = bkms.keys() |
|
3407 | bks = bkms.keys() | |
3408 | bks.sort() |
|
3408 | bks.sort() | |
3409 | if bks: |
|
3409 | if bks: | |
3410 | size = max(map(len,bks)) |
|
3410 | size = max(map(len,bks)) | |
3411 | else: |
|
3411 | else: | |
3412 | size = 0 |
|
3412 | size = 0 | |
3413 | fmt = '%-'+str(size)+'s -> %s' |
|
3413 | fmt = '%-'+str(size)+'s -> %s' | |
3414 | print 'Current bookmarks:' |
|
3414 | print 'Current bookmarks:' | |
3415 | for bk in bks: |
|
3415 | for bk in bks: | |
3416 | print fmt % (bk,bkms[bk]) |
|
3416 | print fmt % (bk,bkms[bk]) | |
3417 | else: |
|
3417 | else: | |
3418 | if not args: |
|
3418 | if not args: | |
3419 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3419 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3420 | elif len(args)==1: |
|
3420 | elif len(args)==1: | |
3421 | bkms[args[0]] = os.getcwdu() |
|
3421 | bkms[args[0]] = os.getcwdu() | |
3422 | elif len(args)==2: |
|
3422 | elif len(args)==2: | |
3423 | bkms[args[0]] = args[1] |
|
3423 | bkms[args[0]] = args[1] | |
3424 | self.shell.db['bookmarks'] = bkms |
|
3424 | self.shell.db['bookmarks'] = bkms | |
3425 |
|
3425 | |||
3426 | @line_magic |
|
3426 | @line_magic | |
3427 | def pycat(self, parameter_s=''): |
|
3427 | def pycat(self, parameter_s=''): | |
3428 | """Show a syntax-highlighted file through a pager. |
|
3428 | """Show a syntax-highlighted file through a pager. | |
3429 |
|
3429 | |||
3430 | This magic is similar to the cat utility, but it will assume the file |
|
3430 | This magic is similar to the cat utility, but it will assume the file | |
3431 | to be Python source and will show it with syntax highlighting. """ |
|
3431 | to be Python source and will show it with syntax highlighting. """ | |
3432 |
|
3432 | |||
3433 | try: |
|
3433 | try: | |
3434 | filename = get_py_filename(parameter_s) |
|
3434 | filename = get_py_filename(parameter_s) | |
3435 | cont = file_read(filename) |
|
3435 | cont = file_read(filename) | |
3436 | except IOError: |
|
3436 | except IOError: | |
3437 | try: |
|
3437 | try: | |
3438 | cont = eval(parameter_s, self.shell.user_ns) |
|
3438 | cont = eval(parameter_s, self.shell.user_ns) | |
3439 | except NameError: |
|
3439 | except NameError: | |
3440 | cont = None |
|
3440 | cont = None | |
3441 | if cont is None: |
|
3441 | if cont is None: | |
3442 | print "Error: no such file or variable" |
|
3442 | print "Error: no such file or variable" | |
3443 | return |
|
3443 | return | |
3444 |
|
3444 | |||
3445 | page.page(self.shell.pycolorize(cont)) |
|
3445 | page.page(self.shell.pycolorize(cont)) | |
3446 |
|
3446 | |||
3447 |
|
3447 | |||
3448 | @register_magics |
|
3448 | @register_magics | |
3449 | class LoggingMagics(Magics): |
|
3449 | class LoggingMagics(Magics): | |
3450 | """Magics related to all logging machinery.""" |
|
3450 | """Magics related to all logging machinery.""" | |
3451 |
|
3451 | |||
3452 | @line_magic |
|
3452 | @line_magic | |
3453 | def logstart(self, parameter_s=''): |
|
3453 | def logstart(self, parameter_s=''): | |
3454 | """Start logging anywhere in a session. |
|
3454 | """Start logging anywhere in a session. | |
3455 |
|
3455 | |||
3456 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
3456 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
3457 |
|
3457 | |||
3458 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
3458 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
3459 | current directory, in 'rotate' mode (see below). |
|
3459 | current directory, in 'rotate' mode (see below). | |
3460 |
|
3460 | |||
3461 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
3461 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
3462 | history up to that point and then continues logging. |
|
3462 | history up to that point and then continues logging. | |
3463 |
|
3463 | |||
3464 | %logstart takes a second optional parameter: logging mode. This can be one |
|
3464 | %logstart takes a second optional parameter: logging mode. This can be one | |
3465 | of (note that the modes are given unquoted):\\ |
|
3465 | of (note that the modes are given unquoted):\\ | |
3466 | append: well, that says it.\\ |
|
3466 | append: well, that says it.\\ | |
3467 | backup: rename (if exists) to name~ and start name.\\ |
|
3467 | backup: rename (if exists) to name~ and start name.\\ | |
3468 | global: single logfile in your home dir, appended to.\\ |
|
3468 | global: single logfile in your home dir, appended to.\\ | |
3469 | over : overwrite existing log.\\ |
|
3469 | over : overwrite existing log.\\ | |
3470 | rotate: create rotating logs name.1~, name.2~, etc. |
|
3470 | rotate: create rotating logs name.1~, name.2~, etc. | |
3471 |
|
3471 | |||
3472 | Options: |
|
3472 | Options: | |
3473 |
|
3473 | |||
3474 | -o: log also IPython's output. In this mode, all commands which |
|
3474 | -o: log also IPython's output. In this mode, all commands which | |
3475 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
3475 | generate an Out[NN] prompt are recorded to the logfile, right after | |
3476 | their corresponding input line. The output lines are always |
|
3476 | their corresponding input line. The output lines are always | |
3477 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
3477 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
3478 | Python code. |
|
3478 | Python code. | |
3479 |
|
3479 | |||
3480 | Since this marker is always the same, filtering only the output from |
|
3480 | Since this marker is always the same, filtering only the output from | |
3481 | a log is very easy, using for example a simple awk call:: |
|
3481 | a log is very easy, using for example a simple awk call:: | |
3482 |
|
3482 | |||
3483 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
3483 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
3484 |
|
3484 | |||
3485 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
3485 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
3486 | input, so that user lines are logged in their final form, converted |
|
3486 | input, so that user lines are logged in their final form, converted | |
3487 | into valid Python. For example, %Exit is logged as |
|
3487 | into valid Python. For example, %Exit is logged as | |
3488 | _ip.magic("Exit"). If the -r flag is given, all input is logged |
|
3488 | _ip.magic("Exit"). If the -r flag is given, all input is logged | |
3489 | exactly as typed, with no transformations applied. |
|
3489 | exactly as typed, with no transformations applied. | |
3490 |
|
3490 | |||
3491 | -t: put timestamps before each input line logged (these are put in |
|
3491 | -t: put timestamps before each input line logged (these are put in | |
3492 | comments).""" |
|
3492 | comments).""" | |
3493 |
|
3493 | |||
3494 | opts,par = self.parse_options(parameter_s,'ort') |
|
3494 | opts,par = self.parse_options(parameter_s,'ort') | |
3495 | log_output = 'o' in opts |
|
3495 | log_output = 'o' in opts | |
3496 | log_raw_input = 'r' in opts |
|
3496 | log_raw_input = 'r' in opts | |
3497 | timestamp = 't' in opts |
|
3497 | timestamp = 't' in opts | |
3498 |
|
3498 | |||
3499 | logger = self.shell.logger |
|
3499 | logger = self.shell.logger | |
3500 |
|
3500 | |||
3501 | # if no args are given, the defaults set in the logger constructor by |
|
3501 | # if no args are given, the defaults set in the logger constructor by | |
3502 | # ipython remain valid |
|
3502 | # ipython remain valid | |
3503 | if par: |
|
3503 | if par: | |
3504 | try: |
|
3504 | try: | |
3505 | logfname,logmode = par.split() |
|
3505 | logfname,logmode = par.split() | |
3506 | except: |
|
3506 | except: | |
3507 | logfname = par |
|
3507 | logfname = par | |
3508 | logmode = 'backup' |
|
3508 | logmode = 'backup' | |
3509 | else: |
|
3509 | else: | |
3510 | logfname = logger.logfname |
|
3510 | logfname = logger.logfname | |
3511 | logmode = logger.logmode |
|
3511 | logmode = logger.logmode | |
3512 | # put logfname into rc struct as if it had been called on the command |
|
3512 | # put logfname into rc struct as if it had been called on the command | |
3513 | # line, so it ends up saved in the log header Save it in case we need |
|
3513 | # line, so it ends up saved in the log header Save it in case we need | |
3514 | # to restore it... |
|
3514 | # to restore it... | |
3515 | old_logfile = self.shell.logfile |
|
3515 | old_logfile = self.shell.logfile | |
3516 | if logfname: |
|
3516 | if logfname: | |
3517 | logfname = os.path.expanduser(logfname) |
|
3517 | logfname = os.path.expanduser(logfname) | |
3518 | self.shell.logfile = logfname |
|
3518 | self.shell.logfile = logfname | |
3519 |
|
3519 | |||
3520 | loghead = '# IPython log file\n\n' |
|
3520 | loghead = '# IPython log file\n\n' | |
3521 | try: |
|
3521 | try: | |
3522 | logger.logstart(logfname, loghead, logmode, log_output, timestamp, |
|
3522 | logger.logstart(logfname, loghead, logmode, log_output, timestamp, | |
3523 | log_raw_input) |
|
3523 | log_raw_input) | |
3524 | except: |
|
3524 | except: | |
3525 | self.shell.logfile = old_logfile |
|
3525 | self.shell.logfile = old_logfile | |
3526 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
3526 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
3527 | else: |
|
3527 | else: | |
3528 | # log input history up to this point, optionally interleaving |
|
3528 | # log input history up to this point, optionally interleaving | |
3529 | # output if requested |
|
3529 | # output if requested | |
3530 |
|
3530 | |||
3531 | if timestamp: |
|
3531 | if timestamp: | |
3532 | # disable timestamping for the previous history, since we've |
|
3532 | # disable timestamping for the previous history, since we've | |
3533 | # lost those already (no time machine here). |
|
3533 | # lost those already (no time machine here). | |
3534 | logger.timestamp = False |
|
3534 | logger.timestamp = False | |
3535 |
|
3535 | |||
3536 | if log_raw_input: |
|
3536 | if log_raw_input: | |
3537 | input_hist = self.shell.history_manager.input_hist_raw |
|
3537 | input_hist = self.shell.history_manager.input_hist_raw | |
3538 | else: |
|
3538 | else: | |
3539 | input_hist = self.shell.history_manager.input_hist_parsed |
|
3539 | input_hist = self.shell.history_manager.input_hist_parsed | |
3540 |
|
3540 | |||
3541 | if log_output: |
|
3541 | if log_output: | |
3542 | log_write = logger.log_write |
|
3542 | log_write = logger.log_write | |
3543 | output_hist = self.shell.history_manager.output_hist |
|
3543 | output_hist = self.shell.history_manager.output_hist | |
3544 | for n in range(1,len(input_hist)-1): |
|
3544 | for n in range(1,len(input_hist)-1): | |
3545 | log_write(input_hist[n].rstrip() + '\n') |
|
3545 | log_write(input_hist[n].rstrip() + '\n') | |
3546 | if n in output_hist: |
|
3546 | if n in output_hist: | |
3547 | log_write(repr(output_hist[n]),'output') |
|
3547 | log_write(repr(output_hist[n]),'output') | |
3548 | else: |
|
3548 | else: | |
3549 | logger.log_write('\n'.join(input_hist[1:])) |
|
3549 | logger.log_write('\n'.join(input_hist[1:])) | |
3550 | logger.log_write('\n') |
|
3550 | logger.log_write('\n') | |
3551 | if timestamp: |
|
3551 | if timestamp: | |
3552 | # re-enable timestamping |
|
3552 | # re-enable timestamping | |
3553 | logger.timestamp = True |
|
3553 | logger.timestamp = True | |
3554 |
|
3554 | |||
3555 | print ('Activating auto-logging. ' |
|
3555 | print ('Activating auto-logging. ' | |
3556 | 'Current session state plus future input saved.') |
|
3556 | 'Current session state plus future input saved.') | |
3557 | logger.logstate() |
|
3557 | logger.logstate() | |
3558 |
|
3558 | |||
3559 | @line_magic |
|
3559 | @line_magic | |
3560 | def logstop(self, parameter_s=''): |
|
3560 | def logstop(self, parameter_s=''): | |
3561 | """Fully stop logging and close log file. |
|
3561 | """Fully stop logging and close log file. | |
3562 |
|
3562 | |||
3563 | In order to start logging again, a new %logstart call needs to be made, |
|
3563 | In order to start logging again, a new %logstart call needs to be made, | |
3564 | possibly (though not necessarily) with a new filename, mode and other |
|
3564 | possibly (though not necessarily) with a new filename, mode and other | |
3565 | options.""" |
|
3565 | options.""" | |
3566 | self.logger.logstop() |
|
3566 | self.logger.logstop() | |
3567 |
|
3567 | |||
3568 | @line_magic |
|
3568 | @line_magic | |
3569 | def logoff(self, parameter_s=''): |
|
3569 | def logoff(self, parameter_s=''): | |
3570 | """Temporarily stop logging. |
|
3570 | """Temporarily stop logging. | |
3571 |
|
3571 | |||
3572 | You must have previously started logging.""" |
|
3572 | You must have previously started logging.""" | |
3573 | self.shell.logger.switch_log(0) |
|
3573 | self.shell.logger.switch_log(0) | |
3574 |
|
3574 | |||
3575 | @line_magic |
|
3575 | @line_magic | |
3576 | def logon(self, parameter_s=''): |
|
3576 | def logon(self, parameter_s=''): | |
3577 | """Restart logging. |
|
3577 | """Restart logging. | |
3578 |
|
3578 | |||
3579 | This function is for restarting logging which you've temporarily |
|
3579 | This function is for restarting logging which you've temporarily | |
3580 | stopped with %logoff. For starting logging for the first time, you |
|
3580 | stopped with %logoff. For starting logging for the first time, you | |
3581 | must use the %logstart function, which allows you to specify an |
|
3581 | must use the %logstart function, which allows you to specify an | |
3582 | optional log filename.""" |
|
3582 | optional log filename.""" | |
3583 |
|
3583 | |||
3584 | self.shell.logger.switch_log(1) |
|
3584 | self.shell.logger.switch_log(1) | |
3585 |
|
3585 | |||
3586 | @line_magic |
|
3586 | @line_magic | |
3587 | def logstate(self, parameter_s=''): |
|
3587 | def logstate(self, parameter_s=''): | |
3588 | """Print the status of the logging system.""" |
|
3588 | """Print the status of the logging system.""" | |
3589 |
|
3589 | |||
3590 | self.shell.logger.logstate() |
|
3590 | self.shell.logger.logstate() | |
3591 |
|
3591 | |||
3592 |
|
3592 | |||
3593 | @register_magics |
|
3593 | @register_magics | |
3594 | class ExtensionsMagics(Magics): |
|
3594 | class ExtensionsMagics(Magics): | |
3595 | """Magics to manage the IPython extensions system.""" |
|
3595 | """Magics to manage the IPython extensions system.""" | |
3596 |
|
3596 | |||
3597 | @line_magic |
|
3597 | @line_magic | |
3598 | def install_ext(self, parameter_s=''): |
|
3598 | def install_ext(self, parameter_s=''): | |
3599 | """Download and install an extension from a URL, e.g.:: |
|
3599 | """Download and install an extension from a URL, e.g.:: | |
3600 |
|
3600 | |||
3601 | %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py |
|
3601 | %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py | |
3602 |
|
3602 | |||
3603 | The URL should point to an importable Python module - either a .py file |
|
3603 | The URL should point to an importable Python module - either a .py file | |
3604 | or a .zip file. |
|
3604 | or a .zip file. | |
3605 |
|
3605 | |||
3606 | Parameters: |
|
3606 | Parameters: | |
3607 |
|
3607 | |||
3608 | -n filename : Specify a name for the file, rather than taking it from |
|
3608 | -n filename : Specify a name for the file, rather than taking it from | |
3609 | the URL. |
|
3609 | the URL. | |
3610 | """ |
|
3610 | """ | |
3611 | opts, args = self.parse_options(parameter_s, 'n:') |
|
3611 | opts, args = self.parse_options(parameter_s, 'n:') | |
3612 | try: |
|
3612 | try: | |
3613 | filename = self.shell.extension_manager.install_extension(args, |
|
3613 | filename = self.shell.extension_manager.install_extension(args, | |
3614 | opts.get('n')) |
|
3614 | opts.get('n')) | |
3615 | except ValueError as e: |
|
3615 | except ValueError as e: | |
3616 | print e |
|
3616 | print e | |
3617 | return |
|
3617 | return | |
3618 |
|
3618 | |||
3619 | filename = os.path.basename(filename) |
|
3619 | filename = os.path.basename(filename) | |
3620 | print "Installed %s. To use it, type:" % filename |
|
3620 | print "Installed %s. To use it, type:" % filename | |
3621 | print " %%load_ext %s" % os.path.splitext(filename)[0] |
|
3621 | print " %%load_ext %s" % os.path.splitext(filename)[0] | |
3622 |
|
3622 | |||
3623 |
|
3623 | |||
3624 | @line_magic |
|
3624 | @line_magic | |
3625 | def load_ext(self, module_str): |
|
3625 | def load_ext(self, module_str): | |
3626 | """Load an IPython extension by its module name.""" |
|
3626 | """Load an IPython extension by its module name.""" | |
3627 | return self.shell.extension_manager.load_extension(module_str) |
|
3627 | return self.shell.extension_manager.load_extension(module_str) | |
3628 |
|
3628 | |||
3629 | @line_magic |
|
3629 | @line_magic | |
3630 | def unload_ext(self, module_str): |
|
3630 | def unload_ext(self, module_str): | |
3631 | """Unload an IPython extension by its module name.""" |
|
3631 | """Unload an IPython extension by its module name.""" | |
3632 | self.shell.extension_manager.unload_extension(module_str) |
|
3632 | self.shell.extension_manager.unload_extension(module_str) | |
3633 |
|
3633 | |||
3634 | @line_magic |
|
3634 | @line_magic | |
3635 | def reload_ext(self, module_str): |
|
3635 | def reload_ext(self, module_str): | |
3636 | """Reload an IPython extension by its module name.""" |
|
3636 | """Reload an IPython extension by its module name.""" | |
3637 | self.shell.extension_manager.reload_extension(module_str) |
|
3637 | self.shell.extension_manager.reload_extension(module_str) | |
3638 |
|
3638 | |||
3639 |
|
3639 | |||
3640 | @register_magics |
|
3640 | @register_magics | |
3641 | class PylabMagics(Magics): |
|
3641 | class PylabMagics(Magics): | |
3642 | """Magics related to matplotlib's pylab support""" |
|
3642 | """Magics related to matplotlib's pylab support""" | |
3643 |
|
3643 | |||
3644 | @skip_doctest |
|
3644 | @skip_doctest | |
3645 | @line_magic |
|
3645 | @line_magic | |
3646 | def pylab(self, parameter_s=''): |
|
3646 | def pylab(self, parameter_s=''): | |
3647 | """Load numpy and matplotlib to work interactively. |
|
3647 | """Load numpy and matplotlib to work interactively. | |
3648 |
|
3648 | |||
3649 | %pylab [GUINAME] |
|
3649 | %pylab [GUINAME] | |
3650 |
|
3650 | |||
3651 | This function lets you activate pylab (matplotlib, numpy and |
|
3651 | This function lets you activate pylab (matplotlib, numpy and | |
3652 | interactive support) at any point during an IPython session. |
|
3652 | interactive support) at any point during an IPython session. | |
3653 |
|
3653 | |||
3654 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3654 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3655 | pylab and mlab, as well as all names from numpy and pylab. |
|
3655 | pylab and mlab, as well as all names from numpy and pylab. | |
3656 |
|
3656 | |||
3657 | If you are using the inline matplotlib backend for embedded figures, |
|
3657 | If you are using the inline matplotlib backend for embedded figures, | |
3658 | you can adjust its behavior via the %config magic:: |
|
3658 | you can adjust its behavior via the %config magic:: | |
3659 |
|
3659 | |||
3660 | # enable SVG figures, necessary for SVG+XHTML export in the qtconsole |
|
3660 | # enable SVG figures, necessary for SVG+XHTML export in the qtconsole | |
3661 | In [1]: %config InlineBackend.figure_format = 'svg' |
|
3661 | In [1]: %config InlineBackend.figure_format = 'svg' | |
3662 |
|
3662 | |||
3663 | # change the behavior of closing all figures at the end of each |
|
3663 | # change the behavior of closing all figures at the end of each | |
3664 | # execution (cell), or allowing reuse of active figures across |
|
3664 | # execution (cell), or allowing reuse of active figures across | |
3665 | # cells: |
|
3665 | # cells: | |
3666 | In [2]: %config InlineBackend.close_figures = False |
|
3666 | In [2]: %config InlineBackend.close_figures = False | |
3667 |
|
3667 | |||
3668 | Parameters |
|
3668 | Parameters | |
3669 | ---------- |
|
3669 | ---------- | |
3670 | guiname : optional |
|
3670 | guiname : optional | |
3671 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', |
|
3671 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', | |
3672 | 'osx' or 'tk'). If given, the corresponding Matplotlib backend is |
|
3672 | 'osx' or 'tk'). If given, the corresponding Matplotlib backend is | |
3673 | used, otherwise matplotlib's default (which you can override in your |
|
3673 | used, otherwise matplotlib's default (which you can override in your | |
3674 | matplotlib config file) is used. |
|
3674 | matplotlib config file) is used. | |
3675 |
|
3675 | |||
3676 | Examples |
|
3676 | Examples | |
3677 | -------- |
|
3677 | -------- | |
3678 | In this case, where the MPL default is TkAgg:: |
|
3678 | In this case, where the MPL default is TkAgg:: | |
3679 |
|
3679 | |||
3680 | In [2]: %pylab |
|
3680 | In [2]: %pylab | |
3681 |
|
3681 | |||
3682 | Welcome to pylab, a matplotlib-based Python environment. |
|
3682 | Welcome to pylab, a matplotlib-based Python environment. | |
3683 | Backend in use: TkAgg |
|
3683 | Backend in use: TkAgg | |
3684 | For more information, type 'help(pylab)'. |
|
3684 | For more information, type 'help(pylab)'. | |
3685 |
|
3685 | |||
3686 | But you can explicitly request a different backend:: |
|
3686 | But you can explicitly request a different backend:: | |
3687 |
|
3687 | |||
3688 | In [3]: %pylab qt |
|
3688 | In [3]: %pylab qt | |
3689 |
|
3689 | |||
3690 | Welcome to pylab, a matplotlib-based Python environment. |
|
3690 | Welcome to pylab, a matplotlib-based Python environment. | |
3691 | Backend in use: Qt4Agg |
|
3691 | Backend in use: Qt4Agg | |
3692 | For more information, type 'help(pylab)'. |
|
3692 | For more information, type 'help(pylab)'. | |
3693 | """ |
|
3693 | """ | |
3694 |
|
3694 | |||
3695 | if Application.initialized(): |
|
3695 | if Application.initialized(): | |
3696 | app = Application.instance() |
|
3696 | app = Application.instance() | |
3697 | try: |
|
3697 | try: | |
3698 | import_all_status = app.pylab_import_all |
|
3698 | import_all_status = app.pylab_import_all | |
3699 | except AttributeError: |
|
3699 | except AttributeError: | |
3700 | import_all_status = True |
|
3700 | import_all_status = True | |
3701 | else: |
|
3701 | else: | |
3702 | import_all_status = True |
|
3702 | import_all_status = True | |
3703 |
|
3703 | |||
3704 | self.shell.enable_pylab(parameter_s, import_all=import_all_status) |
|
3704 | self.shell.enable_pylab(parameter_s, import_all=import_all_status) | |
3705 |
|
3705 | |||
3706 |
|
3706 | |||
3707 | @register_magics |
|
3707 | @register_magics | |
3708 | class DeprecatedMagics(Magics): |
|
3708 | class DeprecatedMagics(Magics): | |
3709 | """Magics slated for later removal.""" |
|
3709 | """Magics slated for later removal.""" | |
3710 |
|
3710 | |||
3711 | @line_magic |
|
3711 | @line_magic | |
3712 | def install_profiles(self, parameter_s=''): |
|
3712 | def install_profiles(self, parameter_s=''): | |
3713 | """%install_profiles has been deprecated.""" |
|
3713 | """%install_profiles has been deprecated.""" | |
3714 | print '\n'.join([ |
|
3714 | print '\n'.join([ | |
3715 | "%install_profiles has been deprecated.", |
|
3715 | "%install_profiles has been deprecated.", | |
3716 | "Use `ipython profile list` to view available profiles.", |
|
3716 | "Use `ipython profile list` to view available profiles.", | |
3717 | "Requesting a profile with `ipython profile create <name>`", |
|
3717 | "Requesting a profile with `ipython profile create <name>`", | |
3718 | "or `ipython --profile=<name>` will start with the bundled", |
|
3718 | "or `ipython --profile=<name>` will start with the bundled", | |
3719 | "profile of that name if it exists." |
|
3719 | "profile of that name if it exists." | |
3720 | ]) |
|
3720 | ]) | |
3721 |
|
3721 | |||
3722 | @line_magic |
|
3722 | @line_magic | |
3723 | def install_default_config(self, parameter_s=''): |
|
3723 | def install_default_config(self, parameter_s=''): | |
3724 | """%install_default_config has been deprecated.""" |
|
3724 | """%install_default_config has been deprecated.""" | |
3725 | print '\n'.join([ |
|
3725 | print '\n'.join([ | |
3726 | "%install_default_config has been deprecated.", |
|
3726 | "%install_default_config has been deprecated.", | |
3727 | "Use `ipython profile create <name>` to initialize a profile", |
|
3727 | "Use `ipython profile create <name>` to initialize a profile", | |
3728 | "with the default config files.", |
|
3728 | "with the default config files.", | |
3729 | "Add `--reset` to overwrite already existing config files with defaults." |
|
3729 | "Add `--reset` to overwrite already existing config files with defaults." | |
3730 | ]) |
|
3730 | ]) |
@@ -1,480 +1,485 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Tests for various magic functions. |
|
2 | """Tests for various magic functions. | |
3 |
|
3 | |||
4 | Needs to be run by nose (to make ipython session available). |
|
4 | Needs to be run by nose (to make ipython session available). | |
5 | """ |
|
5 | """ | |
6 | from __future__ import absolute_import |
|
6 | from __future__ import absolute_import | |
7 |
|
7 | |||
8 | #----------------------------------------------------------------------------- |
|
8 | #----------------------------------------------------------------------------- | |
9 | # Imports |
|
9 | # Imports | |
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 |
|
11 | |||
12 | import io |
|
12 | import io | |
13 | import os |
|
13 | import os | |
14 | import sys |
|
14 | import sys | |
15 | from StringIO import StringIO |
|
15 | from StringIO import StringIO | |
16 |
|
16 | |||
17 | import nose.tools as nt |
|
17 | import nose.tools as nt | |
18 |
|
18 | |||
|
19 | from IPython.core import magic | |||
|
20 | from IPython.core import magic_functions as mf | |||
19 | from IPython.nbformat.v3.tests.nbexamples import nb0 |
|
21 | from IPython.nbformat.v3.tests.nbexamples import nb0 | |
20 | from IPython.nbformat import current |
|
22 | from IPython.nbformat import current | |
21 | from IPython.testing import decorators as dec |
|
23 | from IPython.testing import decorators as dec | |
22 | from IPython.testing import tools as tt |
|
24 | from IPython.testing import tools as tt | |
23 | from IPython.utils import py3compat |
|
25 | from IPython.utils import py3compat | |
24 | from IPython.utils.tempdir import TemporaryDirectory |
|
26 | from IPython.utils.tempdir import TemporaryDirectory | |
25 |
|
27 | |||
26 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
27 | # Test functions begin |
|
29 | # Test functions begin | |
28 | #----------------------------------------------------------------------------- |
|
30 | #----------------------------------------------------------------------------- | |
29 |
|
31 | |||
30 |
|
32 | |||
31 | def test_rehashx(): |
|
33 | def test_rehashx(): | |
32 | # clear up everything |
|
34 | # clear up everything | |
33 | _ip = get_ipython() |
|
35 | _ip = get_ipython() | |
34 | _ip.alias_manager.alias_table.clear() |
|
36 | _ip.alias_manager.alias_table.clear() | |
35 | del _ip.db['syscmdlist'] |
|
37 | del _ip.db['syscmdlist'] | |
36 |
|
38 | |||
37 | _ip.magic('rehashx') |
|
39 | _ip.magic('rehashx') | |
38 | # Practically ALL ipython development systems will have more than 10 aliases |
|
40 | # Practically ALL ipython development systems will have more than 10 aliases | |
39 |
|
41 | |||
40 | yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10) |
|
42 | yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10) | |
41 | for key, val in _ip.alias_manager.alias_table.iteritems(): |
|
43 | for key, val in _ip.alias_manager.alias_table.iteritems(): | |
42 | # we must strip dots from alias names |
|
44 | # we must strip dots from alias names | |
43 | nt.assert_true('.' not in key) |
|
45 | nt.assert_true('.' not in key) | |
44 |
|
46 | |||
45 | # rehashx must fill up syscmdlist |
|
47 | # rehashx must fill up syscmdlist | |
46 | scoms = _ip.db['syscmdlist'] |
|
48 | scoms = _ip.db['syscmdlist'] | |
47 | yield (nt.assert_true, len(scoms) > 10) |
|
49 | yield (nt.assert_true, len(scoms) > 10) | |
48 |
|
50 | |||
49 |
|
51 | |||
50 | def test_magic_parse_options(): |
|
52 | def test_magic_parse_options(): | |
51 | """Test that we don't mangle paths when parsing magic options.""" |
|
53 | """Test that we don't mangle paths when parsing magic options.""" | |
52 | ip = get_ipython() |
|
54 | ip = get_ipython() | |
53 | path = 'c:\\x' |
|
55 | path = 'c:\\x' | |
54 | opts = ip._magic.parse_options('-f %s' % path,'f:')[0] |
|
56 | m = magic.Magics(ip) | |
|
57 | opts = m.parse_options('-f %s' % path,'f:')[0] | |||
55 | # argv splitting is os-dependent |
|
58 | # argv splitting is os-dependent | |
56 | if os.name == 'posix': |
|
59 | if os.name == 'posix': | |
57 | expected = 'c:x' |
|
60 | expected = 'c:x' | |
58 | else: |
|
61 | else: | |
59 | expected = path |
|
62 | expected = path | |
60 | nt.assert_equals(opts['f'], expected) |
|
63 | nt.assert_equals(opts['f'], expected) | |
61 |
|
64 | |||
62 |
|
65 | |||
63 | @dec.skip_without('sqlite3') |
|
66 | @dec.skip_without('sqlite3') | |
64 | def doctest_hist_f(): |
|
67 | def doctest_hist_f(): | |
65 | """Test %hist -f with temporary filename. |
|
68 | """Test %hist -f with temporary filename. | |
66 |
|
69 | |||
67 | In [9]: import tempfile |
|
70 | In [9]: import tempfile | |
68 |
|
71 | |||
69 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') |
|
72 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') | |
70 |
|
73 | |||
71 | In [11]: %hist -nl -f $tfile 3 |
|
74 | In [11]: %hist -nl -f $tfile 3 | |
72 |
|
75 | |||
73 | In [13]: import os; os.unlink(tfile) |
|
76 | In [13]: import os; os.unlink(tfile) | |
74 | """ |
|
77 | """ | |
75 |
|
78 | |||
76 |
|
79 | |||
77 | @dec.skip_without('sqlite3') |
|
80 | @dec.skip_without('sqlite3') | |
78 | def doctest_hist_r(): |
|
81 | def doctest_hist_r(): | |
79 | """Test %hist -r |
|
82 | """Test %hist -r | |
80 |
|
83 | |||
81 | XXX - This test is not recording the output correctly. For some reason, in |
|
84 | XXX - This test is not recording the output correctly. For some reason, in | |
82 | testing mode the raw history isn't getting populated. No idea why. |
|
85 | testing mode the raw history isn't getting populated. No idea why. | |
83 | Disabling the output checking for now, though at least we do run it. |
|
86 | Disabling the output checking for now, though at least we do run it. | |
84 |
|
87 | |||
85 | In [1]: 'hist' in _ip.lsmagic() |
|
88 | In [1]: 'hist' in _ip.lsmagic() | |
86 | Out[1]: True |
|
89 | Out[1]: True | |
87 |
|
90 | |||
88 | In [2]: x=1 |
|
91 | In [2]: x=1 | |
89 |
|
92 | |||
90 | In [3]: %hist -rl 2 |
|
93 | In [3]: %hist -rl 2 | |
91 | x=1 # random |
|
94 | x=1 # random | |
92 | %hist -r 2 |
|
95 | %hist -r 2 | |
93 | """ |
|
96 | """ | |
94 |
|
97 | |||
95 |
|
98 | |||
96 | @dec.skip_without('sqlite3') |
|
99 | @dec.skip_without('sqlite3') | |
97 | def doctest_hist_op(): |
|
100 | def doctest_hist_op(): | |
98 | """Test %hist -op |
|
101 | """Test %hist -op | |
99 |
|
102 | |||
100 | In [1]: class b(float): |
|
103 | In [1]: class b(float): | |
101 | ...: pass |
|
104 | ...: pass | |
102 | ...: |
|
105 | ...: | |
103 |
|
106 | |||
104 | In [2]: class s(object): |
|
107 | In [2]: class s(object): | |
105 | ...: def __str__(self): |
|
108 | ...: def __str__(self): | |
106 | ...: return 's' |
|
109 | ...: return 's' | |
107 | ...: |
|
110 | ...: | |
108 |
|
111 | |||
109 | In [3]: |
|
112 | In [3]: | |
110 |
|
113 | |||
111 | In [4]: class r(b): |
|
114 | In [4]: class r(b): | |
112 | ...: def __repr__(self): |
|
115 | ...: def __repr__(self): | |
113 | ...: return 'r' |
|
116 | ...: return 'r' | |
114 | ...: |
|
117 | ...: | |
115 |
|
118 | |||
116 | In [5]: class sr(s,r): pass |
|
119 | In [5]: class sr(s,r): pass | |
117 | ...: |
|
120 | ...: | |
118 |
|
121 | |||
119 | In [6]: |
|
122 | In [6]: | |
120 |
|
123 | |||
121 | In [7]: bb=b() |
|
124 | In [7]: bb=b() | |
122 |
|
125 | |||
123 | In [8]: ss=s() |
|
126 | In [8]: ss=s() | |
124 |
|
127 | |||
125 | In [9]: rr=r() |
|
128 | In [9]: rr=r() | |
126 |
|
129 | |||
127 | In [10]: ssrr=sr() |
|
130 | In [10]: ssrr=sr() | |
128 |
|
131 | |||
129 | In [11]: 4.5 |
|
132 | In [11]: 4.5 | |
130 | Out[11]: 4.5 |
|
133 | Out[11]: 4.5 | |
131 |
|
134 | |||
132 | In [12]: str(ss) |
|
135 | In [12]: str(ss) | |
133 | Out[12]: 's' |
|
136 | Out[12]: 's' | |
134 |
|
137 | |||
135 | In [13]: |
|
138 | In [13]: | |
136 |
|
139 | |||
137 | In [14]: %hist -op |
|
140 | In [14]: %hist -op | |
138 | >>> class b: |
|
141 | >>> class b: | |
139 | ... pass |
|
142 | ... pass | |
140 | ... |
|
143 | ... | |
141 | >>> class s(b): |
|
144 | >>> class s(b): | |
142 | ... def __str__(self): |
|
145 | ... def __str__(self): | |
143 | ... return 's' |
|
146 | ... return 's' | |
144 | ... |
|
147 | ... | |
145 | >>> |
|
148 | >>> | |
146 | >>> class r(b): |
|
149 | >>> class r(b): | |
147 | ... def __repr__(self): |
|
150 | ... def __repr__(self): | |
148 | ... return 'r' |
|
151 | ... return 'r' | |
149 | ... |
|
152 | ... | |
150 | >>> class sr(s,r): pass |
|
153 | >>> class sr(s,r): pass | |
151 | >>> |
|
154 | >>> | |
152 | >>> bb=b() |
|
155 | >>> bb=b() | |
153 | >>> ss=s() |
|
156 | >>> ss=s() | |
154 | >>> rr=r() |
|
157 | >>> rr=r() | |
155 | >>> ssrr=sr() |
|
158 | >>> ssrr=sr() | |
156 | >>> 4.5 |
|
159 | >>> 4.5 | |
157 | 4.5 |
|
160 | 4.5 | |
158 | >>> str(ss) |
|
161 | >>> str(ss) | |
159 | 's' |
|
162 | 's' | |
160 | >>> |
|
163 | >>> | |
161 | """ |
|
164 | """ | |
162 |
|
165 | |||
163 |
|
166 | |||
164 | @dec.skip_without('sqlite3') |
|
167 | @dec.skip_without('sqlite3') | |
165 | def test_macro(): |
|
168 | def test_macro(): | |
166 | ip = get_ipython() |
|
169 | ip = get_ipython() | |
167 | ip.history_manager.reset() # Clear any existing history. |
|
170 | ip.history_manager.reset() # Clear any existing history. | |
168 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] |
|
171 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] | |
169 | for i, cmd in enumerate(cmds, start=1): |
|
172 | for i, cmd in enumerate(cmds, start=1): | |
170 | ip.history_manager.store_inputs(i, cmd) |
|
173 | ip.history_manager.store_inputs(i, cmd) | |
171 | ip.magic("macro test 1-3") |
|
174 | ip.magic("macro test 1-3") | |
172 | nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n") |
|
175 | nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n") | |
173 |
|
176 | |||
174 | # List macros. |
|
177 | # List macros. | |
175 | assert "test" in ip.magic("macro") |
|
178 | assert "test" in ip.magic("macro") | |
176 |
|
179 | |||
177 |
|
180 | |||
178 | @dec.skip_without('sqlite3') |
|
181 | @dec.skip_without('sqlite3') | |
179 | def test_macro_run(): |
|
182 | def test_macro_run(): | |
180 | """Test that we can run a multi-line macro successfully.""" |
|
183 | """Test that we can run a multi-line macro successfully.""" | |
181 | ip = get_ipython() |
|
184 | ip = get_ipython() | |
182 | ip.history_manager.reset() |
|
185 | ip.history_manager.reset() | |
183 | cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"), |
|
186 | cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"), | |
184 | "%macro test 2-3"] |
|
187 | "%macro test 2-3"] | |
185 | for cmd in cmds: |
|
188 | for cmd in cmds: | |
186 | ip.run_cell(cmd, store_history=True) |
|
189 | ip.run_cell(cmd, store_history=True) | |
187 | nt.assert_equal(ip.user_ns["test"].value, |
|
190 | nt.assert_equal(ip.user_ns["test"].value, | |
188 | py3compat.doctest_refactor_print("a+=1\nprint a\n")) |
|
191 | py3compat.doctest_refactor_print("a+=1\nprint a\n")) | |
189 | with tt.AssertPrints("12"): |
|
192 | with tt.AssertPrints("12"): | |
190 | ip.run_cell("test") |
|
193 | ip.run_cell("test") | |
191 | with tt.AssertPrints("13"): |
|
194 | with tt.AssertPrints("13"): | |
192 | ip.run_cell("test") |
|
195 | ip.run_cell("test") | |
193 |
|
196 | |||
194 |
|
197 | |||
195 | @dec.skipif_not_numpy |
|
198 | @dec.skipif_not_numpy | |
196 | def test_numpy_reset_array_undec(): |
|
199 | def test_numpy_reset_array_undec(): | |
197 | "Test '%reset array' functionality" |
|
200 | "Test '%reset array' functionality" | |
198 | _ip.ex('import numpy as np') |
|
201 | _ip.ex('import numpy as np') | |
199 | _ip.ex('a = np.empty(2)') |
|
202 | _ip.ex('a = np.empty(2)') | |
200 | yield (nt.assert_true, 'a' in _ip.user_ns) |
|
203 | yield (nt.assert_true, 'a' in _ip.user_ns) | |
201 | _ip.magic('reset -f array') |
|
204 | _ip.magic('reset -f array') | |
202 | yield (nt.assert_false, 'a' in _ip.user_ns) |
|
205 | yield (nt.assert_false, 'a' in _ip.user_ns) | |
203 |
|
206 | |||
204 | def test_reset_out(): |
|
207 | def test_reset_out(): | |
205 | "Test '%reset out' magic" |
|
208 | "Test '%reset out' magic" | |
206 | _ip.run_cell("parrot = 'dead'", store_history=True) |
|
209 | _ip.run_cell("parrot = 'dead'", store_history=True) | |
207 | # test '%reset -f out', make an Out prompt |
|
210 | # test '%reset -f out', make an Out prompt | |
208 | _ip.run_cell("parrot", store_history=True) |
|
211 | _ip.run_cell("parrot", store_history=True) | |
209 | nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___']) |
|
212 | nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___']) | |
210 | _ip.magic('reset -f out') |
|
213 | _ip.magic('reset -f out') | |
211 | nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___']) |
|
214 | nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___']) | |
212 | nt.assert_true(len(_ip.user_ns['Out']) == 0) |
|
215 | nt.assert_true(len(_ip.user_ns['Out']) == 0) | |
213 |
|
216 | |||
214 | def test_reset_in(): |
|
217 | def test_reset_in(): | |
215 | "Test '%reset in' magic" |
|
218 | "Test '%reset in' magic" | |
216 | # test '%reset -f in' |
|
219 | # test '%reset -f in' | |
217 | _ip.run_cell("parrot", store_history=True) |
|
220 | _ip.run_cell("parrot", store_history=True) | |
218 | nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) |
|
221 | nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) | |
219 | _ip.magic('%reset -f in') |
|
222 | _ip.magic('%reset -f in') | |
220 | nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) |
|
223 | nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii']) | |
221 | nt.assert_true(len(set(_ip.user_ns['In'])) == 1) |
|
224 | nt.assert_true(len(set(_ip.user_ns['In'])) == 1) | |
222 |
|
225 | |||
223 | def test_reset_dhist(): |
|
226 | def test_reset_dhist(): | |
224 | "Test '%reset dhist' magic" |
|
227 | "Test '%reset dhist' magic" | |
225 | _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing |
|
228 | _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing | |
226 | _ip.magic('cd ' + os.path.dirname(nt.__file__)) |
|
229 | _ip.magic('cd ' + os.path.dirname(nt.__file__)) | |
227 | _ip.magic('cd -') |
|
230 | _ip.magic('cd -') | |
228 | nt.assert_true(len(_ip.user_ns['_dh']) > 0) |
|
231 | nt.assert_true(len(_ip.user_ns['_dh']) > 0) | |
229 | _ip.magic('reset -f dhist') |
|
232 | _ip.magic('reset -f dhist') | |
230 | nt.assert_true(len(_ip.user_ns['_dh']) == 0) |
|
233 | nt.assert_true(len(_ip.user_ns['_dh']) == 0) | |
231 | _ip.run_cell("_dh = [d for d in tmp]") #restore |
|
234 | _ip.run_cell("_dh = [d for d in tmp]") #restore | |
232 |
|
235 | |||
233 | def test_reset_in_length(): |
|
236 | def test_reset_in_length(): | |
234 | "Test that '%reset in' preserves In[] length" |
|
237 | "Test that '%reset in' preserves In[] length" | |
235 | _ip.run_cell("print 'foo'") |
|
238 | _ip.run_cell("print 'foo'") | |
236 | _ip.run_cell("reset -f in") |
|
239 | _ip.run_cell("reset -f in") | |
237 | nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1) |
|
240 | nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1) | |
238 |
|
241 | |||
239 | def test_time(): |
|
242 | def test_time(): | |
240 | _ip.magic('time None') |
|
243 | _ip.magic('time None') | |
241 |
|
244 | |||
242 | def test_tb_syntaxerror(): |
|
245 | def test_tb_syntaxerror(): | |
243 | """test %tb after a SyntaxError""" |
|
246 | """test %tb after a SyntaxError""" | |
244 | ip = get_ipython() |
|
247 | ip = get_ipython() | |
245 | ip.run_cell("for") |
|
248 | ip.run_cell("for") | |
246 |
|
249 | |||
247 | # trap and validate stdout |
|
250 | # trap and validate stdout | |
248 | save_stdout = sys.stdout |
|
251 | save_stdout = sys.stdout | |
249 | try: |
|
252 | try: | |
250 | sys.stdout = StringIO() |
|
253 | sys.stdout = StringIO() | |
251 | ip.run_cell("%tb") |
|
254 | ip.run_cell("%tb") | |
252 | out = sys.stdout.getvalue() |
|
255 | out = sys.stdout.getvalue() | |
253 | finally: |
|
256 | finally: | |
254 | sys.stdout = save_stdout |
|
257 | sys.stdout = save_stdout | |
255 | # trim output, and only check the last line |
|
258 | # trim output, and only check the last line | |
256 | last_line = out.rstrip().splitlines()[-1].strip() |
|
259 | last_line = out.rstrip().splitlines()[-1].strip() | |
257 | nt.assert_equals(last_line, "SyntaxError: invalid syntax") |
|
260 | nt.assert_equals(last_line, "SyntaxError: invalid syntax") | |
258 |
|
261 | |||
259 |
|
262 | |||
260 | @py3compat.doctest_refactor_print |
|
263 | @py3compat.doctest_refactor_print | |
261 | def doctest_time(): |
|
264 | def doctest_time(): | |
262 | """ |
|
265 | """ | |
263 | In [10]: %time None |
|
266 | In [10]: %time None | |
264 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
267 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
265 | Wall time: 0.00 s |
|
268 | Wall time: 0.00 s | |
266 |
|
269 | |||
267 | In [11]: def f(kmjy): |
|
270 | In [11]: def f(kmjy): | |
268 | ....: %time print 2*kmjy |
|
271 | ....: %time print 2*kmjy | |
269 |
|
272 | |||
270 | In [12]: f(3) |
|
273 | In [12]: f(3) | |
271 | 6 |
|
274 | 6 | |
272 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
275 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
273 | Wall time: 0.00 s |
|
276 | Wall time: 0.00 s | |
274 | """ |
|
277 | """ | |
275 |
|
278 | |||
276 |
|
279 | |||
277 | def test_doctest_mode(): |
|
280 | def test_doctest_mode(): | |
278 | "Toggle doctest_mode twice, it should be a no-op and run without error" |
|
281 | "Toggle doctest_mode twice, it should be a no-op and run without error" | |
279 | _ip.magic('doctest_mode') |
|
282 | _ip.magic('doctest_mode') | |
280 | _ip.magic('doctest_mode') |
|
283 | _ip.magic('doctest_mode') | |
281 |
|
284 | |||
282 |
|
285 | |||
283 | def test_parse_options(): |
|
286 | def test_parse_options(): | |
284 | """Tests for basic options parsing in magics.""" |
|
287 | """Tests for basic options parsing in magics.""" | |
285 | # These are only the most minimal of tests, more should be added later. At |
|
288 | # These are only the most minimal of tests, more should be added later. At | |
286 | # the very least we check that basic text/unicode calls work OK. |
|
289 | # the very least we check that basic text/unicode calls work OK. | |
287 | nt.assert_equal(_ip._magic.parse_options('foo', '')[1], 'foo') |
|
290 | m = magic.Magics(ip) | |
288 |
nt.assert_equal( |
|
291 | nt.assert_equal(m.parse_options('foo', '')[1], 'foo') | |
|
292 | nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo') | |||
289 |
|
293 | |||
290 |
|
294 | |||
291 | def test_dirops(): |
|
295 | def test_dirops(): | |
292 | """Test various directory handling operations.""" |
|
296 | """Test various directory handling operations.""" | |
293 | # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/') |
|
297 | # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/') | |
294 | curpath = os.getcwdu |
|
298 | curpath = os.getcwdu | |
295 | startdir = os.getcwdu() |
|
299 | startdir = os.getcwdu() | |
296 | ipdir = os.path.realpath(_ip.ipython_dir) |
|
300 | ipdir = os.path.realpath(_ip.ipython_dir) | |
297 | try: |
|
301 | try: | |
298 | _ip.magic('cd "%s"' % ipdir) |
|
302 | _ip.magic('cd "%s"' % ipdir) | |
299 | nt.assert_equal(curpath(), ipdir) |
|
303 | nt.assert_equal(curpath(), ipdir) | |
300 | _ip.magic('cd -') |
|
304 | _ip.magic('cd -') | |
301 | nt.assert_equal(curpath(), startdir) |
|
305 | nt.assert_equal(curpath(), startdir) | |
302 | _ip.magic('pushd "%s"' % ipdir) |
|
306 | _ip.magic('pushd "%s"' % ipdir) | |
303 | nt.assert_equal(curpath(), ipdir) |
|
307 | nt.assert_equal(curpath(), ipdir) | |
304 | _ip.magic('popd') |
|
308 | _ip.magic('popd') | |
305 | nt.assert_equal(curpath(), startdir) |
|
309 | nt.assert_equal(curpath(), startdir) | |
306 | finally: |
|
310 | finally: | |
307 | os.chdir(startdir) |
|
311 | os.chdir(startdir) | |
308 |
|
312 | |||
309 |
|
313 | |||
310 | def test_xmode(): |
|
314 | def test_xmode(): | |
311 | # Calling xmode three times should be a no-op |
|
315 | # Calling xmode three times should be a no-op | |
312 | xmode = _ip.InteractiveTB.mode |
|
316 | xmode = _ip.InteractiveTB.mode | |
313 | for i in range(3): |
|
317 | for i in range(3): | |
314 | _ip.magic("xmode") |
|
318 | _ip.magic("xmode") | |
315 | nt.assert_equal(_ip.InteractiveTB.mode, xmode) |
|
319 | nt.assert_equal(_ip.InteractiveTB.mode, xmode) | |
316 |
|
320 | |||
317 | def test_reset_hard(): |
|
321 | def test_reset_hard(): | |
318 | monitor = [] |
|
322 | monitor = [] | |
319 | class A(object): |
|
323 | class A(object): | |
320 | def __del__(self): |
|
324 | def __del__(self): | |
321 | monitor.append(1) |
|
325 | monitor.append(1) | |
322 | def __repr__(self): |
|
326 | def __repr__(self): | |
323 | return "<A instance>" |
|
327 | return "<A instance>" | |
324 |
|
328 | |||
325 | _ip.user_ns["a"] = A() |
|
329 | _ip.user_ns["a"] = A() | |
326 | _ip.run_cell("a") |
|
330 | _ip.run_cell("a") | |
327 |
|
331 | |||
328 | nt.assert_equal(monitor, []) |
|
332 | nt.assert_equal(monitor, []) | |
329 | _ip.magic("reset -f") |
|
333 | _ip.magic("reset -f") | |
330 | nt.assert_equal(monitor, [1]) |
|
334 | nt.assert_equal(monitor, [1]) | |
331 |
|
335 | |||
332 | class TestXdel(tt.TempFileMixin): |
|
336 | class TestXdel(tt.TempFileMixin): | |
333 | def test_xdel(self): |
|
337 | def test_xdel(self): | |
334 | """Test that references from %run are cleared by xdel.""" |
|
338 | """Test that references from %run are cleared by xdel.""" | |
335 | src = ("class A(object):\n" |
|
339 | src = ("class A(object):\n" | |
336 | " monitor = []\n" |
|
340 | " monitor = []\n" | |
337 | " def __del__(self):\n" |
|
341 | " def __del__(self):\n" | |
338 | " self.monitor.append(1)\n" |
|
342 | " self.monitor.append(1)\n" | |
339 | "a = A()\n") |
|
343 | "a = A()\n") | |
340 | self.mktmp(src) |
|
344 | self.mktmp(src) | |
341 | # %run creates some hidden references... |
|
345 | # %run creates some hidden references... | |
342 | _ip.magic("run %s" % self.fname) |
|
346 | _ip.magic("run %s" % self.fname) | |
343 | # ... as does the displayhook. |
|
347 | # ... as does the displayhook. | |
344 | _ip.run_cell("a") |
|
348 | _ip.run_cell("a") | |
345 |
|
349 | |||
346 | monitor = _ip.user_ns["A"].monitor |
|
350 | monitor = _ip.user_ns["A"].monitor | |
347 | nt.assert_equal(monitor, []) |
|
351 | nt.assert_equal(monitor, []) | |
348 |
|
352 | |||
349 | _ip.magic("xdel a") |
|
353 | _ip.magic("xdel a") | |
350 |
|
354 | |||
351 | # Check that a's __del__ method has been called. |
|
355 | # Check that a's __del__ method has been called. | |
352 | nt.assert_equal(monitor, [1]) |
|
356 | nt.assert_equal(monitor, [1]) | |
353 |
|
357 | |||
354 | def doctest_who(): |
|
358 | def doctest_who(): | |
355 | """doctest for %who |
|
359 | """doctest for %who | |
356 |
|
360 | |||
357 | In [1]: %reset -f |
|
361 | In [1]: %reset -f | |
358 |
|
362 | |||
359 | In [2]: alpha = 123 |
|
363 | In [2]: alpha = 123 | |
360 |
|
364 | |||
361 | In [3]: beta = 'beta' |
|
365 | In [3]: beta = 'beta' | |
362 |
|
366 | |||
363 | In [4]: %who int |
|
367 | In [4]: %who int | |
364 | alpha |
|
368 | alpha | |
365 |
|
369 | |||
366 | In [5]: %who str |
|
370 | In [5]: %who str | |
367 | beta |
|
371 | beta | |
368 |
|
372 | |||
369 | In [6]: %whos |
|
373 | In [6]: %whos | |
370 | Variable Type Data/Info |
|
374 | Variable Type Data/Info | |
371 | ---------------------------- |
|
375 | ---------------------------- | |
372 | alpha int 123 |
|
376 | alpha int 123 | |
373 | beta str beta |
|
377 | beta str beta | |
374 |
|
378 | |||
375 | In [7]: %who_ls |
|
379 | In [7]: %who_ls | |
376 | Out[7]: ['alpha', 'beta'] |
|
380 | Out[7]: ['alpha', 'beta'] | |
377 | """ |
|
381 | """ | |
378 |
|
382 | |||
379 | def test_whos(): |
|
383 | def test_whos(): | |
380 | """Check that whos is protected against objects where repr() fails.""" |
|
384 | """Check that whos is protected against objects where repr() fails.""" | |
381 | class A(object): |
|
385 | class A(object): | |
382 | def __repr__(self): |
|
386 | def __repr__(self): | |
383 | raise Exception() |
|
387 | raise Exception() | |
384 | _ip.user_ns['a'] = A() |
|
388 | _ip.user_ns['a'] = A() | |
385 | _ip.magic("whos") |
|
389 | _ip.magic("whos") | |
386 |
|
390 | |||
387 | @py3compat.u_format |
|
391 | @py3compat.u_format | |
388 | def doctest_precision(): |
|
392 | def doctest_precision(): | |
389 | """doctest for %precision |
|
393 | """doctest for %precision | |
390 |
|
394 | |||
391 | In [1]: f = get_ipython().display_formatter.formatters['text/plain'] |
|
395 | In [1]: f = get_ipython().display_formatter.formatters['text/plain'] | |
392 |
|
396 | |||
393 | In [2]: %precision 5 |
|
397 | In [2]: %precision 5 | |
394 | Out[2]: {u}'%.5f' |
|
398 | Out[2]: {u}'%.5f' | |
395 |
|
399 | |||
396 | In [3]: f.float_format |
|
400 | In [3]: f.float_format | |
397 | Out[3]: {u}'%.5f' |
|
401 | Out[3]: {u}'%.5f' | |
398 |
|
402 | |||
399 | In [4]: %precision %e |
|
403 | In [4]: %precision %e | |
400 | Out[4]: {u}'%e' |
|
404 | Out[4]: {u}'%e' | |
401 |
|
405 | |||
402 | In [5]: f(3.1415927) |
|
406 | In [5]: f(3.1415927) | |
403 | Out[5]: {u}'3.141593e+00' |
|
407 | Out[5]: {u}'3.141593e+00' | |
404 | """ |
|
408 | """ | |
405 |
|
409 | |||
406 | def test_psearch(): |
|
410 | def test_psearch(): | |
407 | with tt.AssertPrints("dict.fromkeys"): |
|
411 | with tt.AssertPrints("dict.fromkeys"): | |
408 | _ip.run_cell("dict.fr*?") |
|
412 | _ip.run_cell("dict.fr*?") | |
409 |
|
413 | |||
410 | def test_timeit_shlex(): |
|
414 | def test_timeit_shlex(): | |
411 | """test shlex issues with timeit (#1109)""" |
|
415 | """test shlex issues with timeit (#1109)""" | |
412 | _ip.ex("def f(*a,**kw): pass") |
|
416 | _ip.ex("def f(*a,**kw): pass") | |
413 | _ip.magic('timeit -n1 "this is a bug".count(" ")') |
|
417 | _ip.magic('timeit -n1 "this is a bug".count(" ")') | |
414 | _ip.magic('timeit -r1 -n1 f(" ", 1)') |
|
418 | _ip.magic('timeit -r1 -n1 f(" ", 1)') | |
415 | _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")') |
|
419 | _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")') | |
416 | _ip.magic('timeit -r1 -n1 ("a " + "b")') |
|
420 | _ip.magic('timeit -r1 -n1 ("a " + "b")') | |
417 | _ip.magic('timeit -r1 -n1 f("a " + "b")') |
|
421 | _ip.magic('timeit -r1 -n1 f("a " + "b")') | |
418 | _ip.magic('timeit -r1 -n1 f("a " + "b ")') |
|
422 | _ip.magic('timeit -r1 -n1 f("a " + "b ")') | |
419 |
|
423 | |||
420 |
|
424 | |||
421 | def test_timeit_arguments(): |
|
425 | def test_timeit_arguments(): | |
422 | "Test valid timeit arguments, should not cause SyntaxError (GH #1269)" |
|
426 | "Test valid timeit arguments, should not cause SyntaxError (GH #1269)" | |
423 | _ip.magic("timeit ('#')") |
|
427 | _ip.magic("timeit ('#')") | |
424 |
|
428 | |||
425 | @dec.skipif(_ip._magic.magic_prun == _ip._magic.profile_missing_notice) |
|
429 | ||
|
430 | @dec.skipif(mf.profile is None) | |||
426 | def test_prun_quotes(): |
|
431 | def test_prun_quotes(): | |
427 | "Test that prun does not clobber string escapes (GH #1302)" |
|
432 | "Test that prun does not clobber string escapes (GH #1302)" | |
428 | _ip.magic("prun -q x = '\t'") |
|
433 | _ip.magic("prun -q x = '\t'") | |
429 | nt.assert_equal(_ip.user_ns['x'], '\t') |
|
434 | nt.assert_equal(_ip.user_ns['x'], '\t') | |
430 |
|
435 | |||
431 | def test_extension(): |
|
436 | def test_extension(): | |
432 | tmpdir = TemporaryDirectory() |
|
437 | tmpdir = TemporaryDirectory() | |
433 | orig_ipython_dir = _ip.ipython_dir |
|
438 | orig_ipython_dir = _ip.ipython_dir | |
434 | try: |
|
439 | try: | |
435 | _ip.ipython_dir = tmpdir.name |
|
440 | _ip.ipython_dir = tmpdir.name | |
436 | nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension") |
|
441 | nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension") | |
437 | url = os.path.join(os.path.dirname(__file__), "daft_extension.py") |
|
442 | url = os.path.join(os.path.dirname(__file__), "daft_extension.py") | |
438 | _ip.magic("install_ext %s" % url) |
|
443 | _ip.magic("install_ext %s" % url) | |
439 | _ip.user_ns.pop('arq', None) |
|
444 | _ip.user_ns.pop('arq', None) | |
440 | _ip.magic("load_ext daft_extension") |
|
445 | _ip.magic("load_ext daft_extension") | |
441 | tt.assert_equal(_ip.user_ns['arq'], 185) |
|
446 | tt.assert_equal(_ip.user_ns['arq'], 185) | |
442 | _ip.magic("unload_ext daft_extension") |
|
447 | _ip.magic("unload_ext daft_extension") | |
443 | assert 'arq' not in _ip.user_ns |
|
448 | assert 'arq' not in _ip.user_ns | |
444 | finally: |
|
449 | finally: | |
445 | _ip.ipython_dir = orig_ipython_dir |
|
450 | _ip.ipython_dir = orig_ipython_dir | |
446 |
|
451 | |||
447 | def test_notebook_export_json(): |
|
452 | def test_notebook_export_json(): | |
448 | with TemporaryDirectory() as td: |
|
453 | with TemporaryDirectory() as td: | |
449 | outfile = os.path.join(td, "nb.ipynb") |
|
454 | outfile = os.path.join(td, "nb.ipynb") | |
450 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) |
|
455 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) | |
451 | _ip.magic("notebook -e %s" % outfile) |
|
456 | _ip.magic("notebook -e %s" % outfile) | |
452 |
|
457 | |||
453 | def test_notebook_export_py(): |
|
458 | def test_notebook_export_py(): | |
454 | with TemporaryDirectory() as td: |
|
459 | with TemporaryDirectory() as td: | |
455 | outfile = os.path.join(td, "nb.py") |
|
460 | outfile = os.path.join(td, "nb.py") | |
456 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) |
|
461 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) | |
457 | _ip.magic("notebook -e %s" % outfile) |
|
462 | _ip.magic("notebook -e %s" % outfile) | |
458 |
|
463 | |||
459 | def test_notebook_reformat_py(): |
|
464 | def test_notebook_reformat_py(): | |
460 | with TemporaryDirectory() as td: |
|
465 | with TemporaryDirectory() as td: | |
461 | infile = os.path.join(td, "nb.ipynb") |
|
466 | infile = os.path.join(td, "nb.ipynb") | |
462 | with io.open(infile, 'w', encoding='utf-8') as f: |
|
467 | with io.open(infile, 'w', encoding='utf-8') as f: | |
463 | current.write(nb0, f, 'json') |
|
468 | current.write(nb0, f, 'json') | |
464 |
|
469 | |||
465 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) |
|
470 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) | |
466 | _ip.magic("notebook -f py %s" % infile) |
|
471 | _ip.magic("notebook -f py %s" % infile) | |
467 |
|
472 | |||
468 | def test_notebook_reformat_json(): |
|
473 | def test_notebook_reformat_json(): | |
469 | with TemporaryDirectory() as td: |
|
474 | with TemporaryDirectory() as td: | |
470 | infile = os.path.join(td, "nb.py") |
|
475 | infile = os.path.join(td, "nb.py") | |
471 | with io.open(infile, 'w', encoding='utf-8') as f: |
|
476 | with io.open(infile, 'w', encoding='utf-8') as f: | |
472 | current.write(nb0, f, 'py') |
|
477 | current.write(nb0, f, 'py') | |
473 |
|
478 | |||
474 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) |
|
479 | _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'")) | |
475 | _ip.magic("notebook -f ipynb %s" % infile) |
|
480 | _ip.magic("notebook -f ipynb %s" % infile) | |
476 | _ip.magic("notebook -f json %s" % infile) |
|
481 | _ip.magic("notebook -f json %s" % infile) | |
477 |
|
482 | |||
478 | def test_env(): |
|
483 | def test_env(): | |
479 | env = _ip.magic("env") |
|
484 | env = _ip.magic("env") | |
480 | assert isinstance(env, dict), type(env) |
|
485 | assert isinstance(env, dict), type(env) |
@@ -1,110 +1,110 b'' | |||||
1 | """Tests for input manipulation machinery.""" |
|
1 | """Tests for input manipulation machinery.""" | |
2 |
|
2 | |||
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Imports |
|
4 | # Imports | |
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | import nose.tools as nt |
|
6 | import nose.tools as nt | |
7 |
|
7 | |||
8 | from IPython.core.prefilter import AutocallChecker |
|
8 | from IPython.core.prefilter import AutocallChecker | |
9 | from IPython.testing import tools as tt, decorators as dec |
|
9 | from IPython.testing import tools as tt, decorators as dec | |
10 | from IPython.testing.globalipapp import get_ipython |
|
10 | from IPython.testing.globalipapp import get_ipython | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Tests |
|
13 | # Tests | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | ip = get_ipython() |
|
15 | ip = get_ipython() | |
16 |
|
16 | |||
17 | @dec.parametric |
|
17 | @dec.parametric | |
18 | def test_prefilter(): |
|
18 | def test_prefilter(): | |
19 | """Test user input conversions""" |
|
19 | """Test user input conversions""" | |
20 |
|
20 | |||
21 | # pairs of (raw, expected correct) input |
|
21 | # pairs of (raw, expected correct) input | |
22 | pairs = [ ('2+2','2+2'), |
|
22 | pairs = [ ('2+2','2+2'), | |
23 | ('>>> 2+2','2+2'), |
|
23 | ('>>> 2+2','2+2'), | |
24 | ('>>> # This is a comment\n' |
|
24 | ('>>> # This is a comment\n' | |
25 | '... 2+2', |
|
25 | '... 2+2', | |
26 | '# This is a comment\n' |
|
26 | '# This is a comment\n' | |
27 | '2+2'), |
|
27 | '2+2'), | |
28 | # Some IPython input |
|
28 | # Some IPython input | |
29 | ('In [1]: 1', '1'), |
|
29 | ('In [1]: 1', '1'), | |
30 | ('In [2]: for i in range(5):\n' |
|
30 | ('In [2]: for i in range(5):\n' | |
31 | ' ...: print i,', |
|
31 | ' ...: print i,', | |
32 | 'for i in range(5):\n' |
|
32 | 'for i in range(5):\n' | |
33 | ' print i,'), |
|
33 | ' print i,'), | |
34 | ] |
|
34 | ] | |
35 |
|
35 | |||
36 | for raw, correct in pairs: |
|
36 | for raw, correct in pairs: | |
37 | yield nt.assert_equals(ip.prefilter(raw), correct) |
|
37 | yield nt.assert_equals(ip.prefilter(raw), correct) | |
38 |
|
38 | |||
39 |
|
39 | |||
40 | @dec.parametric |
|
40 | @dec.parametric | |
41 | def test_autocall_binops(): |
|
41 | def test_autocall_binops(): | |
42 | """See https://github.com/ipython/ipython/issues/81""" |
|
42 | """See https://github.com/ipython/ipython/issues/81""" | |
43 | ip.magic('autocall 2') |
|
43 | ip.magic('autocall 2') | |
44 | f = lambda x: x |
|
44 | f = lambda x: x | |
45 | ip.user_ns['f'] = f |
|
45 | ip.user_ns['f'] = f | |
46 | try: |
|
46 | try: | |
47 | yield nt.assert_equals(ip.prefilter('f 1'),'f(1)') |
|
47 | yield nt.assert_equals(ip.prefilter('f 1'),'f(1)') | |
48 | for t in ['f +1', 'f -1']: |
|
48 | for t in ['f +1', 'f -1']: | |
49 | yield nt.assert_equals(ip.prefilter(t), t) |
|
49 | yield nt.assert_equals(ip.prefilter(t), t) | |
50 |
|
50 | |||
51 | # Run tests again with a more permissive exclude_regexp, which will |
|
51 | # Run tests again with a more permissive exclude_regexp, which will | |
52 | # allow transformation of binary operations ('f -1' -> 'f(-1)'). |
|
52 | # allow transformation of binary operations ('f -1' -> 'f(-1)'). | |
53 | pm = ip.prefilter_manager |
|
53 | pm = ip.prefilter_manager | |
54 | ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, |
|
54 | ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, | |
55 | config=pm.config) |
|
55 | config=pm.config) | |
56 | try: |
|
56 | try: | |
57 | ac.priority = 1 |
|
57 | ac.priority = 1 | |
58 | ac.exclude_regexp = r'^[,&^\|\*/]|^is |^not |^in |^and |^or ' |
|
58 | ac.exclude_regexp = r'^[,&^\|\*/]|^is |^not |^in |^and |^or ' | |
59 | pm.sort_checkers() |
|
59 | pm.sort_checkers() | |
60 |
|
60 | |||
61 | yield nt.assert_equals(ip.prefilter('f -1'), 'f(-1)') |
|
61 | yield nt.assert_equals(ip.prefilter('f -1'), 'f(-1)') | |
62 | yield nt.assert_equals(ip.prefilter('f +1'), 'f(+1)') |
|
62 | yield nt.assert_equals(ip.prefilter('f +1'), 'f(+1)') | |
63 | finally: |
|
63 | finally: | |
64 | pm.unregister_checker(ac) |
|
64 | pm.unregister_checker(ac) | |
65 | finally: |
|
65 | finally: | |
66 | ip.magic('autocall 0') |
|
66 | ip.magic('autocall 0') | |
67 | del ip.user_ns['f'] |
|
67 | del ip.user_ns['f'] | |
68 |
|
68 | |||
69 |
|
69 | |||
70 | @dec.parametric |
|
70 | @dec.parametric | |
71 | def test_issue_114(): |
|
71 | def test_issue_114(): | |
72 | """Check that multiline string literals don't expand as magic |
|
72 | """Check that multiline string literals don't expand as magic | |
73 | see http://github.com/ipython/ipython/issues/114""" |
|
73 | see http://github.com/ipython/ipython/issues/114""" | |
74 |
|
74 | |||
75 | template = '"""\n%s\n"""' |
|
75 | template = '"""\n%s\n"""' | |
76 | # Store the current value of multi_line_specials and turn it off before |
|
76 | # Store the current value of multi_line_specials and turn it off before | |
77 | # running test, since it could be true (case in which the test doesn't make |
|
77 | # running test, since it could be true (case in which the test doesn't make | |
78 | # sense, as multiline string literals *will* expand as magic in that case). |
|
78 | # sense, as multiline string literals *will* expand as magic in that case). | |
79 | msp = ip.prefilter_manager.multi_line_specials |
|
79 | msp = ip.prefilter_manager.multi_line_specials | |
80 | ip.prefilter_manager.multi_line_specials = False |
|
80 | ip.prefilter_manager.multi_line_specials = False | |
81 | try: |
|
81 | try: | |
82 |
for mgk in ip. |
|
82 | for mgk in ip.magics_manager.lsmagic()['line']: | |
83 | raw = template % mgk |
|
83 | raw = template % mgk | |
84 | yield nt.assert_equals(ip.prefilter(raw), raw) |
|
84 | yield nt.assert_equals(ip.prefilter(raw), raw) | |
85 | finally: |
|
85 | finally: | |
86 | ip.prefilter_manager.multi_line_specials = msp |
|
86 | ip.prefilter_manager.multi_line_specials = msp | |
87 |
|
87 | |||
88 |
|
88 | |||
89 | def test_prefilter_attribute_errors(): |
|
89 | def test_prefilter_attribute_errors(): | |
90 | """Capture exceptions thrown by user objects on attribute access. |
|
90 | """Capture exceptions thrown by user objects on attribute access. | |
91 |
|
91 | |||
92 | See http://github.com/ipython/ipython/issues/988.""" |
|
92 | See http://github.com/ipython/ipython/issues/988.""" | |
93 |
|
93 | |||
94 | class X(object): |
|
94 | class X(object): | |
95 | def __getattr__(self, k): |
|
95 | def __getattr__(self, k): | |
96 | raise ValueError('broken object') |
|
96 | raise ValueError('broken object') | |
97 | def __call__(self, x): |
|
97 | def __call__(self, x): | |
98 | return x |
|
98 | return x | |
99 |
|
99 | |||
100 | # Create a callable broken object |
|
100 | # Create a callable broken object | |
101 | ip.user_ns['x'] = X() |
|
101 | ip.user_ns['x'] = X() | |
102 | ip.magic('autocall 2') |
|
102 | ip.magic('autocall 2') | |
103 | try: |
|
103 | try: | |
104 | # Even if x throws an attribute error when looking at its rewrite |
|
104 | # Even if x throws an attribute error when looking at its rewrite | |
105 | # attribute, we should not crash. So the test here is simply making |
|
105 | # attribute, we should not crash. So the test here is simply making | |
106 | # the prefilter call and not having an exception. |
|
106 | # the prefilter call and not having an exception. | |
107 | ip.prefilter('x 1') |
|
107 | ip.prefilter('x 1') | |
108 | finally: |
|
108 | finally: | |
109 | del ip.user_ns['x'] |
|
109 | del ip.user_ns['x'] | |
110 | ip.magic('autocall 0') |
|
110 | ip.magic('autocall 0') |
General Comments 0
You need to be logged in to leave comments.
Login now