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