Show More
@@ -1,3502 +1,3501 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-2007 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 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 |
|
17 | |||
18 | import __builtin__ |
|
18 | import __builtin__ | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | import shutil |
|
24 | import shutil | |
25 | import re |
|
25 | import re | |
26 | import time |
|
26 | import time | |
27 | import textwrap |
|
27 | import textwrap | |
28 | import types |
|
28 | import types | |
29 | from cStringIO import StringIO |
|
29 | from cStringIO import StringIO | |
30 | from getopt import getopt,GetoptError |
|
30 | from getopt import getopt,GetoptError | |
31 | from pprint import pformat |
|
31 | from pprint import pformat | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | import IPython |
|
44 | import IPython | |
45 | from IPython.core import debugger, oinspect |
|
45 | from IPython.core import debugger, oinspect | |
46 | from IPython.core.error import TryNext |
|
46 | from IPython.core.error import TryNext | |
47 | from IPython.core.error import UsageError |
|
47 | from IPython.core.error import UsageError | |
48 | from IPython.core.fakemodule import FakeModule |
|
48 | from IPython.core.fakemodule import FakeModule | |
49 | from IPython.core.macro import Macro |
|
49 | from IPython.core.macro import Macro | |
50 | from IPython.core import page |
|
50 | from IPython.core import page | |
51 | from IPython.core.prefilter import ESC_MAGIC |
|
51 | from IPython.core.prefilter import ESC_MAGIC | |
52 | from IPython.lib.pylabtools import mpl_runner |
|
52 | from IPython.lib.pylabtools import mpl_runner | |
53 | from IPython.external.Itpl import itpl, printpl |
|
53 | from IPython.external.Itpl import itpl, printpl | |
54 | from IPython.testing import decorators as testdec |
|
54 | from IPython.testing import decorators as testdec | |
55 | from IPython.utils.io import file_read, nlprint |
|
55 | from IPython.utils.io import file_read, nlprint | |
56 | import IPython.utils.io |
|
56 | import IPython.utils.io | |
57 | from IPython.utils.path import get_py_filename |
|
57 | from IPython.utils.path import get_py_filename | |
58 | from IPython.utils.process import arg_split, abbrev_cwd |
|
58 | from IPython.utils.process import arg_split, 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 LSString, SList, format_screen |
|
60 | from IPython.utils.text import LSString, SList, 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 | from IPython.utils.ipstruct import Struct |
|
63 | from IPython.utils.ipstruct import Struct | |
64 | import IPython.utils.generics |
|
64 | import IPython.utils.generics | |
65 |
|
65 | |||
66 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
67 | # Utility functions |
|
67 | # Utility functions | |
68 | #----------------------------------------------------------------------------- |
|
68 | #----------------------------------------------------------------------------- | |
69 |
|
69 | |||
70 | def on_off(tag): |
|
70 | def on_off(tag): | |
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
71 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
72 | return ['OFF','ON'][tag] |
|
72 | return ['OFF','ON'][tag] | |
73 |
|
73 | |||
74 | class Bunch: pass |
|
74 | class Bunch: pass | |
75 |
|
75 | |||
76 | def compress_dhist(dh): |
|
76 | def compress_dhist(dh): | |
77 | head, tail = dh[:-10], dh[-10:] |
|
77 | head, tail = dh[:-10], dh[-10:] | |
78 |
|
78 | |||
79 | newhead = [] |
|
79 | newhead = [] | |
80 | done = set() |
|
80 | done = set() | |
81 | for h in head: |
|
81 | for h in head: | |
82 | if h in done: |
|
82 | if h in done: | |
83 | continue |
|
83 | continue | |
84 | newhead.append(h) |
|
84 | newhead.append(h) | |
85 | done.add(h) |
|
85 | done.add(h) | |
86 |
|
86 | |||
87 | return newhead + tail |
|
87 | return newhead + tail | |
88 |
|
88 | |||
89 |
|
89 | |||
90 | #*************************************************************************** |
|
90 | #*************************************************************************** | |
91 | # Main class implementing Magic functionality |
|
91 | # Main class implementing Magic functionality | |
92 |
|
92 | |||
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
93 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
94 | # on construction of the main InteractiveShell object. Something odd is going |
|
94 | # on construction of the main InteractiveShell object. Something odd is going | |
95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
95 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
96 | # eventually this needs to be clarified. |
|
96 | # eventually this needs to be clarified. | |
97 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
97 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
98 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
98 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
99 | # make Magic a configurable that InteractiveShell does not subclass. |
|
99 | # make Magic a configurable that InteractiveShell does not subclass. | |
100 |
|
100 | |||
101 | class Magic: |
|
101 | class Magic: | |
102 | """Magic functions for InteractiveShell. |
|
102 | """Magic functions for InteractiveShell. | |
103 |
|
103 | |||
104 | Shell functions which can be reached as %function_name. All magic |
|
104 | Shell functions which can be reached as %function_name. All magic | |
105 | functions should accept a string, which they can parse for their own |
|
105 | functions should accept a string, which they can parse for their own | |
106 | needs. This can make some functions easier to type, eg `%cd ../` |
|
106 | needs. This can make some functions easier to type, eg `%cd ../` | |
107 | vs. `%cd("../")` |
|
107 | vs. `%cd("../")` | |
108 |
|
108 | |||
109 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
109 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
110 | at the command line, but it is is needed in the definition. """ |
|
110 | at the command line, but it is is needed in the definition. """ | |
111 |
|
111 | |||
112 | # class globals |
|
112 | # class globals | |
113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
113 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
114 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
115 |
|
115 | |||
116 | #...................................................................... |
|
116 | #...................................................................... | |
117 | # some utility functions |
|
117 | # some utility functions | |
118 |
|
118 | |||
119 | def __init__(self,shell): |
|
119 | def __init__(self,shell): | |
120 |
|
120 | |||
121 | self.options_table = {} |
|
121 | self.options_table = {} | |
122 | if profile is None: |
|
122 | if profile is None: | |
123 | self.magic_prun = self.profile_missing_notice |
|
123 | self.magic_prun = self.profile_missing_notice | |
124 | self.shell = shell |
|
124 | self.shell = shell | |
125 |
|
125 | |||
126 | # namespace for holding state we may need |
|
126 | # namespace for holding state we may need | |
127 | self._magic_state = Bunch() |
|
127 | self._magic_state = Bunch() | |
128 |
|
128 | |||
129 | def profile_missing_notice(self, *args, **kwargs): |
|
129 | def profile_missing_notice(self, *args, **kwargs): | |
130 | error("""\ |
|
130 | error("""\ | |
131 | The profile module could not be found. It has been removed from the standard |
|
131 | The profile module could not be found. It has been removed from the standard | |
132 | python packages because of its non-free license. To use profiling, install the |
|
132 | python packages because of its non-free license. To use profiling, install the | |
133 | python-profiler package from non-free.""") |
|
133 | python-profiler package from non-free.""") | |
134 |
|
134 | |||
135 | def default_option(self,fn,optstr): |
|
135 | def default_option(self,fn,optstr): | |
136 | """Make an entry in the options_table for fn, with value optstr""" |
|
136 | """Make an entry in the options_table for fn, with value optstr""" | |
137 |
|
137 | |||
138 | if fn not in self.lsmagic(): |
|
138 | if fn not in self.lsmagic(): | |
139 | error("%s is not a magic function" % fn) |
|
139 | error("%s is not a magic function" % fn) | |
140 | self.options_table[fn] = optstr |
|
140 | self.options_table[fn] = optstr | |
141 |
|
141 | |||
142 | def lsmagic(self): |
|
142 | def lsmagic(self): | |
143 | """Return a list of currently available magic functions. |
|
143 | """Return a list of currently available magic functions. | |
144 |
|
144 | |||
145 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
145 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
146 | ['magic_ls','magic_cd',...]""" |
|
146 | ['magic_ls','magic_cd',...]""" | |
147 |
|
147 | |||
148 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
148 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
149 |
|
149 | |||
150 | # magics in class definition |
|
150 | # magics in class definition | |
151 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
151 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
152 | callable(Magic.__dict__[fn]) |
|
152 | callable(Magic.__dict__[fn]) | |
153 | # in instance namespace (run-time user additions) |
|
153 | # in instance namespace (run-time user additions) | |
154 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
154 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
155 | callable(self.__dict__[fn]) |
|
155 | callable(self.__dict__[fn]) | |
156 | # and bound magics by user (so they can access self): |
|
156 | # and bound magics by user (so they can access self): | |
157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
157 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
158 | callable(self.__class__.__dict__[fn]) |
|
158 | callable(self.__class__.__dict__[fn]) | |
159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
159 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
160 | filter(inst_magic,self.__dict__.keys()) + \ |
|
160 | filter(inst_magic,self.__dict__.keys()) + \ | |
161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
161 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
162 | out = [] |
|
162 | out = [] | |
163 | for fn in set(magics): |
|
163 | for fn in set(magics): | |
164 | out.append(fn.replace('magic_','',1)) |
|
164 | out.append(fn.replace('magic_','',1)) | |
165 | out.sort() |
|
165 | out.sort() | |
166 | return out |
|
166 | return out | |
167 |
|
167 | |||
168 | def extract_input_slices(self,slices,raw=False): |
|
168 | def extract_input_slices(self,slices,raw=False): | |
169 | """Return as a string a set of input history slices. |
|
169 | """Return as a string a set of input history slices. | |
170 |
|
170 | |||
171 | Inputs: |
|
171 | Inputs: | |
172 |
|
172 | |||
173 | - slices: the set of slices is given as a list of strings (like |
|
173 | - slices: the set of slices is given as a list of strings (like | |
174 | ['1','4:8','9'], since this function is for use by magic functions |
|
174 | ['1','4:8','9'], since this function is for use by magic functions | |
175 | which get their arguments as strings. |
|
175 | which get their arguments as strings. | |
176 |
|
176 | |||
177 | Optional inputs: |
|
177 | Optional inputs: | |
178 |
|
178 | |||
179 | - raw(False): by default, the processed input is used. If this is |
|
179 | - raw(False): by default, the processed input is used. If this is | |
180 | true, the raw input history is used instead. |
|
180 | true, the raw input history is used instead. | |
181 |
|
181 | |||
182 | Note that slices can be called with two notations: |
|
182 | Note that slices can be called with two notations: | |
183 |
|
183 | |||
184 | N:M -> standard python form, means including items N...(M-1). |
|
184 | N:M -> standard python form, means including items N...(M-1). | |
185 |
|
185 | |||
186 | N-M -> include items N..M (closed endpoint).""" |
|
186 | N-M -> include items N..M (closed endpoint).""" | |
187 | history_manager = self.shell.history_manager |
|
187 | history_manager = self.shell.history_manager | |
188 |
|
188 | |||
189 | cmds = [] |
|
189 | cmds = [] | |
190 | for chunk in slices: |
|
190 | for chunk in slices: | |
191 | if ':' in chunk: |
|
191 | if ':' in chunk: | |
192 | ini,fin = map(int,chunk.split(':')) |
|
192 | ini,fin = map(int,chunk.split(':')) | |
193 | elif '-' in chunk: |
|
193 | elif '-' in chunk: | |
194 | ini,fin = map(int,chunk.split('-')) |
|
194 | ini,fin = map(int,chunk.split('-')) | |
195 | fin += 1 |
|
195 | fin += 1 | |
196 | else: |
|
196 | else: | |
197 | ini = int(chunk) |
|
197 | ini = int(chunk) | |
198 | fin = ini+1 |
|
198 | fin = ini+1 | |
199 | hist = history_manager.get_history((ini,fin), raw=raw, output=False) |
|
199 | hist = history_manager.get_history((ini,fin), raw=raw, output=False) | |
200 | cmds.append('\n'.join(hist[i] for i in sorted(hist.iterkeys()))) |
|
200 | cmds.append('\n'.join(hist[i] for i in sorted(hist.iterkeys()))) | |
201 | return cmds |
|
201 | return cmds | |
202 |
|
202 | |||
203 | def arg_err(self,func): |
|
203 | def arg_err(self,func): | |
204 | """Print docstring if incorrect arguments were passed""" |
|
204 | """Print docstring if incorrect arguments were passed""" | |
205 | print 'Error in arguments:' |
|
205 | print 'Error in arguments:' | |
206 | print oinspect.getdoc(func) |
|
206 | print oinspect.getdoc(func) | |
207 |
|
207 | |||
208 | def format_latex(self,strng): |
|
208 | def format_latex(self,strng): | |
209 | """Format a string for latex inclusion.""" |
|
209 | """Format a string for latex inclusion.""" | |
210 |
|
210 | |||
211 | # Characters that need to be escaped for latex: |
|
211 | # Characters that need to be escaped for latex: | |
212 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
212 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
213 | # Magic command names as headers: |
|
213 | # Magic command names as headers: | |
214 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
214 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
215 | re.MULTILINE) |
|
215 | re.MULTILINE) | |
216 | # Magic commands |
|
216 | # Magic commands | |
217 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
217 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
218 | re.MULTILINE) |
|
218 | re.MULTILINE) | |
219 | # Paragraph continue |
|
219 | # Paragraph continue | |
220 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
220 | par_re = re.compile(r'\\$',re.MULTILINE) | |
221 |
|
221 | |||
222 | # The "\n" symbol |
|
222 | # The "\n" symbol | |
223 | newline_re = re.compile(r'\\n') |
|
223 | newline_re = re.compile(r'\\n') | |
224 |
|
224 | |||
225 | # Now build the string for output: |
|
225 | # Now build the string for output: | |
226 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
226 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
227 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
227 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
228 | strng) |
|
228 | strng) | |
229 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
229 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
230 | strng = par_re.sub(r'\\\\',strng) |
|
230 | strng = par_re.sub(r'\\\\',strng) | |
231 | strng = escape_re.sub(r'\\\1',strng) |
|
231 | strng = escape_re.sub(r'\\\1',strng) | |
232 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
232 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
233 | return strng |
|
233 | return strng | |
234 |
|
234 | |||
235 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
235 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
236 | """Parse options passed to an argument string. |
|
236 | """Parse options passed to an argument string. | |
237 |
|
237 | |||
238 | The interface is similar to that of getopt(), but it returns back a |
|
238 | The interface is similar to that of getopt(), but it returns back a | |
239 | Struct with the options as keys and the stripped argument string still |
|
239 | Struct with the options as keys and the stripped argument string still | |
240 | as a string. |
|
240 | as a string. | |
241 |
|
241 | |||
242 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
242 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
243 | This allows us to easily expand variables, glob files, quote |
|
243 | This allows us to easily expand variables, glob files, quote | |
244 | arguments, etc. |
|
244 | arguments, etc. | |
245 |
|
245 | |||
246 | Options: |
|
246 | Options: | |
247 | -mode: default 'string'. If given as 'list', the argument string is |
|
247 | -mode: default 'string'. If given as 'list', the argument string is | |
248 | returned as a list (split on whitespace) instead of a string. |
|
248 | returned as a list (split on whitespace) instead of a string. | |
249 |
|
249 | |||
250 | -list_all: put all option values in lists. Normally only options |
|
250 | -list_all: put all option values in lists. Normally only options | |
251 | appearing more than once are put in a list. |
|
251 | appearing more than once are put in a list. | |
252 |
|
252 | |||
253 | -posix (True): whether to split the input line in POSIX mode or not, |
|
253 | -posix (True): whether to split the input line in POSIX mode or not, | |
254 | as per the conventions outlined in the shlex module from the |
|
254 | as per the conventions outlined in the shlex module from the | |
255 | standard library.""" |
|
255 | standard library.""" | |
256 |
|
256 | |||
257 | # inject default options at the beginning of the input line |
|
257 | # inject default options at the beginning of the input line | |
258 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
258 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
259 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
259 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
260 |
|
260 | |||
261 | mode = kw.get('mode','string') |
|
261 | mode = kw.get('mode','string') | |
262 | if mode not in ['string','list']: |
|
262 | if mode not in ['string','list']: | |
263 | raise ValueError,'incorrect mode given: %s' % mode |
|
263 | raise ValueError,'incorrect mode given: %s' % mode | |
264 | # Get options |
|
264 | # Get options | |
265 | list_all = kw.get('list_all',0) |
|
265 | list_all = kw.get('list_all',0) | |
266 | posix = kw.get('posix', os.name == 'posix') |
|
266 | posix = kw.get('posix', os.name == 'posix') | |
267 |
|
267 | |||
268 | # Check if we have more than one argument to warrant extra processing: |
|
268 | # Check if we have more than one argument to warrant extra processing: | |
269 | odict = {} # Dictionary with options |
|
269 | odict = {} # Dictionary with options | |
270 | args = arg_str.split() |
|
270 | args = arg_str.split() | |
271 | if len(args) >= 1: |
|
271 | if len(args) >= 1: | |
272 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
272 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
273 | # need to look for options |
|
273 | # need to look for options | |
274 | argv = arg_split(arg_str,posix) |
|
274 | argv = arg_split(arg_str,posix) | |
275 | # Do regular option processing |
|
275 | # Do regular option processing | |
276 | try: |
|
276 | try: | |
277 | opts,args = getopt(argv,opt_str,*long_opts) |
|
277 | opts,args = getopt(argv,opt_str,*long_opts) | |
278 | except GetoptError,e: |
|
278 | except GetoptError,e: | |
279 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
279 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
280 | " ".join(long_opts))) |
|
280 | " ".join(long_opts))) | |
281 | for o,a in opts: |
|
281 | for o,a in opts: | |
282 | if o.startswith('--'): |
|
282 | if o.startswith('--'): | |
283 | o = o[2:] |
|
283 | o = o[2:] | |
284 | else: |
|
284 | else: | |
285 | o = o[1:] |
|
285 | o = o[1:] | |
286 | try: |
|
286 | try: | |
287 | odict[o].append(a) |
|
287 | odict[o].append(a) | |
288 | except AttributeError: |
|
288 | except AttributeError: | |
289 | odict[o] = [odict[o],a] |
|
289 | odict[o] = [odict[o],a] | |
290 | except KeyError: |
|
290 | except KeyError: | |
291 | if list_all: |
|
291 | if list_all: | |
292 | odict[o] = [a] |
|
292 | odict[o] = [a] | |
293 | else: |
|
293 | else: | |
294 | odict[o] = a |
|
294 | odict[o] = a | |
295 |
|
295 | |||
296 | # Prepare opts,args for return |
|
296 | # Prepare opts,args for return | |
297 | opts = Struct(odict) |
|
297 | opts = Struct(odict) | |
298 | if mode == 'string': |
|
298 | if mode == 'string': | |
299 | args = ' '.join(args) |
|
299 | args = ' '.join(args) | |
300 |
|
300 | |||
301 | return opts,args |
|
301 | return opts,args | |
302 |
|
302 | |||
303 | #...................................................................... |
|
303 | #...................................................................... | |
304 | # And now the actual magic functions |
|
304 | # And now the actual magic functions | |
305 |
|
305 | |||
306 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
306 | # Functions for IPython shell work (vars,funcs, config, etc) | |
307 | def magic_lsmagic(self, parameter_s = ''): |
|
307 | def magic_lsmagic(self, parameter_s = ''): | |
308 | """List currently available magic functions.""" |
|
308 | """List currently available magic functions.""" | |
309 | mesc = ESC_MAGIC |
|
309 | mesc = ESC_MAGIC | |
310 | print 'Available magic functions:\n'+mesc+\ |
|
310 | print 'Available magic functions:\n'+mesc+\ | |
311 | (' '+mesc).join(self.lsmagic()) |
|
311 | (' '+mesc).join(self.lsmagic()) | |
312 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
312 | print '\n' + Magic.auto_status[self.shell.automagic] | |
313 | return None |
|
313 | return None | |
314 |
|
314 | |||
315 | def magic_magic(self, parameter_s = ''): |
|
315 | def magic_magic(self, parameter_s = ''): | |
316 | """Print information about the magic function system. |
|
316 | """Print information about the magic function system. | |
317 |
|
317 | |||
318 | Supported formats: -latex, -brief, -rest |
|
318 | Supported formats: -latex, -brief, -rest | |
319 | """ |
|
319 | """ | |
320 |
|
320 | |||
321 | mode = '' |
|
321 | mode = '' | |
322 | try: |
|
322 | try: | |
323 | if parameter_s.split()[0] == '-latex': |
|
323 | if parameter_s.split()[0] == '-latex': | |
324 | mode = 'latex' |
|
324 | mode = 'latex' | |
325 | if parameter_s.split()[0] == '-brief': |
|
325 | if parameter_s.split()[0] == '-brief': | |
326 | mode = 'brief' |
|
326 | mode = 'brief' | |
327 | if parameter_s.split()[0] == '-rest': |
|
327 | if parameter_s.split()[0] == '-rest': | |
328 | mode = 'rest' |
|
328 | mode = 'rest' | |
329 | rest_docs = [] |
|
329 | rest_docs = [] | |
330 | except: |
|
330 | except: | |
331 | pass |
|
331 | pass | |
332 |
|
332 | |||
333 | magic_docs = [] |
|
333 | magic_docs = [] | |
334 | for fname in self.lsmagic(): |
|
334 | for fname in self.lsmagic(): | |
335 | mname = 'magic_' + fname |
|
335 | mname = 'magic_' + fname | |
336 | for space in (Magic,self,self.__class__): |
|
336 | for space in (Magic,self,self.__class__): | |
337 | try: |
|
337 | try: | |
338 | fn = space.__dict__[mname] |
|
338 | fn = space.__dict__[mname] | |
339 | except KeyError: |
|
339 | except KeyError: | |
340 | pass |
|
340 | pass | |
341 | else: |
|
341 | else: | |
342 | break |
|
342 | break | |
343 | if mode == 'brief': |
|
343 | if mode == 'brief': | |
344 | # only first line |
|
344 | # only first line | |
345 | if fn.__doc__: |
|
345 | if fn.__doc__: | |
346 | fndoc = fn.__doc__.split('\n',1)[0] |
|
346 | fndoc = fn.__doc__.split('\n',1)[0] | |
347 | else: |
|
347 | else: | |
348 | fndoc = 'No documentation' |
|
348 | fndoc = 'No documentation' | |
349 | else: |
|
349 | else: | |
350 | if fn.__doc__: |
|
350 | if fn.__doc__: | |
351 | fndoc = fn.__doc__.rstrip() |
|
351 | fndoc = fn.__doc__.rstrip() | |
352 | else: |
|
352 | else: | |
353 | fndoc = 'No documentation' |
|
353 | fndoc = 'No documentation' | |
354 |
|
354 | |||
355 |
|
355 | |||
356 | if mode == 'rest': |
|
356 | if mode == 'rest': | |
357 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
357 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
358 | fname,fndoc)) |
|
358 | fname,fndoc)) | |
359 |
|
359 | |||
360 | else: |
|
360 | else: | |
361 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
361 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
362 | fname,fndoc)) |
|
362 | fname,fndoc)) | |
363 |
|
363 | |||
364 | magic_docs = ''.join(magic_docs) |
|
364 | magic_docs = ''.join(magic_docs) | |
365 |
|
365 | |||
366 | if mode == 'rest': |
|
366 | if mode == 'rest': | |
367 | return "".join(rest_docs) |
|
367 | return "".join(rest_docs) | |
368 |
|
368 | |||
369 | if mode == 'latex': |
|
369 | if mode == 'latex': | |
370 | print self.format_latex(magic_docs) |
|
370 | print self.format_latex(magic_docs) | |
371 | return |
|
371 | return | |
372 | else: |
|
372 | else: | |
373 | magic_docs = format_screen(magic_docs) |
|
373 | magic_docs = format_screen(magic_docs) | |
374 | if mode == 'brief': |
|
374 | if mode == 'brief': | |
375 | return magic_docs |
|
375 | return magic_docs | |
376 |
|
376 | |||
377 | outmsg = """ |
|
377 | outmsg = """ | |
378 | IPython's 'magic' functions |
|
378 | IPython's 'magic' functions | |
379 | =========================== |
|
379 | =========================== | |
380 |
|
380 | |||
381 | The magic function system provides a series of functions which allow you to |
|
381 | The magic function system provides a series of functions which allow you to | |
382 | control the behavior of IPython itself, plus a lot of system-type |
|
382 | control the behavior of IPython itself, plus a lot of system-type | |
383 | features. All these functions are prefixed with a % character, but parameters |
|
383 | features. All these functions are prefixed with a % character, but parameters | |
384 | are given without parentheses or quotes. |
|
384 | are given without parentheses or quotes. | |
385 |
|
385 | |||
386 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
386 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
387 | %automagic function), you don't need to type in the % explicitly. By default, |
|
387 | %automagic function), you don't need to type in the % explicitly. By default, | |
388 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
388 | IPython ships with automagic on, so you should only rarely need the % escape. | |
389 |
|
389 | |||
390 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
390 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
391 | to 'mydir', if it exists. |
|
391 | to 'mydir', if it exists. | |
392 |
|
392 | |||
393 | You can define your own magic functions to extend the system. See the supplied |
|
393 | You can define your own magic functions to extend the system. See the supplied | |
394 | ipythonrc and example-magic.py files for details (in your ipython |
|
394 | ipythonrc and example-magic.py files for details (in your ipython | |
395 | configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere). |
|
395 | configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere). | |
396 |
|
396 | |||
397 | You can also define your own aliased names for magic functions. In your |
|
397 | You can also define your own aliased names for magic functions. In your | |
398 | ipythonrc file, placing a line like: |
|
398 | ipythonrc file, placing a line like: | |
399 |
|
399 | |||
400 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
400 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
401 |
|
401 | |||
402 | will define %pf as a new name for %profile. |
|
402 | will define %pf as a new name for %profile. | |
403 |
|
403 | |||
404 | You can also call magics in code using the magic() function, which IPython |
|
404 | You can also call magics in code using the magic() function, which IPython | |
405 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
405 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
406 |
|
406 | |||
407 | For a list of the available magic functions, use %lsmagic. For a description |
|
407 | For a list of the available magic functions, use %lsmagic. For a description | |
408 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
408 | of any of them, type %magic_name?, e.g. '%cd?'. | |
409 |
|
409 | |||
410 | Currently the magic system has the following functions:\n""" |
|
410 | Currently the magic system has the following functions:\n""" | |
411 |
|
411 | |||
412 | mesc = ESC_MAGIC |
|
412 | mesc = ESC_MAGIC | |
413 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
413 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
414 | "\n\n%s%s\n\n%s" % (outmsg, |
|
414 | "\n\n%s%s\n\n%s" % (outmsg, | |
415 | magic_docs,mesc,mesc, |
|
415 | magic_docs,mesc,mesc, | |
416 | (' '+mesc).join(self.lsmagic()), |
|
416 | (' '+mesc).join(self.lsmagic()), | |
417 | Magic.auto_status[self.shell.automagic] ) ) |
|
417 | Magic.auto_status[self.shell.automagic] ) ) | |
418 | page.page(outmsg) |
|
418 | page.page(outmsg) | |
419 |
|
419 | |||
420 | def magic_automagic(self, parameter_s = ''): |
|
420 | def magic_automagic(self, parameter_s = ''): | |
421 | """Make magic functions callable without having to type the initial %. |
|
421 | """Make magic functions callable without having to type the initial %. | |
422 |
|
422 | |||
423 | Without argumentsl toggles on/off (when off, you must call it as |
|
423 | Without argumentsl toggles on/off (when off, you must call it as | |
424 | %automagic, of course). With arguments it sets the value, and you can |
|
424 | %automagic, of course). With arguments it sets the value, and you can | |
425 | use any of (case insensitive): |
|
425 | use any of (case insensitive): | |
426 |
|
426 | |||
427 | - on,1,True: to activate |
|
427 | - on,1,True: to activate | |
428 |
|
428 | |||
429 | - off,0,False: to deactivate. |
|
429 | - off,0,False: to deactivate. | |
430 |
|
430 | |||
431 | Note that magic functions have lowest priority, so if there's a |
|
431 | Note that magic functions have lowest priority, so if there's a | |
432 | variable whose name collides with that of a magic fn, automagic won't |
|
432 | variable whose name collides with that of a magic fn, automagic won't | |
433 | work for that function (you get the variable instead). However, if you |
|
433 | work for that function (you get the variable instead). However, if you | |
434 | delete the variable (del var), the previously shadowed magic function |
|
434 | delete the variable (del var), the previously shadowed magic function | |
435 | becomes visible to automagic again.""" |
|
435 | becomes visible to automagic again.""" | |
436 |
|
436 | |||
437 | arg = parameter_s.lower() |
|
437 | arg = parameter_s.lower() | |
438 | if parameter_s in ('on','1','true'): |
|
438 | if parameter_s in ('on','1','true'): | |
439 | self.shell.automagic = True |
|
439 | self.shell.automagic = True | |
440 | elif parameter_s in ('off','0','false'): |
|
440 | elif parameter_s in ('off','0','false'): | |
441 | self.shell.automagic = False |
|
441 | self.shell.automagic = False | |
442 | else: |
|
442 | else: | |
443 | self.shell.automagic = not self.shell.automagic |
|
443 | self.shell.automagic = not self.shell.automagic | |
444 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
444 | print '\n' + Magic.auto_status[self.shell.automagic] | |
445 |
|
445 | |||
446 | @testdec.skip_doctest |
|
446 | @testdec.skip_doctest | |
447 | def magic_autocall(self, parameter_s = ''): |
|
447 | def magic_autocall(self, parameter_s = ''): | |
448 | """Make functions callable without having to type parentheses. |
|
448 | """Make functions callable without having to type parentheses. | |
449 |
|
449 | |||
450 | Usage: |
|
450 | Usage: | |
451 |
|
451 | |||
452 | %autocall [mode] |
|
452 | %autocall [mode] | |
453 |
|
453 | |||
454 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
454 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
455 | value is toggled on and off (remembering the previous state). |
|
455 | value is toggled on and off (remembering the previous state). | |
456 |
|
456 | |||
457 | In more detail, these values mean: |
|
457 | In more detail, these values mean: | |
458 |
|
458 | |||
459 | 0 -> fully disabled |
|
459 | 0 -> fully disabled | |
460 |
|
460 | |||
461 | 1 -> active, but do not apply if there are no arguments on the line. |
|
461 | 1 -> active, but do not apply if there are no arguments on the line. | |
462 |
|
462 | |||
463 | In this mode, you get: |
|
463 | In this mode, you get: | |
464 |
|
464 | |||
465 | In [1]: callable |
|
465 | In [1]: callable | |
466 | Out[1]: <built-in function callable> |
|
466 | Out[1]: <built-in function callable> | |
467 |
|
467 | |||
468 | In [2]: callable 'hello' |
|
468 | In [2]: callable 'hello' | |
469 | ------> callable('hello') |
|
469 | ------> callable('hello') | |
470 | Out[2]: False |
|
470 | Out[2]: False | |
471 |
|
471 | |||
472 | 2 -> Active always. Even if no arguments are present, the callable |
|
472 | 2 -> Active always. Even if no arguments are present, the callable | |
473 | object is called: |
|
473 | object is called: | |
474 |
|
474 | |||
475 | In [2]: float |
|
475 | In [2]: float | |
476 | ------> float() |
|
476 | ------> float() | |
477 | Out[2]: 0.0 |
|
477 | Out[2]: 0.0 | |
478 |
|
478 | |||
479 | Note that even with autocall off, you can still use '/' at the start of |
|
479 | Note that even with autocall off, you can still use '/' at the start of | |
480 | a line to treat the first argument on the command line as a function |
|
480 | a line to treat the first argument on the command line as a function | |
481 | and add parentheses to it: |
|
481 | and add parentheses to it: | |
482 |
|
482 | |||
483 | In [8]: /str 43 |
|
483 | In [8]: /str 43 | |
484 | ------> str(43) |
|
484 | ------> str(43) | |
485 | Out[8]: '43' |
|
485 | Out[8]: '43' | |
486 |
|
486 | |||
487 | # all-random (note for auto-testing) |
|
487 | # all-random (note for auto-testing) | |
488 | """ |
|
488 | """ | |
489 |
|
489 | |||
490 | if parameter_s: |
|
490 | if parameter_s: | |
491 | arg = int(parameter_s) |
|
491 | arg = int(parameter_s) | |
492 | else: |
|
492 | else: | |
493 | arg = 'toggle' |
|
493 | arg = 'toggle' | |
494 |
|
494 | |||
495 | if not arg in (0,1,2,'toggle'): |
|
495 | if not arg in (0,1,2,'toggle'): | |
496 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
496 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
497 | return |
|
497 | return | |
498 |
|
498 | |||
499 | if arg in (0,1,2): |
|
499 | if arg in (0,1,2): | |
500 | self.shell.autocall = arg |
|
500 | self.shell.autocall = arg | |
501 | else: # toggle |
|
501 | else: # toggle | |
502 | if self.shell.autocall: |
|
502 | if self.shell.autocall: | |
503 | self._magic_state.autocall_save = self.shell.autocall |
|
503 | self._magic_state.autocall_save = self.shell.autocall | |
504 | self.shell.autocall = 0 |
|
504 | self.shell.autocall = 0 | |
505 | else: |
|
505 | else: | |
506 | try: |
|
506 | try: | |
507 | self.shell.autocall = self._magic_state.autocall_save |
|
507 | self.shell.autocall = self._magic_state.autocall_save | |
508 | except AttributeError: |
|
508 | except AttributeError: | |
509 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
509 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
510 |
|
510 | |||
511 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
511 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
512 |
|
512 | |||
513 |
|
513 | |||
514 | def magic_page(self, parameter_s=''): |
|
514 | def magic_page(self, parameter_s=''): | |
515 | """Pretty print the object and display it through a pager. |
|
515 | """Pretty print the object and display it through a pager. | |
516 |
|
516 | |||
517 | %page [options] OBJECT |
|
517 | %page [options] OBJECT | |
518 |
|
518 | |||
519 | If no object is given, use _ (last output). |
|
519 | If no object is given, use _ (last output). | |
520 |
|
520 | |||
521 | Options: |
|
521 | Options: | |
522 |
|
522 | |||
523 | -r: page str(object), don't pretty-print it.""" |
|
523 | -r: page str(object), don't pretty-print it.""" | |
524 |
|
524 | |||
525 | # After a function contributed by Olivier Aubert, slightly modified. |
|
525 | # After a function contributed by Olivier Aubert, slightly modified. | |
526 |
|
526 | |||
527 | # Process options/args |
|
527 | # Process options/args | |
528 | opts,args = self.parse_options(parameter_s,'r') |
|
528 | opts,args = self.parse_options(parameter_s,'r') | |
529 | raw = 'r' in opts |
|
529 | raw = 'r' in opts | |
530 |
|
530 | |||
531 | oname = args and args or '_' |
|
531 | oname = args and args or '_' | |
532 | info = self._ofind(oname) |
|
532 | info = self._ofind(oname) | |
533 | if info['found']: |
|
533 | if info['found']: | |
534 | txt = (raw and str or pformat)( info['obj'] ) |
|
534 | txt = (raw and str or pformat)( info['obj'] ) | |
535 | page.page(txt) |
|
535 | page.page(txt) | |
536 | else: |
|
536 | else: | |
537 | print 'Object `%s` not found' % oname |
|
537 | print 'Object `%s` not found' % oname | |
538 |
|
538 | |||
539 | def magic_profile(self, parameter_s=''): |
|
539 | def magic_profile(self, parameter_s=''): | |
540 | """Print your currently active IPython profile.""" |
|
540 | """Print your currently active IPython profile.""" | |
541 | if self.shell.profile: |
|
541 | if self.shell.profile: | |
542 | printpl('Current IPython profile: $self.shell.profile.') |
|
542 | printpl('Current IPython profile: $self.shell.profile.') | |
543 | else: |
|
543 | else: | |
544 | print 'No profile active.' |
|
544 | print 'No profile active.' | |
545 |
|
545 | |||
546 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
546 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
547 | """Provide detailed information about an object. |
|
547 | """Provide detailed information about an object. | |
548 |
|
548 | |||
549 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
549 | '%pinfo object' is just a synonym for object? or ?object.""" | |
550 |
|
550 | |||
551 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
551 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
552 |
|
552 | |||
553 |
|
553 | |||
554 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
554 | # detail_level: 0 -> obj? , 1 -> obj?? | |
555 | detail_level = 0 |
|
555 | detail_level = 0 | |
556 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
556 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
557 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
557 | # happen if the user types 'pinfo foo?' at the cmd line. | |
558 | pinfo,qmark1,oname,qmark2 = \ |
|
558 | pinfo,qmark1,oname,qmark2 = \ | |
559 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
559 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
560 | if pinfo or qmark1 or qmark2: |
|
560 | if pinfo or qmark1 or qmark2: | |
561 | detail_level = 1 |
|
561 | detail_level = 1 | |
562 | if "*" in oname: |
|
562 | if "*" in oname: | |
563 | self.magic_psearch(oname) |
|
563 | self.magic_psearch(oname) | |
564 | else: |
|
564 | else: | |
565 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
565 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
566 | namespaces=namespaces) |
|
566 | namespaces=namespaces) | |
567 |
|
567 | |||
568 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
568 | def magic_pinfo2(self, parameter_s='', namespaces=None): | |
569 | """Provide extra detailed information about an object. |
|
569 | """Provide extra detailed information about an object. | |
570 |
|
570 | |||
571 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
571 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
572 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
572 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
573 | namespaces=namespaces) |
|
573 | namespaces=namespaces) | |
574 |
|
574 | |||
575 | @testdec.skip_doctest |
|
575 | @testdec.skip_doctest | |
576 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
576 | def magic_pdef(self, parameter_s='', namespaces=None): | |
577 | """Print the definition header for any callable object. |
|
577 | """Print the definition header for any callable object. | |
578 |
|
578 | |||
579 | If the object is a class, print the constructor information. |
|
579 | If the object is a class, print the constructor information. | |
580 |
|
580 | |||
581 | Examples |
|
581 | Examples | |
582 | -------- |
|
582 | -------- | |
583 | :: |
|
583 | :: | |
584 |
|
584 | |||
585 | In [3]: %pdef urllib.urlopen |
|
585 | In [3]: %pdef urllib.urlopen | |
586 | urllib.urlopen(url, data=None, proxies=None) |
|
586 | urllib.urlopen(url, data=None, proxies=None) | |
587 | """ |
|
587 | """ | |
588 | self._inspect('pdef',parameter_s, namespaces) |
|
588 | self._inspect('pdef',parameter_s, namespaces) | |
589 |
|
589 | |||
590 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
590 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
591 | """Print the docstring for an object. |
|
591 | """Print the docstring for an object. | |
592 |
|
592 | |||
593 | If the given object is a class, it will print both the class and the |
|
593 | If the given object is a class, it will print both the class and the | |
594 | constructor docstrings.""" |
|
594 | constructor docstrings.""" | |
595 | self._inspect('pdoc',parameter_s, namespaces) |
|
595 | self._inspect('pdoc',parameter_s, namespaces) | |
596 |
|
596 | |||
597 | def magic_psource(self, parameter_s='', namespaces=None): |
|
597 | def magic_psource(self, parameter_s='', namespaces=None): | |
598 | """Print (or run through pager) the source code for an object.""" |
|
598 | """Print (or run through pager) the source code for an object.""" | |
599 | self._inspect('psource',parameter_s, namespaces) |
|
599 | self._inspect('psource',parameter_s, namespaces) | |
600 |
|
600 | |||
601 | def magic_pfile(self, parameter_s=''): |
|
601 | def magic_pfile(self, parameter_s=''): | |
602 | """Print (or run through pager) the file where an object is defined. |
|
602 | """Print (or run through pager) the file where an object is defined. | |
603 |
|
603 | |||
604 | The file opens at the line where the object definition begins. IPython |
|
604 | The file opens at the line where the object definition begins. IPython | |
605 | will honor the environment variable PAGER if set, and otherwise will |
|
605 | will honor the environment variable PAGER if set, and otherwise will | |
606 | do its best to print the file in a convenient form. |
|
606 | do its best to print the file in a convenient form. | |
607 |
|
607 | |||
608 | If the given argument is not an object currently defined, IPython will |
|
608 | If the given argument is not an object currently defined, IPython will | |
609 | try to interpret it as a filename (automatically adding a .py extension |
|
609 | try to interpret it as a filename (automatically adding a .py extension | |
610 | if needed). You can thus use %pfile as a syntax highlighting code |
|
610 | if needed). You can thus use %pfile as a syntax highlighting code | |
611 | viewer.""" |
|
611 | viewer.""" | |
612 |
|
612 | |||
613 | # first interpret argument as an object name |
|
613 | # first interpret argument as an object name | |
614 | out = self._inspect('pfile',parameter_s) |
|
614 | out = self._inspect('pfile',parameter_s) | |
615 | # if not, try the input as a filename |
|
615 | # if not, try the input as a filename | |
616 | if out == 'not found': |
|
616 | if out == 'not found': | |
617 | try: |
|
617 | try: | |
618 | filename = get_py_filename(parameter_s) |
|
618 | filename = get_py_filename(parameter_s) | |
619 | except IOError,msg: |
|
619 | except IOError,msg: | |
620 | print msg |
|
620 | print msg | |
621 | return |
|
621 | return | |
622 | page.page(self.shell.inspector.format(file(filename).read())) |
|
622 | page.page(self.shell.inspector.format(file(filename).read())) | |
623 |
|
623 | |||
624 | def magic_psearch(self, parameter_s=''): |
|
624 | def magic_psearch(self, parameter_s=''): | |
625 | """Search for object in namespaces by wildcard. |
|
625 | """Search for object in namespaces by wildcard. | |
626 |
|
626 | |||
627 | %psearch [options] PATTERN [OBJECT TYPE] |
|
627 | %psearch [options] PATTERN [OBJECT TYPE] | |
628 |
|
628 | |||
629 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
629 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
630 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
630 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
631 | rest of the command line must be unchanged (options come first), so |
|
631 | rest of the command line must be unchanged (options come first), so | |
632 | for example the following forms are equivalent |
|
632 | for example the following forms are equivalent | |
633 |
|
633 | |||
634 | %psearch -i a* function |
|
634 | %psearch -i a* function | |
635 | -i a* function? |
|
635 | -i a* function? | |
636 | ?-i a* function |
|
636 | ?-i a* function | |
637 |
|
637 | |||
638 | Arguments: |
|
638 | Arguments: | |
639 |
|
639 | |||
640 | PATTERN |
|
640 | PATTERN | |
641 |
|
641 | |||
642 | where PATTERN is a string containing * as a wildcard similar to its |
|
642 | where PATTERN is a string containing * as a wildcard similar to its | |
643 | use in a shell. The pattern is matched in all namespaces on the |
|
643 | use in a shell. The pattern is matched in all namespaces on the | |
644 | search path. By default objects starting with a single _ are not |
|
644 | search path. By default objects starting with a single _ are not | |
645 | matched, many IPython generated objects have a single |
|
645 | matched, many IPython generated objects have a single | |
646 | underscore. The default is case insensitive matching. Matching is |
|
646 | underscore. The default is case insensitive matching. Matching is | |
647 | also done on the attributes of objects and not only on the objects |
|
647 | also done on the attributes of objects and not only on the objects | |
648 | in a module. |
|
648 | in a module. | |
649 |
|
649 | |||
650 | [OBJECT TYPE] |
|
650 | [OBJECT TYPE] | |
651 |
|
651 | |||
652 | Is the name of a python type from the types module. The name is |
|
652 | Is the name of a python type from the types module. The name is | |
653 | given in lowercase without the ending type, ex. StringType is |
|
653 | given in lowercase without the ending type, ex. StringType is | |
654 | written string. By adding a type here only objects matching the |
|
654 | written string. By adding a type here only objects matching the | |
655 | given type are matched. Using all here makes the pattern match all |
|
655 | given type are matched. Using all here makes the pattern match all | |
656 | types (this is the default). |
|
656 | types (this is the default). | |
657 |
|
657 | |||
658 | Options: |
|
658 | Options: | |
659 |
|
659 | |||
660 | -a: makes the pattern match even objects whose names start with a |
|
660 | -a: makes the pattern match even objects whose names start with a | |
661 | single underscore. These names are normally ommitted from the |
|
661 | single underscore. These names are normally ommitted from the | |
662 | search. |
|
662 | search. | |
663 |
|
663 | |||
664 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
664 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
665 | these options is given, the default is read from your ipythonrc |
|
665 | these options is given, the default is read from your ipythonrc | |
666 | file. The option name which sets this value is |
|
666 | file. The option name which sets this value is | |
667 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
667 | 'wildcards_case_sensitive'. If this option is not specified in your | |
668 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
668 | ipythonrc file, IPython's internal default is to do a case sensitive | |
669 | search. |
|
669 | search. | |
670 |
|
670 | |||
671 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
671 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
672 | specifiy can be searched in any of the following namespaces: |
|
672 | specifiy can be searched in any of the following namespaces: | |
673 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
673 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
674 | 'builtin' and 'user' are the search defaults. Note that you should |
|
674 | 'builtin' and 'user' are the search defaults. Note that you should | |
675 | not use quotes when specifying namespaces. |
|
675 | not use quotes when specifying namespaces. | |
676 |
|
676 | |||
677 | 'Builtin' contains the python module builtin, 'user' contains all |
|
677 | 'Builtin' contains the python module builtin, 'user' contains all | |
678 | user data, 'alias' only contain the shell aliases and no python |
|
678 | user data, 'alias' only contain the shell aliases and no python | |
679 | objects, 'internal' contains objects used by IPython. The |
|
679 | objects, 'internal' contains objects used by IPython. The | |
680 | 'user_global' namespace is only used by embedded IPython instances, |
|
680 | 'user_global' namespace is only used by embedded IPython instances, | |
681 | and it contains module-level globals. You can add namespaces to the |
|
681 | and it contains module-level globals. You can add namespaces to the | |
682 | search with -s or exclude them with -e (these options can be given |
|
682 | search with -s or exclude them with -e (these options can be given | |
683 | more than once). |
|
683 | more than once). | |
684 |
|
684 | |||
685 | Examples: |
|
685 | Examples: | |
686 |
|
686 | |||
687 | %psearch a* -> objects beginning with an a |
|
687 | %psearch a* -> objects beginning with an a | |
688 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
688 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
689 | %psearch a* function -> all functions beginning with an a |
|
689 | %psearch a* function -> all functions beginning with an a | |
690 | %psearch re.e* -> objects beginning with an e in module re |
|
690 | %psearch re.e* -> objects beginning with an e in module re | |
691 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
691 | %psearch r*.e* -> objects that start with e in modules starting in r | |
692 | %psearch r*.* string -> all strings in modules beginning with r |
|
692 | %psearch r*.* string -> all strings in modules beginning with r | |
693 |
|
693 | |||
694 | Case sensitve search: |
|
694 | Case sensitve search: | |
695 |
|
695 | |||
696 | %psearch -c a* list all object beginning with lower case a |
|
696 | %psearch -c a* list all object beginning with lower case a | |
697 |
|
697 | |||
698 | Show objects beginning with a single _: |
|
698 | Show objects beginning with a single _: | |
699 |
|
699 | |||
700 | %psearch -a _* list objects beginning with a single underscore""" |
|
700 | %psearch -a _* list objects beginning with a single underscore""" | |
701 | try: |
|
701 | try: | |
702 | parameter_s = parameter_s.encode('ascii') |
|
702 | parameter_s = parameter_s.encode('ascii') | |
703 | except UnicodeEncodeError: |
|
703 | except UnicodeEncodeError: | |
704 | print 'Python identifiers can only contain ascii characters.' |
|
704 | print 'Python identifiers can only contain ascii characters.' | |
705 | return |
|
705 | return | |
706 |
|
706 | |||
707 | # default namespaces to be searched |
|
707 | # default namespaces to be searched | |
708 | def_search = ['user','builtin'] |
|
708 | def_search = ['user','builtin'] | |
709 |
|
709 | |||
710 | # Process options/args |
|
710 | # Process options/args | |
711 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
711 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
712 | opt = opts.get |
|
712 | opt = opts.get | |
713 | shell = self.shell |
|
713 | shell = self.shell | |
714 | psearch = shell.inspector.psearch |
|
714 | psearch = shell.inspector.psearch | |
715 |
|
715 | |||
716 | # select case options |
|
716 | # select case options | |
717 | if opts.has_key('i'): |
|
717 | if opts.has_key('i'): | |
718 | ignore_case = True |
|
718 | ignore_case = True | |
719 | elif opts.has_key('c'): |
|
719 | elif opts.has_key('c'): | |
720 | ignore_case = False |
|
720 | ignore_case = False | |
721 | else: |
|
721 | else: | |
722 | ignore_case = not shell.wildcards_case_sensitive |
|
722 | ignore_case = not shell.wildcards_case_sensitive | |
723 |
|
723 | |||
724 | # Build list of namespaces to search from user options |
|
724 | # Build list of namespaces to search from user options | |
725 | def_search.extend(opt('s',[])) |
|
725 | def_search.extend(opt('s',[])) | |
726 | ns_exclude = ns_exclude=opt('e',[]) |
|
726 | ns_exclude = ns_exclude=opt('e',[]) | |
727 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
727 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
728 |
|
728 | |||
729 | # Call the actual search |
|
729 | # Call the actual search | |
730 | try: |
|
730 | try: | |
731 | psearch(args,shell.ns_table,ns_search, |
|
731 | psearch(args,shell.ns_table,ns_search, | |
732 | show_all=opt('a'),ignore_case=ignore_case) |
|
732 | show_all=opt('a'),ignore_case=ignore_case) | |
733 | except: |
|
733 | except: | |
734 | shell.showtraceback() |
|
734 | shell.showtraceback() | |
735 |
|
735 | |||
736 | @testdec.skip_doctest |
|
736 | @testdec.skip_doctest | |
737 | def magic_who_ls(self, parameter_s=''): |
|
737 | def magic_who_ls(self, parameter_s=''): | |
738 | """Return a sorted list of all interactive variables. |
|
738 | """Return a sorted list of all interactive variables. | |
739 |
|
739 | |||
740 | If arguments are given, only variables of types matching these |
|
740 | If arguments are given, only variables of types matching these | |
741 | arguments are returned. |
|
741 | arguments are returned. | |
742 |
|
742 | |||
743 | Examples |
|
743 | Examples | |
744 | -------- |
|
744 | -------- | |
745 |
|
745 | |||
746 | Define two variables and list them with who_ls:: |
|
746 | Define two variables and list them with who_ls:: | |
747 |
|
747 | |||
748 | In [1]: alpha = 123 |
|
748 | In [1]: alpha = 123 | |
749 |
|
749 | |||
750 | In [2]: beta = 'test' |
|
750 | In [2]: beta = 'test' | |
751 |
|
751 | |||
752 | In [3]: %who_ls |
|
752 | In [3]: %who_ls | |
753 | Out[3]: ['alpha', 'beta'] |
|
753 | Out[3]: ['alpha', 'beta'] | |
754 |
|
754 | |||
755 | In [4]: %who_ls int |
|
755 | In [4]: %who_ls int | |
756 | Out[4]: ['alpha'] |
|
756 | Out[4]: ['alpha'] | |
757 |
|
757 | |||
758 | In [5]: %who_ls str |
|
758 | In [5]: %who_ls str | |
759 | Out[5]: ['beta'] |
|
759 | Out[5]: ['beta'] | |
760 | """ |
|
760 | """ | |
761 |
|
761 | |||
762 | user_ns = self.shell.user_ns |
|
762 | user_ns = self.shell.user_ns | |
763 | internal_ns = self.shell.internal_ns |
|
763 | internal_ns = self.shell.internal_ns | |
764 | user_ns_hidden = self.shell.user_ns_hidden |
|
764 | user_ns_hidden = self.shell.user_ns_hidden | |
765 | out = [ i for i in user_ns |
|
765 | out = [ i for i in user_ns | |
766 | if not i.startswith('_') \ |
|
766 | if not i.startswith('_') \ | |
767 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
767 | and not (i in internal_ns or i in user_ns_hidden) ] | |
768 |
|
768 | |||
769 | typelist = parameter_s.split() |
|
769 | typelist = parameter_s.split() | |
770 | if typelist: |
|
770 | if typelist: | |
771 | typeset = set(typelist) |
|
771 | typeset = set(typelist) | |
772 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
772 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
773 |
|
773 | |||
774 | out.sort() |
|
774 | out.sort() | |
775 | return out |
|
775 | return out | |
776 |
|
776 | |||
777 | @testdec.skip_doctest |
|
777 | @testdec.skip_doctest | |
778 | def magic_who(self, parameter_s=''): |
|
778 | def magic_who(self, parameter_s=''): | |
779 | """Print all interactive variables, with some minimal formatting. |
|
779 | """Print all interactive variables, with some minimal formatting. | |
780 |
|
780 | |||
781 | If any arguments are given, only variables whose type matches one of |
|
781 | If any arguments are given, only variables whose type matches one of | |
782 | these are printed. For example: |
|
782 | these are printed. For example: | |
783 |
|
783 | |||
784 | %who function str |
|
784 | %who function str | |
785 |
|
785 | |||
786 | will only list functions and strings, excluding all other types of |
|
786 | will only list functions and strings, excluding all other types of | |
787 | variables. To find the proper type names, simply use type(var) at a |
|
787 | variables. To find the proper type names, simply use type(var) at a | |
788 | command line to see how python prints type names. For example: |
|
788 | command line to see how python prints type names. For example: | |
789 |
|
789 | |||
790 | In [1]: type('hello')\\ |
|
790 | In [1]: type('hello')\\ | |
791 | Out[1]: <type 'str'> |
|
791 | Out[1]: <type 'str'> | |
792 |
|
792 | |||
793 | indicates that the type name for strings is 'str'. |
|
793 | indicates that the type name for strings is 'str'. | |
794 |
|
794 | |||
795 | %who always excludes executed names loaded through your configuration |
|
795 | %who always excludes executed names loaded through your configuration | |
796 | file and things which are internal to IPython. |
|
796 | file and things which are internal to IPython. | |
797 |
|
797 | |||
798 | This is deliberate, as typically you may load many modules and the |
|
798 | This is deliberate, as typically you may load many modules and the | |
799 | purpose of %who is to show you only what you've manually defined. |
|
799 | purpose of %who is to show you only what you've manually defined. | |
800 |
|
800 | |||
801 | Examples |
|
801 | Examples | |
802 | -------- |
|
802 | -------- | |
803 |
|
803 | |||
804 | Define two variables and list them with who:: |
|
804 | Define two variables and list them with who:: | |
805 |
|
805 | |||
806 | In [1]: alpha = 123 |
|
806 | In [1]: alpha = 123 | |
807 |
|
807 | |||
808 | In [2]: beta = 'test' |
|
808 | In [2]: beta = 'test' | |
809 |
|
809 | |||
810 | In [3]: %who |
|
810 | In [3]: %who | |
811 | alpha beta |
|
811 | alpha beta | |
812 |
|
812 | |||
813 | In [4]: %who int |
|
813 | In [4]: %who int | |
814 | alpha |
|
814 | alpha | |
815 |
|
815 | |||
816 | In [5]: %who str |
|
816 | In [5]: %who str | |
817 | beta |
|
817 | beta | |
818 | """ |
|
818 | """ | |
819 |
|
819 | |||
820 | varlist = self.magic_who_ls(parameter_s) |
|
820 | varlist = self.magic_who_ls(parameter_s) | |
821 | if not varlist: |
|
821 | if not varlist: | |
822 | if parameter_s: |
|
822 | if parameter_s: | |
823 | print 'No variables match your requested type.' |
|
823 | print 'No variables match your requested type.' | |
824 | else: |
|
824 | else: | |
825 | print 'Interactive namespace is empty.' |
|
825 | print 'Interactive namespace is empty.' | |
826 | return |
|
826 | return | |
827 |
|
827 | |||
828 | # if we have variables, move on... |
|
828 | # if we have variables, move on... | |
829 | count = 0 |
|
829 | count = 0 | |
830 | for i in varlist: |
|
830 | for i in varlist: | |
831 | print i+'\t', |
|
831 | print i+'\t', | |
832 | count += 1 |
|
832 | count += 1 | |
833 | if count > 8: |
|
833 | if count > 8: | |
834 | count = 0 |
|
834 | count = 0 | |
835 |
|
835 | |||
836 |
|
836 | |||
837 |
|
837 | |||
838 | @testdec.skip_doctest |
|
838 | @testdec.skip_doctest | |
839 | def magic_whos(self, parameter_s=''): |
|
839 | def magic_whos(self, parameter_s=''): | |
840 | """Like %who, but gives some extra information about each variable. |
|
840 | """Like %who, but gives some extra information about each variable. | |
841 |
|
841 | |||
842 | The same type filtering of %who can be applied here. |
|
842 | The same type filtering of %who can be applied here. | |
843 |
|
843 | |||
844 | For all variables, the type is printed. Additionally it prints: |
|
844 | For all variables, the type is printed. Additionally it prints: | |
845 |
|
845 | |||
846 | - For {},[],(): their length. |
|
846 | - For {},[],(): their length. | |
847 |
|
847 | |||
848 | - For numpy and Numeric arrays, a summary with shape, number of |
|
848 | - For numpy and Numeric arrays, a summary with shape, number of | |
849 | elements, typecode and size in memory. |
|
849 | elements, typecode and size in memory. | |
850 |
|
850 | |||
851 | - Everything else: a string representation, snipping their middle if |
|
851 | - Everything else: a string representation, snipping their middle if | |
852 | too long. |
|
852 | too long. | |
853 |
|
853 | |||
854 | Examples |
|
854 | Examples | |
855 | -------- |
|
855 | -------- | |
856 |
|
856 | |||
857 | Define two variables and list them with whos:: |
|
857 | Define two variables and list them with whos:: | |
858 |
|
858 | |||
859 | In [1]: alpha = 123 |
|
859 | In [1]: alpha = 123 | |
860 |
|
860 | |||
861 | In [2]: beta = 'test' |
|
861 | In [2]: beta = 'test' | |
862 |
|
862 | |||
863 | In [3]: %whos |
|
863 | In [3]: %whos | |
864 | Variable Type Data/Info |
|
864 | Variable Type Data/Info | |
865 | -------------------------------- |
|
865 | -------------------------------- | |
866 | alpha int 123 |
|
866 | alpha int 123 | |
867 | beta str test |
|
867 | beta str test | |
868 | """ |
|
868 | """ | |
869 |
|
869 | |||
870 | varnames = self.magic_who_ls(parameter_s) |
|
870 | varnames = self.magic_who_ls(parameter_s) | |
871 | if not varnames: |
|
871 | if not varnames: | |
872 | if parameter_s: |
|
872 | if parameter_s: | |
873 | print 'No variables match your requested type.' |
|
873 | print 'No variables match your requested type.' | |
874 | else: |
|
874 | else: | |
875 | print 'Interactive namespace is empty.' |
|
875 | print 'Interactive namespace is empty.' | |
876 | return |
|
876 | return | |
877 |
|
877 | |||
878 | # if we have variables, move on... |
|
878 | # if we have variables, move on... | |
879 |
|
879 | |||
880 | # for these types, show len() instead of data: |
|
880 | # for these types, show len() instead of data: | |
881 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
881 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
882 |
|
882 | |||
883 | # for numpy/Numeric arrays, display summary info |
|
883 | # for numpy/Numeric arrays, display summary info | |
884 | try: |
|
884 | try: | |
885 | import numpy |
|
885 | import numpy | |
886 | except ImportError: |
|
886 | except ImportError: | |
887 | ndarray_type = None |
|
887 | ndarray_type = None | |
888 | else: |
|
888 | else: | |
889 | ndarray_type = numpy.ndarray.__name__ |
|
889 | ndarray_type = numpy.ndarray.__name__ | |
890 | try: |
|
890 | try: | |
891 | import Numeric |
|
891 | import Numeric | |
892 | except ImportError: |
|
892 | except ImportError: | |
893 | array_type = None |
|
893 | array_type = None | |
894 | else: |
|
894 | else: | |
895 | array_type = Numeric.ArrayType.__name__ |
|
895 | array_type = Numeric.ArrayType.__name__ | |
896 |
|
896 | |||
897 | # Find all variable names and types so we can figure out column sizes |
|
897 | # Find all variable names and types so we can figure out column sizes | |
898 | def get_vars(i): |
|
898 | def get_vars(i): | |
899 | return self.shell.user_ns[i] |
|
899 | return self.shell.user_ns[i] | |
900 |
|
900 | |||
901 | # some types are well known and can be shorter |
|
901 | # some types are well known and can be shorter | |
902 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
902 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
903 | def type_name(v): |
|
903 | def type_name(v): | |
904 | tn = type(v).__name__ |
|
904 | tn = type(v).__name__ | |
905 | return abbrevs.get(tn,tn) |
|
905 | return abbrevs.get(tn,tn) | |
906 |
|
906 | |||
907 | varlist = map(get_vars,varnames) |
|
907 | varlist = map(get_vars,varnames) | |
908 |
|
908 | |||
909 | typelist = [] |
|
909 | typelist = [] | |
910 | for vv in varlist: |
|
910 | for vv in varlist: | |
911 | tt = type_name(vv) |
|
911 | tt = type_name(vv) | |
912 |
|
912 | |||
913 | if tt=='instance': |
|
913 | if tt=='instance': | |
914 | typelist.append( abbrevs.get(str(vv.__class__), |
|
914 | typelist.append( abbrevs.get(str(vv.__class__), | |
915 | str(vv.__class__))) |
|
915 | str(vv.__class__))) | |
916 | else: |
|
916 | else: | |
917 | typelist.append(tt) |
|
917 | typelist.append(tt) | |
918 |
|
918 | |||
919 | # column labels and # of spaces as separator |
|
919 | # column labels and # of spaces as separator | |
920 | varlabel = 'Variable' |
|
920 | varlabel = 'Variable' | |
921 | typelabel = 'Type' |
|
921 | typelabel = 'Type' | |
922 | datalabel = 'Data/Info' |
|
922 | datalabel = 'Data/Info' | |
923 | colsep = 3 |
|
923 | colsep = 3 | |
924 | # variable format strings |
|
924 | # variable format strings | |
925 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
925 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
926 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
926 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
927 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
927 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
928 | # find the size of the columns to format the output nicely |
|
928 | # find the size of the columns to format the output nicely | |
929 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
929 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
930 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
930 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
931 | # table header |
|
931 | # table header | |
932 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
932 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
933 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
933 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
934 | # and the table itself |
|
934 | # and the table itself | |
935 | kb = 1024 |
|
935 | kb = 1024 | |
936 | Mb = 1048576 # kb**2 |
|
936 | Mb = 1048576 # kb**2 | |
937 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
937 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
938 | print itpl(vformat), |
|
938 | print itpl(vformat), | |
939 | if vtype in seq_types: |
|
939 | if vtype in seq_types: | |
940 | print len(var) |
|
940 | print len(var) | |
941 | elif vtype in [array_type,ndarray_type]: |
|
941 | elif vtype in [array_type,ndarray_type]: | |
942 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
942 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
943 | if vtype==ndarray_type: |
|
943 | if vtype==ndarray_type: | |
944 | # numpy |
|
944 | # numpy | |
945 | vsize = var.size |
|
945 | vsize = var.size | |
946 | vbytes = vsize*var.itemsize |
|
946 | vbytes = vsize*var.itemsize | |
947 | vdtype = var.dtype |
|
947 | vdtype = var.dtype | |
948 | else: |
|
948 | else: | |
949 | # Numeric |
|
949 | # Numeric | |
950 | vsize = Numeric.size(var) |
|
950 | vsize = Numeric.size(var) | |
951 | vbytes = vsize*var.itemsize() |
|
951 | vbytes = vsize*var.itemsize() | |
952 | vdtype = var.typecode() |
|
952 | vdtype = var.typecode() | |
953 |
|
953 | |||
954 | if vbytes < 100000: |
|
954 | if vbytes < 100000: | |
955 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
955 | print aformat % (vshape,vsize,vdtype,vbytes) | |
956 | else: |
|
956 | else: | |
957 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
957 | print aformat % (vshape,vsize,vdtype,vbytes), | |
958 | if vbytes < Mb: |
|
958 | if vbytes < Mb: | |
959 | print '(%s kb)' % (vbytes/kb,) |
|
959 | print '(%s kb)' % (vbytes/kb,) | |
960 | else: |
|
960 | else: | |
961 | print '(%s Mb)' % (vbytes/Mb,) |
|
961 | print '(%s Mb)' % (vbytes/Mb,) | |
962 | else: |
|
962 | else: | |
963 | try: |
|
963 | try: | |
964 | vstr = str(var) |
|
964 | vstr = str(var) | |
965 | except UnicodeEncodeError: |
|
965 | except UnicodeEncodeError: | |
966 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
966 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
967 | 'backslashreplace') |
|
967 | 'backslashreplace') | |
968 | vstr = vstr.replace('\n','\\n') |
|
968 | vstr = vstr.replace('\n','\\n') | |
969 | if len(vstr) < 50: |
|
969 | if len(vstr) < 50: | |
970 | print vstr |
|
970 | print vstr | |
971 | else: |
|
971 | else: | |
972 | printpl(vfmt_short) |
|
972 | printpl(vfmt_short) | |
973 |
|
973 | |||
974 | def magic_reset(self, parameter_s=''): |
|
974 | def magic_reset(self, parameter_s=''): | |
975 | """Resets the namespace by removing all names defined by the user. |
|
975 | """Resets the namespace by removing all names defined by the user. | |
976 |
|
976 | |||
977 | Input/Output history are left around in case you need them. |
|
977 | Input/Output history are left around in case you need them. | |
978 |
|
978 | |||
979 | Parameters |
|
979 | Parameters | |
980 | ---------- |
|
980 | ---------- | |
981 | -y : force reset without asking for confirmation. |
|
981 | -y : force reset without asking for confirmation. | |
982 |
|
982 | |||
983 | Examples |
|
983 | Examples | |
984 | -------- |
|
984 | -------- | |
985 | In [6]: a = 1 |
|
985 | In [6]: a = 1 | |
986 |
|
986 | |||
987 | In [7]: a |
|
987 | In [7]: a | |
988 | Out[7]: 1 |
|
988 | Out[7]: 1 | |
989 |
|
989 | |||
990 | In [8]: 'a' in _ip.user_ns |
|
990 | In [8]: 'a' in _ip.user_ns | |
991 | Out[8]: True |
|
991 | Out[8]: True | |
992 |
|
992 | |||
993 | In [9]: %reset -f |
|
993 | In [9]: %reset -f | |
994 |
|
994 | |||
995 | In [10]: 'a' in _ip.user_ns |
|
995 | In [10]: 'a' in _ip.user_ns | |
996 | Out[10]: False |
|
996 | Out[10]: False | |
997 | """ |
|
997 | """ | |
998 |
|
998 | |||
999 | if parameter_s == '-f': |
|
999 | if parameter_s == '-f': | |
1000 | ans = True |
|
1000 | ans = True | |
1001 | else: |
|
1001 | else: | |
1002 | ans = self.shell.ask_yes_no( |
|
1002 | ans = self.shell.ask_yes_no( | |
1003 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1003 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1004 | if not ans: |
|
1004 | if not ans: | |
1005 | print 'Nothing done.' |
|
1005 | print 'Nothing done.' | |
1006 | return |
|
1006 | return | |
1007 | user_ns = self.shell.user_ns |
|
1007 | user_ns = self.shell.user_ns | |
1008 | for i in self.magic_who_ls(): |
|
1008 | for i in self.magic_who_ls(): | |
1009 | del(user_ns[i]) |
|
1009 | del(user_ns[i]) | |
1010 |
|
1010 | |||
1011 | # Also flush the private list of module references kept for script |
|
1011 | # Also flush the private list of module references kept for script | |
1012 | # execution protection |
|
1012 | # execution protection | |
1013 | self.shell.clear_main_mod_cache() |
|
1013 | self.shell.clear_main_mod_cache() | |
1014 |
|
1014 | |||
1015 | def magic_reset_selective(self, parameter_s=''): |
|
1015 | def magic_reset_selective(self, parameter_s=''): | |
1016 | """Resets the namespace by removing names defined by the user. |
|
1016 | """Resets the namespace by removing names defined by the user. | |
1017 |
|
1017 | |||
1018 | Input/Output history are left around in case you need them. |
|
1018 | Input/Output history are left around in case you need them. | |
1019 |
|
1019 | |||
1020 | %reset_selective [-f] regex |
|
1020 | %reset_selective [-f] regex | |
1021 |
|
1021 | |||
1022 | No action is taken if regex is not included |
|
1022 | No action is taken if regex is not included | |
1023 |
|
1023 | |||
1024 | Options |
|
1024 | Options | |
1025 | -f : force reset without asking for confirmation. |
|
1025 | -f : force reset without asking for confirmation. | |
1026 |
|
1026 | |||
1027 | Examples |
|
1027 | Examples | |
1028 | -------- |
|
1028 | -------- | |
1029 |
|
1029 | |||
1030 | We first fully reset the namespace so your output looks identical to |
|
1030 | We first fully reset the namespace so your output looks identical to | |
1031 | this example for pedagogical reasons; in practice you do not need a |
|
1031 | this example for pedagogical reasons; in practice you do not need a | |
1032 | full reset. |
|
1032 | full reset. | |
1033 |
|
1033 | |||
1034 | In [1]: %reset -f |
|
1034 | In [1]: %reset -f | |
1035 |
|
1035 | |||
1036 | Now, with a clean namespace we can make a few variables and use |
|
1036 | Now, with a clean namespace we can make a few variables and use | |
1037 | %reset_selective to only delete names that match our regexp: |
|
1037 | %reset_selective to only delete names that match our regexp: | |
1038 |
|
1038 | |||
1039 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1039 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
1040 |
|
1040 | |||
1041 | In [3]: who_ls |
|
1041 | In [3]: who_ls | |
1042 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1042 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
1043 |
|
1043 | |||
1044 | In [4]: %reset_selective -f b[2-3]m |
|
1044 | In [4]: %reset_selective -f b[2-3]m | |
1045 |
|
1045 | |||
1046 | In [5]: who_ls |
|
1046 | In [5]: who_ls | |
1047 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1047 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1048 |
|
1048 | |||
1049 | In [6]: %reset_selective -f d |
|
1049 | In [6]: %reset_selective -f d | |
1050 |
|
1050 | |||
1051 | In [7]: who_ls |
|
1051 | In [7]: who_ls | |
1052 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1052 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
1053 |
|
1053 | |||
1054 | In [8]: %reset_selective -f c |
|
1054 | In [8]: %reset_selective -f c | |
1055 |
|
1055 | |||
1056 | In [9]: who_ls |
|
1056 | In [9]: who_ls | |
1057 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1057 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1058 |
|
1058 | |||
1059 | In [10]: %reset_selective -f b |
|
1059 | In [10]: %reset_selective -f b | |
1060 |
|
1060 | |||
1061 | In [11]: who_ls |
|
1061 | In [11]: who_ls | |
1062 | Out[11]: ['a'] |
|
1062 | Out[11]: ['a'] | |
1063 | """ |
|
1063 | """ | |
1064 |
|
1064 | |||
1065 | opts, regex = self.parse_options(parameter_s,'f') |
|
1065 | opts, regex = self.parse_options(parameter_s,'f') | |
1066 |
|
1066 | |||
1067 | if opts.has_key('f'): |
|
1067 | if opts.has_key('f'): | |
1068 | ans = True |
|
1068 | ans = True | |
1069 | else: |
|
1069 | else: | |
1070 | ans = self.shell.ask_yes_no( |
|
1070 | ans = self.shell.ask_yes_no( | |
1071 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1071 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1072 | if not ans: |
|
1072 | if not ans: | |
1073 | print 'Nothing done.' |
|
1073 | print 'Nothing done.' | |
1074 | return |
|
1074 | return | |
1075 | user_ns = self.shell.user_ns |
|
1075 | user_ns = self.shell.user_ns | |
1076 | if not regex: |
|
1076 | if not regex: | |
1077 | print 'No regex pattern specified. Nothing done.' |
|
1077 | print 'No regex pattern specified. Nothing done.' | |
1078 | return |
|
1078 | return | |
1079 | else: |
|
1079 | else: | |
1080 | try: |
|
1080 | try: | |
1081 | m = re.compile(regex) |
|
1081 | m = re.compile(regex) | |
1082 | except TypeError: |
|
1082 | except TypeError: | |
1083 | raise TypeError('regex must be a string or compiled pattern') |
|
1083 | raise TypeError('regex must be a string or compiled pattern') | |
1084 | for i in self.magic_who_ls(): |
|
1084 | for i in self.magic_who_ls(): | |
1085 | if m.search(i): |
|
1085 | if m.search(i): | |
1086 | del(user_ns[i]) |
|
1086 | del(user_ns[i]) | |
1087 |
|
1087 | |||
1088 | def magic_logstart(self,parameter_s=''): |
|
1088 | def magic_logstart(self,parameter_s=''): | |
1089 | """Start logging anywhere in a session. |
|
1089 | """Start logging anywhere in a session. | |
1090 |
|
1090 | |||
1091 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1091 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1092 |
|
1092 | |||
1093 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1093 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1094 | current directory, in 'rotate' mode (see below). |
|
1094 | current directory, in 'rotate' mode (see below). | |
1095 |
|
1095 | |||
1096 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1096 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1097 | history up to that point and then continues logging. |
|
1097 | history up to that point and then continues logging. | |
1098 |
|
1098 | |||
1099 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1099 | %logstart takes a second optional parameter: logging mode. This can be one | |
1100 | of (note that the modes are given unquoted):\\ |
|
1100 | of (note that the modes are given unquoted):\\ | |
1101 | append: well, that says it.\\ |
|
1101 | append: well, that says it.\\ | |
1102 | backup: rename (if exists) to name~ and start name.\\ |
|
1102 | backup: rename (if exists) to name~ and start name.\\ | |
1103 | global: single logfile in your home dir, appended to.\\ |
|
1103 | global: single logfile in your home dir, appended to.\\ | |
1104 | over : overwrite existing log.\\ |
|
1104 | over : overwrite existing log.\\ | |
1105 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1105 | rotate: create rotating logs name.1~, name.2~, etc. | |
1106 |
|
1106 | |||
1107 | Options: |
|
1107 | Options: | |
1108 |
|
1108 | |||
1109 | -o: log also IPython's output. In this mode, all commands which |
|
1109 | -o: log also IPython's output. In this mode, all commands which | |
1110 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1110 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1111 | their corresponding input line. The output lines are always |
|
1111 | their corresponding input line. The output lines are always | |
1112 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1112 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1113 | Python code. |
|
1113 | Python code. | |
1114 |
|
1114 | |||
1115 | Since this marker is always the same, filtering only the output from |
|
1115 | Since this marker is always the same, filtering only the output from | |
1116 | a log is very easy, using for example a simple awk call: |
|
1116 | a log is very easy, using for example a simple awk call: | |
1117 |
|
1117 | |||
1118 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1118 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1119 |
|
1119 | |||
1120 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1120 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1121 | input, so that user lines are logged in their final form, converted |
|
1121 | input, so that user lines are logged in their final form, converted | |
1122 | into valid Python. For example, %Exit is logged as |
|
1122 | into valid Python. For example, %Exit is logged as | |
1123 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1123 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1124 | exactly as typed, with no transformations applied. |
|
1124 | exactly as typed, with no transformations applied. | |
1125 |
|
1125 | |||
1126 | -t: put timestamps before each input line logged (these are put in |
|
1126 | -t: put timestamps before each input line logged (these are put in | |
1127 | comments).""" |
|
1127 | comments).""" | |
1128 |
|
1128 | |||
1129 | opts,par = self.parse_options(parameter_s,'ort') |
|
1129 | opts,par = self.parse_options(parameter_s,'ort') | |
1130 | log_output = 'o' in opts |
|
1130 | log_output = 'o' in opts | |
1131 | log_raw_input = 'r' in opts |
|
1131 | log_raw_input = 'r' in opts | |
1132 | timestamp = 't' in opts |
|
1132 | timestamp = 't' in opts | |
1133 |
|
1133 | |||
1134 | logger = self.shell.logger |
|
1134 | logger = self.shell.logger | |
1135 |
|
1135 | |||
1136 | # if no args are given, the defaults set in the logger constructor by |
|
1136 | # if no args are given, the defaults set in the logger constructor by | |
1137 | # ipytohn remain valid |
|
1137 | # ipytohn remain valid | |
1138 | if par: |
|
1138 | if par: | |
1139 | try: |
|
1139 | try: | |
1140 | logfname,logmode = par.split() |
|
1140 | logfname,logmode = par.split() | |
1141 | except: |
|
1141 | except: | |
1142 | logfname = par |
|
1142 | logfname = par | |
1143 | logmode = 'backup' |
|
1143 | logmode = 'backup' | |
1144 | else: |
|
1144 | else: | |
1145 | logfname = logger.logfname |
|
1145 | logfname = logger.logfname | |
1146 | logmode = logger.logmode |
|
1146 | logmode = logger.logmode | |
1147 | # put logfname into rc struct as if it had been called on the command |
|
1147 | # put logfname into rc struct as if it had been called on the command | |
1148 | # line, so it ends up saved in the log header Save it in case we need |
|
1148 | # line, so it ends up saved in the log header Save it in case we need | |
1149 | # to restore it... |
|
1149 | # to restore it... | |
1150 | old_logfile = self.shell.logfile |
|
1150 | old_logfile = self.shell.logfile | |
1151 | if logfname: |
|
1151 | if logfname: | |
1152 | logfname = os.path.expanduser(logfname) |
|
1152 | logfname = os.path.expanduser(logfname) | |
1153 | self.shell.logfile = logfname |
|
1153 | self.shell.logfile = logfname | |
1154 |
|
1154 | |||
1155 | loghead = '# IPython log file\n\n' |
|
1155 | loghead = '# IPython log file\n\n' | |
1156 | try: |
|
1156 | try: | |
1157 | started = logger.logstart(logfname,loghead,logmode, |
|
1157 | started = logger.logstart(logfname,loghead,logmode, | |
1158 | log_output,timestamp,log_raw_input) |
|
1158 | log_output,timestamp,log_raw_input) | |
1159 | except: |
|
1159 | except: | |
1160 | self.shell.logfile = old_logfile |
|
1160 | self.shell.logfile = old_logfile | |
1161 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1161 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1162 | else: |
|
1162 | else: | |
1163 | # log input history up to this point, optionally interleaving |
|
1163 | # log input history up to this point, optionally interleaving | |
1164 | # output if requested |
|
1164 | # output if requested | |
1165 |
|
1165 | |||
1166 | if timestamp: |
|
1166 | if timestamp: | |
1167 | # disable timestamping for the previous history, since we've |
|
1167 | # disable timestamping for the previous history, since we've | |
1168 | # lost those already (no time machine here). |
|
1168 | # lost those already (no time machine here). | |
1169 | logger.timestamp = False |
|
1169 | logger.timestamp = False | |
1170 |
|
1170 | |||
1171 | if log_raw_input: |
|
1171 | if log_raw_input: | |
1172 | input_hist = self.shell.history_manager.input_hist_raw |
|
1172 | input_hist = self.shell.history_manager.input_hist_raw | |
1173 | else: |
|
1173 | else: | |
1174 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1174 | input_hist = self.shell.history_manager.input_hist_parsed | |
1175 |
|
1175 | |||
1176 | if log_output: |
|
1176 | if log_output: | |
1177 | log_write = logger.log_write |
|
1177 | log_write = logger.log_write | |
1178 | output_hist = self.shell.history_manager.output_hist |
|
1178 | output_hist = self.shell.history_manager.output_hist | |
1179 | for n in range(1,len(input_hist)-1): |
|
1179 | for n in range(1,len(input_hist)-1): | |
1180 | log_write(input_hist[n].rstrip()) |
|
1180 | log_write(input_hist[n].rstrip()) | |
1181 | if n in output_hist: |
|
1181 | if n in output_hist: | |
1182 | log_write(repr(output_hist[n]),'output') |
|
1182 | log_write(repr(output_hist[n]),'output') | |
1183 | else: |
|
1183 | else: | |
1184 | logger.log_write(''.join(input_hist[1:])) |
|
1184 | logger.log_write(''.join(input_hist[1:])) | |
1185 | if timestamp: |
|
1185 | if timestamp: | |
1186 | # re-enable timestamping |
|
1186 | # re-enable timestamping | |
1187 | logger.timestamp = True |
|
1187 | logger.timestamp = True | |
1188 |
|
1188 | |||
1189 | print ('Activating auto-logging. ' |
|
1189 | print ('Activating auto-logging. ' | |
1190 | 'Current session state plus future input saved.') |
|
1190 | 'Current session state plus future input saved.') | |
1191 | logger.logstate() |
|
1191 | logger.logstate() | |
1192 |
|
1192 | |||
1193 | def magic_logstop(self,parameter_s=''): |
|
1193 | def magic_logstop(self,parameter_s=''): | |
1194 | """Fully stop logging and close log file. |
|
1194 | """Fully stop logging and close log file. | |
1195 |
|
1195 | |||
1196 | In order to start logging again, a new %logstart call needs to be made, |
|
1196 | In order to start logging again, a new %logstart call needs to be made, | |
1197 | possibly (though not necessarily) with a new filename, mode and other |
|
1197 | possibly (though not necessarily) with a new filename, mode and other | |
1198 | options.""" |
|
1198 | options.""" | |
1199 | self.logger.logstop() |
|
1199 | self.logger.logstop() | |
1200 |
|
1200 | |||
1201 | def magic_logoff(self,parameter_s=''): |
|
1201 | def magic_logoff(self,parameter_s=''): | |
1202 | """Temporarily stop logging. |
|
1202 | """Temporarily stop logging. | |
1203 |
|
1203 | |||
1204 | You must have previously started logging.""" |
|
1204 | You must have previously started logging.""" | |
1205 | self.shell.logger.switch_log(0) |
|
1205 | self.shell.logger.switch_log(0) | |
1206 |
|
1206 | |||
1207 | def magic_logon(self,parameter_s=''): |
|
1207 | def magic_logon(self,parameter_s=''): | |
1208 | """Restart logging. |
|
1208 | """Restart logging. | |
1209 |
|
1209 | |||
1210 | This function is for restarting logging which you've temporarily |
|
1210 | This function is for restarting logging which you've temporarily | |
1211 | stopped with %logoff. For starting logging for the first time, you |
|
1211 | stopped with %logoff. For starting logging for the first time, you | |
1212 | must use the %logstart function, which allows you to specify an |
|
1212 | must use the %logstart function, which allows you to specify an | |
1213 | optional log filename.""" |
|
1213 | optional log filename.""" | |
1214 |
|
1214 | |||
1215 | self.shell.logger.switch_log(1) |
|
1215 | self.shell.logger.switch_log(1) | |
1216 |
|
1216 | |||
1217 | def magic_logstate(self,parameter_s=''): |
|
1217 | def magic_logstate(self,parameter_s=''): | |
1218 | """Print the status of the logging system.""" |
|
1218 | """Print the status of the logging system.""" | |
1219 |
|
1219 | |||
1220 | self.shell.logger.logstate() |
|
1220 | self.shell.logger.logstate() | |
1221 |
|
1221 | |||
1222 | def magic_pdb(self, parameter_s=''): |
|
1222 | def magic_pdb(self, parameter_s=''): | |
1223 | """Control the automatic calling of the pdb interactive debugger. |
|
1223 | """Control the automatic calling of the pdb interactive debugger. | |
1224 |
|
1224 | |||
1225 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1225 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1226 | argument it works as a toggle. |
|
1226 | argument it works as a toggle. | |
1227 |
|
1227 | |||
1228 | When an exception is triggered, IPython can optionally call the |
|
1228 | When an exception is triggered, IPython can optionally call the | |
1229 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1229 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1230 | this feature on and off. |
|
1230 | this feature on and off. | |
1231 |
|
1231 | |||
1232 | The initial state of this feature is set in your ipythonrc |
|
1232 | The initial state of this feature is set in your ipythonrc | |
1233 | configuration file (the variable is called 'pdb'). |
|
1233 | configuration file (the variable is called 'pdb'). | |
1234 |
|
1234 | |||
1235 | If you want to just activate the debugger AFTER an exception has fired, |
|
1235 | If you want to just activate the debugger AFTER an exception has fired, | |
1236 | without having to type '%pdb on' and rerunning your code, you can use |
|
1236 | without having to type '%pdb on' and rerunning your code, you can use | |
1237 | the %debug magic.""" |
|
1237 | the %debug magic.""" | |
1238 |
|
1238 | |||
1239 | par = parameter_s.strip().lower() |
|
1239 | par = parameter_s.strip().lower() | |
1240 |
|
1240 | |||
1241 | if par: |
|
1241 | if par: | |
1242 | try: |
|
1242 | try: | |
1243 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1243 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1244 | except KeyError: |
|
1244 | except KeyError: | |
1245 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1245 | print ('Incorrect argument. Use on/1, off/0, ' | |
1246 | 'or nothing for a toggle.') |
|
1246 | 'or nothing for a toggle.') | |
1247 | return |
|
1247 | return | |
1248 | else: |
|
1248 | else: | |
1249 | # toggle |
|
1249 | # toggle | |
1250 | new_pdb = not self.shell.call_pdb |
|
1250 | new_pdb = not self.shell.call_pdb | |
1251 |
|
1251 | |||
1252 | # set on the shell |
|
1252 | # set on the shell | |
1253 | self.shell.call_pdb = new_pdb |
|
1253 | self.shell.call_pdb = new_pdb | |
1254 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1254 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1255 |
|
1255 | |||
1256 | def magic_debug(self, parameter_s=''): |
|
1256 | def magic_debug(self, parameter_s=''): | |
1257 | """Activate the interactive debugger in post-mortem mode. |
|
1257 | """Activate the interactive debugger in post-mortem mode. | |
1258 |
|
1258 | |||
1259 | If an exception has just occurred, this lets you inspect its stack |
|
1259 | If an exception has just occurred, this lets you inspect its stack | |
1260 | frames interactively. Note that this will always work only on the last |
|
1260 | frames interactively. Note that this will always work only on the last | |
1261 | traceback that occurred, so you must call this quickly after an |
|
1261 | traceback that occurred, so you must call this quickly after an | |
1262 | exception that you wish to inspect has fired, because if another one |
|
1262 | exception that you wish to inspect has fired, because if another one | |
1263 | occurs, it clobbers the previous one. |
|
1263 | occurs, it clobbers the previous one. | |
1264 |
|
1264 | |||
1265 | If you want IPython to automatically do this on every exception, see |
|
1265 | If you want IPython to automatically do this on every exception, see | |
1266 | the %pdb magic for more details. |
|
1266 | the %pdb magic for more details. | |
1267 | """ |
|
1267 | """ | |
1268 | self.shell.debugger(force=True) |
|
1268 | self.shell.debugger(force=True) | |
1269 |
|
1269 | |||
1270 | @testdec.skip_doctest |
|
1270 | @testdec.skip_doctest | |
1271 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1271 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1272 | opts=None,arg_lst=None,prog_ns=None): |
|
1272 | opts=None,arg_lst=None,prog_ns=None): | |
1273 |
|
1273 | |||
1274 | """Run a statement through the python code profiler. |
|
1274 | """Run a statement through the python code profiler. | |
1275 |
|
1275 | |||
1276 | Usage: |
|
1276 | Usage: | |
1277 | %prun [options] statement |
|
1277 | %prun [options] statement | |
1278 |
|
1278 | |||
1279 | The given statement (which doesn't require quote marks) is run via the |
|
1279 | The given statement (which doesn't require quote marks) is run via the | |
1280 | python profiler in a manner similar to the profile.run() function. |
|
1280 | python profiler in a manner similar to the profile.run() function. | |
1281 | Namespaces are internally managed to work correctly; profile.run |
|
1281 | Namespaces are internally managed to work correctly; profile.run | |
1282 | cannot be used in IPython because it makes certain assumptions about |
|
1282 | cannot be used in IPython because it makes certain assumptions about | |
1283 | namespaces which do not hold under IPython. |
|
1283 | namespaces which do not hold under IPython. | |
1284 |
|
1284 | |||
1285 | Options: |
|
1285 | Options: | |
1286 |
|
1286 | |||
1287 | -l <limit>: you can place restrictions on what or how much of the |
|
1287 | -l <limit>: you can place restrictions on what or how much of the | |
1288 | profile gets printed. The limit value can be: |
|
1288 | profile gets printed. The limit value can be: | |
1289 |
|
1289 | |||
1290 | * A string: only information for function names containing this string |
|
1290 | * A string: only information for function names containing this string | |
1291 | is printed. |
|
1291 | is printed. | |
1292 |
|
1292 | |||
1293 | * An integer: only these many lines are printed. |
|
1293 | * An integer: only these many lines are printed. | |
1294 |
|
1294 | |||
1295 | * A float (between 0 and 1): this fraction of the report is printed |
|
1295 | * A float (between 0 and 1): this fraction of the report is printed | |
1296 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1296 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1297 |
|
1297 | |||
1298 | You can combine several limits with repeated use of the option. For |
|
1298 | You can combine several limits with repeated use of the option. For | |
1299 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1299 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1300 | information about class constructors. |
|
1300 | information about class constructors. | |
1301 |
|
1301 | |||
1302 | -r: return the pstats.Stats object generated by the profiling. This |
|
1302 | -r: return the pstats.Stats object generated by the profiling. This | |
1303 | object has all the information about the profile in it, and you can |
|
1303 | object has all the information about the profile in it, and you can | |
1304 | later use it for further analysis or in other functions. |
|
1304 | later use it for further analysis or in other functions. | |
1305 |
|
1305 | |||
1306 | -s <key>: sort profile by given key. You can provide more than one key |
|
1306 | -s <key>: sort profile by given key. You can provide more than one key | |
1307 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1307 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1308 | default sorting key is 'time'. |
|
1308 | default sorting key is 'time'. | |
1309 |
|
1309 | |||
1310 | The following is copied verbatim from the profile documentation |
|
1310 | The following is copied verbatim from the profile documentation | |
1311 | referenced below: |
|
1311 | referenced below: | |
1312 |
|
1312 | |||
1313 | When more than one key is provided, additional keys are used as |
|
1313 | When more than one key is provided, additional keys are used as | |
1314 | secondary criteria when the there is equality in all keys selected |
|
1314 | secondary criteria when the there is equality in all keys selected | |
1315 | before them. |
|
1315 | before them. | |
1316 |
|
1316 | |||
1317 | Abbreviations can be used for any key names, as long as the |
|
1317 | Abbreviations can be used for any key names, as long as the | |
1318 | abbreviation is unambiguous. The following are the keys currently |
|
1318 | abbreviation is unambiguous. The following are the keys currently | |
1319 | defined: |
|
1319 | defined: | |
1320 |
|
1320 | |||
1321 | Valid Arg Meaning |
|
1321 | Valid Arg Meaning | |
1322 | "calls" call count |
|
1322 | "calls" call count | |
1323 | "cumulative" cumulative time |
|
1323 | "cumulative" cumulative time | |
1324 | "file" file name |
|
1324 | "file" file name | |
1325 | "module" file name |
|
1325 | "module" file name | |
1326 | "pcalls" primitive call count |
|
1326 | "pcalls" primitive call count | |
1327 | "line" line number |
|
1327 | "line" line number | |
1328 | "name" function name |
|
1328 | "name" function name | |
1329 | "nfl" name/file/line |
|
1329 | "nfl" name/file/line | |
1330 | "stdname" standard name |
|
1330 | "stdname" standard name | |
1331 | "time" internal time |
|
1331 | "time" internal time | |
1332 |
|
1332 | |||
1333 | Note that all sorts on statistics are in descending order (placing |
|
1333 | Note that all sorts on statistics are in descending order (placing | |
1334 | most time consuming items first), where as name, file, and line number |
|
1334 | most time consuming items first), where as name, file, and line number | |
1335 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1335 | searches are in ascending order (i.e., alphabetical). The subtle | |
1336 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1336 | distinction between "nfl" and "stdname" is that the standard name is a | |
1337 | sort of the name as printed, which means that the embedded line |
|
1337 | sort of the name as printed, which means that the embedded line | |
1338 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1338 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1339 | would (if the file names were the same) appear in the string order |
|
1339 | would (if the file names were the same) appear in the string order | |
1340 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1340 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1341 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1341 | line numbers. In fact, sort_stats("nfl") is the same as | |
1342 | sort_stats("name", "file", "line"). |
|
1342 | sort_stats("name", "file", "line"). | |
1343 |
|
1343 | |||
1344 | -T <filename>: save profile results as shown on screen to a text |
|
1344 | -T <filename>: save profile results as shown on screen to a text | |
1345 | file. The profile is still shown on screen. |
|
1345 | file. The profile is still shown on screen. | |
1346 |
|
1346 | |||
1347 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1347 | -D <filename>: save (via dump_stats) profile statistics to given | |
1348 | filename. This data is in a format understod by the pstats module, and |
|
1348 | filename. This data is in a format understod by the pstats module, and | |
1349 | is generated by a call to the dump_stats() method of profile |
|
1349 | is generated by a call to the dump_stats() method of profile | |
1350 | objects. The profile is still shown on screen. |
|
1350 | objects. The profile is still shown on screen. | |
1351 |
|
1351 | |||
1352 | If you want to run complete programs under the profiler's control, use |
|
1352 | If you want to run complete programs under the profiler's control, use | |
1353 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1353 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1354 | contains profiler specific options as described here. |
|
1354 | contains profiler specific options as described here. | |
1355 |
|
1355 | |||
1356 | You can read the complete documentation for the profile module with:: |
|
1356 | You can read the complete documentation for the profile module with:: | |
1357 |
|
1357 | |||
1358 | In [1]: import profile; profile.help() |
|
1358 | In [1]: import profile; profile.help() | |
1359 | """ |
|
1359 | """ | |
1360 |
|
1360 | |||
1361 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1361 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1362 | # protect user quote marks |
|
1362 | # protect user quote marks | |
1363 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1363 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1364 |
|
1364 | |||
1365 | if user_mode: # regular user call |
|
1365 | if user_mode: # regular user call | |
1366 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1366 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1367 | list_all=1) |
|
1367 | list_all=1) | |
1368 | namespace = self.shell.user_ns |
|
1368 | namespace = self.shell.user_ns | |
1369 | else: # called to run a program by %run -p |
|
1369 | else: # called to run a program by %run -p | |
1370 | try: |
|
1370 | try: | |
1371 | filename = get_py_filename(arg_lst[0]) |
|
1371 | filename = get_py_filename(arg_lst[0]) | |
1372 | except IOError,msg: |
|
1372 | except IOError,msg: | |
1373 | error(msg) |
|
1373 | error(msg) | |
1374 | return |
|
1374 | return | |
1375 |
|
1375 | |||
1376 | arg_str = 'execfile(filename,prog_ns)' |
|
1376 | arg_str = 'execfile(filename,prog_ns)' | |
1377 | namespace = locals() |
|
1377 | namespace = locals() | |
1378 |
|
1378 | |||
1379 | opts.merge(opts_def) |
|
1379 | opts.merge(opts_def) | |
1380 |
|
1380 | |||
1381 | prof = profile.Profile() |
|
1381 | prof = profile.Profile() | |
1382 | try: |
|
1382 | try: | |
1383 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1383 | prof = prof.runctx(arg_str,namespace,namespace) | |
1384 | sys_exit = '' |
|
1384 | sys_exit = '' | |
1385 | except SystemExit: |
|
1385 | except SystemExit: | |
1386 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1386 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1387 |
|
1387 | |||
1388 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1388 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1389 |
|
1389 | |||
1390 | lims = opts.l |
|
1390 | lims = opts.l | |
1391 | if lims: |
|
1391 | if lims: | |
1392 | lims = [] # rebuild lims with ints/floats/strings |
|
1392 | lims = [] # rebuild lims with ints/floats/strings | |
1393 | for lim in opts.l: |
|
1393 | for lim in opts.l: | |
1394 | try: |
|
1394 | try: | |
1395 | lims.append(int(lim)) |
|
1395 | lims.append(int(lim)) | |
1396 | except ValueError: |
|
1396 | except ValueError: | |
1397 | try: |
|
1397 | try: | |
1398 | lims.append(float(lim)) |
|
1398 | lims.append(float(lim)) | |
1399 | except ValueError: |
|
1399 | except ValueError: | |
1400 | lims.append(lim) |
|
1400 | lims.append(lim) | |
1401 |
|
1401 | |||
1402 | # Trap output. |
|
1402 | # Trap output. | |
1403 | stdout_trap = StringIO() |
|
1403 | stdout_trap = StringIO() | |
1404 |
|
1404 | |||
1405 | if hasattr(stats,'stream'): |
|
1405 | if hasattr(stats,'stream'): | |
1406 | # In newer versions of python, the stats object has a 'stream' |
|
1406 | # In newer versions of python, the stats object has a 'stream' | |
1407 | # attribute to write into. |
|
1407 | # attribute to write into. | |
1408 | stats.stream = stdout_trap |
|
1408 | stats.stream = stdout_trap | |
1409 | stats.print_stats(*lims) |
|
1409 | stats.print_stats(*lims) | |
1410 | else: |
|
1410 | else: | |
1411 | # For older versions, we manually redirect stdout during printing |
|
1411 | # For older versions, we manually redirect stdout during printing | |
1412 | sys_stdout = sys.stdout |
|
1412 | sys_stdout = sys.stdout | |
1413 | try: |
|
1413 | try: | |
1414 | sys.stdout = stdout_trap |
|
1414 | sys.stdout = stdout_trap | |
1415 | stats.print_stats(*lims) |
|
1415 | stats.print_stats(*lims) | |
1416 | finally: |
|
1416 | finally: | |
1417 | sys.stdout = sys_stdout |
|
1417 | sys.stdout = sys_stdout | |
1418 |
|
1418 | |||
1419 | output = stdout_trap.getvalue() |
|
1419 | output = stdout_trap.getvalue() | |
1420 | output = output.rstrip() |
|
1420 | output = output.rstrip() | |
1421 |
|
1421 | |||
1422 | page.page(output) |
|
1422 | page.page(output) | |
1423 | print sys_exit, |
|
1423 | print sys_exit, | |
1424 |
|
1424 | |||
1425 | dump_file = opts.D[0] |
|
1425 | dump_file = opts.D[0] | |
1426 | text_file = opts.T[0] |
|
1426 | text_file = opts.T[0] | |
1427 | if dump_file: |
|
1427 | if dump_file: | |
1428 | prof.dump_stats(dump_file) |
|
1428 | prof.dump_stats(dump_file) | |
1429 | print '\n*** Profile stats marshalled to file',\ |
|
1429 | print '\n*** Profile stats marshalled to file',\ | |
1430 | `dump_file`+'.',sys_exit |
|
1430 | `dump_file`+'.',sys_exit | |
1431 | if text_file: |
|
1431 | if text_file: | |
1432 | pfile = file(text_file,'w') |
|
1432 | pfile = file(text_file,'w') | |
1433 | pfile.write(output) |
|
1433 | pfile.write(output) | |
1434 | pfile.close() |
|
1434 | pfile.close() | |
1435 | print '\n*** Profile printout saved to text file',\ |
|
1435 | print '\n*** Profile printout saved to text file',\ | |
1436 | `text_file`+'.',sys_exit |
|
1436 | `text_file`+'.',sys_exit | |
1437 |
|
1437 | |||
1438 | if opts.has_key('r'): |
|
1438 | if opts.has_key('r'): | |
1439 | return stats |
|
1439 | return stats | |
1440 | else: |
|
1440 | else: | |
1441 | return None |
|
1441 | return None | |
1442 |
|
1442 | |||
1443 | @testdec.skip_doctest |
|
1443 | @testdec.skip_doctest | |
1444 | def magic_run(self, parameter_s ='',runner=None, |
|
1444 | def magic_run(self, parameter_s ='',runner=None, | |
1445 | file_finder=get_py_filename): |
|
1445 | file_finder=get_py_filename): | |
1446 | """Run the named file inside IPython as a program. |
|
1446 | """Run the named file inside IPython as a program. | |
1447 |
|
1447 | |||
1448 | Usage:\\ |
|
1448 | Usage:\\ | |
1449 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1449 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1450 |
|
1450 | |||
1451 | Parameters after the filename are passed as command-line arguments to |
|
1451 | Parameters after the filename are passed as command-line arguments to | |
1452 | the program (put in sys.argv). Then, control returns to IPython's |
|
1452 | the program (put in sys.argv). Then, control returns to IPython's | |
1453 | prompt. |
|
1453 | prompt. | |
1454 |
|
1454 | |||
1455 | This is similar to running at a system prompt:\\ |
|
1455 | This is similar to running at a system prompt:\\ | |
1456 | $ python file args\\ |
|
1456 | $ python file args\\ | |
1457 | but with the advantage of giving you IPython's tracebacks, and of |
|
1457 | but with the advantage of giving you IPython's tracebacks, and of | |
1458 | loading all variables into your interactive namespace for further use |
|
1458 | loading all variables into your interactive namespace for further use | |
1459 | (unless -p is used, see below). |
|
1459 | (unless -p is used, see below). | |
1460 |
|
1460 | |||
1461 | The file is executed in a namespace initially consisting only of |
|
1461 | The file is executed in a namespace initially consisting only of | |
1462 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1462 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1463 | sees its environment as if it were being run as a stand-alone program |
|
1463 | sees its environment as if it were being run as a stand-alone program | |
1464 | (except for sharing global objects such as previously imported |
|
1464 | (except for sharing global objects such as previously imported | |
1465 | modules). But after execution, the IPython interactive namespace gets |
|
1465 | modules). But after execution, the IPython interactive namespace gets | |
1466 | updated with all variables defined in the program (except for __name__ |
|
1466 | updated with all variables defined in the program (except for __name__ | |
1467 | and sys.argv). This allows for very convenient loading of code for |
|
1467 | and sys.argv). This allows for very convenient loading of code for | |
1468 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1468 | interactive work, while giving each program a 'clean sheet' to run in. | |
1469 |
|
1469 | |||
1470 | Options: |
|
1470 | Options: | |
1471 |
|
1471 | |||
1472 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1472 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1473 | without extension (as python does under import). This allows running |
|
1473 | without extension (as python does under import). This allows running | |
1474 | scripts and reloading the definitions in them without calling code |
|
1474 | scripts and reloading the definitions in them without calling code | |
1475 | protected by an ' if __name__ == "__main__" ' clause. |
|
1475 | protected by an ' if __name__ == "__main__" ' clause. | |
1476 |
|
1476 | |||
1477 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1477 | -i: run the file in IPython's namespace instead of an empty one. This | |
1478 | is useful if you are experimenting with code written in a text editor |
|
1478 | is useful if you are experimenting with code written in a text editor | |
1479 | which depends on variables defined interactively. |
|
1479 | which depends on variables defined interactively. | |
1480 |
|
1480 | |||
1481 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1481 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1482 | being run. This is particularly useful if IPython is being used to |
|
1482 | being run. This is particularly useful if IPython is being used to | |
1483 | run unittests, which always exit with a sys.exit() call. In such |
|
1483 | run unittests, which always exit with a sys.exit() call. In such | |
1484 | cases you are interested in the output of the test results, not in |
|
1484 | cases you are interested in the output of the test results, not in | |
1485 | seeing a traceback of the unittest module. |
|
1485 | seeing a traceback of the unittest module. | |
1486 |
|
1486 | |||
1487 | -t: print timing information at the end of the run. IPython will give |
|
1487 | -t: print timing information at the end of the run. IPython will give | |
1488 | you an estimated CPU time consumption for your script, which under |
|
1488 | you an estimated CPU time consumption for your script, which under | |
1489 | Unix uses the resource module to avoid the wraparound problems of |
|
1489 | Unix uses the resource module to avoid the wraparound problems of | |
1490 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1490 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1491 | is also given (for Windows platforms this is reported as 0.0). |
|
1491 | is also given (for Windows platforms this is reported as 0.0). | |
1492 |
|
1492 | |||
1493 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1493 | If -t is given, an additional -N<N> option can be given, where <N> | |
1494 | must be an integer indicating how many times you want the script to |
|
1494 | must be an integer indicating how many times you want the script to | |
1495 | run. The final timing report will include total and per run results. |
|
1495 | run. The final timing report will include total and per run results. | |
1496 |
|
1496 | |||
1497 | For example (testing the script uniq_stable.py): |
|
1497 | For example (testing the script uniq_stable.py): | |
1498 |
|
1498 | |||
1499 | In [1]: run -t uniq_stable |
|
1499 | In [1]: run -t uniq_stable | |
1500 |
|
1500 | |||
1501 | IPython CPU timings (estimated):\\ |
|
1501 | IPython CPU timings (estimated):\\ | |
1502 | User : 0.19597 s.\\ |
|
1502 | User : 0.19597 s.\\ | |
1503 | System: 0.0 s.\\ |
|
1503 | System: 0.0 s.\\ | |
1504 |
|
1504 | |||
1505 | In [2]: run -t -N5 uniq_stable |
|
1505 | In [2]: run -t -N5 uniq_stable | |
1506 |
|
1506 | |||
1507 | IPython CPU timings (estimated):\\ |
|
1507 | IPython CPU timings (estimated):\\ | |
1508 | Total runs performed: 5\\ |
|
1508 | Total runs performed: 5\\ | |
1509 | Times : Total Per run\\ |
|
1509 | Times : Total Per run\\ | |
1510 | User : 0.910862 s, 0.1821724 s.\\ |
|
1510 | User : 0.910862 s, 0.1821724 s.\\ | |
1511 | System: 0.0 s, 0.0 s. |
|
1511 | System: 0.0 s, 0.0 s. | |
1512 |
|
1512 | |||
1513 | -d: run your program under the control of pdb, the Python debugger. |
|
1513 | -d: run your program under the control of pdb, the Python debugger. | |
1514 | This allows you to execute your program step by step, watch variables, |
|
1514 | This allows you to execute your program step by step, watch variables, | |
1515 | etc. Internally, what IPython does is similar to calling: |
|
1515 | etc. Internally, what IPython does is similar to calling: | |
1516 |
|
1516 | |||
1517 | pdb.run('execfile("YOURFILENAME")') |
|
1517 | pdb.run('execfile("YOURFILENAME")') | |
1518 |
|
1518 | |||
1519 | with a breakpoint set on line 1 of your file. You can change the line |
|
1519 | with a breakpoint set on line 1 of your file. You can change the line | |
1520 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1520 | number for this automatic breakpoint to be <N> by using the -bN option | |
1521 | (where N must be an integer). For example: |
|
1521 | (where N must be an integer). For example: | |
1522 |
|
1522 | |||
1523 | %run -d -b40 myscript |
|
1523 | %run -d -b40 myscript | |
1524 |
|
1524 | |||
1525 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1525 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1526 | the first breakpoint must be set on a line which actually does |
|
1526 | the first breakpoint must be set on a line which actually does | |
1527 | something (not a comment or docstring) for it to stop execution. |
|
1527 | something (not a comment or docstring) for it to stop execution. | |
1528 |
|
1528 | |||
1529 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1529 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1530 | first enter 'c' (without qoutes) to start execution up to the first |
|
1530 | first enter 'c' (without qoutes) to start execution up to the first | |
1531 | breakpoint. |
|
1531 | breakpoint. | |
1532 |
|
1532 | |||
1533 | Entering 'help' gives information about the use of the debugger. You |
|
1533 | Entering 'help' gives information about the use of the debugger. You | |
1534 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1534 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1535 | at a prompt. |
|
1535 | at a prompt. | |
1536 |
|
1536 | |||
1537 | -p: run program under the control of the Python profiler module (which |
|
1537 | -p: run program under the control of the Python profiler module (which | |
1538 | prints a detailed report of execution times, function calls, etc). |
|
1538 | prints a detailed report of execution times, function calls, etc). | |
1539 |
|
1539 | |||
1540 | You can pass other options after -p which affect the behavior of the |
|
1540 | You can pass other options after -p which affect the behavior of the | |
1541 | profiler itself. See the docs for %prun for details. |
|
1541 | profiler itself. See the docs for %prun for details. | |
1542 |
|
1542 | |||
1543 | In this mode, the program's variables do NOT propagate back to the |
|
1543 | In this mode, the program's variables do NOT propagate back to the | |
1544 | IPython interactive namespace (because they remain in the namespace |
|
1544 | IPython interactive namespace (because they remain in the namespace | |
1545 | where the profiler executes them). |
|
1545 | where the profiler executes them). | |
1546 |
|
1546 | |||
1547 | Internally this triggers a call to %prun, see its documentation for |
|
1547 | Internally this triggers a call to %prun, see its documentation for | |
1548 | details on the options available specifically for profiling. |
|
1548 | details on the options available specifically for profiling. | |
1549 |
|
1549 | |||
1550 | There is one special usage for which the text above doesn't apply: |
|
1550 | There is one special usage for which the text above doesn't apply: | |
1551 | if the filename ends with .ipy, the file is run as ipython script, |
|
1551 | if the filename ends with .ipy, the file is run as ipython script, | |
1552 | just as if the commands were written on IPython prompt. |
|
1552 | just as if the commands were written on IPython prompt. | |
1553 | """ |
|
1553 | """ | |
1554 |
|
1554 | |||
1555 | # get arguments and set sys.argv for program to be run. |
|
1555 | # get arguments and set sys.argv for program to be run. | |
1556 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1556 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1557 | mode='list',list_all=1) |
|
1557 | mode='list',list_all=1) | |
1558 |
|
1558 | |||
1559 | try: |
|
1559 | try: | |
1560 | filename = file_finder(arg_lst[0]) |
|
1560 | filename = file_finder(arg_lst[0]) | |
1561 | except IndexError: |
|
1561 | except IndexError: | |
1562 | warn('you must provide at least a filename.') |
|
1562 | warn('you must provide at least a filename.') | |
1563 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1563 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1564 | return |
|
1564 | return | |
1565 | except IOError,msg: |
|
1565 | except IOError,msg: | |
1566 | error(msg) |
|
1566 | error(msg) | |
1567 | return |
|
1567 | return | |
1568 |
|
1568 | |||
1569 | if filename.lower().endswith('.ipy'): |
|
1569 | if filename.lower().endswith('.ipy'): | |
1570 | self.shell.safe_execfile_ipy(filename) |
|
1570 | self.shell.safe_execfile_ipy(filename) | |
1571 | return |
|
1571 | return | |
1572 |
|
1572 | |||
1573 | # Control the response to exit() calls made by the script being run |
|
1573 | # Control the response to exit() calls made by the script being run | |
1574 | exit_ignore = opts.has_key('e') |
|
1574 | exit_ignore = opts.has_key('e') | |
1575 |
|
1575 | |||
1576 | # Make sure that the running script gets a proper sys.argv as if it |
|
1576 | # Make sure that the running script gets a proper sys.argv as if it | |
1577 | # were run from a system shell. |
|
1577 | # were run from a system shell. | |
1578 | save_argv = sys.argv # save it for later restoring |
|
1578 | save_argv = sys.argv # save it for later restoring | |
1579 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1579 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1580 |
|
1580 | |||
1581 | if opts.has_key('i'): |
|
1581 | if opts.has_key('i'): | |
1582 | # Run in user's interactive namespace |
|
1582 | # Run in user's interactive namespace | |
1583 | prog_ns = self.shell.user_ns |
|
1583 | prog_ns = self.shell.user_ns | |
1584 | __name__save = self.shell.user_ns['__name__'] |
|
1584 | __name__save = self.shell.user_ns['__name__'] | |
1585 | prog_ns['__name__'] = '__main__' |
|
1585 | prog_ns['__name__'] = '__main__' | |
1586 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1586 | main_mod = self.shell.new_main_mod(prog_ns) | |
1587 | else: |
|
1587 | else: | |
1588 | # Run in a fresh, empty namespace |
|
1588 | # Run in a fresh, empty namespace | |
1589 | if opts.has_key('n'): |
|
1589 | if opts.has_key('n'): | |
1590 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1590 | name = os.path.splitext(os.path.basename(filename))[0] | |
1591 | else: |
|
1591 | else: | |
1592 | name = '__main__' |
|
1592 | name = '__main__' | |
1593 |
|
1593 | |||
1594 | main_mod = self.shell.new_main_mod() |
|
1594 | main_mod = self.shell.new_main_mod() | |
1595 | prog_ns = main_mod.__dict__ |
|
1595 | prog_ns = main_mod.__dict__ | |
1596 | prog_ns['__name__'] = name |
|
1596 | prog_ns['__name__'] = name | |
1597 |
|
1597 | |||
1598 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1598 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1599 | # set the __file__ global in the script's namespace |
|
1599 | # set the __file__ global in the script's namespace | |
1600 | prog_ns['__file__'] = filename |
|
1600 | prog_ns['__file__'] = filename | |
1601 |
|
1601 | |||
1602 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1602 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1603 | # that, if we overwrite __main__, we replace it at the end |
|
1603 | # that, if we overwrite __main__, we replace it at the end | |
1604 | main_mod_name = prog_ns['__name__'] |
|
1604 | main_mod_name = prog_ns['__name__'] | |
1605 |
|
1605 | |||
1606 | if main_mod_name == '__main__': |
|
1606 | if main_mod_name == '__main__': | |
1607 | restore_main = sys.modules['__main__'] |
|
1607 | restore_main = sys.modules['__main__'] | |
1608 | else: |
|
1608 | else: | |
1609 | restore_main = False |
|
1609 | restore_main = False | |
1610 |
|
1610 | |||
1611 | # This needs to be undone at the end to prevent holding references to |
|
1611 | # This needs to be undone at the end to prevent holding references to | |
1612 | # every single object ever created. |
|
1612 | # every single object ever created. | |
1613 | sys.modules[main_mod_name] = main_mod |
|
1613 | sys.modules[main_mod_name] = main_mod | |
1614 |
|
1614 | |||
1615 | stats = None |
|
1615 | stats = None | |
1616 | try: |
|
1616 | try: | |
1617 | self.shell.save_history() |
|
1617 | self.shell.save_history() | |
1618 |
|
1618 | |||
1619 | if opts.has_key('p'): |
|
1619 | if opts.has_key('p'): | |
1620 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1620 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1621 | else: |
|
1621 | else: | |
1622 | if opts.has_key('d'): |
|
1622 | if opts.has_key('d'): | |
1623 | deb = debugger.Pdb(self.shell.colors) |
|
1623 | deb = debugger.Pdb(self.shell.colors) | |
1624 | # reset Breakpoint state, which is moronically kept |
|
1624 | # reset Breakpoint state, which is moronically kept | |
1625 | # in a class |
|
1625 | # in a class | |
1626 | bdb.Breakpoint.next = 1 |
|
1626 | bdb.Breakpoint.next = 1 | |
1627 | bdb.Breakpoint.bplist = {} |
|
1627 | bdb.Breakpoint.bplist = {} | |
1628 | bdb.Breakpoint.bpbynumber = [None] |
|
1628 | bdb.Breakpoint.bpbynumber = [None] | |
1629 | # Set an initial breakpoint to stop execution |
|
1629 | # Set an initial breakpoint to stop execution | |
1630 | maxtries = 10 |
|
1630 | maxtries = 10 | |
1631 | bp = int(opts.get('b',[1])[0]) |
|
1631 | bp = int(opts.get('b',[1])[0]) | |
1632 | checkline = deb.checkline(filename,bp) |
|
1632 | checkline = deb.checkline(filename,bp) | |
1633 | if not checkline: |
|
1633 | if not checkline: | |
1634 | for bp in range(bp+1,bp+maxtries+1): |
|
1634 | for bp in range(bp+1,bp+maxtries+1): | |
1635 | if deb.checkline(filename,bp): |
|
1635 | if deb.checkline(filename,bp): | |
1636 | break |
|
1636 | break | |
1637 | else: |
|
1637 | else: | |
1638 | msg = ("\nI failed to find a valid line to set " |
|
1638 | msg = ("\nI failed to find a valid line to set " | |
1639 | "a breakpoint\n" |
|
1639 | "a breakpoint\n" | |
1640 | "after trying up to line: %s.\n" |
|
1640 | "after trying up to line: %s.\n" | |
1641 | "Please set a valid breakpoint manually " |
|
1641 | "Please set a valid breakpoint manually " | |
1642 | "with the -b option." % bp) |
|
1642 | "with the -b option." % bp) | |
1643 | error(msg) |
|
1643 | error(msg) | |
1644 | return |
|
1644 | return | |
1645 | # if we find a good linenumber, set the breakpoint |
|
1645 | # if we find a good linenumber, set the breakpoint | |
1646 | deb.do_break('%s:%s' % (filename,bp)) |
|
1646 | deb.do_break('%s:%s' % (filename,bp)) | |
1647 | # Start file run |
|
1647 | # Start file run | |
1648 | print "NOTE: Enter 'c' at the", |
|
1648 | print "NOTE: Enter 'c' at the", | |
1649 | print "%s prompt to start your script." % deb.prompt |
|
1649 | print "%s prompt to start your script." % deb.prompt | |
1650 | try: |
|
1650 | try: | |
1651 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1651 | deb.run('execfile("%s")' % filename,prog_ns) | |
1652 |
|
1652 | |||
1653 | except: |
|
1653 | except: | |
1654 | etype, value, tb = sys.exc_info() |
|
1654 | etype, value, tb = sys.exc_info() | |
1655 | # Skip three frames in the traceback: the %run one, |
|
1655 | # Skip three frames in the traceback: the %run one, | |
1656 | # one inside bdb.py, and the command-line typed by the |
|
1656 | # one inside bdb.py, and the command-line typed by the | |
1657 | # user (run by exec in pdb itself). |
|
1657 | # user (run by exec in pdb itself). | |
1658 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1658 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1659 | else: |
|
1659 | else: | |
1660 | if runner is None: |
|
1660 | if runner is None: | |
1661 | runner = self.shell.safe_execfile |
|
1661 | runner = self.shell.safe_execfile | |
1662 | if opts.has_key('t'): |
|
1662 | if opts.has_key('t'): | |
1663 | # timed execution |
|
1663 | # timed execution | |
1664 | try: |
|
1664 | try: | |
1665 | nruns = int(opts['N'][0]) |
|
1665 | nruns = int(opts['N'][0]) | |
1666 | if nruns < 1: |
|
1666 | if nruns < 1: | |
1667 | error('Number of runs must be >=1') |
|
1667 | error('Number of runs must be >=1') | |
1668 | return |
|
1668 | return | |
1669 | except (KeyError): |
|
1669 | except (KeyError): | |
1670 | nruns = 1 |
|
1670 | nruns = 1 | |
1671 | if nruns == 1: |
|
1671 | if nruns == 1: | |
1672 | t0 = clock2() |
|
1672 | t0 = clock2() | |
1673 | runner(filename,prog_ns,prog_ns, |
|
1673 | runner(filename,prog_ns,prog_ns, | |
1674 | exit_ignore=exit_ignore) |
|
1674 | exit_ignore=exit_ignore) | |
1675 | t1 = clock2() |
|
1675 | t1 = clock2() | |
1676 | t_usr = t1[0]-t0[0] |
|
1676 | t_usr = t1[0]-t0[0] | |
1677 | t_sys = t1[1]-t0[1] |
|
1677 | t_sys = t1[1]-t0[1] | |
1678 | print "\nIPython CPU timings (estimated):" |
|
1678 | print "\nIPython CPU timings (estimated):" | |
1679 | print " User : %10s s." % t_usr |
|
1679 | print " User : %10s s." % t_usr | |
1680 | print " System: %10s s." % t_sys |
|
1680 | print " System: %10s s." % t_sys | |
1681 | else: |
|
1681 | else: | |
1682 | runs = range(nruns) |
|
1682 | runs = range(nruns) | |
1683 | t0 = clock2() |
|
1683 | t0 = clock2() | |
1684 | for nr in runs: |
|
1684 | for nr in runs: | |
1685 | runner(filename,prog_ns,prog_ns, |
|
1685 | runner(filename,prog_ns,prog_ns, | |
1686 | exit_ignore=exit_ignore) |
|
1686 | exit_ignore=exit_ignore) | |
1687 | t1 = clock2() |
|
1687 | t1 = clock2() | |
1688 | t_usr = t1[0]-t0[0] |
|
1688 | t_usr = t1[0]-t0[0] | |
1689 | t_sys = t1[1]-t0[1] |
|
1689 | t_sys = t1[1]-t0[1] | |
1690 | print "\nIPython CPU timings (estimated):" |
|
1690 | print "\nIPython CPU timings (estimated):" | |
1691 | print "Total runs performed:",nruns |
|
1691 | print "Total runs performed:",nruns | |
1692 | print " Times : %10s %10s" % ('Total','Per run') |
|
1692 | print " Times : %10s %10s" % ('Total','Per run') | |
1693 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1693 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1694 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1694 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1695 |
|
1695 | |||
1696 | else: |
|
1696 | else: | |
1697 | # regular execution |
|
1697 | # regular execution | |
1698 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1698 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1699 |
|
1699 | |||
1700 | if opts.has_key('i'): |
|
1700 | if opts.has_key('i'): | |
1701 | self.shell.user_ns['__name__'] = __name__save |
|
1701 | self.shell.user_ns['__name__'] = __name__save | |
1702 | else: |
|
1702 | else: | |
1703 | # The shell MUST hold a reference to prog_ns so after %run |
|
1703 | # The shell MUST hold a reference to prog_ns so after %run | |
1704 | # exits, the python deletion mechanism doesn't zero it out |
|
1704 | # exits, the python deletion mechanism doesn't zero it out | |
1705 | # (leaving dangling references). |
|
1705 | # (leaving dangling references). | |
1706 | self.shell.cache_main_mod(prog_ns,filename) |
|
1706 | self.shell.cache_main_mod(prog_ns,filename) | |
1707 | # update IPython interactive namespace |
|
1707 | # update IPython interactive namespace | |
1708 |
|
1708 | |||
1709 | # Some forms of read errors on the file may mean the |
|
1709 | # Some forms of read errors on the file may mean the | |
1710 | # __name__ key was never set; using pop we don't have to |
|
1710 | # __name__ key was never set; using pop we don't have to | |
1711 | # worry about a possible KeyError. |
|
1711 | # worry about a possible KeyError. | |
1712 | prog_ns.pop('__name__', None) |
|
1712 | prog_ns.pop('__name__', None) | |
1713 |
|
1713 | |||
1714 | self.shell.user_ns.update(prog_ns) |
|
1714 | self.shell.user_ns.update(prog_ns) | |
1715 | finally: |
|
1715 | finally: | |
1716 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1716 | # It's a bit of a mystery why, but __builtins__ can change from | |
1717 | # being a module to becoming a dict missing some key data after |
|
1717 | # being a module to becoming a dict missing some key data after | |
1718 | # %run. As best I can see, this is NOT something IPython is doing |
|
1718 | # %run. As best I can see, this is NOT something IPython is doing | |
1719 | # at all, and similar problems have been reported before: |
|
1719 | # at all, and similar problems have been reported before: | |
1720 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1720 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1721 | # Since this seems to be done by the interpreter itself, the best |
|
1721 | # Since this seems to be done by the interpreter itself, the best | |
1722 | # we can do is to at least restore __builtins__ for the user on |
|
1722 | # we can do is to at least restore __builtins__ for the user on | |
1723 | # exit. |
|
1723 | # exit. | |
1724 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1724 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1725 |
|
1725 | |||
1726 | # Ensure key global structures are restored |
|
1726 | # Ensure key global structures are restored | |
1727 | sys.argv = save_argv |
|
1727 | sys.argv = save_argv | |
1728 | if restore_main: |
|
1728 | if restore_main: | |
1729 | sys.modules['__main__'] = restore_main |
|
1729 | sys.modules['__main__'] = restore_main | |
1730 | else: |
|
1730 | else: | |
1731 | # Remove from sys.modules the reference to main_mod we'd |
|
1731 | # Remove from sys.modules the reference to main_mod we'd | |
1732 | # added. Otherwise it will trap references to objects |
|
1732 | # added. Otherwise it will trap references to objects | |
1733 | # contained therein. |
|
1733 | # contained therein. | |
1734 | del sys.modules[main_mod_name] |
|
1734 | del sys.modules[main_mod_name] | |
1735 |
|
1735 | |||
1736 | self.shell.reload_history() |
|
1736 | self.shell.reload_history() | |
1737 |
|
1737 | |||
1738 | return stats |
|
1738 | return stats | |
1739 |
|
1739 | |||
1740 | @testdec.skip_doctest |
|
1740 | @testdec.skip_doctest | |
1741 | def magic_timeit(self, parameter_s =''): |
|
1741 | def magic_timeit(self, parameter_s =''): | |
1742 | """Time execution of a Python statement or expression |
|
1742 | """Time execution of a Python statement or expression | |
1743 |
|
1743 | |||
1744 | Usage:\\ |
|
1744 | Usage:\\ | |
1745 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1745 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1746 |
|
1746 | |||
1747 | Time execution of a Python statement or expression using the timeit |
|
1747 | Time execution of a Python statement or expression using the timeit | |
1748 | module. |
|
1748 | module. | |
1749 |
|
1749 | |||
1750 | Options: |
|
1750 | Options: | |
1751 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1751 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1752 | is not given, a fitting value is chosen. |
|
1752 | is not given, a fitting value is chosen. | |
1753 |
|
1753 | |||
1754 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1754 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1755 | Default: 3 |
|
1755 | Default: 3 | |
1756 |
|
1756 | |||
1757 | -t: use time.time to measure the time, which is the default on Unix. |
|
1757 | -t: use time.time to measure the time, which is the default on Unix. | |
1758 | This function measures wall time. |
|
1758 | This function measures wall time. | |
1759 |
|
1759 | |||
1760 | -c: use time.clock to measure the time, which is the default on |
|
1760 | -c: use time.clock to measure the time, which is the default on | |
1761 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1761 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1762 | instead and returns the CPU user time. |
|
1762 | instead and returns the CPU user time. | |
1763 |
|
1763 | |||
1764 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1764 | -p<P>: use a precision of <P> digits to display the timing result. | |
1765 | Default: 3 |
|
1765 | Default: 3 | |
1766 |
|
1766 | |||
1767 |
|
1767 | |||
1768 | Examples: |
|
1768 | Examples: | |
1769 |
|
1769 | |||
1770 | In [1]: %timeit pass |
|
1770 | In [1]: %timeit pass | |
1771 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1771 | 10000000 loops, best of 3: 53.3 ns per loop | |
1772 |
|
1772 | |||
1773 | In [2]: u = None |
|
1773 | In [2]: u = None | |
1774 |
|
1774 | |||
1775 | In [3]: %timeit u is None |
|
1775 | In [3]: %timeit u is None | |
1776 | 10000000 loops, best of 3: 184 ns per loop |
|
1776 | 10000000 loops, best of 3: 184 ns per loop | |
1777 |
|
1777 | |||
1778 | In [4]: %timeit -r 4 u == None |
|
1778 | In [4]: %timeit -r 4 u == None | |
1779 | 1000000 loops, best of 4: 242 ns per loop |
|
1779 | 1000000 loops, best of 4: 242 ns per loop | |
1780 |
|
1780 | |||
1781 | In [5]: import time |
|
1781 | In [5]: import time | |
1782 |
|
1782 | |||
1783 | In [6]: %timeit -n1 time.sleep(2) |
|
1783 | In [6]: %timeit -n1 time.sleep(2) | |
1784 | 1 loops, best of 3: 2 s per loop |
|
1784 | 1 loops, best of 3: 2 s per loop | |
1785 |
|
1785 | |||
1786 |
|
1786 | |||
1787 | The times reported by %timeit will be slightly higher than those |
|
1787 | The times reported by %timeit will be slightly higher than those | |
1788 | reported by the timeit.py script when variables are accessed. This is |
|
1788 | reported by the timeit.py script when variables are accessed. This is | |
1789 | due to the fact that %timeit executes the statement in the namespace |
|
1789 | due to the fact that %timeit executes the statement in the namespace | |
1790 | of the shell, compared with timeit.py, which uses a single setup |
|
1790 | of the shell, compared with timeit.py, which uses a single setup | |
1791 | statement to import function or create variables. Generally, the bias |
|
1791 | statement to import function or create variables. Generally, the bias | |
1792 | does not matter as long as results from timeit.py are not mixed with |
|
1792 | does not matter as long as results from timeit.py are not mixed with | |
1793 | those from %timeit.""" |
|
1793 | those from %timeit.""" | |
1794 |
|
1794 | |||
1795 | import timeit |
|
1795 | import timeit | |
1796 | import math |
|
1796 | import math | |
1797 |
|
1797 | |||
1798 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1798 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1799 | # certain terminals. Until we figure out a robust way of |
|
1799 | # certain terminals. Until we figure out a robust way of | |
1800 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1800 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1801 | # microseconds. I am really NOT happy about disabling the proper |
|
1801 | # microseconds. I am really NOT happy about disabling the proper | |
1802 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1802 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1803 | # right solution for this is, I'm all ears... |
|
1803 | # right solution for this is, I'm all ears... | |
1804 | # |
|
1804 | # | |
1805 | # Note: using |
|
1805 | # Note: using | |
1806 | # |
|
1806 | # | |
1807 | # s = u'\xb5' |
|
1807 | # s = u'\xb5' | |
1808 | # s.encode(sys.getdefaultencoding()) |
|
1808 | # s.encode(sys.getdefaultencoding()) | |
1809 | # |
|
1809 | # | |
1810 | # is not sufficient, as I've seen terminals where that fails but |
|
1810 | # is not sufficient, as I've seen terminals where that fails but | |
1811 | # print s |
|
1811 | # print s | |
1812 | # |
|
1812 | # | |
1813 | # succeeds |
|
1813 | # succeeds | |
1814 | # |
|
1814 | # | |
1815 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1815 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1816 |
|
1816 | |||
1817 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1817 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1818 | units = [u"s", u"ms",u'us',"ns"] |
|
1818 | units = [u"s", u"ms",u'us',"ns"] | |
1819 |
|
1819 | |||
1820 | scaling = [1, 1e3, 1e6, 1e9] |
|
1820 | scaling = [1, 1e3, 1e6, 1e9] | |
1821 |
|
1821 | |||
1822 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1822 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1823 | posix=False) |
|
1823 | posix=False) | |
1824 | if stmt == "": |
|
1824 | if stmt == "": | |
1825 | return |
|
1825 | return | |
1826 | timefunc = timeit.default_timer |
|
1826 | timefunc = timeit.default_timer | |
1827 | number = int(getattr(opts, "n", 0)) |
|
1827 | number = int(getattr(opts, "n", 0)) | |
1828 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1828 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1829 | precision = int(getattr(opts, "p", 3)) |
|
1829 | precision = int(getattr(opts, "p", 3)) | |
1830 | if hasattr(opts, "t"): |
|
1830 | if hasattr(opts, "t"): | |
1831 | timefunc = time.time |
|
1831 | timefunc = time.time | |
1832 | if hasattr(opts, "c"): |
|
1832 | if hasattr(opts, "c"): | |
1833 | timefunc = clock |
|
1833 | timefunc = clock | |
1834 |
|
1834 | |||
1835 | timer = timeit.Timer(timer=timefunc) |
|
1835 | timer = timeit.Timer(timer=timefunc) | |
1836 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1836 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1837 | # but is there a better way to achieve that the code stmt has access |
|
1837 | # but is there a better way to achieve that the code stmt has access | |
1838 | # to the shell namespace? |
|
1838 | # to the shell namespace? | |
1839 |
|
1839 | |||
1840 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1840 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1841 | 'setup': "pass"} |
|
1841 | 'setup': "pass"} | |
1842 | # Track compilation time so it can be reported if too long |
|
1842 | # Track compilation time so it can be reported if too long | |
1843 | # Minimum time above which compilation time will be reported |
|
1843 | # Minimum time above which compilation time will be reported | |
1844 | tc_min = 0.1 |
|
1844 | tc_min = 0.1 | |
1845 |
|
1845 | |||
1846 | t0 = clock() |
|
1846 | t0 = clock() | |
1847 | code = compile(src, "<magic-timeit>", "exec") |
|
1847 | code = compile(src, "<magic-timeit>", "exec") | |
1848 | tc = clock()-t0 |
|
1848 | tc = clock()-t0 | |
1849 |
|
1849 | |||
1850 | ns = {} |
|
1850 | ns = {} | |
1851 | exec code in self.shell.user_ns, ns |
|
1851 | exec code in self.shell.user_ns, ns | |
1852 | timer.inner = ns["inner"] |
|
1852 | timer.inner = ns["inner"] | |
1853 |
|
1853 | |||
1854 | if number == 0: |
|
1854 | if number == 0: | |
1855 | # determine number so that 0.2 <= total time < 2.0 |
|
1855 | # determine number so that 0.2 <= total time < 2.0 | |
1856 | number = 1 |
|
1856 | number = 1 | |
1857 | for i in range(1, 10): |
|
1857 | for i in range(1, 10): | |
1858 | if timer.timeit(number) >= 0.2: |
|
1858 | if timer.timeit(number) >= 0.2: | |
1859 | break |
|
1859 | break | |
1860 | number *= 10 |
|
1860 | number *= 10 | |
1861 |
|
1861 | |||
1862 | best = min(timer.repeat(repeat, number)) / number |
|
1862 | best = min(timer.repeat(repeat, number)) / number | |
1863 |
|
1863 | |||
1864 | if best > 0.0 and best < 1000.0: |
|
1864 | if best > 0.0 and best < 1000.0: | |
1865 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1865 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1866 | elif best >= 1000.0: |
|
1866 | elif best >= 1000.0: | |
1867 | order = 0 |
|
1867 | order = 0 | |
1868 | else: |
|
1868 | else: | |
1869 | order = 3 |
|
1869 | order = 3 | |
1870 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1870 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1871 | precision, |
|
1871 | precision, | |
1872 | best * scaling[order], |
|
1872 | best * scaling[order], | |
1873 | units[order]) |
|
1873 | units[order]) | |
1874 | if tc > tc_min: |
|
1874 | if tc > tc_min: | |
1875 | print "Compiler time: %.2f s" % tc |
|
1875 | print "Compiler time: %.2f s" % tc | |
1876 |
|
1876 | |||
1877 | @testdec.skip_doctest |
|
1877 | @testdec.skip_doctest | |
1878 | def magic_time(self,parameter_s = ''): |
|
1878 | def magic_time(self,parameter_s = ''): | |
1879 | """Time execution of a Python statement or expression. |
|
1879 | """Time execution of a Python statement or expression. | |
1880 |
|
1880 | |||
1881 | The CPU and wall clock times are printed, and the value of the |
|
1881 | The CPU and wall clock times are printed, and the value of the | |
1882 | expression (if any) is returned. Note that under Win32, system time |
|
1882 | expression (if any) is returned. Note that under Win32, system time | |
1883 | is always reported as 0, since it can not be measured. |
|
1883 | is always reported as 0, since it can not be measured. | |
1884 |
|
1884 | |||
1885 | This function provides very basic timing functionality. In Python |
|
1885 | This function provides very basic timing functionality. In Python | |
1886 | 2.3, the timeit module offers more control and sophistication, so this |
|
1886 | 2.3, the timeit module offers more control and sophistication, so this | |
1887 | could be rewritten to use it (patches welcome). |
|
1887 | could be rewritten to use it (patches welcome). | |
1888 |
|
1888 | |||
1889 | Some examples: |
|
1889 | Some examples: | |
1890 |
|
1890 | |||
1891 | In [1]: time 2**128 |
|
1891 | In [1]: time 2**128 | |
1892 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1892 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1893 | Wall time: 0.00 |
|
1893 | Wall time: 0.00 | |
1894 | Out[1]: 340282366920938463463374607431768211456L |
|
1894 | Out[1]: 340282366920938463463374607431768211456L | |
1895 |
|
1895 | |||
1896 | In [2]: n = 1000000 |
|
1896 | In [2]: n = 1000000 | |
1897 |
|
1897 | |||
1898 | In [3]: time sum(range(n)) |
|
1898 | In [3]: time sum(range(n)) | |
1899 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1899 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1900 | Wall time: 1.37 |
|
1900 | Wall time: 1.37 | |
1901 | Out[3]: 499999500000L |
|
1901 | Out[3]: 499999500000L | |
1902 |
|
1902 | |||
1903 | In [4]: time print 'hello world' |
|
1903 | In [4]: time print 'hello world' | |
1904 | hello world |
|
1904 | hello world | |
1905 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1905 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1906 | Wall time: 0.00 |
|
1906 | Wall time: 0.00 | |
1907 |
|
1907 | |||
1908 | Note that the time needed by Python to compile the given expression |
|
1908 | Note that the time needed by Python to compile the given expression | |
1909 | will be reported if it is more than 0.1s. In this example, the |
|
1909 | will be reported if it is more than 0.1s. In this example, the | |
1910 | actual exponentiation is done by Python at compilation time, so while |
|
1910 | actual exponentiation is done by Python at compilation time, so while | |
1911 | the expression can take a noticeable amount of time to compute, that |
|
1911 | the expression can take a noticeable amount of time to compute, that | |
1912 | time is purely due to the compilation: |
|
1912 | time is purely due to the compilation: | |
1913 |
|
1913 | |||
1914 | In [5]: time 3**9999; |
|
1914 | In [5]: time 3**9999; | |
1915 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1915 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1916 | Wall time: 0.00 s |
|
1916 | Wall time: 0.00 s | |
1917 |
|
1917 | |||
1918 | In [6]: time 3**999999; |
|
1918 | In [6]: time 3**999999; | |
1919 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1919 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1920 | Wall time: 0.00 s |
|
1920 | Wall time: 0.00 s | |
1921 | Compiler : 0.78 s |
|
1921 | Compiler : 0.78 s | |
1922 | """ |
|
1922 | """ | |
1923 |
|
1923 | |||
1924 | # fail immediately if the given expression can't be compiled |
|
1924 | # fail immediately if the given expression can't be compiled | |
1925 |
|
1925 | |||
1926 | expr = self.shell.prefilter(parameter_s,False) |
|
1926 | expr = self.shell.prefilter(parameter_s,False) | |
1927 |
|
1927 | |||
1928 | # Minimum time above which compilation time will be reported |
|
1928 | # Minimum time above which compilation time will be reported | |
1929 | tc_min = 0.1 |
|
1929 | tc_min = 0.1 | |
1930 |
|
1930 | |||
1931 | try: |
|
1931 | try: | |
1932 | mode = 'eval' |
|
1932 | mode = 'eval' | |
1933 | t0 = clock() |
|
1933 | t0 = clock() | |
1934 | code = compile(expr,'<timed eval>',mode) |
|
1934 | code = compile(expr,'<timed eval>',mode) | |
1935 | tc = clock()-t0 |
|
1935 | tc = clock()-t0 | |
1936 | except SyntaxError: |
|
1936 | except SyntaxError: | |
1937 | mode = 'exec' |
|
1937 | mode = 'exec' | |
1938 | t0 = clock() |
|
1938 | t0 = clock() | |
1939 | code = compile(expr,'<timed exec>',mode) |
|
1939 | code = compile(expr,'<timed exec>',mode) | |
1940 | tc = clock()-t0 |
|
1940 | tc = clock()-t0 | |
1941 | # skew measurement as little as possible |
|
1941 | # skew measurement as little as possible | |
1942 | glob = self.shell.user_ns |
|
1942 | glob = self.shell.user_ns | |
1943 | clk = clock2 |
|
1943 | clk = clock2 | |
1944 | wtime = time.time |
|
1944 | wtime = time.time | |
1945 | # time execution |
|
1945 | # time execution | |
1946 | wall_st = wtime() |
|
1946 | wall_st = wtime() | |
1947 | if mode=='eval': |
|
1947 | if mode=='eval': | |
1948 | st = clk() |
|
1948 | st = clk() | |
1949 | out = eval(code,glob) |
|
1949 | out = eval(code,glob) | |
1950 | end = clk() |
|
1950 | end = clk() | |
1951 | else: |
|
1951 | else: | |
1952 | st = clk() |
|
1952 | st = clk() | |
1953 | exec code in glob |
|
1953 | exec code in glob | |
1954 | end = clk() |
|
1954 | end = clk() | |
1955 | out = None |
|
1955 | out = None | |
1956 | wall_end = wtime() |
|
1956 | wall_end = wtime() | |
1957 | # Compute actual times and report |
|
1957 | # Compute actual times and report | |
1958 | wall_time = wall_end-wall_st |
|
1958 | wall_time = wall_end-wall_st | |
1959 | cpu_user = end[0]-st[0] |
|
1959 | cpu_user = end[0]-st[0] | |
1960 | cpu_sys = end[1]-st[1] |
|
1960 | cpu_sys = end[1]-st[1] | |
1961 | cpu_tot = cpu_user+cpu_sys |
|
1961 | cpu_tot = cpu_user+cpu_sys | |
1962 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1962 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1963 | (cpu_user,cpu_sys,cpu_tot) |
|
1963 | (cpu_user,cpu_sys,cpu_tot) | |
1964 | print "Wall time: %.2f s" % wall_time |
|
1964 | print "Wall time: %.2f s" % wall_time | |
1965 | if tc > tc_min: |
|
1965 | if tc > tc_min: | |
1966 | print "Compiler : %.2f s" % tc |
|
1966 | print "Compiler : %.2f s" % tc | |
1967 | return out |
|
1967 | return out | |
1968 |
|
1968 | |||
1969 | @testdec.skip_doctest |
|
1969 | @testdec.skip_doctest | |
1970 | def magic_macro(self,parameter_s = ''): |
|
1970 | def magic_macro(self,parameter_s = ''): | |
1971 | """Define a set of input lines as a macro for future re-execution. |
|
1971 | """Define a set of input lines as a macro for future re-execution. | |
1972 |
|
1972 | |||
1973 | Usage:\\ |
|
1973 | Usage:\\ | |
1974 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1974 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1975 |
|
1975 | |||
1976 | Options: |
|
1976 | Options: | |
1977 |
|
1977 | |||
1978 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1978 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1979 | so that magics are loaded in their transformed version to valid |
|
1979 | so that magics are loaded in their transformed version to valid | |
1980 | Python. If this option is given, the raw input as typed as the |
|
1980 | Python. If this option is given, the raw input as typed as the | |
1981 | command line is used instead. |
|
1981 | command line is used instead. | |
1982 |
|
1982 | |||
1983 | This will define a global variable called `name` which is a string |
|
1983 | This will define a global variable called `name` which is a string | |
1984 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1984 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1985 | above) from your input history into a single string. This variable |
|
1985 | above) from your input history into a single string. This variable | |
1986 | acts like an automatic function which re-executes those lines as if |
|
1986 | acts like an automatic function which re-executes those lines as if | |
1987 | you had typed them. You just type 'name' at the prompt and the code |
|
1987 | you had typed them. You just type 'name' at the prompt and the code | |
1988 | executes. |
|
1988 | executes. | |
1989 |
|
1989 | |||
1990 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1990 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1991 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1991 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1992 | using the lines numbered 5,6 and 7. |
|
1992 | using the lines numbered 5,6 and 7. | |
1993 |
|
1993 | |||
1994 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1994 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1995 | notation, where N:M means numbers N through M-1. |
|
1995 | notation, where N:M means numbers N through M-1. | |
1996 |
|
1996 | |||
1997 | For example, if your history contains (%hist prints it): |
|
1997 | For example, if your history contains (%hist prints it): | |
1998 |
|
1998 | |||
1999 | 44: x=1 |
|
1999 | 44: x=1 | |
2000 | 45: y=3 |
|
2000 | 45: y=3 | |
2001 | 46: z=x+y |
|
2001 | 46: z=x+y | |
2002 | 47: print x |
|
2002 | 47: print x | |
2003 | 48: a=5 |
|
2003 | 48: a=5 | |
2004 | 49: print 'x',x,'y',y |
|
2004 | 49: print 'x',x,'y',y | |
2005 |
|
2005 | |||
2006 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2006 | you can create a macro with lines 44 through 47 (included) and line 49 | |
2007 | called my_macro with: |
|
2007 | called my_macro with: | |
2008 |
|
2008 | |||
2009 | In [55]: %macro my_macro 44-47 49 |
|
2009 | In [55]: %macro my_macro 44-47 49 | |
2010 |
|
2010 | |||
2011 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2011 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
2012 | in one pass. |
|
2012 | in one pass. | |
2013 |
|
2013 | |||
2014 | You don't need to give the line-numbers in order, and any given line |
|
2014 | You don't need to give the line-numbers in order, and any given line | |
2015 | number can appear multiple times. You can assemble macros with any |
|
2015 | number can appear multiple times. You can assemble macros with any | |
2016 | lines from your input history in any order. |
|
2016 | lines from your input history in any order. | |
2017 |
|
2017 | |||
2018 | The macro is a simple object which holds its value in an attribute, |
|
2018 | The macro is a simple object which holds its value in an attribute, | |
2019 | but IPython's display system checks for macros and executes them as |
|
2019 | but IPython's display system checks for macros and executes them as | |
2020 | code instead of printing them when you type their name. |
|
2020 | code instead of printing them when you type their name. | |
2021 |
|
2021 | |||
2022 | You can view a macro's contents by explicitly printing it with: |
|
2022 | You can view a macro's contents by explicitly printing it with: | |
2023 |
|
2023 | |||
2024 | 'print macro_name'. |
|
2024 | 'print macro_name'. | |
2025 |
|
2025 | |||
2026 | For one-off cases which DON'T contain magic function calls in them you |
|
2026 | For one-off cases which DON'T contain magic function calls in them you | |
2027 | can obtain similar results by explicitly executing slices from your |
|
2027 | can obtain similar results by explicitly executing slices from your | |
2028 | input history with: |
|
2028 | input history with: | |
2029 |
|
2029 | |||
2030 | In [60]: exec In[44:48]+In[49]""" |
|
2030 | In [60]: exec In[44:48]+In[49]""" | |
2031 |
|
2031 | |||
2032 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2032 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2033 | if not args: |
|
2033 | if not args: # List existing macros | |
2034 |
|
|
2034 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ | |
2035 | macs.sort() |
|
2035 | isinstance(v, Macro)) | |
2036 | return macs |
|
|||
2037 | if len(args) == 1: |
|
2036 | if len(args) == 1: | |
2038 | raise UsageError( |
|
2037 | raise UsageError( | |
2039 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2038 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
2040 | name,ranges = args[0], args[1:] |
|
2039 | name,ranges = args[0], args[1:] | |
2041 |
|
2040 | |||
2042 | #print 'rng',ranges # dbg |
|
2041 | #print 'rng',ranges # dbg | |
2043 |
lines = self.extract_input_slices(ranges, |
|
2042 | lines = self.extract_input_slices(ranges,'r' in opts) | |
2044 | macro = Macro("\n".join(lines)) |
|
2043 | macro = Macro("\n".join(lines)) | |
2045 | self.shell.define_macro(name, macro) |
|
2044 | self.shell.define_macro(name, macro) | |
2046 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2045 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
2047 | print 'Macro contents:' |
|
2046 | print 'Macro contents:' | |
2048 | print macro, |
|
2047 | print macro, | |
2049 |
|
2048 | |||
2050 | def magic_save(self,parameter_s = ''): |
|
2049 | def magic_save(self,parameter_s = ''): | |
2051 | """Save a set of lines to a given filename. |
|
2050 | """Save a set of lines to a given filename. | |
2052 |
|
2051 | |||
2053 | Usage:\\ |
|
2052 | Usage:\\ | |
2054 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2053 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
2055 |
|
2054 | |||
2056 | Options: |
|
2055 | Options: | |
2057 |
|
2056 | |||
2058 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2057 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2059 | so that magics are loaded in their transformed version to valid |
|
2058 | so that magics are loaded in their transformed version to valid | |
2060 | Python. If this option is given, the raw input as typed as the |
|
2059 | Python. If this option is given, the raw input as typed as the | |
2061 | command line is used instead. |
|
2060 | command line is used instead. | |
2062 |
|
2061 | |||
2063 | This function uses the same syntax as %macro for line extraction, but |
|
2062 | This function uses the same syntax as %macro for line extraction, but | |
2064 | instead of creating a macro it saves the resulting string to the |
|
2063 | instead of creating a macro it saves the resulting string to the | |
2065 | filename you specify. |
|
2064 | filename you specify. | |
2066 |
|
2065 | |||
2067 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2066 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2068 | it asks for confirmation before overwriting existing files.""" |
|
2067 | it asks for confirmation before overwriting existing files.""" | |
2069 |
|
2068 | |||
2070 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2069 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2071 | fname,ranges = args[0], args[1:] |
|
2070 | fname,ranges = args[0], args[1:] | |
2072 | if not fname.endswith('.py'): |
|
2071 | if not fname.endswith('.py'): | |
2073 | fname += '.py' |
|
2072 | fname += '.py' | |
2074 | if os.path.isfile(fname): |
|
2073 | if os.path.isfile(fname): | |
2075 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2074 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2076 | if ans.lower() not in ['y','yes']: |
|
2075 | if ans.lower() not in ['y','yes']: | |
2077 | print 'Operation cancelled.' |
|
2076 | print 'Operation cancelled.' | |
2078 | return |
|
2077 | return | |
2079 |
cmds = '\n'.join(self.extract_input_slices(ranges, |
|
2078 | cmds = '\n'.join(self.extract_input_slices(ranges, 'r' in opts)) | |
2080 | with open(fname,'w') as f: |
|
2079 | with open(fname,'w') as f: | |
2081 | f.write(cmds) |
|
2080 | f.write(cmds) | |
2082 | print 'The following commands were written to file `%s`:' % fname |
|
2081 | print 'The following commands were written to file `%s`:' % fname | |
2083 | print cmds |
|
2082 | print cmds | |
2084 |
|
2083 | |||
2085 | def _edit_macro(self,mname,macro): |
|
2084 | def _edit_macro(self,mname,macro): | |
2086 | """open an editor with the macro data in a file""" |
|
2085 | """open an editor with the macro data in a file""" | |
2087 | filename = self.shell.mktempfile(macro.value) |
|
2086 | filename = self.shell.mktempfile(macro.value) | |
2088 | self.shell.hooks.editor(filename) |
|
2087 | self.shell.hooks.editor(filename) | |
2089 |
|
2088 | |||
2090 | # and make a new macro object, to replace the old one |
|
2089 | # and make a new macro object, to replace the old one | |
2091 | mfile = open(filename) |
|
2090 | mfile = open(filename) | |
2092 | mvalue = mfile.read() |
|
2091 | mvalue = mfile.read() | |
2093 | mfile.close() |
|
2092 | mfile.close() | |
2094 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2093 | self.shell.user_ns[mname] = Macro(mvalue) | |
2095 |
|
2094 | |||
2096 | def magic_ed(self,parameter_s=''): |
|
2095 | def magic_ed(self,parameter_s=''): | |
2097 | """Alias to %edit.""" |
|
2096 | """Alias to %edit.""" | |
2098 | return self.magic_edit(parameter_s) |
|
2097 | return self.magic_edit(parameter_s) | |
2099 |
|
2098 | |||
2100 | @testdec.skip_doctest |
|
2099 | @testdec.skip_doctest | |
2101 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2100 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2102 | """Bring up an editor and execute the resulting code. |
|
2101 | """Bring up an editor and execute the resulting code. | |
2103 |
|
2102 | |||
2104 | Usage: |
|
2103 | Usage: | |
2105 | %edit [options] [args] |
|
2104 | %edit [options] [args] | |
2106 |
|
2105 | |||
2107 | %edit runs IPython's editor hook. The default version of this hook is |
|
2106 | %edit runs IPython's editor hook. The default version of this hook is | |
2108 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2107 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2109 | environment variable $EDITOR. If this isn't found, it will default to |
|
2108 | environment variable $EDITOR. If this isn't found, it will default to | |
2110 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2109 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2111 | docstring for how to change the editor hook. |
|
2110 | docstring for how to change the editor hook. | |
2112 |
|
2111 | |||
2113 | You can also set the value of this editor via the command line option |
|
2112 | You can also set the value of this editor via the command line option | |
2114 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2113 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2115 | specifically for IPython an editor different from your typical default |
|
2114 | specifically for IPython an editor different from your typical default | |
2116 | (and for Windows users who typically don't set environment variables). |
|
2115 | (and for Windows users who typically don't set environment variables). | |
2117 |
|
2116 | |||
2118 | This command allows you to conveniently edit multi-line code right in |
|
2117 | This command allows you to conveniently edit multi-line code right in | |
2119 | your IPython session. |
|
2118 | your IPython session. | |
2120 |
|
2119 | |||
2121 | If called without arguments, %edit opens up an empty editor with a |
|
2120 | If called without arguments, %edit opens up an empty editor with a | |
2122 | temporary file and will execute the contents of this file when you |
|
2121 | temporary file and will execute the contents of this file when you | |
2123 | close it (don't forget to save it!). |
|
2122 | close it (don't forget to save it!). | |
2124 |
|
2123 | |||
2125 |
|
2124 | |||
2126 | Options: |
|
2125 | Options: | |
2127 |
|
2126 | |||
2128 | -n <number>: open the editor at a specified line number. By default, |
|
2127 | -n <number>: open the editor at a specified line number. By default, | |
2129 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2128 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2130 | you can configure this by providing your own modified hook if your |
|
2129 | you can configure this by providing your own modified hook if your | |
2131 | favorite editor supports line-number specifications with a different |
|
2130 | favorite editor supports line-number specifications with a different | |
2132 | syntax. |
|
2131 | syntax. | |
2133 |
|
2132 | |||
2134 | -p: this will call the editor with the same data as the previous time |
|
2133 | -p: this will call the editor with the same data as the previous time | |
2135 | it was used, regardless of how long ago (in your current session) it |
|
2134 | it was used, regardless of how long ago (in your current session) it | |
2136 | was. |
|
2135 | was. | |
2137 |
|
2136 | |||
2138 | -r: use 'raw' input. This option only applies to input taken from the |
|
2137 | -r: use 'raw' input. This option only applies to input taken from the | |
2139 | user's history. By default, the 'processed' history is used, so that |
|
2138 | user's history. By default, the 'processed' history is used, so that | |
2140 | magics are loaded in their transformed version to valid Python. If |
|
2139 | magics are loaded in their transformed version to valid Python. If | |
2141 | this option is given, the raw input as typed as the command line is |
|
2140 | this option is given, the raw input as typed as the command line is | |
2142 | used instead. When you exit the editor, it will be executed by |
|
2141 | used instead. When you exit the editor, it will be executed by | |
2143 | IPython's own processor. |
|
2142 | IPython's own processor. | |
2144 |
|
2143 | |||
2145 | -x: do not execute the edited code immediately upon exit. This is |
|
2144 | -x: do not execute the edited code immediately upon exit. This is | |
2146 | mainly useful if you are editing programs which need to be called with |
|
2145 | mainly useful if you are editing programs which need to be called with | |
2147 | command line arguments, which you can then do using %run. |
|
2146 | command line arguments, which you can then do using %run. | |
2148 |
|
2147 | |||
2149 |
|
2148 | |||
2150 | Arguments: |
|
2149 | Arguments: | |
2151 |
|
2150 | |||
2152 | If arguments are given, the following possibilites exist: |
|
2151 | If arguments are given, the following possibilites exist: | |
2153 |
|
2152 | |||
2154 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2153 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2155 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2154 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2156 | loaded into the editor. The syntax is the same of the %macro command. |
|
2155 | loaded into the editor. The syntax is the same of the %macro command. | |
2157 |
|
2156 | |||
2158 | - If the argument doesn't start with a number, it is evaluated as a |
|
2157 | - If the argument doesn't start with a number, it is evaluated as a | |
2159 | variable and its contents loaded into the editor. You can thus edit |
|
2158 | variable and its contents loaded into the editor. You can thus edit | |
2160 | any string which contains python code (including the result of |
|
2159 | any string which contains python code (including the result of | |
2161 | previous edits). |
|
2160 | previous edits). | |
2162 |
|
2161 | |||
2163 | - If the argument is the name of an object (other than a string), |
|
2162 | - If the argument is the name of an object (other than a string), | |
2164 | IPython will try to locate the file where it was defined and open the |
|
2163 | IPython will try to locate the file where it was defined and open the | |
2165 | editor at the point where it is defined. You can use `%edit function` |
|
2164 | editor at the point where it is defined. You can use `%edit function` | |
2166 | to load an editor exactly at the point where 'function' is defined, |
|
2165 | to load an editor exactly at the point where 'function' is defined, | |
2167 | edit it and have the file be executed automatically. |
|
2166 | edit it and have the file be executed automatically. | |
2168 |
|
2167 | |||
2169 | If the object is a macro (see %macro for details), this opens up your |
|
2168 | If the object is a macro (see %macro for details), this opens up your | |
2170 | specified editor with a temporary file containing the macro's data. |
|
2169 | specified editor with a temporary file containing the macro's data. | |
2171 | Upon exit, the macro is reloaded with the contents of the file. |
|
2170 | Upon exit, the macro is reloaded with the contents of the file. | |
2172 |
|
2171 | |||
2173 | Note: opening at an exact line is only supported under Unix, and some |
|
2172 | Note: opening at an exact line is only supported under Unix, and some | |
2174 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2173 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2175 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2174 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2176 | (X)Emacs, vi, jed, pico and joe all do. |
|
2175 | (X)Emacs, vi, jed, pico and joe all do. | |
2177 |
|
2176 | |||
2178 | - If the argument is not found as a variable, IPython will look for a |
|
2177 | - If the argument is not found as a variable, IPython will look for a | |
2179 | file with that name (adding .py if necessary) and load it into the |
|
2178 | file with that name (adding .py if necessary) and load it into the | |
2180 | editor. It will execute its contents with execfile() when you exit, |
|
2179 | editor. It will execute its contents with execfile() when you exit, | |
2181 | loading any code in the file into your interactive namespace. |
|
2180 | loading any code in the file into your interactive namespace. | |
2182 |
|
2181 | |||
2183 | After executing your code, %edit will return as output the code you |
|
2182 | After executing your code, %edit will return as output the code you | |
2184 | typed in the editor (except when it was an existing file). This way |
|
2183 | typed in the editor (except when it was an existing file). This way | |
2185 | you can reload the code in further invocations of %edit as a variable, |
|
2184 | you can reload the code in further invocations of %edit as a variable, | |
2186 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2185 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2187 | the output. |
|
2186 | the output. | |
2188 |
|
2187 | |||
2189 | Note that %edit is also available through the alias %ed. |
|
2188 | Note that %edit is also available through the alias %ed. | |
2190 |
|
2189 | |||
2191 | This is an example of creating a simple function inside the editor and |
|
2190 | This is an example of creating a simple function inside the editor and | |
2192 | then modifying it. First, start up the editor: |
|
2191 | then modifying it. First, start up the editor: | |
2193 |
|
2192 | |||
2194 | In [1]: ed |
|
2193 | In [1]: ed | |
2195 | Editing... done. Executing edited code... |
|
2194 | Editing... done. Executing edited code... | |
2196 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2195 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2197 |
|
2196 | |||
2198 | We can then call the function foo(): |
|
2197 | We can then call the function foo(): | |
2199 |
|
2198 | |||
2200 | In [2]: foo() |
|
2199 | In [2]: foo() | |
2201 | foo() was defined in an editing session |
|
2200 | foo() was defined in an editing session | |
2202 |
|
2201 | |||
2203 | Now we edit foo. IPython automatically loads the editor with the |
|
2202 | Now we edit foo. IPython automatically loads the editor with the | |
2204 | (temporary) file where foo() was previously defined: |
|
2203 | (temporary) file where foo() was previously defined: | |
2205 |
|
2204 | |||
2206 | In [3]: ed foo |
|
2205 | In [3]: ed foo | |
2207 | Editing... done. Executing edited code... |
|
2206 | Editing... done. Executing edited code... | |
2208 |
|
2207 | |||
2209 | And if we call foo() again we get the modified version: |
|
2208 | And if we call foo() again we get the modified version: | |
2210 |
|
2209 | |||
2211 | In [4]: foo() |
|
2210 | In [4]: foo() | |
2212 | foo() has now been changed! |
|
2211 | foo() has now been changed! | |
2213 |
|
2212 | |||
2214 | Here is an example of how to edit a code snippet successive |
|
2213 | Here is an example of how to edit a code snippet successive | |
2215 | times. First we call the editor: |
|
2214 | times. First we call the editor: | |
2216 |
|
2215 | |||
2217 | In [5]: ed |
|
2216 | In [5]: ed | |
2218 | Editing... done. Executing edited code... |
|
2217 | Editing... done. Executing edited code... | |
2219 | hello |
|
2218 | hello | |
2220 | Out[5]: "print 'hello'n" |
|
2219 | Out[5]: "print 'hello'n" | |
2221 |
|
2220 | |||
2222 | Now we call it again with the previous output (stored in _): |
|
2221 | Now we call it again with the previous output (stored in _): | |
2223 |
|
2222 | |||
2224 | In [6]: ed _ |
|
2223 | In [6]: ed _ | |
2225 | Editing... done. Executing edited code... |
|
2224 | Editing... done. Executing edited code... | |
2226 | hello world |
|
2225 | hello world | |
2227 | Out[6]: "print 'hello world'n" |
|
2226 | Out[6]: "print 'hello world'n" | |
2228 |
|
2227 | |||
2229 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2228 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2230 |
|
2229 | |||
2231 | In [7]: ed _8 |
|
2230 | In [7]: ed _8 | |
2232 | Editing... done. Executing edited code... |
|
2231 | Editing... done. Executing edited code... | |
2233 | hello again |
|
2232 | hello again | |
2234 | Out[7]: "print 'hello again'n" |
|
2233 | Out[7]: "print 'hello again'n" | |
2235 |
|
2234 | |||
2236 |
|
2235 | |||
2237 | Changing the default editor hook: |
|
2236 | Changing the default editor hook: | |
2238 |
|
2237 | |||
2239 | If you wish to write your own editor hook, you can put it in a |
|
2238 | If you wish to write your own editor hook, you can put it in a | |
2240 | configuration file which you load at startup time. The default hook |
|
2239 | configuration file which you load at startup time. The default hook | |
2241 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2240 | is defined in the IPython.core.hooks module, and you can use that as a | |
2242 | starting example for further modifications. That file also has |
|
2241 | starting example for further modifications. That file also has | |
2243 | general instructions on how to set a new hook for use once you've |
|
2242 | general instructions on how to set a new hook for use once you've | |
2244 | defined it.""" |
|
2243 | defined it.""" | |
2245 |
|
2244 | |||
2246 | # FIXME: This function has become a convoluted mess. It needs a |
|
2245 | # FIXME: This function has become a convoluted mess. It needs a | |
2247 | # ground-up rewrite with clean, simple logic. |
|
2246 | # ground-up rewrite with clean, simple logic. | |
2248 |
|
2247 | |||
2249 | def make_filename(arg): |
|
2248 | def make_filename(arg): | |
2250 | "Make a filename from the given args" |
|
2249 | "Make a filename from the given args" | |
2251 | try: |
|
2250 | try: | |
2252 | filename = get_py_filename(arg) |
|
2251 | filename = get_py_filename(arg) | |
2253 | except IOError: |
|
2252 | except IOError: | |
2254 | if args.endswith('.py'): |
|
2253 | if args.endswith('.py'): | |
2255 | filename = arg |
|
2254 | filename = arg | |
2256 | else: |
|
2255 | else: | |
2257 | filename = None |
|
2256 | filename = None | |
2258 | return filename |
|
2257 | return filename | |
2259 |
|
2258 | |||
2260 | # custom exceptions |
|
2259 | # custom exceptions | |
2261 | class DataIsObject(Exception): pass |
|
2260 | class DataIsObject(Exception): pass | |
2262 |
|
2261 | |||
2263 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2262 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2264 | # Set a few locals from the options for convenience: |
|
2263 | # Set a few locals from the options for convenience: | |
2265 | opts_p = opts.has_key('p') |
|
2264 | opts_p = opts.has_key('p') | |
2266 | opts_r = opts.has_key('r') |
|
2265 | opts_r = opts.has_key('r') | |
2267 |
|
2266 | |||
2268 | # Default line number value |
|
2267 | # Default line number value | |
2269 | lineno = opts.get('n',None) |
|
2268 | lineno = opts.get('n',None) | |
2270 |
|
2269 | |||
2271 | if opts_p: |
|
2270 | if opts_p: | |
2272 | args = '_%s' % last_call[0] |
|
2271 | args = '_%s' % last_call[0] | |
2273 | if not self.shell.user_ns.has_key(args): |
|
2272 | if not self.shell.user_ns.has_key(args): | |
2274 | args = last_call[1] |
|
2273 | args = last_call[1] | |
2275 |
|
2274 | |||
2276 | # use last_call to remember the state of the previous call, but don't |
|
2275 | # use last_call to remember the state of the previous call, but don't | |
2277 | # let it be clobbered by successive '-p' calls. |
|
2276 | # let it be clobbered by successive '-p' calls. | |
2278 | try: |
|
2277 | try: | |
2279 | last_call[0] = self.shell.displayhook.prompt_count |
|
2278 | last_call[0] = self.shell.displayhook.prompt_count | |
2280 | if not opts_p: |
|
2279 | if not opts_p: | |
2281 | last_call[1] = parameter_s |
|
2280 | last_call[1] = parameter_s | |
2282 | except: |
|
2281 | except: | |
2283 | pass |
|
2282 | pass | |
2284 |
|
2283 | |||
2285 | # by default this is done with temp files, except when the given |
|
2284 | # by default this is done with temp files, except when the given | |
2286 | # arg is a filename |
|
2285 | # arg is a filename | |
2287 | use_temp = True |
|
2286 | use_temp = True | |
2288 |
|
2287 | |||
2289 | data = '' |
|
2288 | data = '' | |
2290 | if args[0].isdigit(): |
|
2289 | if args[0].isdigit(): | |
2291 | # Mode where user specifies ranges of lines, like in %macro. |
|
2290 | # Mode where user specifies ranges of lines, like in %macro. | |
2292 | # This means that you can't edit files whose names begin with |
|
2291 | # This means that you can't edit files whose names begin with | |
2293 | # numbers this way. Tough. |
|
2292 | # numbers this way. Tough. | |
2294 | ranges = args.split() |
|
2293 | ranges = args.split() | |
2295 | data = '\n'.join(self.extract_input_slices(ranges,opts_r)) |
|
2294 | data = '\n'.join(self.extract_input_slices(ranges,opts_r)) | |
2296 | elif args.endswith('.py'): |
|
2295 | elif args.endswith('.py'): | |
2297 | filename = make_filename(args) |
|
2296 | filename = make_filename(args) | |
2298 | use_temp = False |
|
2297 | use_temp = False | |
2299 | elif args: |
|
2298 | elif args: | |
2300 | try: |
|
2299 | try: | |
2301 | # Load the parameter given as a variable. If not a string, |
|
2300 | # Load the parameter given as a variable. If not a string, | |
2302 | # process it as an object instead (below) |
|
2301 | # process it as an object instead (below) | |
2303 |
|
2302 | |||
2304 | #print '*** args',args,'type',type(args) # dbg |
|
2303 | #print '*** args',args,'type',type(args) # dbg | |
2305 | data = eval(args, self.shell.user_ns) |
|
2304 | data = eval(args, self.shell.user_ns) | |
2306 | if not isinstance(data, basestring): |
|
2305 | if not isinstance(data, basestring): | |
2307 | raise DataIsObject |
|
2306 | raise DataIsObject | |
2308 |
|
2307 | |||
2309 | except (NameError,SyntaxError): |
|
2308 | except (NameError,SyntaxError): | |
2310 | # given argument is not a variable, try as a filename |
|
2309 | # given argument is not a variable, try as a filename | |
2311 | filename = make_filename(args) |
|
2310 | filename = make_filename(args) | |
2312 | if filename is None: |
|
2311 | if filename is None: | |
2313 | warn("Argument given (%s) can't be found as a variable " |
|
2312 | warn("Argument given (%s) can't be found as a variable " | |
2314 | "or as a filename." % args) |
|
2313 | "or as a filename." % args) | |
2315 | return |
|
2314 | return | |
2316 | use_temp = False |
|
2315 | use_temp = False | |
2317 |
|
2316 | |||
2318 | except DataIsObject: |
|
2317 | except DataIsObject: | |
2319 | # macros have a special edit function |
|
2318 | # macros have a special edit function | |
2320 | if isinstance(data, Macro): |
|
2319 | if isinstance(data, Macro): | |
2321 | self._edit_macro(args,data) |
|
2320 | self._edit_macro(args,data) | |
2322 | return |
|
2321 | return | |
2323 |
|
2322 | |||
2324 | # For objects, try to edit the file where they are defined |
|
2323 | # For objects, try to edit the file where they are defined | |
2325 | try: |
|
2324 | try: | |
2326 | filename = inspect.getabsfile(data) |
|
2325 | filename = inspect.getabsfile(data) | |
2327 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2326 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2328 | # class created by %edit? Try to find source |
|
2327 | # class created by %edit? Try to find source | |
2329 | # by looking for method definitions instead, the |
|
2328 | # by looking for method definitions instead, the | |
2330 | # __module__ in those classes is FakeModule. |
|
2329 | # __module__ in those classes is FakeModule. | |
2331 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2330 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2332 | for attr in attrs: |
|
2331 | for attr in attrs: | |
2333 | if not inspect.ismethod(attr): |
|
2332 | if not inspect.ismethod(attr): | |
2334 | continue |
|
2333 | continue | |
2335 | filename = inspect.getabsfile(attr) |
|
2334 | filename = inspect.getabsfile(attr) | |
2336 | if filename and 'fakemodule' not in filename.lower(): |
|
2335 | if filename and 'fakemodule' not in filename.lower(): | |
2337 | # change the attribute to be the edit target instead |
|
2336 | # change the attribute to be the edit target instead | |
2338 | data = attr |
|
2337 | data = attr | |
2339 | break |
|
2338 | break | |
2340 |
|
2339 | |||
2341 | datafile = 1 |
|
2340 | datafile = 1 | |
2342 | except TypeError: |
|
2341 | except TypeError: | |
2343 | filename = make_filename(args) |
|
2342 | filename = make_filename(args) | |
2344 | datafile = 1 |
|
2343 | datafile = 1 | |
2345 | warn('Could not find file where `%s` is defined.\n' |
|
2344 | warn('Could not find file where `%s` is defined.\n' | |
2346 | 'Opening a file named `%s`' % (args,filename)) |
|
2345 | 'Opening a file named `%s`' % (args,filename)) | |
2347 | # Now, make sure we can actually read the source (if it was in |
|
2346 | # Now, make sure we can actually read the source (if it was in | |
2348 | # a temp file it's gone by now). |
|
2347 | # a temp file it's gone by now). | |
2349 | if datafile: |
|
2348 | if datafile: | |
2350 | try: |
|
2349 | try: | |
2351 | if lineno is None: |
|
2350 | if lineno is None: | |
2352 | lineno = inspect.getsourcelines(data)[1] |
|
2351 | lineno = inspect.getsourcelines(data)[1] | |
2353 | except IOError: |
|
2352 | except IOError: | |
2354 | filename = make_filename(args) |
|
2353 | filename = make_filename(args) | |
2355 | if filename is None: |
|
2354 | if filename is None: | |
2356 | warn('The file `%s` where `%s` was defined cannot ' |
|
2355 | warn('The file `%s` where `%s` was defined cannot ' | |
2357 | 'be read.' % (filename,data)) |
|
2356 | 'be read.' % (filename,data)) | |
2358 | return |
|
2357 | return | |
2359 | use_temp = False |
|
2358 | use_temp = False | |
2360 |
|
2359 | |||
2361 | if use_temp: |
|
2360 | if use_temp: | |
2362 | filename = self.shell.mktempfile(data) |
|
2361 | filename = self.shell.mktempfile(data) | |
2363 | print 'IPython will make a temporary file named:',filename |
|
2362 | print 'IPython will make a temporary file named:',filename | |
2364 |
|
2363 | |||
2365 | # do actual editing here |
|
2364 | # do actual editing here | |
2366 | print 'Editing...', |
|
2365 | print 'Editing...', | |
2367 | sys.stdout.flush() |
|
2366 | sys.stdout.flush() | |
2368 | try: |
|
2367 | try: | |
2369 | # Quote filenames that may have spaces in them |
|
2368 | # Quote filenames that may have spaces in them | |
2370 | if ' ' in filename: |
|
2369 | if ' ' in filename: | |
2371 | filename = "%s" % filename |
|
2370 | filename = "%s" % filename | |
2372 | self.shell.hooks.editor(filename,lineno) |
|
2371 | self.shell.hooks.editor(filename,lineno) | |
2373 | except TryNext: |
|
2372 | except TryNext: | |
2374 | warn('Could not open editor') |
|
2373 | warn('Could not open editor') | |
2375 | return |
|
2374 | return | |
2376 |
|
2375 | |||
2377 | # XXX TODO: should this be generalized for all string vars? |
|
2376 | # XXX TODO: should this be generalized for all string vars? | |
2378 | # For now, this is special-cased to blocks created by cpaste |
|
2377 | # For now, this is special-cased to blocks created by cpaste | |
2379 | if args.strip() == 'pasted_block': |
|
2378 | if args.strip() == 'pasted_block': | |
2380 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2379 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2381 |
|
2380 | |||
2382 | if 'x' in opts: # -x prevents actual execution |
|
2381 | if 'x' in opts: # -x prevents actual execution | |
2383 |
|
2382 | |||
2384 | else: |
|
2383 | else: | |
2385 | print 'done. Executing edited code...' |
|
2384 | print 'done. Executing edited code...' | |
2386 | if opts_r: |
|
2385 | if opts_r: | |
2387 | self.shell.run_cell(file_read(filename)) |
|
2386 | self.shell.run_cell(file_read(filename)) | |
2388 | else: |
|
2387 | else: | |
2389 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2388 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2390 | self.shell.user_ns) |
|
2389 | self.shell.user_ns) | |
2391 |
|
2390 | |||
2392 |
|
2391 | |||
2393 | if use_temp: |
|
2392 | if use_temp: | |
2394 | try: |
|
2393 | try: | |
2395 | return open(filename).read() |
|
2394 | return open(filename).read() | |
2396 | except IOError,msg: |
|
2395 | except IOError,msg: | |
2397 | if msg.filename == filename: |
|
2396 | if msg.filename == filename: | |
2398 | warn('File not found. Did you forget to save?') |
|
2397 | warn('File not found. Did you forget to save?') | |
2399 | return |
|
2398 | return | |
2400 | else: |
|
2399 | else: | |
2401 | self.shell.showtraceback() |
|
2400 | self.shell.showtraceback() | |
2402 |
|
2401 | |||
2403 | def magic_xmode(self,parameter_s = ''): |
|
2402 | def magic_xmode(self,parameter_s = ''): | |
2404 | """Switch modes for the exception handlers. |
|
2403 | """Switch modes for the exception handlers. | |
2405 |
|
2404 | |||
2406 | Valid modes: Plain, Context and Verbose. |
|
2405 | Valid modes: Plain, Context and Verbose. | |
2407 |
|
2406 | |||
2408 | If called without arguments, acts as a toggle.""" |
|
2407 | If called without arguments, acts as a toggle.""" | |
2409 |
|
2408 | |||
2410 | def xmode_switch_err(name): |
|
2409 | def xmode_switch_err(name): | |
2411 | warn('Error changing %s exception modes.\n%s' % |
|
2410 | warn('Error changing %s exception modes.\n%s' % | |
2412 | (name,sys.exc_info()[1])) |
|
2411 | (name,sys.exc_info()[1])) | |
2413 |
|
2412 | |||
2414 | shell = self.shell |
|
2413 | shell = self.shell | |
2415 | new_mode = parameter_s.strip().capitalize() |
|
2414 | new_mode = parameter_s.strip().capitalize() | |
2416 | try: |
|
2415 | try: | |
2417 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2416 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2418 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2417 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2419 | except: |
|
2418 | except: | |
2420 | xmode_switch_err('user') |
|
2419 | xmode_switch_err('user') | |
2421 |
|
2420 | |||
2422 | def magic_colors(self,parameter_s = ''): |
|
2421 | def magic_colors(self,parameter_s = ''): | |
2423 | """Switch color scheme for prompts, info system and exception handlers. |
|
2422 | """Switch color scheme for prompts, info system and exception handlers. | |
2424 |
|
2423 | |||
2425 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2424 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2426 |
|
2425 | |||
2427 | Color scheme names are not case-sensitive. |
|
2426 | Color scheme names are not case-sensitive. | |
2428 |
|
2427 | |||
2429 | Examples |
|
2428 | Examples | |
2430 | -------- |
|
2429 | -------- | |
2431 | To get a plain black and white terminal:: |
|
2430 | To get a plain black and white terminal:: | |
2432 |
|
2431 | |||
2433 | %colors nocolor |
|
2432 | %colors nocolor | |
2434 | """ |
|
2433 | """ | |
2435 |
|
2434 | |||
2436 | def color_switch_err(name): |
|
2435 | def color_switch_err(name): | |
2437 | warn('Error changing %s color schemes.\n%s' % |
|
2436 | warn('Error changing %s color schemes.\n%s' % | |
2438 | (name,sys.exc_info()[1])) |
|
2437 | (name,sys.exc_info()[1])) | |
2439 |
|
2438 | |||
2440 |
|
2439 | |||
2441 | new_scheme = parameter_s.strip() |
|
2440 | new_scheme = parameter_s.strip() | |
2442 | if not new_scheme: |
|
2441 | if not new_scheme: | |
2443 | raise UsageError( |
|
2442 | raise UsageError( | |
2444 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2443 | "%colors: you must specify a color scheme. See '%colors?'") | |
2445 | return |
|
2444 | return | |
2446 | # local shortcut |
|
2445 | # local shortcut | |
2447 | shell = self.shell |
|
2446 | shell = self.shell | |
2448 |
|
2447 | |||
2449 | import IPython.utils.rlineimpl as readline |
|
2448 | import IPython.utils.rlineimpl as readline | |
2450 |
|
2449 | |||
2451 | if not readline.have_readline and sys.platform == "win32": |
|
2450 | if not readline.have_readline and sys.platform == "win32": | |
2452 | msg = """\ |
|
2451 | msg = """\ | |
2453 | Proper color support under MS Windows requires the pyreadline library. |
|
2452 | Proper color support under MS Windows requires the pyreadline library. | |
2454 | You can find it at: |
|
2453 | You can find it at: | |
2455 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2454 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2456 | Gary's readline needs the ctypes module, from: |
|
2455 | Gary's readline needs the ctypes module, from: | |
2457 | http://starship.python.net/crew/theller/ctypes |
|
2456 | http://starship.python.net/crew/theller/ctypes | |
2458 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2457 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2459 |
|
2458 | |||
2460 | Defaulting color scheme to 'NoColor'""" |
|
2459 | Defaulting color scheme to 'NoColor'""" | |
2461 | new_scheme = 'NoColor' |
|
2460 | new_scheme = 'NoColor' | |
2462 | warn(msg) |
|
2461 | warn(msg) | |
2463 |
|
2462 | |||
2464 | # readline option is 0 |
|
2463 | # readline option is 0 | |
2465 | if not shell.has_readline: |
|
2464 | if not shell.has_readline: | |
2466 | new_scheme = 'NoColor' |
|
2465 | new_scheme = 'NoColor' | |
2467 |
|
2466 | |||
2468 | # Set prompt colors |
|
2467 | # Set prompt colors | |
2469 | try: |
|
2468 | try: | |
2470 | shell.displayhook.set_colors(new_scheme) |
|
2469 | shell.displayhook.set_colors(new_scheme) | |
2471 | except: |
|
2470 | except: | |
2472 | color_switch_err('prompt') |
|
2471 | color_switch_err('prompt') | |
2473 | else: |
|
2472 | else: | |
2474 | shell.colors = \ |
|
2473 | shell.colors = \ | |
2475 | shell.displayhook.color_table.active_scheme_name |
|
2474 | shell.displayhook.color_table.active_scheme_name | |
2476 | # Set exception colors |
|
2475 | # Set exception colors | |
2477 | try: |
|
2476 | try: | |
2478 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2477 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2479 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2478 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2480 | except: |
|
2479 | except: | |
2481 | color_switch_err('exception') |
|
2480 | color_switch_err('exception') | |
2482 |
|
2481 | |||
2483 | # Set info (for 'object?') colors |
|
2482 | # Set info (for 'object?') colors | |
2484 | if shell.color_info: |
|
2483 | if shell.color_info: | |
2485 | try: |
|
2484 | try: | |
2486 | shell.inspector.set_active_scheme(new_scheme) |
|
2485 | shell.inspector.set_active_scheme(new_scheme) | |
2487 | except: |
|
2486 | except: | |
2488 | color_switch_err('object inspector') |
|
2487 | color_switch_err('object inspector') | |
2489 | else: |
|
2488 | else: | |
2490 | shell.inspector.set_active_scheme('NoColor') |
|
2489 | shell.inspector.set_active_scheme('NoColor') | |
2491 |
|
2490 | |||
2492 | def magic_pprint(self, parameter_s=''): |
|
2491 | def magic_pprint(self, parameter_s=''): | |
2493 | """Toggle pretty printing on/off.""" |
|
2492 | """Toggle pretty printing on/off.""" | |
2494 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
2493 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
2495 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
2494 | ptformatter.pprint = bool(1 - ptformatter.pprint) | |
2496 | print 'Pretty printing has been turned', \ |
|
2495 | print 'Pretty printing has been turned', \ | |
2497 | ['OFF','ON'][ptformatter.pprint] |
|
2496 | ['OFF','ON'][ptformatter.pprint] | |
2498 |
|
2497 | |||
2499 | def magic_Exit(self, parameter_s=''): |
|
2498 | def magic_Exit(self, parameter_s=''): | |
2500 | """Exit IPython.""" |
|
2499 | """Exit IPython.""" | |
2501 |
|
2500 | |||
2502 | self.shell.ask_exit() |
|
2501 | self.shell.ask_exit() | |
2503 |
|
2502 | |||
2504 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
2503 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. | |
2505 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
2504 | magic_exit = magic_quit = magic_Quit = magic_Exit | |
2506 |
|
2505 | |||
2507 | #...................................................................... |
|
2506 | #...................................................................... | |
2508 | # Functions to implement unix shell-type things |
|
2507 | # Functions to implement unix shell-type things | |
2509 |
|
2508 | |||
2510 | @testdec.skip_doctest |
|
2509 | @testdec.skip_doctest | |
2511 | def magic_alias(self, parameter_s = ''): |
|
2510 | def magic_alias(self, parameter_s = ''): | |
2512 | """Define an alias for a system command. |
|
2511 | """Define an alias for a system command. | |
2513 |
|
2512 | |||
2514 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2513 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2515 |
|
2514 | |||
2516 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2515 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2517 | params' (from your underlying operating system). |
|
2516 | params' (from your underlying operating system). | |
2518 |
|
2517 | |||
2519 | Aliases have lower precedence than magic functions and Python normal |
|
2518 | Aliases have lower precedence than magic functions and Python normal | |
2520 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2519 | variables, so if 'foo' is both a Python variable and an alias, the | |
2521 | alias can not be executed until 'del foo' removes the Python variable. |
|
2520 | alias can not be executed until 'del foo' removes the Python variable. | |
2522 |
|
2521 | |||
2523 | You can use the %l specifier in an alias definition to represent the |
|
2522 | You can use the %l specifier in an alias definition to represent the | |
2524 | whole line when the alias is called. For example: |
|
2523 | whole line when the alias is called. For example: | |
2525 |
|
2524 | |||
2526 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2525 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2527 | In [3]: bracket hello world |
|
2526 | In [3]: bracket hello world | |
2528 | Input in brackets: <hello world> |
|
2527 | Input in brackets: <hello world> | |
2529 |
|
2528 | |||
2530 | You can also define aliases with parameters using %s specifiers (one |
|
2529 | You can also define aliases with parameters using %s specifiers (one | |
2531 | per parameter): |
|
2530 | per parameter): | |
2532 |
|
2531 | |||
2533 | In [1]: alias parts echo first %s second %s |
|
2532 | In [1]: alias parts echo first %s second %s | |
2534 | In [2]: %parts A B |
|
2533 | In [2]: %parts A B | |
2535 | first A second B |
|
2534 | first A second B | |
2536 | In [3]: %parts A |
|
2535 | In [3]: %parts A | |
2537 | Incorrect number of arguments: 2 expected. |
|
2536 | Incorrect number of arguments: 2 expected. | |
2538 | parts is an alias to: 'echo first %s second %s' |
|
2537 | parts is an alias to: 'echo first %s second %s' | |
2539 |
|
2538 | |||
2540 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2539 | Note that %l and %s are mutually exclusive. You can only use one or | |
2541 | the other in your aliases. |
|
2540 | the other in your aliases. | |
2542 |
|
2541 | |||
2543 | Aliases expand Python variables just like system calls using ! or !! |
|
2542 | Aliases expand Python variables just like system calls using ! or !! | |
2544 | do: all expressions prefixed with '$' get expanded. For details of |
|
2543 | do: all expressions prefixed with '$' get expanded. For details of | |
2545 | the semantic rules, see PEP-215: |
|
2544 | the semantic rules, see PEP-215: | |
2546 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2545 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2547 | IPython for variable expansion. If you want to access a true shell |
|
2546 | IPython for variable expansion. If you want to access a true shell | |
2548 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2547 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2549 |
|
2548 | |||
2550 | In [6]: alias show echo |
|
2549 | In [6]: alias show echo | |
2551 | In [7]: PATH='A Python string' |
|
2550 | In [7]: PATH='A Python string' | |
2552 | In [8]: show $PATH |
|
2551 | In [8]: show $PATH | |
2553 | A Python string |
|
2552 | A Python string | |
2554 | In [9]: show $$PATH |
|
2553 | In [9]: show $$PATH | |
2555 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2554 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2556 |
|
2555 | |||
2557 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2556 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2558 | and %rehashx functions, which automatically create aliases for the |
|
2557 | and %rehashx functions, which automatically create aliases for the | |
2559 | contents of your $PATH. |
|
2558 | contents of your $PATH. | |
2560 |
|
2559 | |||
2561 | If called with no parameters, %alias prints the current alias table.""" |
|
2560 | If called with no parameters, %alias prints the current alias table.""" | |
2562 |
|
2561 | |||
2563 | par = parameter_s.strip() |
|
2562 | par = parameter_s.strip() | |
2564 | if not par: |
|
2563 | if not par: | |
2565 | stored = self.db.get('stored_aliases', {} ) |
|
2564 | stored = self.db.get('stored_aliases', {} ) | |
2566 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2565 | aliases = sorted(self.shell.alias_manager.aliases) | |
2567 | # for k, v in stored: |
|
2566 | # for k, v in stored: | |
2568 | # atab.append(k, v[0]) |
|
2567 | # atab.append(k, v[0]) | |
2569 |
|
2568 | |||
2570 | print "Total number of aliases:", len(aliases) |
|
2569 | print "Total number of aliases:", len(aliases) | |
2571 | sys.stdout.flush() |
|
2570 | sys.stdout.flush() | |
2572 | return aliases |
|
2571 | return aliases | |
2573 |
|
2572 | |||
2574 | # Now try to define a new one |
|
2573 | # Now try to define a new one | |
2575 | try: |
|
2574 | try: | |
2576 | alias,cmd = par.split(None, 1) |
|
2575 | alias,cmd = par.split(None, 1) | |
2577 | except: |
|
2576 | except: | |
2578 | print oinspect.getdoc(self.magic_alias) |
|
2577 | print oinspect.getdoc(self.magic_alias) | |
2579 | else: |
|
2578 | else: | |
2580 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2579 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2581 | # end magic_alias |
|
2580 | # end magic_alias | |
2582 |
|
2581 | |||
2583 | def magic_unalias(self, parameter_s = ''): |
|
2582 | def magic_unalias(self, parameter_s = ''): | |
2584 | """Remove an alias""" |
|
2583 | """Remove an alias""" | |
2585 |
|
2584 | |||
2586 | aname = parameter_s.strip() |
|
2585 | aname = parameter_s.strip() | |
2587 | self.shell.alias_manager.undefine_alias(aname) |
|
2586 | self.shell.alias_manager.undefine_alias(aname) | |
2588 | stored = self.db.get('stored_aliases', {} ) |
|
2587 | stored = self.db.get('stored_aliases', {} ) | |
2589 | if aname in stored: |
|
2588 | if aname in stored: | |
2590 | print "Removing %stored alias",aname |
|
2589 | print "Removing %stored alias",aname | |
2591 | del stored[aname] |
|
2590 | del stored[aname] | |
2592 | self.db['stored_aliases'] = stored |
|
2591 | self.db['stored_aliases'] = stored | |
2593 |
|
2592 | |||
2594 | def magic_rehashx(self, parameter_s = ''): |
|
2593 | def magic_rehashx(self, parameter_s = ''): | |
2595 | """Update the alias table with all executable files in $PATH. |
|
2594 | """Update the alias table with all executable files in $PATH. | |
2596 |
|
2595 | |||
2597 | This version explicitly checks that every entry in $PATH is a file |
|
2596 | This version explicitly checks that every entry in $PATH is a file | |
2598 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2597 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2599 |
|
2598 | |||
2600 | Under Windows, it checks executability as a match agains a |
|
2599 | Under Windows, it checks executability as a match agains a | |
2601 | '|'-separated string of extensions, stored in the IPython config |
|
2600 | '|'-separated string of extensions, stored in the IPython config | |
2602 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2601 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2603 |
|
2602 | |||
2604 | This function also resets the root module cache of module completer, |
|
2603 | This function also resets the root module cache of module completer, | |
2605 | used on slow filesystems. |
|
2604 | used on slow filesystems. | |
2606 | """ |
|
2605 | """ | |
2607 | from IPython.core.alias import InvalidAliasError |
|
2606 | from IPython.core.alias import InvalidAliasError | |
2608 |
|
2607 | |||
2609 | # for the benefit of module completer in ipy_completers.py |
|
2608 | # for the benefit of module completer in ipy_completers.py | |
2610 | del self.db['rootmodules'] |
|
2609 | del self.db['rootmodules'] | |
2611 |
|
2610 | |||
2612 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2611 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2613 | os.environ.get('PATH','').split(os.pathsep)] |
|
2612 | os.environ.get('PATH','').split(os.pathsep)] | |
2614 | path = filter(os.path.isdir,path) |
|
2613 | path = filter(os.path.isdir,path) | |
2615 |
|
2614 | |||
2616 | syscmdlist = [] |
|
2615 | syscmdlist = [] | |
2617 | # Now define isexec in a cross platform manner. |
|
2616 | # Now define isexec in a cross platform manner. | |
2618 | if os.name == 'posix': |
|
2617 | if os.name == 'posix': | |
2619 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2618 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2620 | os.access(fname,os.X_OK) |
|
2619 | os.access(fname,os.X_OK) | |
2621 | else: |
|
2620 | else: | |
2622 | try: |
|
2621 | try: | |
2623 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2622 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2624 | except KeyError: |
|
2623 | except KeyError: | |
2625 | winext = 'exe|com|bat|py' |
|
2624 | winext = 'exe|com|bat|py' | |
2626 | if 'py' not in winext: |
|
2625 | if 'py' not in winext: | |
2627 | winext += '|py' |
|
2626 | winext += '|py' | |
2628 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2627 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2629 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2628 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2630 | savedir = os.getcwd() |
|
2629 | savedir = os.getcwd() | |
2631 |
|
2630 | |||
2632 | # Now walk the paths looking for executables to alias. |
|
2631 | # Now walk the paths looking for executables to alias. | |
2633 | try: |
|
2632 | try: | |
2634 | # write the whole loop for posix/Windows so we don't have an if in |
|
2633 | # write the whole loop for posix/Windows so we don't have an if in | |
2635 | # the innermost part |
|
2634 | # the innermost part | |
2636 | if os.name == 'posix': |
|
2635 | if os.name == 'posix': | |
2637 | for pdir in path: |
|
2636 | for pdir in path: | |
2638 | os.chdir(pdir) |
|
2637 | os.chdir(pdir) | |
2639 | for ff in os.listdir(pdir): |
|
2638 | for ff in os.listdir(pdir): | |
2640 | if isexec(ff): |
|
2639 | if isexec(ff): | |
2641 | try: |
|
2640 | try: | |
2642 | # Removes dots from the name since ipython |
|
2641 | # Removes dots from the name since ipython | |
2643 | # will assume names with dots to be python. |
|
2642 | # will assume names with dots to be python. | |
2644 | self.shell.alias_manager.define_alias( |
|
2643 | self.shell.alias_manager.define_alias( | |
2645 | ff.replace('.',''), ff) |
|
2644 | ff.replace('.',''), ff) | |
2646 | except InvalidAliasError: |
|
2645 | except InvalidAliasError: | |
2647 | pass |
|
2646 | pass | |
2648 | else: |
|
2647 | else: | |
2649 | syscmdlist.append(ff) |
|
2648 | syscmdlist.append(ff) | |
2650 | else: |
|
2649 | else: | |
2651 | no_alias = self.shell.alias_manager.no_alias |
|
2650 | no_alias = self.shell.alias_manager.no_alias | |
2652 | for pdir in path: |
|
2651 | for pdir in path: | |
2653 | os.chdir(pdir) |
|
2652 | os.chdir(pdir) | |
2654 | for ff in os.listdir(pdir): |
|
2653 | for ff in os.listdir(pdir): | |
2655 | base, ext = os.path.splitext(ff) |
|
2654 | base, ext = os.path.splitext(ff) | |
2656 | if isexec(ff) and base.lower() not in no_alias: |
|
2655 | if isexec(ff) and base.lower() not in no_alias: | |
2657 | if ext.lower() == '.exe': |
|
2656 | if ext.lower() == '.exe': | |
2658 | ff = base |
|
2657 | ff = base | |
2659 | try: |
|
2658 | try: | |
2660 | # Removes dots from the name since ipython |
|
2659 | # Removes dots from the name since ipython | |
2661 | # will assume names with dots to be python. |
|
2660 | # will assume names with dots to be python. | |
2662 | self.shell.alias_manager.define_alias( |
|
2661 | self.shell.alias_manager.define_alias( | |
2663 | base.lower().replace('.',''), ff) |
|
2662 | base.lower().replace('.',''), ff) | |
2664 | except InvalidAliasError: |
|
2663 | except InvalidAliasError: | |
2665 | pass |
|
2664 | pass | |
2666 | syscmdlist.append(ff) |
|
2665 | syscmdlist.append(ff) | |
2667 | db = self.db |
|
2666 | db = self.db | |
2668 | db['syscmdlist'] = syscmdlist |
|
2667 | db['syscmdlist'] = syscmdlist | |
2669 | finally: |
|
2668 | finally: | |
2670 | os.chdir(savedir) |
|
2669 | os.chdir(savedir) | |
2671 |
|
2670 | |||
2672 | @testdec.skip_doctest |
|
2671 | @testdec.skip_doctest | |
2673 | def magic_pwd(self, parameter_s = ''): |
|
2672 | def magic_pwd(self, parameter_s = ''): | |
2674 | """Return the current working directory path. |
|
2673 | """Return the current working directory path. | |
2675 |
|
2674 | |||
2676 | Examples |
|
2675 | Examples | |
2677 | -------- |
|
2676 | -------- | |
2678 | :: |
|
2677 | :: | |
2679 |
|
2678 | |||
2680 | In [9]: pwd |
|
2679 | In [9]: pwd | |
2681 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2680 | Out[9]: '/home/tsuser/sprint/ipython' | |
2682 | """ |
|
2681 | """ | |
2683 | return os.getcwd() |
|
2682 | return os.getcwd() | |
2684 |
|
2683 | |||
2685 | @testdec.skip_doctest |
|
2684 | @testdec.skip_doctest | |
2686 | def magic_cd(self, parameter_s=''): |
|
2685 | def magic_cd(self, parameter_s=''): | |
2687 | """Change the current working directory. |
|
2686 | """Change the current working directory. | |
2688 |
|
2687 | |||
2689 | This command automatically maintains an internal list of directories |
|
2688 | This command automatically maintains an internal list of directories | |
2690 | you visit during your IPython session, in the variable _dh. The |
|
2689 | you visit during your IPython session, in the variable _dh. The | |
2691 | command %dhist shows this history nicely formatted. You can also |
|
2690 | command %dhist shows this history nicely formatted. You can also | |
2692 | do 'cd -<tab>' to see directory history conveniently. |
|
2691 | do 'cd -<tab>' to see directory history conveniently. | |
2693 |
|
2692 | |||
2694 | Usage: |
|
2693 | Usage: | |
2695 |
|
2694 | |||
2696 | cd 'dir': changes to directory 'dir'. |
|
2695 | cd 'dir': changes to directory 'dir'. | |
2697 |
|
2696 | |||
2698 | cd -: changes to the last visited directory. |
|
2697 | cd -: changes to the last visited directory. | |
2699 |
|
2698 | |||
2700 | cd -<n>: changes to the n-th directory in the directory history. |
|
2699 | cd -<n>: changes to the n-th directory in the directory history. | |
2701 |
|
2700 | |||
2702 | cd --foo: change to directory that matches 'foo' in history |
|
2701 | cd --foo: change to directory that matches 'foo' in history | |
2703 |
|
2702 | |||
2704 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2703 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2705 | (note: cd <bookmark_name> is enough if there is no |
|
2704 | (note: cd <bookmark_name> is enough if there is no | |
2706 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2705 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2707 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2706 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2708 |
|
2707 | |||
2709 | Options: |
|
2708 | Options: | |
2710 |
|
2709 | |||
2711 | -q: quiet. Do not print the working directory after the cd command is |
|
2710 | -q: quiet. Do not print the working directory after the cd command is | |
2712 | executed. By default IPython's cd command does print this directory, |
|
2711 | executed. By default IPython's cd command does print this directory, | |
2713 | since the default prompts do not display path information. |
|
2712 | since the default prompts do not display path information. | |
2714 |
|
2713 | |||
2715 | Note that !cd doesn't work for this purpose because the shell where |
|
2714 | Note that !cd doesn't work for this purpose because the shell where | |
2716 | !command runs is immediately discarded after executing 'command'. |
|
2715 | !command runs is immediately discarded after executing 'command'. | |
2717 |
|
2716 | |||
2718 | Examples |
|
2717 | Examples | |
2719 | -------- |
|
2718 | -------- | |
2720 | :: |
|
2719 | :: | |
2721 |
|
2720 | |||
2722 | In [10]: cd parent/child |
|
2721 | In [10]: cd parent/child | |
2723 | /home/tsuser/parent/child |
|
2722 | /home/tsuser/parent/child | |
2724 | """ |
|
2723 | """ | |
2725 |
|
2724 | |||
2726 | parameter_s = parameter_s.strip() |
|
2725 | parameter_s = parameter_s.strip() | |
2727 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2726 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2728 |
|
2727 | |||
2729 | oldcwd = os.getcwd() |
|
2728 | oldcwd = os.getcwd() | |
2730 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2729 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2731 | # jump in directory history by number |
|
2730 | # jump in directory history by number | |
2732 | if numcd: |
|
2731 | if numcd: | |
2733 | nn = int(numcd.group(2)) |
|
2732 | nn = int(numcd.group(2)) | |
2734 | try: |
|
2733 | try: | |
2735 | ps = self.shell.user_ns['_dh'][nn] |
|
2734 | ps = self.shell.user_ns['_dh'][nn] | |
2736 | except IndexError: |
|
2735 | except IndexError: | |
2737 | print 'The requested directory does not exist in history.' |
|
2736 | print 'The requested directory does not exist in history.' | |
2738 | return |
|
2737 | return | |
2739 | else: |
|
2738 | else: | |
2740 | opts = {} |
|
2739 | opts = {} | |
2741 | elif parameter_s.startswith('--'): |
|
2740 | elif parameter_s.startswith('--'): | |
2742 | ps = None |
|
2741 | ps = None | |
2743 | fallback = None |
|
2742 | fallback = None | |
2744 | pat = parameter_s[2:] |
|
2743 | pat = parameter_s[2:] | |
2745 | dh = self.shell.user_ns['_dh'] |
|
2744 | dh = self.shell.user_ns['_dh'] | |
2746 | # first search only by basename (last component) |
|
2745 | # first search only by basename (last component) | |
2747 | for ent in reversed(dh): |
|
2746 | for ent in reversed(dh): | |
2748 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2747 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2749 | ps = ent |
|
2748 | ps = ent | |
2750 | break |
|
2749 | break | |
2751 |
|
2750 | |||
2752 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2751 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2753 | fallback = ent |
|
2752 | fallback = ent | |
2754 |
|
2753 | |||
2755 | # if we have no last part match, pick the first full path match |
|
2754 | # if we have no last part match, pick the first full path match | |
2756 | if ps is None: |
|
2755 | if ps is None: | |
2757 | ps = fallback |
|
2756 | ps = fallback | |
2758 |
|
2757 | |||
2759 | if ps is None: |
|
2758 | if ps is None: | |
2760 | print "No matching entry in directory history" |
|
2759 | print "No matching entry in directory history" | |
2761 | return |
|
2760 | return | |
2762 | else: |
|
2761 | else: | |
2763 | opts = {} |
|
2762 | opts = {} | |
2764 |
|
2763 | |||
2765 |
|
2764 | |||
2766 | else: |
|
2765 | else: | |
2767 | #turn all non-space-escaping backslashes to slashes, |
|
2766 | #turn all non-space-escaping backslashes to slashes, | |
2768 | # for c:\windows\directory\names\ |
|
2767 | # for c:\windows\directory\names\ | |
2769 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2768 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2770 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2769 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2771 | # jump to previous |
|
2770 | # jump to previous | |
2772 | if ps == '-': |
|
2771 | if ps == '-': | |
2773 | try: |
|
2772 | try: | |
2774 | ps = self.shell.user_ns['_dh'][-2] |
|
2773 | ps = self.shell.user_ns['_dh'][-2] | |
2775 | except IndexError: |
|
2774 | except IndexError: | |
2776 | raise UsageError('%cd -: No previous directory to change to.') |
|
2775 | raise UsageError('%cd -: No previous directory to change to.') | |
2777 | # jump to bookmark if needed |
|
2776 | # jump to bookmark if needed | |
2778 | else: |
|
2777 | else: | |
2779 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2778 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2780 | bkms = self.db.get('bookmarks', {}) |
|
2779 | bkms = self.db.get('bookmarks', {}) | |
2781 |
|
2780 | |||
2782 | if bkms.has_key(ps): |
|
2781 | if bkms.has_key(ps): | |
2783 | target = bkms[ps] |
|
2782 | target = bkms[ps] | |
2784 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2783 | print '(bookmark:%s) -> %s' % (ps,target) | |
2785 | ps = target |
|
2784 | ps = target | |
2786 | else: |
|
2785 | else: | |
2787 | if opts.has_key('b'): |
|
2786 | if opts.has_key('b'): | |
2788 | raise UsageError("Bookmark '%s' not found. " |
|
2787 | raise UsageError("Bookmark '%s' not found. " | |
2789 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2788 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2790 |
|
2789 | |||
2791 | # at this point ps should point to the target dir |
|
2790 | # at this point ps should point to the target dir | |
2792 | if ps: |
|
2791 | if ps: | |
2793 | try: |
|
2792 | try: | |
2794 | os.chdir(os.path.expanduser(ps)) |
|
2793 | os.chdir(os.path.expanduser(ps)) | |
2795 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2794 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2796 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2795 | set_term_title('IPython: ' + abbrev_cwd()) | |
2797 | except OSError: |
|
2796 | except OSError: | |
2798 | print sys.exc_info()[1] |
|
2797 | print sys.exc_info()[1] | |
2799 | else: |
|
2798 | else: | |
2800 | cwd = os.getcwd() |
|
2799 | cwd = os.getcwd() | |
2801 | dhist = self.shell.user_ns['_dh'] |
|
2800 | dhist = self.shell.user_ns['_dh'] | |
2802 | if oldcwd != cwd: |
|
2801 | if oldcwd != cwd: | |
2803 | dhist.append(cwd) |
|
2802 | dhist.append(cwd) | |
2804 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2803 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2805 |
|
2804 | |||
2806 | else: |
|
2805 | else: | |
2807 | os.chdir(self.shell.home_dir) |
|
2806 | os.chdir(self.shell.home_dir) | |
2808 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2807 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2809 | set_term_title('IPython: ' + '~') |
|
2808 | set_term_title('IPython: ' + '~') | |
2810 | cwd = os.getcwd() |
|
2809 | cwd = os.getcwd() | |
2811 | dhist = self.shell.user_ns['_dh'] |
|
2810 | dhist = self.shell.user_ns['_dh'] | |
2812 |
|
2811 | |||
2813 | if oldcwd != cwd: |
|
2812 | if oldcwd != cwd: | |
2814 | dhist.append(cwd) |
|
2813 | dhist.append(cwd) | |
2815 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2814 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2816 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2815 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2817 | print self.shell.user_ns['_dh'][-1] |
|
2816 | print self.shell.user_ns['_dh'][-1] | |
2818 |
|
2817 | |||
2819 |
|
2818 | |||
2820 | def magic_env(self, parameter_s=''): |
|
2819 | def magic_env(self, parameter_s=''): | |
2821 | """List environment variables.""" |
|
2820 | """List environment variables.""" | |
2822 |
|
2821 | |||
2823 | return os.environ.data |
|
2822 | return os.environ.data | |
2824 |
|
2823 | |||
2825 | def magic_pushd(self, parameter_s=''): |
|
2824 | def magic_pushd(self, parameter_s=''): | |
2826 | """Place the current dir on stack and change directory. |
|
2825 | """Place the current dir on stack and change directory. | |
2827 |
|
2826 | |||
2828 | Usage:\\ |
|
2827 | Usage:\\ | |
2829 | %pushd ['dirname'] |
|
2828 | %pushd ['dirname'] | |
2830 | """ |
|
2829 | """ | |
2831 |
|
2830 | |||
2832 | dir_s = self.shell.dir_stack |
|
2831 | dir_s = self.shell.dir_stack | |
2833 | tgt = os.path.expanduser(parameter_s) |
|
2832 | tgt = os.path.expanduser(parameter_s) | |
2834 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2833 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2835 | if tgt: |
|
2834 | if tgt: | |
2836 | self.magic_cd(parameter_s) |
|
2835 | self.magic_cd(parameter_s) | |
2837 | dir_s.insert(0,cwd) |
|
2836 | dir_s.insert(0,cwd) | |
2838 | return self.magic_dirs() |
|
2837 | return self.magic_dirs() | |
2839 |
|
2838 | |||
2840 | def magic_popd(self, parameter_s=''): |
|
2839 | def magic_popd(self, parameter_s=''): | |
2841 | """Change to directory popped off the top of the stack. |
|
2840 | """Change to directory popped off the top of the stack. | |
2842 | """ |
|
2841 | """ | |
2843 | if not self.shell.dir_stack: |
|
2842 | if not self.shell.dir_stack: | |
2844 | raise UsageError("%popd on empty stack") |
|
2843 | raise UsageError("%popd on empty stack") | |
2845 | top = self.shell.dir_stack.pop(0) |
|
2844 | top = self.shell.dir_stack.pop(0) | |
2846 | self.magic_cd(top) |
|
2845 | self.magic_cd(top) | |
2847 | print "popd ->",top |
|
2846 | print "popd ->",top | |
2848 |
|
2847 | |||
2849 | def magic_dirs(self, parameter_s=''): |
|
2848 | def magic_dirs(self, parameter_s=''): | |
2850 | """Return the current directory stack.""" |
|
2849 | """Return the current directory stack.""" | |
2851 |
|
2850 | |||
2852 | return self.shell.dir_stack |
|
2851 | return self.shell.dir_stack | |
2853 |
|
2852 | |||
2854 | def magic_dhist(self, parameter_s=''): |
|
2853 | def magic_dhist(self, parameter_s=''): | |
2855 | """Print your history of visited directories. |
|
2854 | """Print your history of visited directories. | |
2856 |
|
2855 | |||
2857 | %dhist -> print full history\\ |
|
2856 | %dhist -> print full history\\ | |
2858 | %dhist n -> print last n entries only\\ |
|
2857 | %dhist n -> print last n entries only\\ | |
2859 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2858 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2860 |
|
2859 | |||
2861 | This history is automatically maintained by the %cd command, and |
|
2860 | This history is automatically maintained by the %cd command, and | |
2862 | always available as the global list variable _dh. You can use %cd -<n> |
|
2861 | always available as the global list variable _dh. You can use %cd -<n> | |
2863 | to go to directory number <n>. |
|
2862 | to go to directory number <n>. | |
2864 |
|
2863 | |||
2865 | Note that most of time, you should view directory history by entering |
|
2864 | Note that most of time, you should view directory history by entering | |
2866 | cd -<TAB>. |
|
2865 | cd -<TAB>. | |
2867 |
|
2866 | |||
2868 | """ |
|
2867 | """ | |
2869 |
|
2868 | |||
2870 | dh = self.shell.user_ns['_dh'] |
|
2869 | dh = self.shell.user_ns['_dh'] | |
2871 | if parameter_s: |
|
2870 | if parameter_s: | |
2872 | try: |
|
2871 | try: | |
2873 | args = map(int,parameter_s.split()) |
|
2872 | args = map(int,parameter_s.split()) | |
2874 | except: |
|
2873 | except: | |
2875 | self.arg_err(Magic.magic_dhist) |
|
2874 | self.arg_err(Magic.magic_dhist) | |
2876 | return |
|
2875 | return | |
2877 | if len(args) == 1: |
|
2876 | if len(args) == 1: | |
2878 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2877 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2879 | elif len(args) == 2: |
|
2878 | elif len(args) == 2: | |
2880 | ini,fin = args |
|
2879 | ini,fin = args | |
2881 | else: |
|
2880 | else: | |
2882 | self.arg_err(Magic.magic_dhist) |
|
2881 | self.arg_err(Magic.magic_dhist) | |
2883 | return |
|
2882 | return | |
2884 | else: |
|
2883 | else: | |
2885 | ini,fin = 0,len(dh) |
|
2884 | ini,fin = 0,len(dh) | |
2886 | nlprint(dh, |
|
2885 | nlprint(dh, | |
2887 | header = 'Directory history (kept in _dh)', |
|
2886 | header = 'Directory history (kept in _dh)', | |
2888 | start=ini,stop=fin) |
|
2887 | start=ini,stop=fin) | |
2889 |
|
2888 | |||
2890 | @testdec.skip_doctest |
|
2889 | @testdec.skip_doctest | |
2891 | def magic_sc(self, parameter_s=''): |
|
2890 | def magic_sc(self, parameter_s=''): | |
2892 | """Shell capture - execute a shell command and capture its output. |
|
2891 | """Shell capture - execute a shell command and capture its output. | |
2893 |
|
2892 | |||
2894 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2893 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2895 |
|
2894 | |||
2896 | You should use the form 'var = !command' instead. Example: |
|
2895 | You should use the form 'var = !command' instead. Example: | |
2897 |
|
2896 | |||
2898 | "%sc -l myfiles = ls ~" should now be written as |
|
2897 | "%sc -l myfiles = ls ~" should now be written as | |
2899 |
|
2898 | |||
2900 | "myfiles = !ls ~" |
|
2899 | "myfiles = !ls ~" | |
2901 |
|
2900 | |||
2902 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2901 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2903 | below. |
|
2902 | below. | |
2904 |
|
2903 | |||
2905 | -- |
|
2904 | -- | |
2906 | %sc [options] varname=command |
|
2905 | %sc [options] varname=command | |
2907 |
|
2906 | |||
2908 | IPython will run the given command using commands.getoutput(), and |
|
2907 | IPython will run the given command using commands.getoutput(), and | |
2909 | will then update the user's interactive namespace with a variable |
|
2908 | will then update the user's interactive namespace with a variable | |
2910 | called varname, containing the value of the call. Your command can |
|
2909 | called varname, containing the value of the call. Your command can | |
2911 | contain shell wildcards, pipes, etc. |
|
2910 | contain shell wildcards, pipes, etc. | |
2912 |
|
2911 | |||
2913 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2912 | The '=' sign in the syntax is mandatory, and the variable name you | |
2914 | supply must follow Python's standard conventions for valid names. |
|
2913 | supply must follow Python's standard conventions for valid names. | |
2915 |
|
2914 | |||
2916 | (A special format without variable name exists for internal use) |
|
2915 | (A special format without variable name exists for internal use) | |
2917 |
|
2916 | |||
2918 | Options: |
|
2917 | Options: | |
2919 |
|
2918 | |||
2920 | -l: list output. Split the output on newlines into a list before |
|
2919 | -l: list output. Split the output on newlines into a list before | |
2921 | assigning it to the given variable. By default the output is stored |
|
2920 | assigning it to the given variable. By default the output is stored | |
2922 | as a single string. |
|
2921 | as a single string. | |
2923 |
|
2922 | |||
2924 | -v: verbose. Print the contents of the variable. |
|
2923 | -v: verbose. Print the contents of the variable. | |
2925 |
|
2924 | |||
2926 | In most cases you should not need to split as a list, because the |
|
2925 | In most cases you should not need to split as a list, because the | |
2927 | returned value is a special type of string which can automatically |
|
2926 | returned value is a special type of string which can automatically | |
2928 | provide its contents either as a list (split on newlines) or as a |
|
2927 | provide its contents either as a list (split on newlines) or as a | |
2929 | space-separated string. These are convenient, respectively, either |
|
2928 | space-separated string. These are convenient, respectively, either | |
2930 | for sequential processing or to be passed to a shell command. |
|
2929 | for sequential processing or to be passed to a shell command. | |
2931 |
|
2930 | |||
2932 | For example: |
|
2931 | For example: | |
2933 |
|
2932 | |||
2934 | # all-random |
|
2933 | # all-random | |
2935 |
|
2934 | |||
2936 | # Capture into variable a |
|
2935 | # Capture into variable a | |
2937 | In [1]: sc a=ls *py |
|
2936 | In [1]: sc a=ls *py | |
2938 |
|
2937 | |||
2939 | # a is a string with embedded newlines |
|
2938 | # a is a string with embedded newlines | |
2940 | In [2]: a |
|
2939 | In [2]: a | |
2941 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2940 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2942 |
|
2941 | |||
2943 | # which can be seen as a list: |
|
2942 | # which can be seen as a list: | |
2944 | In [3]: a.l |
|
2943 | In [3]: a.l | |
2945 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2944 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2946 |
|
2945 | |||
2947 | # or as a whitespace-separated string: |
|
2946 | # or as a whitespace-separated string: | |
2948 | In [4]: a.s |
|
2947 | In [4]: a.s | |
2949 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2948 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2950 |
|
2949 | |||
2951 | # a.s is useful to pass as a single command line: |
|
2950 | # a.s is useful to pass as a single command line: | |
2952 | In [5]: !wc -l $a.s |
|
2951 | In [5]: !wc -l $a.s | |
2953 | 146 setup.py |
|
2952 | 146 setup.py | |
2954 | 130 win32_manual_post_install.py |
|
2953 | 130 win32_manual_post_install.py | |
2955 | 276 total |
|
2954 | 276 total | |
2956 |
|
2955 | |||
2957 | # while the list form is useful to loop over: |
|
2956 | # while the list form is useful to loop over: | |
2958 | In [6]: for f in a.l: |
|
2957 | In [6]: for f in a.l: | |
2959 | ...: !wc -l $f |
|
2958 | ...: !wc -l $f | |
2960 | ...: |
|
2959 | ...: | |
2961 | 146 setup.py |
|
2960 | 146 setup.py | |
2962 | 130 win32_manual_post_install.py |
|
2961 | 130 win32_manual_post_install.py | |
2963 |
|
2962 | |||
2964 | Similiarly, the lists returned by the -l option are also special, in |
|
2963 | Similiarly, the lists returned by the -l option are also special, in | |
2965 | the sense that you can equally invoke the .s attribute on them to |
|
2964 | the sense that you can equally invoke the .s attribute on them to | |
2966 | automatically get a whitespace-separated string from their contents: |
|
2965 | automatically get a whitespace-separated string from their contents: | |
2967 |
|
2966 | |||
2968 | In [7]: sc -l b=ls *py |
|
2967 | In [7]: sc -l b=ls *py | |
2969 |
|
2968 | |||
2970 | In [8]: b |
|
2969 | In [8]: b | |
2971 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2970 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2972 |
|
2971 | |||
2973 | In [9]: b.s |
|
2972 | In [9]: b.s | |
2974 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2973 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2975 |
|
2974 | |||
2976 | In summary, both the lists and strings used for ouptut capture have |
|
2975 | In summary, both the lists and strings used for ouptut capture have | |
2977 | the following special attributes: |
|
2976 | the following special attributes: | |
2978 |
|
2977 | |||
2979 | .l (or .list) : value as list. |
|
2978 | .l (or .list) : value as list. | |
2980 | .n (or .nlstr): value as newline-separated string. |
|
2979 | .n (or .nlstr): value as newline-separated string. | |
2981 | .s (or .spstr): value as space-separated string. |
|
2980 | .s (or .spstr): value as space-separated string. | |
2982 | """ |
|
2981 | """ | |
2983 |
|
2982 | |||
2984 | opts,args = self.parse_options(parameter_s,'lv') |
|
2983 | opts,args = self.parse_options(parameter_s,'lv') | |
2985 | # Try to get a variable name and command to run |
|
2984 | # Try to get a variable name and command to run | |
2986 | try: |
|
2985 | try: | |
2987 | # the variable name must be obtained from the parse_options |
|
2986 | # the variable name must be obtained from the parse_options | |
2988 | # output, which uses shlex.split to strip options out. |
|
2987 | # output, which uses shlex.split to strip options out. | |
2989 | var,_ = args.split('=',1) |
|
2988 | var,_ = args.split('=',1) | |
2990 | var = var.strip() |
|
2989 | var = var.strip() | |
2991 | # But the the command has to be extracted from the original input |
|
2990 | # But the the command has to be extracted from the original input | |
2992 | # parameter_s, not on what parse_options returns, to avoid the |
|
2991 | # parameter_s, not on what parse_options returns, to avoid the | |
2993 | # quote stripping which shlex.split performs on it. |
|
2992 | # quote stripping which shlex.split performs on it. | |
2994 | _,cmd = parameter_s.split('=',1) |
|
2993 | _,cmd = parameter_s.split('=',1) | |
2995 | except ValueError: |
|
2994 | except ValueError: | |
2996 | var,cmd = '','' |
|
2995 | var,cmd = '','' | |
2997 | # If all looks ok, proceed |
|
2996 | # If all looks ok, proceed | |
2998 | split = 'l' in opts |
|
2997 | split = 'l' in opts | |
2999 | out = self.shell.getoutput(cmd, split=split) |
|
2998 | out = self.shell.getoutput(cmd, split=split) | |
3000 | if opts.has_key('v'): |
|
2999 | if opts.has_key('v'): | |
3001 | print '%s ==\n%s' % (var,pformat(out)) |
|
3000 | print '%s ==\n%s' % (var,pformat(out)) | |
3002 | if var: |
|
3001 | if var: | |
3003 | self.shell.user_ns.update({var:out}) |
|
3002 | self.shell.user_ns.update({var:out}) | |
3004 | else: |
|
3003 | else: | |
3005 | return out |
|
3004 | return out | |
3006 |
|
3005 | |||
3007 | def magic_sx(self, parameter_s=''): |
|
3006 | def magic_sx(self, parameter_s=''): | |
3008 | """Shell execute - run a shell command and capture its output. |
|
3007 | """Shell execute - run a shell command and capture its output. | |
3009 |
|
3008 | |||
3010 | %sx command |
|
3009 | %sx command | |
3011 |
|
3010 | |||
3012 | IPython will run the given command using commands.getoutput(), and |
|
3011 | IPython will run the given command using commands.getoutput(), and | |
3013 | return the result formatted as a list (split on '\\n'). Since the |
|
3012 | return the result formatted as a list (split on '\\n'). Since the | |
3014 | output is _returned_, it will be stored in ipython's regular output |
|
3013 | output is _returned_, it will be stored in ipython's regular output | |
3015 | cache Out[N] and in the '_N' automatic variables. |
|
3014 | cache Out[N] and in the '_N' automatic variables. | |
3016 |
|
3015 | |||
3017 | Notes: |
|
3016 | Notes: | |
3018 |
|
3017 | |||
3019 | 1) If an input line begins with '!!', then %sx is automatically |
|
3018 | 1) If an input line begins with '!!', then %sx is automatically | |
3020 | invoked. That is, while: |
|
3019 | invoked. That is, while: | |
3021 | !ls |
|
3020 | !ls | |
3022 | causes ipython to simply issue system('ls'), typing |
|
3021 | causes ipython to simply issue system('ls'), typing | |
3023 | !!ls |
|
3022 | !!ls | |
3024 | is a shorthand equivalent to: |
|
3023 | is a shorthand equivalent to: | |
3025 | %sx ls |
|
3024 | %sx ls | |
3026 |
|
3025 | |||
3027 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3026 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
3028 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3027 | like '%sc -l'. The reason for this is to make it as easy as possible | |
3029 | to process line-oriented shell output via further python commands. |
|
3028 | to process line-oriented shell output via further python commands. | |
3030 | %sc is meant to provide much finer control, but requires more |
|
3029 | %sc is meant to provide much finer control, but requires more | |
3031 | typing. |
|
3030 | typing. | |
3032 |
|
3031 | |||
3033 | 3) Just like %sc -l, this is a list with special attributes: |
|
3032 | 3) Just like %sc -l, this is a list with special attributes: | |
3034 |
|
3033 | |||
3035 | .l (or .list) : value as list. |
|
3034 | .l (or .list) : value as list. | |
3036 | .n (or .nlstr): value as newline-separated string. |
|
3035 | .n (or .nlstr): value as newline-separated string. | |
3037 | .s (or .spstr): value as whitespace-separated string. |
|
3036 | .s (or .spstr): value as whitespace-separated string. | |
3038 |
|
3037 | |||
3039 | This is very useful when trying to use such lists as arguments to |
|
3038 | This is very useful when trying to use such lists as arguments to | |
3040 | system commands.""" |
|
3039 | system commands.""" | |
3041 |
|
3040 | |||
3042 | if parameter_s: |
|
3041 | if parameter_s: | |
3043 | return self.shell.getoutput(parameter_s) |
|
3042 | return self.shell.getoutput(parameter_s) | |
3044 |
|
3043 | |||
3045 | def magic_r(self, parameter_s=''): |
|
3044 | def magic_r(self, parameter_s=''): | |
3046 | """Repeat previous input. |
|
3045 | """Repeat previous input. | |
3047 |
|
3046 | |||
3048 | Note: Consider using the more powerfull %rep instead! |
|
3047 | Note: Consider using the more powerfull %rep instead! | |
3049 |
|
3048 | |||
3050 | If given an argument, repeats the previous command which starts with |
|
3049 | If given an argument, repeats the previous command which starts with | |
3051 | the same string, otherwise it just repeats the previous input. |
|
3050 | the same string, otherwise it just repeats the previous input. | |
3052 |
|
3051 | |||
3053 | Shell escaped commands (with ! as first character) are not recognized |
|
3052 | Shell escaped commands (with ! as first character) are not recognized | |
3054 | by this system, only pure python code and magic commands. |
|
3053 | by this system, only pure python code and magic commands. | |
3055 | """ |
|
3054 | """ | |
3056 |
|
3055 | |||
3057 | start = parameter_s.strip() |
|
3056 | start = parameter_s.strip() | |
3058 | esc_magic = ESC_MAGIC |
|
3057 | esc_magic = ESC_MAGIC | |
3059 | # Identify magic commands even if automagic is on (which means |
|
3058 | # Identify magic commands even if automagic is on (which means | |
3060 | # the in-memory version is different from that typed by the user). |
|
3059 | # the in-memory version is different from that typed by the user). | |
3061 | if self.shell.automagic: |
|
3060 | if self.shell.automagic: | |
3062 | start_magic = esc_magic+start |
|
3061 | start_magic = esc_magic+start | |
3063 | else: |
|
3062 | else: | |
3064 | start_magic = start |
|
3063 | start_magic = start | |
3065 | # Look through the input history in reverse |
|
3064 | # Look through the input history in reverse | |
3066 | for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1): |
|
3065 | for n in range(len(self.shell.history_manager.input_hist_parsed)-2,0,-1): | |
3067 | input = self.shell.history_manager.input_hist_parsed[n] |
|
3066 | input = self.shell.history_manager.input_hist_parsed[n] | |
3068 | # skip plain 'r' lines so we don't recurse to infinity |
|
3067 | # skip plain 'r' lines so we don't recurse to infinity | |
3069 | if input != '_ip.magic("r")\n' and \ |
|
3068 | if input != '_ip.magic("r")\n' and \ | |
3070 | (input.startswith(start) or input.startswith(start_magic)): |
|
3069 | (input.startswith(start) or input.startswith(start_magic)): | |
3071 | #print 'match',`input` # dbg |
|
3070 | #print 'match',`input` # dbg | |
3072 | print 'Executing:',input, |
|
3071 | print 'Executing:',input, | |
3073 | self.shell.run_cell(input) |
|
3072 | self.shell.run_cell(input) | |
3074 | return |
|
3073 | return | |
3075 | print 'No previous input matching `%s` found.' % start |
|
3074 | print 'No previous input matching `%s` found.' % start | |
3076 |
|
3075 | |||
3077 |
|
3076 | |||
3078 | def magic_bookmark(self, parameter_s=''): |
|
3077 | def magic_bookmark(self, parameter_s=''): | |
3079 | """Manage IPython's bookmark system. |
|
3078 | """Manage IPython's bookmark system. | |
3080 |
|
3079 | |||
3081 | %bookmark <name> - set bookmark to current dir |
|
3080 | %bookmark <name> - set bookmark to current dir | |
3082 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3081 | %bookmark <name> <dir> - set bookmark to <dir> | |
3083 | %bookmark -l - list all bookmarks |
|
3082 | %bookmark -l - list all bookmarks | |
3084 | %bookmark -d <name> - remove bookmark |
|
3083 | %bookmark -d <name> - remove bookmark | |
3085 | %bookmark -r - remove all bookmarks |
|
3084 | %bookmark -r - remove all bookmarks | |
3086 |
|
3085 | |||
3087 | You can later on access a bookmarked folder with: |
|
3086 | You can later on access a bookmarked folder with: | |
3088 | %cd -b <name> |
|
3087 | %cd -b <name> | |
3089 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3088 | or simply '%cd <name>' if there is no directory called <name> AND | |
3090 | there is such a bookmark defined. |
|
3089 | there is such a bookmark defined. | |
3091 |
|
3090 | |||
3092 | Your bookmarks persist through IPython sessions, but they are |
|
3091 | Your bookmarks persist through IPython sessions, but they are | |
3093 | associated with each profile.""" |
|
3092 | associated with each profile.""" | |
3094 |
|
3093 | |||
3095 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3094 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3096 | if len(args) > 2: |
|
3095 | if len(args) > 2: | |
3097 | raise UsageError("%bookmark: too many arguments") |
|
3096 | raise UsageError("%bookmark: too many arguments") | |
3098 |
|
3097 | |||
3099 | bkms = self.db.get('bookmarks',{}) |
|
3098 | bkms = self.db.get('bookmarks',{}) | |
3100 |
|
3099 | |||
3101 | if opts.has_key('d'): |
|
3100 | if opts.has_key('d'): | |
3102 | try: |
|
3101 | try: | |
3103 | todel = args[0] |
|
3102 | todel = args[0] | |
3104 | except IndexError: |
|
3103 | except IndexError: | |
3105 | raise UsageError( |
|
3104 | raise UsageError( | |
3106 | "%bookmark -d: must provide a bookmark to delete") |
|
3105 | "%bookmark -d: must provide a bookmark to delete") | |
3107 | else: |
|
3106 | else: | |
3108 | try: |
|
3107 | try: | |
3109 | del bkms[todel] |
|
3108 | del bkms[todel] | |
3110 | except KeyError: |
|
3109 | except KeyError: | |
3111 | raise UsageError( |
|
3110 | raise UsageError( | |
3112 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3111 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3113 |
|
3112 | |||
3114 | elif opts.has_key('r'): |
|
3113 | elif opts.has_key('r'): | |
3115 | bkms = {} |
|
3114 | bkms = {} | |
3116 | elif opts.has_key('l'): |
|
3115 | elif opts.has_key('l'): | |
3117 | bks = bkms.keys() |
|
3116 | bks = bkms.keys() | |
3118 | bks.sort() |
|
3117 | bks.sort() | |
3119 | if bks: |
|
3118 | if bks: | |
3120 | size = max(map(len,bks)) |
|
3119 | size = max(map(len,bks)) | |
3121 | else: |
|
3120 | else: | |
3122 | size = 0 |
|
3121 | size = 0 | |
3123 | fmt = '%-'+str(size)+'s -> %s' |
|
3122 | fmt = '%-'+str(size)+'s -> %s' | |
3124 | print 'Current bookmarks:' |
|
3123 | print 'Current bookmarks:' | |
3125 | for bk in bks: |
|
3124 | for bk in bks: | |
3126 | print fmt % (bk,bkms[bk]) |
|
3125 | print fmt % (bk,bkms[bk]) | |
3127 | else: |
|
3126 | else: | |
3128 | if not args: |
|
3127 | if not args: | |
3129 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3128 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3130 | elif len(args)==1: |
|
3129 | elif len(args)==1: | |
3131 | bkms[args[0]] = os.getcwd() |
|
3130 | bkms[args[0]] = os.getcwd() | |
3132 | elif len(args)==2: |
|
3131 | elif len(args)==2: | |
3133 | bkms[args[0]] = args[1] |
|
3132 | bkms[args[0]] = args[1] | |
3134 | self.db['bookmarks'] = bkms |
|
3133 | self.db['bookmarks'] = bkms | |
3135 |
|
3134 | |||
3136 | def magic_pycat(self, parameter_s=''): |
|
3135 | def magic_pycat(self, parameter_s=''): | |
3137 | """Show a syntax-highlighted file through a pager. |
|
3136 | """Show a syntax-highlighted file through a pager. | |
3138 |
|
3137 | |||
3139 | This magic is similar to the cat utility, but it will assume the file |
|
3138 | This magic is similar to the cat utility, but it will assume the file | |
3140 | to be Python source and will show it with syntax highlighting. """ |
|
3139 | to be Python source and will show it with syntax highlighting. """ | |
3141 |
|
3140 | |||
3142 | try: |
|
3141 | try: | |
3143 | filename = get_py_filename(parameter_s) |
|
3142 | filename = get_py_filename(parameter_s) | |
3144 | cont = file_read(filename) |
|
3143 | cont = file_read(filename) | |
3145 | except IOError: |
|
3144 | except IOError: | |
3146 | try: |
|
3145 | try: | |
3147 | cont = eval(parameter_s,self.user_ns) |
|
3146 | cont = eval(parameter_s,self.user_ns) | |
3148 | except NameError: |
|
3147 | except NameError: | |
3149 | cont = None |
|
3148 | cont = None | |
3150 | if cont is None: |
|
3149 | if cont is None: | |
3151 | print "Error: no such file or variable" |
|
3150 | print "Error: no such file or variable" | |
3152 | return |
|
3151 | return | |
3153 |
|
3152 | |||
3154 | page.page(self.shell.pycolorize(cont)) |
|
3153 | page.page(self.shell.pycolorize(cont)) | |
3155 |
|
3154 | |||
3156 | def _rerun_pasted(self): |
|
3155 | def _rerun_pasted(self): | |
3157 | """ Rerun a previously pasted command. |
|
3156 | """ Rerun a previously pasted command. | |
3158 | """ |
|
3157 | """ | |
3159 | b = self.user_ns.get('pasted_block', None) |
|
3158 | b = self.user_ns.get('pasted_block', None) | |
3160 | if b is None: |
|
3159 | if b is None: | |
3161 | raise UsageError('No previous pasted block available') |
|
3160 | raise UsageError('No previous pasted block available') | |
3162 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3161 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3163 | exec b in self.user_ns |
|
3162 | exec b in self.user_ns | |
3164 |
|
3163 | |||
3165 | def _get_pasted_lines(self, sentinel): |
|
3164 | def _get_pasted_lines(self, sentinel): | |
3166 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3165 | """ Yield pasted lines until the user enters the given sentinel value. | |
3167 | """ |
|
3166 | """ | |
3168 | from IPython.core import interactiveshell |
|
3167 | from IPython.core import interactiveshell | |
3169 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3168 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3170 | while True: |
|
3169 | while True: | |
3171 | l = interactiveshell.raw_input_original(':') |
|
3170 | l = interactiveshell.raw_input_original(':') | |
3172 | if l == sentinel: |
|
3171 | if l == sentinel: | |
3173 | return |
|
3172 | return | |
3174 | else: |
|
3173 | else: | |
3175 | yield l |
|
3174 | yield l | |
3176 |
|
3175 | |||
3177 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3176 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3178 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3177 | """ Strip non-code parts of a sequence of lines to return a block of | |
3179 | code. |
|
3178 | code. | |
3180 | """ |
|
3179 | """ | |
3181 | # Regular expressions that declare text we strip from the input: |
|
3180 | # Regular expressions that declare text we strip from the input: | |
3182 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3181 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3183 | r'^\s*(\s?>)+', # Python input prompt |
|
3182 | r'^\s*(\s?>)+', # Python input prompt | |
3184 | r'^\s*\.{3,}', # Continuation prompts |
|
3183 | r'^\s*\.{3,}', # Continuation prompts | |
3185 | r'^\++', |
|
3184 | r'^\++', | |
3186 | ] |
|
3185 | ] | |
3187 |
|
3186 | |||
3188 | strip_from_start = map(re.compile,strip_re) |
|
3187 | strip_from_start = map(re.compile,strip_re) | |
3189 |
|
3188 | |||
3190 | lines = [] |
|
3189 | lines = [] | |
3191 | for l in raw_lines: |
|
3190 | for l in raw_lines: | |
3192 | for pat in strip_from_start: |
|
3191 | for pat in strip_from_start: | |
3193 | l = pat.sub('',l) |
|
3192 | l = pat.sub('',l) | |
3194 | lines.append(l) |
|
3193 | lines.append(l) | |
3195 |
|
3194 | |||
3196 | block = "\n".join(lines) + '\n' |
|
3195 | block = "\n".join(lines) + '\n' | |
3197 | #print "block:\n",block |
|
3196 | #print "block:\n",block | |
3198 | return block |
|
3197 | return block | |
3199 |
|
3198 | |||
3200 | def _execute_block(self, block, par): |
|
3199 | def _execute_block(self, block, par): | |
3201 | """ Execute a block, or store it in a variable, per the user's request. |
|
3200 | """ Execute a block, or store it in a variable, per the user's request. | |
3202 | """ |
|
3201 | """ | |
3203 | if not par: |
|
3202 | if not par: | |
3204 | b = textwrap.dedent(block) |
|
3203 | b = textwrap.dedent(block) | |
3205 | self.user_ns['pasted_block'] = b |
|
3204 | self.user_ns['pasted_block'] = b | |
3206 | exec b in self.user_ns |
|
3205 | exec b in self.user_ns | |
3207 | else: |
|
3206 | else: | |
3208 | self.user_ns[par] = SList(block.splitlines()) |
|
3207 | self.user_ns[par] = SList(block.splitlines()) | |
3209 | print "Block assigned to '%s'" % par |
|
3208 | print "Block assigned to '%s'" % par | |
3210 |
|
3209 | |||
3211 | def magic_quickref(self,arg): |
|
3210 | def magic_quickref(self,arg): | |
3212 | """ Show a quick reference sheet """ |
|
3211 | """ Show a quick reference sheet """ | |
3213 | import IPython.core.usage |
|
3212 | import IPython.core.usage | |
3214 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3213 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3215 |
|
3214 | |||
3216 | page.page(qr) |
|
3215 | page.page(qr) | |
3217 |
|
3216 | |||
3218 | def magic_doctest_mode(self,parameter_s=''): |
|
3217 | def magic_doctest_mode(self,parameter_s=''): | |
3219 | """Toggle doctest mode on and off. |
|
3218 | """Toggle doctest mode on and off. | |
3220 |
|
3219 | |||
3221 | This mode is intended to make IPython behave as much as possible like a |
|
3220 | This mode is intended to make IPython behave as much as possible like a | |
3222 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3221 | plain Python shell, from the perspective of how its prompts, exceptions | |
3223 | and output look. This makes it easy to copy and paste parts of a |
|
3222 | and output look. This makes it easy to copy and paste parts of a | |
3224 | session into doctests. It does so by: |
|
3223 | session into doctests. It does so by: | |
3225 |
|
3224 | |||
3226 | - Changing the prompts to the classic ``>>>`` ones. |
|
3225 | - Changing the prompts to the classic ``>>>`` ones. | |
3227 | - Changing the exception reporting mode to 'Plain'. |
|
3226 | - Changing the exception reporting mode to 'Plain'. | |
3228 | - Disabling pretty-printing of output. |
|
3227 | - Disabling pretty-printing of output. | |
3229 |
|
3228 | |||
3230 | Note that IPython also supports the pasting of code snippets that have |
|
3229 | Note that IPython also supports the pasting of code snippets that have | |
3231 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3230 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3232 | doctests from files or docstrings (even if they have leading |
|
3231 | doctests from files or docstrings (even if they have leading | |
3233 | whitespace), and the code will execute correctly. You can then use |
|
3232 | whitespace), and the code will execute correctly. You can then use | |
3234 | '%history -t' to see the translated history; this will give you the |
|
3233 | '%history -t' to see the translated history; this will give you the | |
3235 | input after removal of all the leading prompts and whitespace, which |
|
3234 | input after removal of all the leading prompts and whitespace, which | |
3236 | can be pasted back into an editor. |
|
3235 | can be pasted back into an editor. | |
3237 |
|
3236 | |||
3238 | With these features, you can switch into this mode easily whenever you |
|
3237 | With these features, you can switch into this mode easily whenever you | |
3239 | need to do testing and changes to doctests, without having to leave |
|
3238 | need to do testing and changes to doctests, without having to leave | |
3240 | your existing IPython session. |
|
3239 | your existing IPython session. | |
3241 | """ |
|
3240 | """ | |
3242 |
|
3241 | |||
3243 | from IPython.utils.ipstruct import Struct |
|
3242 | from IPython.utils.ipstruct import Struct | |
3244 |
|
3243 | |||
3245 | # Shorthands |
|
3244 | # Shorthands | |
3246 | shell = self.shell |
|
3245 | shell = self.shell | |
3247 | oc = shell.displayhook |
|
3246 | oc = shell.displayhook | |
3248 | meta = shell.meta |
|
3247 | meta = shell.meta | |
3249 | disp_formatter = self.shell.display_formatter |
|
3248 | disp_formatter = self.shell.display_formatter | |
3250 | ptformatter = disp_formatter.formatters['text/plain'] |
|
3249 | ptformatter = disp_formatter.formatters['text/plain'] | |
3251 | # dstore is a data store kept in the instance metadata bag to track any |
|
3250 | # dstore is a data store kept in the instance metadata bag to track any | |
3252 | # changes we make, so we can undo them later. |
|
3251 | # changes we make, so we can undo them later. | |
3253 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3252 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3254 | save_dstore = dstore.setdefault |
|
3253 | save_dstore = dstore.setdefault | |
3255 |
|
3254 | |||
3256 | # save a few values we'll need to recover later |
|
3255 | # save a few values we'll need to recover later | |
3257 | mode = save_dstore('mode',False) |
|
3256 | mode = save_dstore('mode',False) | |
3258 | save_dstore('rc_pprint',ptformatter.pprint) |
|
3257 | save_dstore('rc_pprint',ptformatter.pprint) | |
3259 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3258 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3260 | save_dstore('rc_separate_out',shell.separate_out) |
|
3259 | save_dstore('rc_separate_out',shell.separate_out) | |
3261 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3260 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3262 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3261 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3263 | save_dstore('rc_separate_in',shell.separate_in) |
|
3262 | save_dstore('rc_separate_in',shell.separate_in) | |
3264 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
3263 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) | |
3265 |
|
3264 | |||
3266 | if mode == False: |
|
3265 | if mode == False: | |
3267 | # turn on |
|
3266 | # turn on | |
3268 | oc.prompt1.p_template = '>>> ' |
|
3267 | oc.prompt1.p_template = '>>> ' | |
3269 | oc.prompt2.p_template = '... ' |
|
3268 | oc.prompt2.p_template = '... ' | |
3270 | oc.prompt_out.p_template = '' |
|
3269 | oc.prompt_out.p_template = '' | |
3271 |
|
3270 | |||
3272 | # Prompt separators like plain python |
|
3271 | # Prompt separators like plain python | |
3273 | oc.input_sep = oc.prompt1.sep = '' |
|
3272 | oc.input_sep = oc.prompt1.sep = '' | |
3274 | oc.output_sep = '' |
|
3273 | oc.output_sep = '' | |
3275 | oc.output_sep2 = '' |
|
3274 | oc.output_sep2 = '' | |
3276 |
|
3275 | |||
3277 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3276 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3278 | oc.prompt_out.pad_left = False |
|
3277 | oc.prompt_out.pad_left = False | |
3279 |
|
3278 | |||
3280 | ptformatter.pprint = False |
|
3279 | ptformatter.pprint = False | |
3281 | disp_formatter.plain_text_only = True |
|
3280 | disp_formatter.plain_text_only = True | |
3282 |
|
3281 | |||
3283 | shell.magic_xmode('Plain') |
|
3282 | shell.magic_xmode('Plain') | |
3284 | else: |
|
3283 | else: | |
3285 | # turn off |
|
3284 | # turn off | |
3286 | oc.prompt1.p_template = shell.prompt_in1 |
|
3285 | oc.prompt1.p_template = shell.prompt_in1 | |
3287 | oc.prompt2.p_template = shell.prompt_in2 |
|
3286 | oc.prompt2.p_template = shell.prompt_in2 | |
3288 | oc.prompt_out.p_template = shell.prompt_out |
|
3287 | oc.prompt_out.p_template = shell.prompt_out | |
3289 |
|
3288 | |||
3290 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3289 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3291 |
|
3290 | |||
3292 | oc.output_sep = dstore.rc_separate_out |
|
3291 | oc.output_sep = dstore.rc_separate_out | |
3293 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3292 | oc.output_sep2 = dstore.rc_separate_out2 | |
3294 |
|
3293 | |||
3295 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3294 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3296 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3295 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3297 |
|
3296 | |||
3298 | ptformatter.pprint = dstore.rc_pprint |
|
3297 | ptformatter.pprint = dstore.rc_pprint | |
3299 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
3298 | disp_formatter.plain_text_only = dstore.rc_plain_text_only | |
3300 |
|
3299 | |||
3301 | shell.magic_xmode(dstore.xmode) |
|
3300 | shell.magic_xmode(dstore.xmode) | |
3302 |
|
3301 | |||
3303 | # Store new mode and inform |
|
3302 | # Store new mode and inform | |
3304 | dstore.mode = bool(1-int(mode)) |
|
3303 | dstore.mode = bool(1-int(mode)) | |
3305 | mode_label = ['OFF','ON'][dstore.mode] |
|
3304 | mode_label = ['OFF','ON'][dstore.mode] | |
3306 | print 'Doctest mode is:', mode_label |
|
3305 | print 'Doctest mode is:', mode_label | |
3307 |
|
3306 | |||
3308 | def magic_gui(self, parameter_s=''): |
|
3307 | def magic_gui(self, parameter_s=''): | |
3309 | """Enable or disable IPython GUI event loop integration. |
|
3308 | """Enable or disable IPython GUI event loop integration. | |
3310 |
|
3309 | |||
3311 | %gui [GUINAME] |
|
3310 | %gui [GUINAME] | |
3312 |
|
3311 | |||
3313 | This magic replaces IPython's threaded shells that were activated |
|
3312 | This magic replaces IPython's threaded shells that were activated | |
3314 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3313 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3315 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3314 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3316 | interrupts should work without any problems. The following toolkits |
|
3315 | interrupts should work without any problems. The following toolkits | |
3317 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3316 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3318 |
|
3317 | |||
3319 | %gui wx # enable wxPython event loop integration |
|
3318 | %gui wx # enable wxPython event loop integration | |
3320 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3319 | %gui qt4|qt # enable PyQt4 event loop integration | |
3321 | %gui gtk # enable PyGTK event loop integration |
|
3320 | %gui gtk # enable PyGTK event loop integration | |
3322 | %gui tk # enable Tk event loop integration |
|
3321 | %gui tk # enable Tk event loop integration | |
3323 | %gui # disable all event loop integration |
|
3322 | %gui # disable all event loop integration | |
3324 |
|
3323 | |||
3325 | WARNING: after any of these has been called you can simply create |
|
3324 | WARNING: after any of these has been called you can simply create | |
3326 | an application object, but DO NOT start the event loop yourself, as |
|
3325 | an application object, but DO NOT start the event loop yourself, as | |
3327 | we have already handled that. |
|
3326 | we have already handled that. | |
3328 | """ |
|
3327 | """ | |
3329 | from IPython.lib.inputhook import enable_gui |
|
3328 | from IPython.lib.inputhook import enable_gui | |
3330 | opts, arg = self.parse_options(parameter_s, '') |
|
3329 | opts, arg = self.parse_options(parameter_s, '') | |
3331 | if arg=='': arg = None |
|
3330 | if arg=='': arg = None | |
3332 | return enable_gui(arg) |
|
3331 | return enable_gui(arg) | |
3333 |
|
3332 | |||
3334 | def magic_load_ext(self, module_str): |
|
3333 | def magic_load_ext(self, module_str): | |
3335 | """Load an IPython extension by its module name.""" |
|
3334 | """Load an IPython extension by its module name.""" | |
3336 | return self.extension_manager.load_extension(module_str) |
|
3335 | return self.extension_manager.load_extension(module_str) | |
3337 |
|
3336 | |||
3338 | def magic_unload_ext(self, module_str): |
|
3337 | def magic_unload_ext(self, module_str): | |
3339 | """Unload an IPython extension by its module name.""" |
|
3338 | """Unload an IPython extension by its module name.""" | |
3340 | self.extension_manager.unload_extension(module_str) |
|
3339 | self.extension_manager.unload_extension(module_str) | |
3341 |
|
3340 | |||
3342 | def magic_reload_ext(self, module_str): |
|
3341 | def magic_reload_ext(self, module_str): | |
3343 | """Reload an IPython extension by its module name.""" |
|
3342 | """Reload an IPython extension by its module name.""" | |
3344 | self.extension_manager.reload_extension(module_str) |
|
3343 | self.extension_manager.reload_extension(module_str) | |
3345 |
|
3344 | |||
3346 | @testdec.skip_doctest |
|
3345 | @testdec.skip_doctest | |
3347 | def magic_install_profiles(self, s): |
|
3346 | def magic_install_profiles(self, s): | |
3348 | """Install the default IPython profiles into the .ipython dir. |
|
3347 | """Install the default IPython profiles into the .ipython dir. | |
3349 |
|
3348 | |||
3350 | If the default profiles have already been installed, they will not |
|
3349 | If the default profiles have already been installed, they will not | |
3351 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3350 | be overwritten. You can force overwriting them by using the ``-o`` | |
3352 | option:: |
|
3351 | option:: | |
3353 |
|
3352 | |||
3354 | In [1]: %install_profiles -o |
|
3353 | In [1]: %install_profiles -o | |
3355 | """ |
|
3354 | """ | |
3356 | if '-o' in s: |
|
3355 | if '-o' in s: | |
3357 | overwrite = True |
|
3356 | overwrite = True | |
3358 | else: |
|
3357 | else: | |
3359 | overwrite = False |
|
3358 | overwrite = False | |
3360 | from IPython.config import profile |
|
3359 | from IPython.config import profile | |
3361 | profile_dir = os.path.split(profile.__file__)[0] |
|
3360 | profile_dir = os.path.split(profile.__file__)[0] | |
3362 | ipython_dir = self.ipython_dir |
|
3361 | ipython_dir = self.ipython_dir | |
3363 | files = os.listdir(profile_dir) |
|
3362 | files = os.listdir(profile_dir) | |
3364 |
|
3363 | |||
3365 | to_install = [] |
|
3364 | to_install = [] | |
3366 | for f in files: |
|
3365 | for f in files: | |
3367 | if f.startswith('ipython_config'): |
|
3366 | if f.startswith('ipython_config'): | |
3368 | src = os.path.join(profile_dir, f) |
|
3367 | src = os.path.join(profile_dir, f) | |
3369 | dst = os.path.join(ipython_dir, f) |
|
3368 | dst = os.path.join(ipython_dir, f) | |
3370 | if (not os.path.isfile(dst)) or overwrite: |
|
3369 | if (not os.path.isfile(dst)) or overwrite: | |
3371 | to_install.append((f, src, dst)) |
|
3370 | to_install.append((f, src, dst)) | |
3372 | if len(to_install)>0: |
|
3371 | if len(to_install)>0: | |
3373 | print "Installing profiles to: ", ipython_dir |
|
3372 | print "Installing profiles to: ", ipython_dir | |
3374 | for (f, src, dst) in to_install: |
|
3373 | for (f, src, dst) in to_install: | |
3375 | shutil.copy(src, dst) |
|
3374 | shutil.copy(src, dst) | |
3376 | print " %s" % f |
|
3375 | print " %s" % f | |
3377 |
|
3376 | |||
3378 | def magic_install_default_config(self, s): |
|
3377 | def magic_install_default_config(self, s): | |
3379 | """Install IPython's default config file into the .ipython dir. |
|
3378 | """Install IPython's default config file into the .ipython dir. | |
3380 |
|
3379 | |||
3381 | If the default config file (:file:`ipython_config.py`) is already |
|
3380 | If the default config file (:file:`ipython_config.py`) is already | |
3382 | installed, it will not be overwritten. You can force overwriting |
|
3381 | installed, it will not be overwritten. You can force overwriting | |
3383 | by using the ``-o`` option:: |
|
3382 | by using the ``-o`` option:: | |
3384 |
|
3383 | |||
3385 | In [1]: %install_default_config |
|
3384 | In [1]: %install_default_config | |
3386 | """ |
|
3385 | """ | |
3387 | if '-o' in s: |
|
3386 | if '-o' in s: | |
3388 | overwrite = True |
|
3387 | overwrite = True | |
3389 | else: |
|
3388 | else: | |
3390 | overwrite = False |
|
3389 | overwrite = False | |
3391 | from IPython.config import default |
|
3390 | from IPython.config import default | |
3392 | config_dir = os.path.split(default.__file__)[0] |
|
3391 | config_dir = os.path.split(default.__file__)[0] | |
3393 | ipython_dir = self.ipython_dir |
|
3392 | ipython_dir = self.ipython_dir | |
3394 | default_config_file_name = 'ipython_config.py' |
|
3393 | default_config_file_name = 'ipython_config.py' | |
3395 | src = os.path.join(config_dir, default_config_file_name) |
|
3394 | src = os.path.join(config_dir, default_config_file_name) | |
3396 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3395 | dst = os.path.join(ipython_dir, default_config_file_name) | |
3397 | if (not os.path.isfile(dst)) or overwrite: |
|
3396 | if (not os.path.isfile(dst)) or overwrite: | |
3398 | shutil.copy(src, dst) |
|
3397 | shutil.copy(src, dst) | |
3399 | print "Installing default config file: %s" % dst |
|
3398 | print "Installing default config file: %s" % dst | |
3400 |
|
3399 | |||
3401 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3400 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3402 | # handling and modify slightly %run |
|
3401 | # handling and modify slightly %run | |
3403 |
|
3402 | |||
3404 | @testdec.skip_doctest |
|
3403 | @testdec.skip_doctest | |
3405 | def _pylab_magic_run(self, parameter_s=''): |
|
3404 | def _pylab_magic_run(self, parameter_s=''): | |
3406 | Magic.magic_run(self, parameter_s, |
|
3405 | Magic.magic_run(self, parameter_s, | |
3407 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3406 | runner=mpl_runner(self.shell.safe_execfile)) | |
3408 |
|
3407 | |||
3409 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3408 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3410 |
|
3409 | |||
3411 | @testdec.skip_doctest |
|
3410 | @testdec.skip_doctest | |
3412 | def magic_pylab(self, s): |
|
3411 | def magic_pylab(self, s): | |
3413 | """Load numpy and matplotlib to work interactively. |
|
3412 | """Load numpy and matplotlib to work interactively. | |
3414 |
|
3413 | |||
3415 | %pylab [GUINAME] |
|
3414 | %pylab [GUINAME] | |
3416 |
|
3415 | |||
3417 | This function lets you activate pylab (matplotlib, numpy and |
|
3416 | This function lets you activate pylab (matplotlib, numpy and | |
3418 | interactive support) at any point during an IPython session. |
|
3417 | interactive support) at any point during an IPython session. | |
3419 |
|
3418 | |||
3420 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3419 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3421 | pylab and mlab, as well as all names from numpy and pylab. |
|
3420 | pylab and mlab, as well as all names from numpy and pylab. | |
3422 |
|
3421 | |||
3423 | Parameters |
|
3422 | Parameters | |
3424 | ---------- |
|
3423 | ---------- | |
3425 | guiname : optional |
|
3424 | guiname : optional | |
3426 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3425 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or | |
3427 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3426 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3428 | otherwise matplotlib's default (which you can override in your |
|
3427 | otherwise matplotlib's default (which you can override in your | |
3429 | matplotlib config file) is used. |
|
3428 | matplotlib config file) is used. | |
3430 |
|
3429 | |||
3431 | Examples |
|
3430 | Examples | |
3432 | -------- |
|
3431 | -------- | |
3433 | In this case, where the MPL default is TkAgg: |
|
3432 | In this case, where the MPL default is TkAgg: | |
3434 | In [2]: %pylab |
|
3433 | In [2]: %pylab | |
3435 |
|
3434 | |||
3436 | Welcome to pylab, a matplotlib-based Python environment. |
|
3435 | Welcome to pylab, a matplotlib-based Python environment. | |
3437 | Backend in use: TkAgg |
|
3436 | Backend in use: TkAgg | |
3438 | For more information, type 'help(pylab)'. |
|
3437 | For more information, type 'help(pylab)'. | |
3439 |
|
3438 | |||
3440 | But you can explicitly request a different backend: |
|
3439 | But you can explicitly request a different backend: | |
3441 | In [3]: %pylab qt |
|
3440 | In [3]: %pylab qt | |
3442 |
|
3441 | |||
3443 | Welcome to pylab, a matplotlib-based Python environment. |
|
3442 | Welcome to pylab, a matplotlib-based Python environment. | |
3444 | Backend in use: Qt4Agg |
|
3443 | Backend in use: Qt4Agg | |
3445 | For more information, type 'help(pylab)'. |
|
3444 | For more information, type 'help(pylab)'. | |
3446 | """ |
|
3445 | """ | |
3447 | self.shell.enable_pylab(s) |
|
3446 | self.shell.enable_pylab(s) | |
3448 |
|
3447 | |||
3449 | def magic_tb(self, s): |
|
3448 | def magic_tb(self, s): | |
3450 | """Print the last traceback with the currently active exception mode. |
|
3449 | """Print the last traceback with the currently active exception mode. | |
3451 |
|
3450 | |||
3452 | See %xmode for changing exception reporting modes.""" |
|
3451 | See %xmode for changing exception reporting modes.""" | |
3453 | self.shell.showtraceback() |
|
3452 | self.shell.showtraceback() | |
3454 |
|
3453 | |||
3455 | @testdec.skip_doctest |
|
3454 | @testdec.skip_doctest | |
3456 | def magic_precision(self, s=''): |
|
3455 | def magic_precision(self, s=''): | |
3457 | """Set floating point precision for pretty printing. |
|
3456 | """Set floating point precision for pretty printing. | |
3458 |
|
3457 | |||
3459 | Can set either integer precision or a format string. |
|
3458 | Can set either integer precision or a format string. | |
3460 |
|
3459 | |||
3461 | If numpy has been imported and precision is an int, |
|
3460 | If numpy has been imported and precision is an int, | |
3462 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
3461 | numpy display precision will also be set, via ``numpy.set_printoptions``. | |
3463 |
|
3462 | |||
3464 | If no argument is given, defaults will be restored. |
|
3463 | If no argument is given, defaults will be restored. | |
3465 |
|
3464 | |||
3466 | Examples |
|
3465 | Examples | |
3467 | -------- |
|
3466 | -------- | |
3468 | :: |
|
3467 | :: | |
3469 |
|
3468 | |||
3470 | In [1]: from math import pi |
|
3469 | In [1]: from math import pi | |
3471 |
|
3470 | |||
3472 | In [2]: %precision 3 |
|
3471 | In [2]: %precision 3 | |
3473 | Out[2]: '%.3f' |
|
3472 | Out[2]: '%.3f' | |
3474 |
|
3473 | |||
3475 | In [3]: pi |
|
3474 | In [3]: pi | |
3476 | Out[3]: 3.142 |
|
3475 | Out[3]: 3.142 | |
3477 |
|
3476 | |||
3478 | In [4]: %precision %i |
|
3477 | In [4]: %precision %i | |
3479 | Out[4]: '%i' |
|
3478 | Out[4]: '%i' | |
3480 |
|
3479 | |||
3481 | In [5]: pi |
|
3480 | In [5]: pi | |
3482 | Out[5]: 3 |
|
3481 | Out[5]: 3 | |
3483 |
|
3482 | |||
3484 | In [6]: %precision %e |
|
3483 | In [6]: %precision %e | |
3485 | Out[6]: '%e' |
|
3484 | Out[6]: '%e' | |
3486 |
|
3485 | |||
3487 | In [7]: pi**10 |
|
3486 | In [7]: pi**10 | |
3488 | Out[7]: 9.364805e+04 |
|
3487 | Out[7]: 9.364805e+04 | |
3489 |
|
3488 | |||
3490 | In [8]: %precision |
|
3489 | In [8]: %precision | |
3491 | Out[8]: '%r' |
|
3490 | Out[8]: '%r' | |
3492 |
|
3491 | |||
3493 | In [9]: pi**10 |
|
3492 | In [9]: pi**10 | |
3494 | Out[9]: 93648.047476082982 |
|
3493 | Out[9]: 93648.047476082982 | |
3495 |
|
3494 | |||
3496 | """ |
|
3495 | """ | |
3497 |
|
3496 | |||
3498 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
3497 | ptformatter = self.shell.display_formatter.formatters['text/plain'] | |
3499 | ptformatter.float_precision = s |
|
3498 | ptformatter.float_precision = s | |
3500 | return ptformatter.float_format |
|
3499 | return ptformatter.float_format | |
3501 |
|
3500 | |||
3502 | # end Magic |
|
3501 | # end Magic |
@@ -1,420 +1,420 b'' | |||||
1 | """Tests for various magic functions. |
|
1 | """Tests for various magic functions. | |
2 |
|
2 | |||
3 | Needs to be run by nose (to make ipython session available). |
|
3 | Needs to be run by nose (to make ipython session available). | |
4 | """ |
|
4 | """ | |
5 | from __future__ import absolute_import |
|
5 | from __future__ import absolute_import | |
6 |
|
6 | |||
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Imports |
|
8 | # Imports | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | import os |
|
11 | import os | |
12 | import sys |
|
12 | import sys | |
13 | import tempfile |
|
13 | import tempfile | |
14 | import types |
|
14 | import types | |
15 | from cStringIO import StringIO |
|
15 | from cStringIO import StringIO | |
16 |
|
16 | |||
17 | import nose.tools as nt |
|
17 | import nose.tools as nt | |
18 |
|
18 | |||
19 | from IPython.utils.path import get_long_path_name |
|
19 | from IPython.utils.path import get_long_path_name | |
20 | from IPython.testing import decorators as dec |
|
20 | from IPython.testing import decorators as dec | |
21 | from IPython.testing import tools as tt |
|
21 | from IPython.testing import tools as tt | |
22 |
|
22 | |||
23 | #----------------------------------------------------------------------------- |
|
23 | #----------------------------------------------------------------------------- | |
24 | # Test functions begin |
|
24 | # Test functions begin | |
25 | #----------------------------------------------------------------------------- |
|
25 | #----------------------------------------------------------------------------- | |
26 | def test_rehashx(): |
|
26 | def test_rehashx(): | |
27 | # clear up everything |
|
27 | # clear up everything | |
28 | _ip = get_ipython() |
|
28 | _ip = get_ipython() | |
29 | _ip.alias_manager.alias_table.clear() |
|
29 | _ip.alias_manager.alias_table.clear() | |
30 | del _ip.db['syscmdlist'] |
|
30 | del _ip.db['syscmdlist'] | |
31 |
|
31 | |||
32 | _ip.magic('rehashx') |
|
32 | _ip.magic('rehashx') | |
33 | # Practically ALL ipython development systems will have more than 10 aliases |
|
33 | # Practically ALL ipython development systems will have more than 10 aliases | |
34 |
|
34 | |||
35 | yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10) |
|
35 | yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10) | |
36 | for key, val in _ip.alias_manager.alias_table.iteritems(): |
|
36 | for key, val in _ip.alias_manager.alias_table.iteritems(): | |
37 | # we must strip dots from alias names |
|
37 | # we must strip dots from alias names | |
38 | nt.assert_true('.' not in key) |
|
38 | nt.assert_true('.' not in key) | |
39 |
|
39 | |||
40 | # rehashx must fill up syscmdlist |
|
40 | # rehashx must fill up syscmdlist | |
41 | scoms = _ip.db['syscmdlist'] |
|
41 | scoms = _ip.db['syscmdlist'] | |
42 | yield (nt.assert_true, len(scoms) > 10) |
|
42 | yield (nt.assert_true, len(scoms) > 10) | |
43 |
|
43 | |||
44 |
|
44 | |||
45 | def test_magic_parse_options(): |
|
45 | def test_magic_parse_options(): | |
46 | """Test that we don't mangle paths when parsing magic options.""" |
|
46 | """Test that we don't mangle paths when parsing magic options.""" | |
47 | ip = get_ipython() |
|
47 | ip = get_ipython() | |
48 | path = 'c:\\x' |
|
48 | path = 'c:\\x' | |
49 | opts = ip.parse_options('-f %s' % path,'f:')[0] |
|
49 | opts = ip.parse_options('-f %s' % path,'f:')[0] | |
50 | # argv splitting is os-dependent |
|
50 | # argv splitting is os-dependent | |
51 | if os.name == 'posix': |
|
51 | if os.name == 'posix': | |
52 | expected = 'c:x' |
|
52 | expected = 'c:x' | |
53 | else: |
|
53 | else: | |
54 | expected = path |
|
54 | expected = path | |
55 | nt.assert_equals(opts['f'], expected) |
|
55 | nt.assert_equals(opts['f'], expected) | |
56 |
|
56 | |||
57 |
|
57 | |||
58 | def doctest_hist_f(): |
|
58 | def doctest_hist_f(): | |
59 | """Test %hist -f with temporary filename. |
|
59 | """Test %hist -f with temporary filename. | |
60 |
|
60 | |||
61 | In [9]: import tempfile |
|
61 | In [9]: import tempfile | |
62 |
|
62 | |||
63 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') |
|
63 | In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-') | |
64 |
|
64 | |||
65 | In [11]: %hist -n -f $tfile 3 |
|
65 | In [11]: %hist -n -f $tfile 3 | |
66 |
|
66 | |||
67 | In [13]: import os; os.unlink(tfile) |
|
67 | In [13]: import os; os.unlink(tfile) | |
68 | """ |
|
68 | """ | |
69 |
|
69 | |||
70 |
|
70 | |||
71 | def doctest_hist_r(): |
|
71 | def doctest_hist_r(): | |
72 | """Test %hist -r |
|
72 | """Test %hist -r | |
73 |
|
73 | |||
74 | XXX - This test is not recording the output correctly. For some reason, in |
|
74 | XXX - This test is not recording the output correctly. For some reason, in | |
75 | testing mode the raw history isn't getting populated. No idea why. |
|
75 | testing mode the raw history isn't getting populated. No idea why. | |
76 | Disabling the output checking for now, though at least we do run it. |
|
76 | Disabling the output checking for now, though at least we do run it. | |
77 |
|
77 | |||
78 | In [1]: 'hist' in _ip.lsmagic() |
|
78 | In [1]: 'hist' in _ip.lsmagic() | |
79 | Out[1]: True |
|
79 | Out[1]: True | |
80 |
|
80 | |||
81 | In [2]: x=1 |
|
81 | In [2]: x=1 | |
82 |
|
82 | |||
83 | In [3]: %hist -r 2 |
|
83 | In [3]: %hist -r 2 | |
84 | x=1 # random |
|
84 | x=1 # random | |
85 | %hist -r 2 |
|
85 | %hist -r 2 | |
86 | """ |
|
86 | """ | |
87 |
|
87 | |||
88 | def doctest_hist_op(): |
|
88 | def doctest_hist_op(): | |
89 | """Test %hist -op |
|
89 | """Test %hist -op | |
90 |
|
90 | |||
91 | In [1]: class b: |
|
91 | In [1]: class b: | |
92 | ...: pass |
|
92 | ...: pass | |
93 | ...: |
|
93 | ...: | |
94 |
|
94 | |||
95 | In [2]: class s(b): |
|
95 | In [2]: class s(b): | |
96 | ...: def __str__(self): |
|
96 | ...: def __str__(self): | |
97 | ...: return 's' |
|
97 | ...: return 's' | |
98 | ...: |
|
98 | ...: | |
99 |
|
99 | |||
100 | In [3]: |
|
100 | In [3]: | |
101 |
|
101 | |||
102 | In [4]: class r(b): |
|
102 | In [4]: class r(b): | |
103 | ...: def __repr__(self): |
|
103 | ...: def __repr__(self): | |
104 | ...: return 'r' |
|
104 | ...: return 'r' | |
105 | ...: |
|
105 | ...: | |
106 |
|
106 | |||
107 | In [5]: class sr(s,r): pass |
|
107 | In [5]: class sr(s,r): pass | |
108 | ...: |
|
108 | ...: | |
109 |
|
109 | |||
110 | In [6]: |
|
110 | In [6]: | |
111 |
|
111 | |||
112 | In [7]: bb=b() |
|
112 | In [7]: bb=b() | |
113 |
|
113 | |||
114 | In [8]: ss=s() |
|
114 | In [8]: ss=s() | |
115 |
|
115 | |||
116 | In [9]: rr=r() |
|
116 | In [9]: rr=r() | |
117 |
|
117 | |||
118 | In [10]: ssrr=sr() |
|
118 | In [10]: ssrr=sr() | |
119 |
|
119 | |||
120 | In [11]: bb |
|
120 | In [11]: bb | |
121 | Out[11]: <...b instance at ...> |
|
121 | Out[11]: <...b instance at ...> | |
122 |
|
122 | |||
123 | In [12]: ss |
|
123 | In [12]: ss | |
124 | Out[12]: <...s instance at ...> |
|
124 | Out[12]: <...s instance at ...> | |
125 |
|
125 | |||
126 | In [13]: |
|
126 | In [13]: | |
127 |
|
127 | |||
128 | In [14]: %hist -op |
|
128 | In [14]: %hist -op | |
129 | >>> class b: |
|
129 | >>> class b: | |
130 | ... pass |
|
130 | ... pass | |
131 | ... |
|
131 | ... | |
132 | >>> class s(b): |
|
132 | >>> class s(b): | |
133 | ... def __str__(self): |
|
133 | ... def __str__(self): | |
134 | ... return 's' |
|
134 | ... return 's' | |
135 | ... |
|
135 | ... | |
136 | >>> |
|
136 | >>> | |
137 | >>> class r(b): |
|
137 | >>> class r(b): | |
138 | ... def __repr__(self): |
|
138 | ... def __repr__(self): | |
139 | ... return 'r' |
|
139 | ... return 'r' | |
140 | ... |
|
140 | ... | |
141 | >>> class sr(s,r): pass |
|
141 | >>> class sr(s,r): pass | |
142 | >>> |
|
142 | >>> | |
143 | >>> bb=b() |
|
143 | >>> bb=b() | |
144 | >>> ss=s() |
|
144 | >>> ss=s() | |
145 | >>> rr=r() |
|
145 | >>> rr=r() | |
146 | >>> ssrr=sr() |
|
146 | >>> ssrr=sr() | |
147 | >>> bb |
|
147 | >>> bb | |
148 | <...b instance at ...> |
|
148 | <...b instance at ...> | |
149 | >>> ss |
|
149 | >>> ss | |
150 | <...s instance at ...> |
|
150 | <...s instance at ...> | |
151 | >>> |
|
151 | >>> | |
152 | """ |
|
152 | """ | |
153 |
|
153 | |||
154 | def test_shist(): |
|
154 | def test_shist(): | |
155 | # Simple tests of ShadowHist class - test generator. |
|
155 | # Simple tests of ShadowHist class - test generator. | |
156 | import os, shutil, tempfile |
|
156 | import os, shutil, tempfile | |
157 |
|
157 | |||
158 | from IPython.utils import pickleshare |
|
158 | from IPython.utils import pickleshare | |
159 | from IPython.core.history import ShadowHist |
|
159 | from IPython.core.history import ShadowHist | |
160 |
|
160 | |||
161 | tfile = tempfile.mktemp('','tmp-ipython-') |
|
161 | tfile = tempfile.mktemp('','tmp-ipython-') | |
162 |
|
162 | |||
163 | db = pickleshare.PickleShareDB(tfile) |
|
163 | db = pickleshare.PickleShareDB(tfile) | |
164 | s = ShadowHist(db, get_ipython()) |
|
164 | s = ShadowHist(db, get_ipython()) | |
165 | s.add('hello') |
|
165 | s.add('hello') | |
166 | s.add('world') |
|
166 | s.add('world') | |
167 | s.add('hello') |
|
167 | s.add('hello') | |
168 | s.add('hello') |
|
168 | s.add('hello') | |
169 | s.add('karhu') |
|
169 | s.add('karhu') | |
170 |
|
170 | |||
171 | yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')] |
|
171 | yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')] | |
172 |
|
172 | |||
173 | yield nt.assert_equal,s.get(2),'world' |
|
173 | yield nt.assert_equal,s.get(2),'world' | |
174 |
|
174 | |||
175 | shutil.rmtree(tfile) |
|
175 | shutil.rmtree(tfile) | |
176 |
|
176 | |||
177 | def test_macro(): |
|
177 | def test_macro(): | |
178 | ip = get_ipython() |
|
178 | ip = get_ipython() | |
179 | ip.history_manager.reset() # Clear any existing history. |
|
179 | ip.history_manager.reset() # Clear any existing history. | |
180 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] |
|
180 | cmds = ["a=1", "def b():\n return a**2", "print(a,b())"] | |
181 | for cmd in cmds: |
|
181 | for cmd in cmds: | |
182 | ip.history_manager.store_inputs(cmd) |
|
182 | ip.history_manager.store_inputs(cmd) | |
183 | ip.magic("macro test 1-3") |
|
183 | ip.magic("macro test 1-3") | |
184 | nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n") |
|
184 | nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n") | |
185 |
|
185 | |||
186 | # List macros. This goes to stdout, so just check it doesn't crash. |
|
186 | # List macros. | |
187 | ip.magic("macro") |
|
187 | assert "test" in ip.magic("macro") | |
188 |
|
188 | |||
189 |
|
189 | |||
190 | # XXX failing for now, until we get clearcmd out of quarantine. But we should |
|
190 | # XXX failing for now, until we get clearcmd out of quarantine. But we should | |
191 | # fix this and revert the skip to happen only if numpy is not around. |
|
191 | # fix this and revert the skip to happen only if numpy is not around. | |
192 | #@dec.skipif_not_numpy |
|
192 | #@dec.skipif_not_numpy | |
193 | @dec.skip_known_failure |
|
193 | @dec.skip_known_failure | |
194 | def test_numpy_clear_array_undec(): |
|
194 | def test_numpy_clear_array_undec(): | |
195 | from IPython.extensions import clearcmd |
|
195 | from IPython.extensions import clearcmd | |
196 |
|
196 | |||
197 | _ip.ex('import numpy as np') |
|
197 | _ip.ex('import numpy as np') | |
198 | _ip.ex('a = np.empty(2)') |
|
198 | _ip.ex('a = np.empty(2)') | |
199 | yield (nt.assert_true, 'a' in _ip.user_ns) |
|
199 | yield (nt.assert_true, 'a' in _ip.user_ns) | |
200 | _ip.magic('clear array') |
|
200 | _ip.magic('clear array') | |
201 | yield (nt.assert_false, 'a' in _ip.user_ns) |
|
201 | yield (nt.assert_false, 'a' in _ip.user_ns) | |
202 |
|
202 | |||
203 |
|
203 | |||
204 | # Multiple tests for clipboard pasting |
|
204 | # Multiple tests for clipboard pasting | |
205 | @dec.parametric |
|
205 | @dec.parametric | |
206 | def test_paste(): |
|
206 | def test_paste(): | |
207 | _ip = get_ipython() |
|
207 | _ip = get_ipython() | |
208 | def paste(txt, flags='-q'): |
|
208 | def paste(txt, flags='-q'): | |
209 | """Paste input text, by default in quiet mode""" |
|
209 | """Paste input text, by default in quiet mode""" | |
210 | hooks.clipboard_get = lambda : txt |
|
210 | hooks.clipboard_get = lambda : txt | |
211 | _ip.magic('paste '+flags) |
|
211 | _ip.magic('paste '+flags) | |
212 |
|
212 | |||
213 | # Inject fake clipboard hook but save original so we can restore it later |
|
213 | # Inject fake clipboard hook but save original so we can restore it later | |
214 | hooks = _ip.hooks |
|
214 | hooks = _ip.hooks | |
215 | user_ns = _ip.user_ns |
|
215 | user_ns = _ip.user_ns | |
216 | original_clip = hooks.clipboard_get |
|
216 | original_clip = hooks.clipboard_get | |
217 |
|
217 | |||
218 | try: |
|
218 | try: | |
219 | # This try/except with an emtpy except clause is here only because |
|
219 | # This try/except with an emtpy except clause is here only because | |
220 | # try/yield/finally is invalid syntax in Python 2.4. This will be |
|
220 | # try/yield/finally is invalid syntax in Python 2.4. This will be | |
221 | # removed when we drop 2.4-compatibility, and the emtpy except below |
|
221 | # removed when we drop 2.4-compatibility, and the emtpy except below | |
222 | # will be changed to a finally. |
|
222 | # will be changed to a finally. | |
223 |
|
223 | |||
224 | # Run tests with fake clipboard function |
|
224 | # Run tests with fake clipboard function | |
225 | user_ns.pop('x', None) |
|
225 | user_ns.pop('x', None) | |
226 | paste('x=1') |
|
226 | paste('x=1') | |
227 | yield nt.assert_equal(user_ns['x'], 1) |
|
227 | yield nt.assert_equal(user_ns['x'], 1) | |
228 |
|
228 | |||
229 | user_ns.pop('x', None) |
|
229 | user_ns.pop('x', None) | |
230 | paste('>>> x=2') |
|
230 | paste('>>> x=2') | |
231 | yield nt.assert_equal(user_ns['x'], 2) |
|
231 | yield nt.assert_equal(user_ns['x'], 2) | |
232 |
|
232 | |||
233 | paste(""" |
|
233 | paste(""" | |
234 | >>> x = [1,2,3] |
|
234 | >>> x = [1,2,3] | |
235 | >>> y = [] |
|
235 | >>> y = [] | |
236 | >>> for i in x: |
|
236 | >>> for i in x: | |
237 | ... y.append(i**2) |
|
237 | ... y.append(i**2) | |
238 | ... |
|
238 | ... | |
239 | """) |
|
239 | """) | |
240 | yield nt.assert_equal(user_ns['x'], [1,2,3]) |
|
240 | yield nt.assert_equal(user_ns['x'], [1,2,3]) | |
241 | yield nt.assert_equal(user_ns['y'], [1,4,9]) |
|
241 | yield nt.assert_equal(user_ns['y'], [1,4,9]) | |
242 |
|
242 | |||
243 | # Now, test that paste -r works |
|
243 | # Now, test that paste -r works | |
244 | user_ns.pop('x', None) |
|
244 | user_ns.pop('x', None) | |
245 | yield nt.assert_false('x' in user_ns) |
|
245 | yield nt.assert_false('x' in user_ns) | |
246 | _ip.magic('paste -r') |
|
246 | _ip.magic('paste -r') | |
247 | yield nt.assert_equal(user_ns['x'], [1,2,3]) |
|
247 | yield nt.assert_equal(user_ns['x'], [1,2,3]) | |
248 |
|
248 | |||
249 | # Also test paste echoing, by temporarily faking the writer |
|
249 | # Also test paste echoing, by temporarily faking the writer | |
250 | w = StringIO() |
|
250 | w = StringIO() | |
251 | writer = _ip.write |
|
251 | writer = _ip.write | |
252 | _ip.write = w.write |
|
252 | _ip.write = w.write | |
253 | code = """ |
|
253 | code = """ | |
254 | a = 100 |
|
254 | a = 100 | |
255 | b = 200""" |
|
255 | b = 200""" | |
256 | try: |
|
256 | try: | |
257 | paste(code,'') |
|
257 | paste(code,'') | |
258 | out = w.getvalue() |
|
258 | out = w.getvalue() | |
259 | finally: |
|
259 | finally: | |
260 | _ip.write = writer |
|
260 | _ip.write = writer | |
261 | yield nt.assert_equal(user_ns['a'], 100) |
|
261 | yield nt.assert_equal(user_ns['a'], 100) | |
262 | yield nt.assert_equal(user_ns['b'], 200) |
|
262 | yield nt.assert_equal(user_ns['b'], 200) | |
263 | yield nt.assert_equal(out, code+"\n## -- End pasted text --\n") |
|
263 | yield nt.assert_equal(out, code+"\n## -- End pasted text --\n") | |
264 |
|
264 | |||
265 | finally: |
|
265 | finally: | |
266 | # This should be in a finally clause, instead of the bare except above. |
|
266 | # This should be in a finally clause, instead of the bare except above. | |
267 | # Restore original hook |
|
267 | # Restore original hook | |
268 | hooks.clipboard_get = original_clip |
|
268 | hooks.clipboard_get = original_clip | |
269 |
|
269 | |||
270 |
|
270 | |||
271 | def test_time(): |
|
271 | def test_time(): | |
272 | _ip.magic('time None') |
|
272 | _ip.magic('time None') | |
273 |
|
273 | |||
274 |
|
274 | |||
275 | def doctest_time(): |
|
275 | def doctest_time(): | |
276 | """ |
|
276 | """ | |
277 | In [10]: %time None |
|
277 | In [10]: %time None | |
278 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
278 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
279 | Wall time: 0.00 s |
|
279 | Wall time: 0.00 s | |
280 | """ |
|
280 | """ | |
281 |
|
281 | |||
282 |
|
282 | |||
283 | def test_doctest_mode(): |
|
283 | def test_doctest_mode(): | |
284 | "Toggle doctest_mode twice, it should be a no-op and run without error" |
|
284 | "Toggle doctest_mode twice, it should be a no-op and run without error" | |
285 | _ip.magic('doctest_mode') |
|
285 | _ip.magic('doctest_mode') | |
286 | _ip.magic('doctest_mode') |
|
286 | _ip.magic('doctest_mode') | |
287 |
|
287 | |||
288 |
|
288 | |||
289 | def test_parse_options(): |
|
289 | def test_parse_options(): | |
290 | """Tests for basic options parsing in magics.""" |
|
290 | """Tests for basic options parsing in magics.""" | |
291 | # These are only the most minimal of tests, more should be added later. At |
|
291 | # These are only the most minimal of tests, more should be added later. At | |
292 | # the very least we check that basic text/unicode calls work OK. |
|
292 | # the very least we check that basic text/unicode calls work OK. | |
293 | nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo') |
|
293 | nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo') | |
294 | nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo') |
|
294 | nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo') | |
295 |
|
295 | |||
296 |
|
296 | |||
297 | def test_dirops(): |
|
297 | def test_dirops(): | |
298 | """Test various directory handling operations.""" |
|
298 | """Test various directory handling operations.""" | |
299 | curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/') |
|
299 | curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/') | |
300 |
|
300 | |||
301 | startdir = os.getcwd() |
|
301 | startdir = os.getcwd() | |
302 | ipdir = _ip.ipython_dir |
|
302 | ipdir = _ip.ipython_dir | |
303 | try: |
|
303 | try: | |
304 | _ip.magic('cd "%s"' % ipdir) |
|
304 | _ip.magic('cd "%s"' % ipdir) | |
305 | nt.assert_equal(curpath(), ipdir) |
|
305 | nt.assert_equal(curpath(), ipdir) | |
306 | _ip.magic('cd -') |
|
306 | _ip.magic('cd -') | |
307 | nt.assert_equal(curpath(), startdir) |
|
307 | nt.assert_equal(curpath(), startdir) | |
308 | _ip.magic('pushd "%s"' % ipdir) |
|
308 | _ip.magic('pushd "%s"' % ipdir) | |
309 | nt.assert_equal(curpath(), ipdir) |
|
309 | nt.assert_equal(curpath(), ipdir) | |
310 | _ip.magic('popd') |
|
310 | _ip.magic('popd') | |
311 | nt.assert_equal(curpath(), startdir) |
|
311 | nt.assert_equal(curpath(), startdir) | |
312 | finally: |
|
312 | finally: | |
313 | os.chdir(startdir) |
|
313 | os.chdir(startdir) | |
314 |
|
314 | |||
315 |
|
315 | |||
316 | def check_cpaste(code, should_fail=False): |
|
316 | def check_cpaste(code, should_fail=False): | |
317 | """Execute code via 'cpaste' and ensure it was executed, unless |
|
317 | """Execute code via 'cpaste' and ensure it was executed, unless | |
318 | should_fail is set. |
|
318 | should_fail is set. | |
319 | """ |
|
319 | """ | |
320 | _ip.user_ns['code_ran'] = False |
|
320 | _ip.user_ns['code_ran'] = False | |
321 |
|
321 | |||
322 | src = StringIO() |
|
322 | src = StringIO() | |
323 | src.write('\n') |
|
323 | src.write('\n') | |
324 | src.write(code) |
|
324 | src.write(code) | |
325 | src.write('\n--\n') |
|
325 | src.write('\n--\n') | |
326 | src.seek(0) |
|
326 | src.seek(0) | |
327 |
|
327 | |||
328 | stdin_save = sys.stdin |
|
328 | stdin_save = sys.stdin | |
329 | sys.stdin = src |
|
329 | sys.stdin = src | |
330 |
|
330 | |||
331 | try: |
|
331 | try: | |
332 | _ip.magic('cpaste') |
|
332 | _ip.magic('cpaste') | |
333 | except: |
|
333 | except: | |
334 | if not should_fail: |
|
334 | if not should_fail: | |
335 | raise AssertionError("Failure not expected : '%s'" % |
|
335 | raise AssertionError("Failure not expected : '%s'" % | |
336 | code) |
|
336 | code) | |
337 | else: |
|
337 | else: | |
338 | assert _ip.user_ns['code_ran'] |
|
338 | assert _ip.user_ns['code_ran'] | |
339 | if should_fail: |
|
339 | if should_fail: | |
340 | raise AssertionError("Failure expected : '%s'" % code) |
|
340 | raise AssertionError("Failure expected : '%s'" % code) | |
341 | finally: |
|
341 | finally: | |
342 | sys.stdin = stdin_save |
|
342 | sys.stdin = stdin_save | |
343 |
|
343 | |||
344 |
|
344 | |||
345 | def test_cpaste(): |
|
345 | def test_cpaste(): | |
346 | """Test cpaste magic""" |
|
346 | """Test cpaste magic""" | |
347 |
|
347 | |||
348 | def run(): |
|
348 | def run(): | |
349 | """Marker function: sets a flag when executed. |
|
349 | """Marker function: sets a flag when executed. | |
350 | """ |
|
350 | """ | |
351 | _ip.user_ns['code_ran'] = True |
|
351 | _ip.user_ns['code_ran'] = True | |
352 | return 'run' # return string so '+ run()' doesn't result in success |
|
352 | return 'run' # return string so '+ run()' doesn't result in success | |
353 |
|
353 | |||
354 | tests = {'pass': ["> > > run()", |
|
354 | tests = {'pass': ["> > > run()", | |
355 | ">>> > run()", |
|
355 | ">>> > run()", | |
356 | "+++ run()", |
|
356 | "+++ run()", | |
357 | "++ run()", |
|
357 | "++ run()", | |
358 | " >>> run()"], |
|
358 | " >>> run()"], | |
359 |
|
359 | |||
360 | 'fail': ["+ + run()", |
|
360 | 'fail': ["+ + run()", | |
361 | " ++ run()"]} |
|
361 | " ++ run()"]} | |
362 |
|
362 | |||
363 | _ip.user_ns['run'] = run |
|
363 | _ip.user_ns['run'] = run | |
364 |
|
364 | |||
365 | for code in tests['pass']: |
|
365 | for code in tests['pass']: | |
366 | check_cpaste(code) |
|
366 | check_cpaste(code) | |
367 |
|
367 | |||
368 | for code in tests['fail']: |
|
368 | for code in tests['fail']: | |
369 | check_cpaste(code, should_fail=True) |
|
369 | check_cpaste(code, should_fail=True) | |
370 |
|
370 | |||
371 | def test_xmode(): |
|
371 | def test_xmode(): | |
372 | # Calling xmode three times should be a no-op |
|
372 | # Calling xmode three times should be a no-op | |
373 | xmode = _ip.InteractiveTB.mode |
|
373 | xmode = _ip.InteractiveTB.mode | |
374 | for i in range(3): |
|
374 | for i in range(3): | |
375 | _ip.magic("xmode") |
|
375 | _ip.magic("xmode") | |
376 | nt.assert_equal(_ip.InteractiveTB.mode, xmode) |
|
376 | nt.assert_equal(_ip.InteractiveTB.mode, xmode) | |
377 |
|
377 | |||
378 | def doctest_who(): |
|
378 | def doctest_who(): | |
379 | """doctest for %who |
|
379 | """doctest for %who | |
380 |
|
380 | |||
381 | In [1]: %reset -f |
|
381 | In [1]: %reset -f | |
382 |
|
382 | |||
383 | In [2]: alpha = 123 |
|
383 | In [2]: alpha = 123 | |
384 |
|
384 | |||
385 | In [3]: beta = 'beta' |
|
385 | In [3]: beta = 'beta' | |
386 |
|
386 | |||
387 | In [4]: %who int |
|
387 | In [4]: %who int | |
388 | alpha |
|
388 | alpha | |
389 |
|
389 | |||
390 | In [5]: %who str |
|
390 | In [5]: %who str | |
391 | beta |
|
391 | beta | |
392 |
|
392 | |||
393 | In [6]: %whos |
|
393 | In [6]: %whos | |
394 | Variable Type Data/Info |
|
394 | Variable Type Data/Info | |
395 | ---------------------------- |
|
395 | ---------------------------- | |
396 | alpha int 123 |
|
396 | alpha int 123 | |
397 | beta str beta |
|
397 | beta str beta | |
398 |
|
398 | |||
399 | In [7]: %who_ls |
|
399 | In [7]: %who_ls | |
400 | Out[7]: ['alpha', 'beta'] |
|
400 | Out[7]: ['alpha', 'beta'] | |
401 | """ |
|
401 | """ | |
402 |
|
402 | |||
403 | def doctest_precision(): |
|
403 | def doctest_precision(): | |
404 | """doctest for %precision |
|
404 | """doctest for %precision | |
405 |
|
405 | |||
406 | In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain'] |
|
406 | In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain'] | |
407 |
|
407 | |||
408 | In [2]: %precision 5 |
|
408 | In [2]: %precision 5 | |
409 | Out[2]: '%.5f' |
|
409 | Out[2]: '%.5f' | |
410 |
|
410 | |||
411 | In [3]: f.float_format |
|
411 | In [3]: f.float_format | |
412 | Out[3]: '%.5f' |
|
412 | Out[3]: '%.5f' | |
413 |
|
413 | |||
414 | In [4]: %precision %e |
|
414 | In [4]: %precision %e | |
415 | Out[4]: '%e' |
|
415 | Out[4]: '%e' | |
416 |
|
416 | |||
417 | In [5]: f(3.1415927) |
|
417 | In [5]: f(3.1415927) | |
418 | Out[5]: '3.141593e+00' |
|
418 | Out[5]: '3.141593e+00' | |
419 | """ |
|
419 | """ | |
420 |
|
420 |
General Comments 0
You need to be logged in to leave comments.
Login now