Show More
@@ -1,3486 +1,3369 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 The IPython Development Team | |
9 |
|
9 | |||
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | import __builtin__ |
|
18 | import __builtin__ | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | import shutil |
|
24 | import shutil | |
25 | import re |
|
25 | import re | |
26 | import time |
|
26 | import time | |
27 | import textwrap |
|
27 | import textwrap | |
28 | import types |
|
28 | import types | |
29 | from cStringIO import StringIO |
|
29 | from cStringIO import StringIO | |
30 | from getopt import getopt,GetoptError |
|
30 | from getopt import getopt,GetoptError | |
31 | from pprint import pformat |
|
31 | from pprint import pformat | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | # print_function was added to __future__ in Python2.6, remove this when we drop |
|
44 | # print_function was added to __future__ in Python2.6, remove this when we drop | |
45 | # 2.5 compatibility |
|
45 | # 2.5 compatibility | |
46 | if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'): |
|
46 | if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'): | |
47 | __future__.CO_FUTURE_PRINT_FUNCTION = 65536 |
|
47 | __future__.CO_FUTURE_PRINT_FUNCTION = 65536 | |
48 |
|
48 | |||
49 | import IPython |
|
49 | import IPython | |
50 | from IPython.core import debugger, oinspect |
|
50 | from IPython.core import debugger, oinspect | |
51 | from IPython.core.error import TryNext |
|
51 | from IPython.core.error import TryNext | |
52 | from IPython.core.error import UsageError |
|
52 | from IPython.core.error import UsageError | |
53 | from IPython.core.fakemodule import FakeModule |
|
53 | from IPython.core.fakemodule import FakeModule | |
54 | from IPython.core.macro import Macro |
|
54 | from IPython.core.macro import Macro | |
55 | from IPython.core import page |
|
55 | from IPython.core import page | |
56 | from IPython.core.prefilter import ESC_MAGIC |
|
56 | from IPython.core.prefilter import ESC_MAGIC | |
57 | from IPython.lib.pylabtools import mpl_runner |
|
57 | from IPython.lib.pylabtools import mpl_runner | |
58 | from IPython.external.Itpl import itpl, printpl |
|
58 | from IPython.external.Itpl import itpl, printpl | |
59 | from IPython.testing import decorators as testdec |
|
59 | from IPython.testing import decorators as testdec | |
60 | from IPython.utils.io import file_read, nlprint |
|
60 | from IPython.utils.io import file_read, nlprint | |
61 | import IPython.utils.io |
|
61 | import IPython.utils.io | |
62 | from IPython.utils.path import get_py_filename |
|
62 | from IPython.utils.path import get_py_filename | |
63 | from IPython.utils.process import arg_split, abbrev_cwd |
|
63 | from IPython.utils.process import arg_split, abbrev_cwd | |
64 | from IPython.utils.terminal import set_term_title |
|
64 | from IPython.utils.terminal import set_term_title | |
65 | from IPython.utils.text import LSString, SList, StringTypes, format_screen |
|
65 | from IPython.utils.text import LSString, SList, StringTypes, format_screen | |
66 | from IPython.utils.timing import clock, clock2 |
|
66 | from IPython.utils.timing import clock, clock2 | |
67 | from IPython.utils.warn import warn, error |
|
67 | from IPython.utils.warn import warn, error | |
68 | from IPython.utils.ipstruct import Struct |
|
68 | from IPython.utils.ipstruct import Struct | |
69 | import IPython.utils.generics |
|
69 | import IPython.utils.generics | |
70 |
|
70 | |||
71 | #----------------------------------------------------------------------------- |
|
71 | #----------------------------------------------------------------------------- | |
72 | # Utility functions |
|
72 | # Utility functions | |
73 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
74 |
|
74 | |||
75 | def on_off(tag): |
|
75 | def on_off(tag): | |
76 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
76 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
77 | return ['OFF','ON'][tag] |
|
77 | return ['OFF','ON'][tag] | |
78 |
|
78 | |||
79 | class Bunch: pass |
|
79 | class Bunch: pass | |
80 |
|
80 | |||
81 | def compress_dhist(dh): |
|
81 | def compress_dhist(dh): | |
82 | head, tail = dh[:-10], dh[-10:] |
|
82 | head, tail = dh[:-10], dh[-10:] | |
83 |
|
83 | |||
84 | newhead = [] |
|
84 | newhead = [] | |
85 | done = set() |
|
85 | done = set() | |
86 | for h in head: |
|
86 | for h in head: | |
87 | if h in done: |
|
87 | if h in done: | |
88 | continue |
|
88 | continue | |
89 | newhead.append(h) |
|
89 | newhead.append(h) | |
90 | done.add(h) |
|
90 | done.add(h) | |
91 |
|
91 | |||
92 | return newhead + tail |
|
92 | return newhead + tail | |
93 |
|
93 | |||
94 |
|
94 | |||
95 | #*************************************************************************** |
|
95 | #*************************************************************************** | |
96 | # Main class implementing Magic functionality |
|
96 | # Main class implementing Magic functionality | |
97 |
|
97 | |||
98 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
98 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
99 | # on construction of the main InteractiveShell object. Something odd is going |
|
99 | # on construction of the main InteractiveShell object. Something odd is going | |
100 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
100 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
101 | # eventually this needs to be clarified. |
|
101 | # eventually this needs to be clarified. | |
102 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
102 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
103 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
103 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
104 | # make Magic a configurable that InteractiveShell does not subclass. |
|
104 | # make Magic a configurable that InteractiveShell does not subclass. | |
105 |
|
105 | |||
106 | class Magic: |
|
106 | class Magic: | |
107 | """Magic functions for InteractiveShell. |
|
107 | """Magic functions for InteractiveShell. | |
108 |
|
108 | |||
109 | Shell functions which can be reached as %function_name. All magic |
|
109 | Shell functions which can be reached as %function_name. All magic | |
110 | functions should accept a string, which they can parse for their own |
|
110 | functions should accept a string, which they can parse for their own | |
111 | needs. This can make some functions easier to type, eg `%cd ../` |
|
111 | needs. This can make some functions easier to type, eg `%cd ../` | |
112 | vs. `%cd("../")` |
|
112 | vs. `%cd("../")` | |
113 |
|
113 | |||
114 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
114 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
115 | at the command line, but it is is needed in the definition. """ |
|
115 | at the command line, but it is is needed in the definition. """ | |
116 |
|
116 | |||
117 | # class globals |
|
117 | # class globals | |
118 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
118 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
119 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
119 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
120 |
|
120 | |||
121 | #...................................................................... |
|
121 | #...................................................................... | |
122 | # some utility functions |
|
122 | # some utility functions | |
123 |
|
123 | |||
124 | def __init__(self,shell): |
|
124 | def __init__(self,shell): | |
125 |
|
125 | |||
126 | self.options_table = {} |
|
126 | self.options_table = {} | |
127 | if profile is None: |
|
127 | if profile is None: | |
128 | self.magic_prun = self.profile_missing_notice |
|
128 | self.magic_prun = self.profile_missing_notice | |
129 | self.shell = shell |
|
129 | self.shell = shell | |
130 |
|
130 | |||
131 | # namespace for holding state we may need |
|
131 | # namespace for holding state we may need | |
132 | self._magic_state = Bunch() |
|
132 | self._magic_state = Bunch() | |
133 |
|
133 | |||
134 | def profile_missing_notice(self, *args, **kwargs): |
|
134 | def profile_missing_notice(self, *args, **kwargs): | |
135 | error("""\ |
|
135 | error("""\ | |
136 | The profile module could not be found. It has been removed from the standard |
|
136 | The profile module could not be found. It has been removed from the standard | |
137 | python packages because of its non-free license. To use profiling, install the |
|
137 | python packages because of its non-free license. To use profiling, install the | |
138 | python-profiler package from non-free.""") |
|
138 | python-profiler package from non-free.""") | |
139 |
|
139 | |||
140 | def default_option(self,fn,optstr): |
|
140 | def default_option(self,fn,optstr): | |
141 | """Make an entry in the options_table for fn, with value optstr""" |
|
141 | """Make an entry in the options_table for fn, with value optstr""" | |
142 |
|
142 | |||
143 | if fn not in self.lsmagic(): |
|
143 | if fn not in self.lsmagic(): | |
144 | error("%s is not a magic function" % fn) |
|
144 | error("%s is not a magic function" % fn) | |
145 | self.options_table[fn] = optstr |
|
145 | self.options_table[fn] = optstr | |
146 |
|
146 | |||
147 | def lsmagic(self): |
|
147 | def lsmagic(self): | |
148 | """Return a list of currently available magic functions. |
|
148 | """Return a list of currently available magic functions. | |
149 |
|
149 | |||
150 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
150 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
151 | ['magic_ls','magic_cd',...]""" |
|
151 | ['magic_ls','magic_cd',...]""" | |
152 |
|
152 | |||
153 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
153 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
154 |
|
154 | |||
155 | # magics in class definition |
|
155 | # magics in class definition | |
156 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
156 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
157 | callable(Magic.__dict__[fn]) |
|
157 | callable(Magic.__dict__[fn]) | |
158 | # in instance namespace (run-time user additions) |
|
158 | # in instance namespace (run-time user additions) | |
159 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
159 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
160 | callable(self.__dict__[fn]) |
|
160 | callable(self.__dict__[fn]) | |
161 | # and bound magics by user (so they can access self): |
|
161 | # and bound magics by user (so they can access self): | |
162 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
162 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
163 | callable(self.__class__.__dict__[fn]) |
|
163 | callable(self.__class__.__dict__[fn]) | |
164 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
164 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
165 | filter(inst_magic,self.__dict__.keys()) + \ |
|
165 | filter(inst_magic,self.__dict__.keys()) + \ | |
166 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
166 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
167 | out = [] |
|
167 | out = [] | |
168 | for fn in set(magics): |
|
168 | for fn in set(magics): | |
169 | out.append(fn.replace('magic_','',1)) |
|
169 | out.append(fn.replace('magic_','',1)) | |
170 | out.sort() |
|
170 | out.sort() | |
171 | return out |
|
171 | return out | |
172 |
|
172 | |||
173 | def extract_input_slices(self,slices,raw=False): |
|
173 | def extract_input_slices(self,slices,raw=False): | |
174 | """Return as a string a set of input history slices. |
|
174 | """Return as a string a set of input history slices. | |
175 |
|
175 | |||
176 | Inputs: |
|
176 | Inputs: | |
177 |
|
177 | |||
178 | - slices: the set of slices is given as a list of strings (like |
|
178 | - slices: the set of slices is given as a list of strings (like | |
179 | ['1','4:8','9'], since this function is for use by magic functions |
|
179 | ['1','4:8','9'], since this function is for use by magic functions | |
180 | which get their arguments as strings. |
|
180 | which get their arguments as strings. | |
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 |
|
192 | |||
193 | if raw: |
|
193 | if raw: | |
194 | hist = self.shell.input_hist_raw |
|
194 | hist = self.shell.input_hist_raw | |
195 | else: |
|
195 | else: | |
196 | hist = self.shell.input_hist |
|
196 | hist = self.shell.input_hist | |
197 |
|
197 | |||
198 | cmds = [] |
|
198 | cmds = [] | |
199 | for chunk in slices: |
|
199 | for chunk in slices: | |
200 | if ':' in chunk: |
|
200 | if ':' in chunk: | |
201 | ini,fin = map(int,chunk.split(':')) |
|
201 | ini,fin = map(int,chunk.split(':')) | |
202 | elif '-' in chunk: |
|
202 | elif '-' in chunk: | |
203 | ini,fin = map(int,chunk.split('-')) |
|
203 | ini,fin = map(int,chunk.split('-')) | |
204 | fin += 1 |
|
204 | fin += 1 | |
205 | else: |
|
205 | else: | |
206 | ini = int(chunk) |
|
206 | ini = int(chunk) | |
207 | fin = ini+1 |
|
207 | fin = ini+1 | |
208 | cmds.append(hist[ini:fin]) |
|
208 | cmds.append(hist[ini:fin]) | |
209 | return cmds |
|
209 | return cmds | |
210 |
|
210 | |||
211 | def arg_err(self,func): |
|
211 | def arg_err(self,func): | |
212 | """Print docstring if incorrect arguments were passed""" |
|
212 | """Print docstring if incorrect arguments were passed""" | |
213 | print 'Error in arguments:' |
|
213 | print 'Error in arguments:' | |
214 | print oinspect.getdoc(func) |
|
214 | print oinspect.getdoc(func) | |
215 |
|
215 | |||
216 | def format_latex(self,strng): |
|
216 | def format_latex(self,strng): | |
217 | """Format a string for latex inclusion.""" |
|
217 | """Format a string for latex inclusion.""" | |
218 |
|
218 | |||
219 | # Characters that need to be escaped for latex: |
|
219 | # Characters that need to be escaped for latex: | |
220 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
220 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
221 | # Magic command names as headers: |
|
221 | # Magic command names as headers: | |
222 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
222 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
223 | re.MULTILINE) |
|
223 | re.MULTILINE) | |
224 | # Magic commands |
|
224 | # Magic commands | |
225 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
225 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
226 | re.MULTILINE) |
|
226 | re.MULTILINE) | |
227 | # Paragraph continue |
|
227 | # Paragraph continue | |
228 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
228 | par_re = re.compile(r'\\$',re.MULTILINE) | |
229 |
|
229 | |||
230 | # The "\n" symbol |
|
230 | # The "\n" symbol | |
231 | newline_re = re.compile(r'\\n') |
|
231 | newline_re = re.compile(r'\\n') | |
232 |
|
232 | |||
233 | # Now build the string for output: |
|
233 | # Now build the string for output: | |
234 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
234 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
235 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
235 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
236 | strng) |
|
236 | strng) | |
237 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
237 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
238 | strng = par_re.sub(r'\\\\',strng) |
|
238 | strng = par_re.sub(r'\\\\',strng) | |
239 | strng = escape_re.sub(r'\\\1',strng) |
|
239 | strng = escape_re.sub(r'\\\1',strng) | |
240 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
240 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
241 | return strng |
|
241 | return strng | |
242 |
|
242 | |||
243 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
243 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
244 | """Parse options passed to an argument string. |
|
244 | """Parse options passed to an argument string. | |
245 |
|
245 | |||
246 | The interface is similar to that of getopt(), but it returns back a |
|
246 | The interface is similar to that of getopt(), but it returns back a | |
247 | Struct with the options as keys and the stripped argument string still |
|
247 | Struct with the options as keys and the stripped argument string still | |
248 | as a string. |
|
248 | as a string. | |
249 |
|
249 | |||
250 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
250 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
251 | This allows us to easily expand variables, glob files, quote |
|
251 | This allows us to easily expand variables, glob files, quote | |
252 | arguments, etc. |
|
252 | arguments, etc. | |
253 |
|
253 | |||
254 | Options: |
|
254 | Options: | |
255 | -mode: default 'string'. If given as 'list', the argument string is |
|
255 | -mode: default 'string'. If given as 'list', the argument string is | |
256 | returned as a list (split on whitespace) instead of a string. |
|
256 | returned as a list (split on whitespace) instead of a string. | |
257 |
|
257 | |||
258 | -list_all: put all option values in lists. Normally only options |
|
258 | -list_all: put all option values in lists. Normally only options | |
259 | appearing more than once are put in a list. |
|
259 | appearing more than once are put in a list. | |
260 |
|
260 | |||
261 | -posix (True): whether to split the input line in POSIX mode or not, |
|
261 | -posix (True): whether to split the input line in POSIX mode or not, | |
262 | as per the conventions outlined in the shlex module from the |
|
262 | as per the conventions outlined in the shlex module from the | |
263 | standard library.""" |
|
263 | standard library.""" | |
264 |
|
264 | |||
265 | # inject default options at the beginning of the input line |
|
265 | # inject default options at the beginning of the input line | |
266 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
266 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
267 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
267 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
268 |
|
268 | |||
269 | mode = kw.get('mode','string') |
|
269 | mode = kw.get('mode','string') | |
270 | if mode not in ['string','list']: |
|
270 | if mode not in ['string','list']: | |
271 | raise ValueError,'incorrect mode given: %s' % mode |
|
271 | raise ValueError,'incorrect mode given: %s' % mode | |
272 | # Get options |
|
272 | # Get options | |
273 | list_all = kw.get('list_all',0) |
|
273 | list_all = kw.get('list_all',0) | |
274 | posix = kw.get('posix', os.name == 'posix') |
|
274 | posix = kw.get('posix', os.name == 'posix') | |
275 |
|
275 | |||
276 | # Check if we have more than one argument to warrant extra processing: |
|
276 | # Check if we have more than one argument to warrant extra processing: | |
277 | odict = {} # Dictionary with options |
|
277 | odict = {} # Dictionary with options | |
278 | args = arg_str.split() |
|
278 | args = arg_str.split() | |
279 | if len(args) >= 1: |
|
279 | if len(args) >= 1: | |
280 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
280 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
281 | # need to look for options |
|
281 | # need to look for options | |
282 | argv = arg_split(arg_str,posix) |
|
282 | argv = arg_split(arg_str,posix) | |
283 | # Do regular option processing |
|
283 | # Do regular option processing | |
284 | try: |
|
284 | try: | |
285 | opts,args = getopt(argv,opt_str,*long_opts) |
|
285 | opts,args = getopt(argv,opt_str,*long_opts) | |
286 | except GetoptError,e: |
|
286 | except GetoptError,e: | |
287 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
287 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
288 | " ".join(long_opts))) |
|
288 | " ".join(long_opts))) | |
289 | for o,a in opts: |
|
289 | for o,a in opts: | |
290 | if o.startswith('--'): |
|
290 | if o.startswith('--'): | |
291 | o = o[2:] |
|
291 | o = o[2:] | |
292 | else: |
|
292 | else: | |
293 | o = o[1:] |
|
293 | o = o[1:] | |
294 | try: |
|
294 | try: | |
295 | odict[o].append(a) |
|
295 | odict[o].append(a) | |
296 | except AttributeError: |
|
296 | except AttributeError: | |
297 | odict[o] = [odict[o],a] |
|
297 | odict[o] = [odict[o],a] | |
298 | except KeyError: |
|
298 | except KeyError: | |
299 | if list_all: |
|
299 | if list_all: | |
300 | odict[o] = [a] |
|
300 | odict[o] = [a] | |
301 | else: |
|
301 | else: | |
302 | odict[o] = a |
|
302 | odict[o] = a | |
303 |
|
303 | |||
304 | # Prepare opts,args for return |
|
304 | # Prepare opts,args for return | |
305 | opts = Struct(odict) |
|
305 | opts = Struct(odict) | |
306 | if mode == 'string': |
|
306 | if mode == 'string': | |
307 | args = ' '.join(args) |
|
307 | args = ' '.join(args) | |
308 |
|
308 | |||
309 | return opts,args |
|
309 | return opts,args | |
310 |
|
310 | |||
311 | #...................................................................... |
|
311 | #...................................................................... | |
312 | # And now the actual magic functions |
|
312 | # And now the actual magic functions | |
313 |
|
313 | |||
314 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
314 | # Functions for IPython shell work (vars,funcs, config, etc) | |
315 | def magic_lsmagic(self, parameter_s = ''): |
|
315 | def magic_lsmagic(self, parameter_s = ''): | |
316 | """List currently available magic functions.""" |
|
316 | """List currently available magic functions.""" | |
317 | mesc = ESC_MAGIC |
|
317 | mesc = ESC_MAGIC | |
318 | print 'Available magic functions:\n'+mesc+\ |
|
318 | print 'Available magic functions:\n'+mesc+\ | |
319 | (' '+mesc).join(self.lsmagic()) |
|
319 | (' '+mesc).join(self.lsmagic()) | |
320 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
320 | print '\n' + Magic.auto_status[self.shell.automagic] | |
321 | return None |
|
321 | return None | |
322 |
|
322 | |||
323 | def magic_magic(self, parameter_s = ''): |
|
323 | def magic_magic(self, parameter_s = ''): | |
324 | """Print information about the magic function system. |
|
324 | """Print information about the magic function system. | |
325 |
|
325 | |||
326 | Supported formats: -latex, -brief, -rest |
|
326 | Supported formats: -latex, -brief, -rest | |
327 | """ |
|
327 | """ | |
328 |
|
328 | |||
329 | mode = '' |
|
329 | mode = '' | |
330 | try: |
|
330 | try: | |
331 | if parameter_s.split()[0] == '-latex': |
|
331 | if parameter_s.split()[0] == '-latex': | |
332 | mode = 'latex' |
|
332 | mode = 'latex' | |
333 | if parameter_s.split()[0] == '-brief': |
|
333 | if parameter_s.split()[0] == '-brief': | |
334 | mode = 'brief' |
|
334 | mode = 'brief' | |
335 | if parameter_s.split()[0] == '-rest': |
|
335 | if parameter_s.split()[0] == '-rest': | |
336 | mode = 'rest' |
|
336 | mode = 'rest' | |
337 | rest_docs = [] |
|
337 | rest_docs = [] | |
338 | except: |
|
338 | except: | |
339 | pass |
|
339 | pass | |
340 |
|
340 | |||
341 | magic_docs = [] |
|
341 | magic_docs = [] | |
342 | for fname in self.lsmagic(): |
|
342 | for fname in self.lsmagic(): | |
343 | mname = 'magic_' + fname |
|
343 | mname = 'magic_' + fname | |
344 | for space in (Magic,self,self.__class__): |
|
344 | for space in (Magic,self,self.__class__): | |
345 | try: |
|
345 | try: | |
346 | fn = space.__dict__[mname] |
|
346 | fn = space.__dict__[mname] | |
347 | except KeyError: |
|
347 | except KeyError: | |
348 | pass |
|
348 | pass | |
349 | else: |
|
349 | else: | |
350 | break |
|
350 | break | |
351 | if mode == 'brief': |
|
351 | if mode == 'brief': | |
352 | # only first line |
|
352 | # only first line | |
353 | if fn.__doc__: |
|
353 | if fn.__doc__: | |
354 | fndoc = fn.__doc__.split('\n',1)[0] |
|
354 | fndoc = fn.__doc__.split('\n',1)[0] | |
355 | else: |
|
355 | else: | |
356 | fndoc = 'No documentation' |
|
356 | fndoc = 'No documentation' | |
357 | else: |
|
357 | else: | |
358 | if fn.__doc__: |
|
358 | if fn.__doc__: | |
359 | fndoc = fn.__doc__.rstrip() |
|
359 | fndoc = fn.__doc__.rstrip() | |
360 | else: |
|
360 | else: | |
361 | fndoc = 'No documentation' |
|
361 | fndoc = 'No documentation' | |
362 |
|
362 | |||
363 |
|
363 | |||
364 | if mode == 'rest': |
|
364 | if mode == 'rest': | |
365 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
365 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
366 | fname,fndoc)) |
|
366 | fname,fndoc)) | |
367 |
|
367 | |||
368 | else: |
|
368 | else: | |
369 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
369 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
370 | fname,fndoc)) |
|
370 | fname,fndoc)) | |
371 |
|
371 | |||
372 | magic_docs = ''.join(magic_docs) |
|
372 | magic_docs = ''.join(magic_docs) | |
373 |
|
373 | |||
374 | if mode == 'rest': |
|
374 | if mode == 'rest': | |
375 | return "".join(rest_docs) |
|
375 | return "".join(rest_docs) | |
376 |
|
376 | |||
377 | if mode == 'latex': |
|
377 | if mode == 'latex': | |
378 | print self.format_latex(magic_docs) |
|
378 | print self.format_latex(magic_docs) | |
379 | return |
|
379 | return | |
380 | else: |
|
380 | else: | |
381 | magic_docs = format_screen(magic_docs) |
|
381 | magic_docs = format_screen(magic_docs) | |
382 | if mode == 'brief': |
|
382 | if mode == 'brief': | |
383 | return magic_docs |
|
383 | return magic_docs | |
384 |
|
384 | |||
385 | outmsg = """ |
|
385 | outmsg = """ | |
386 | IPython's 'magic' functions |
|
386 | IPython's 'magic' functions | |
387 | =========================== |
|
387 | =========================== | |
388 |
|
388 | |||
389 | The magic function system provides a series of functions which allow you to |
|
389 | The magic function system provides a series of functions which allow you to | |
390 | control the behavior of IPython itself, plus a lot of system-type |
|
390 | control the behavior of IPython itself, plus a lot of system-type | |
391 | features. All these functions are prefixed with a % character, but parameters |
|
391 | features. All these functions are prefixed with a % character, but parameters | |
392 | are given without parentheses or quotes. |
|
392 | are given without parentheses or quotes. | |
393 |
|
393 | |||
394 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
394 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
395 | %automagic function), you don't need to type in the % explicitly. By default, |
|
395 | %automagic function), you don't need to type in the % explicitly. By default, | |
396 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
396 | IPython ships with automagic on, so you should only rarely need the % escape. | |
397 |
|
397 | |||
398 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
398 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
399 | to 'mydir', if it exists. |
|
399 | to 'mydir', if it exists. | |
400 |
|
400 | |||
401 | You can define your own magic functions to extend the system. See the supplied |
|
401 | You can define your own magic functions to extend the system. See the supplied | |
402 | ipythonrc and example-magic.py files for details (in your ipython |
|
402 | ipythonrc and example-magic.py files for details (in your ipython | |
403 | configuration directory, typically $HOME/.ipython/). |
|
403 | configuration directory, typically $HOME/.ipython/). | |
404 |
|
404 | |||
405 | You can also define your own aliased names for magic functions. In your |
|
405 | You can also define your own aliased names for magic functions. In your | |
406 | ipythonrc file, placing a line like: |
|
406 | ipythonrc file, placing a line like: | |
407 |
|
407 | |||
408 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
408 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
409 |
|
409 | |||
410 | will define %pf as a new name for %profile. |
|
410 | will define %pf as a new name for %profile. | |
411 |
|
411 | |||
412 | You can also call magics in code using the magic() function, which IPython |
|
412 | You can also call magics in code using the magic() function, which IPython | |
413 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
413 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
414 |
|
414 | |||
415 | For a list of the available magic functions, use %lsmagic. For a description |
|
415 | For a list of the available magic functions, use %lsmagic. For a description | |
416 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
416 | of any of them, type %magic_name?, e.g. '%cd?'. | |
417 |
|
417 | |||
418 | Currently the magic system has the following functions:\n""" |
|
418 | Currently the magic system has the following functions:\n""" | |
419 |
|
419 | |||
420 | mesc = ESC_MAGIC |
|
420 | mesc = ESC_MAGIC | |
421 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
421 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
422 | "\n\n%s%s\n\n%s" % (outmsg, |
|
422 | "\n\n%s%s\n\n%s" % (outmsg, | |
423 | magic_docs,mesc,mesc, |
|
423 | magic_docs,mesc,mesc, | |
424 | (' '+mesc).join(self.lsmagic()), |
|
424 | (' '+mesc).join(self.lsmagic()), | |
425 | Magic.auto_status[self.shell.automagic] ) ) |
|
425 | Magic.auto_status[self.shell.automagic] ) ) | |
426 | page.page(outmsg) |
|
426 | page.page(outmsg) | |
427 |
|
427 | |||
428 | def magic_autoindent(self, parameter_s = ''): |
|
|||
429 | """Toggle autoindent on/off (if available).""" |
|
|||
430 |
|
||||
431 | self.shell.set_autoindent() |
|
|||
432 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
|||
433 |
|
||||
434 | def magic_automagic(self, parameter_s = ''): |
|
428 | def magic_automagic(self, parameter_s = ''): | |
435 | """Make magic functions callable without having to type the initial %. |
|
429 | """Make magic functions callable without having to type the initial %. | |
436 |
|
430 | |||
437 | Without argumentsl toggles on/off (when off, you must call it as |
|
431 | Without argumentsl toggles on/off (when off, you must call it as | |
438 | %automagic, of course). With arguments it sets the value, and you can |
|
432 | %automagic, of course). With arguments it sets the value, and you can | |
439 | use any of (case insensitive): |
|
433 | use any of (case insensitive): | |
440 |
|
434 | |||
441 | - on,1,True: to activate |
|
435 | - on,1,True: to activate | |
442 |
|
436 | |||
443 | - off,0,False: to deactivate. |
|
437 | - off,0,False: to deactivate. | |
444 |
|
438 | |||
445 | Note that magic functions have lowest priority, so if there's a |
|
439 | Note that magic functions have lowest priority, so if there's a | |
446 | variable whose name collides with that of a magic fn, automagic won't |
|
440 | variable whose name collides with that of a magic fn, automagic won't | |
447 | work for that function (you get the variable instead). However, if you |
|
441 | work for that function (you get the variable instead). However, if you | |
448 | delete the variable (del var), the previously shadowed magic function |
|
442 | delete the variable (del var), the previously shadowed magic function | |
449 | becomes visible to automagic again.""" |
|
443 | becomes visible to automagic again.""" | |
450 |
|
444 | |||
451 | arg = parameter_s.lower() |
|
445 | arg = parameter_s.lower() | |
452 | if parameter_s in ('on','1','true'): |
|
446 | if parameter_s in ('on','1','true'): | |
453 | self.shell.automagic = True |
|
447 | self.shell.automagic = True | |
454 | elif parameter_s in ('off','0','false'): |
|
448 | elif parameter_s in ('off','0','false'): | |
455 | self.shell.automagic = False |
|
449 | self.shell.automagic = False | |
456 | else: |
|
450 | else: | |
457 | self.shell.automagic = not self.shell.automagic |
|
451 | self.shell.automagic = not self.shell.automagic | |
458 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
452 | print '\n' + Magic.auto_status[self.shell.automagic] | |
459 |
|
453 | |||
460 | @testdec.skip_doctest |
|
454 | @testdec.skip_doctest | |
461 | def magic_autocall(self, parameter_s = ''): |
|
455 | def magic_autocall(self, parameter_s = ''): | |
462 | """Make functions callable without having to type parentheses. |
|
456 | """Make functions callable without having to type parentheses. | |
463 |
|
457 | |||
464 | Usage: |
|
458 | Usage: | |
465 |
|
459 | |||
466 | %autocall [mode] |
|
460 | %autocall [mode] | |
467 |
|
461 | |||
468 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
462 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
469 | value is toggled on and off (remembering the previous state). |
|
463 | value is toggled on and off (remembering the previous state). | |
470 |
|
464 | |||
471 | In more detail, these values mean: |
|
465 | In more detail, these values mean: | |
472 |
|
466 | |||
473 | 0 -> fully disabled |
|
467 | 0 -> fully disabled | |
474 |
|
468 | |||
475 | 1 -> active, but do not apply if there are no arguments on the line. |
|
469 | 1 -> active, but do not apply if there are no arguments on the line. | |
476 |
|
470 | |||
477 | In this mode, you get: |
|
471 | In this mode, you get: | |
478 |
|
472 | |||
479 | In [1]: callable |
|
473 | In [1]: callable | |
480 | Out[1]: <built-in function callable> |
|
474 | Out[1]: <built-in function callable> | |
481 |
|
475 | |||
482 | In [2]: callable 'hello' |
|
476 | In [2]: callable 'hello' | |
483 | ------> callable('hello') |
|
477 | ------> callable('hello') | |
484 | Out[2]: False |
|
478 | Out[2]: False | |
485 |
|
479 | |||
486 | 2 -> Active always. Even if no arguments are present, the callable |
|
480 | 2 -> Active always. Even if no arguments are present, the callable | |
487 | object is called: |
|
481 | object is called: | |
488 |
|
482 | |||
489 | In [2]: float |
|
483 | In [2]: float | |
490 | ------> float() |
|
484 | ------> float() | |
491 | Out[2]: 0.0 |
|
485 | Out[2]: 0.0 | |
492 |
|
486 | |||
493 | Note that even with autocall off, you can still use '/' at the start of |
|
487 | Note that even with autocall off, you can still use '/' at the start of | |
494 | a line to treat the first argument on the command line as a function |
|
488 | a line to treat the first argument on the command line as a function | |
495 | and add parentheses to it: |
|
489 | and add parentheses to it: | |
496 |
|
490 | |||
497 | In [8]: /str 43 |
|
491 | In [8]: /str 43 | |
498 | ------> str(43) |
|
492 | ------> str(43) | |
499 | Out[8]: '43' |
|
493 | Out[8]: '43' | |
500 |
|
494 | |||
501 | # all-random (note for auto-testing) |
|
495 | # all-random (note for auto-testing) | |
502 | """ |
|
496 | """ | |
503 |
|
497 | |||
504 | if parameter_s: |
|
498 | if parameter_s: | |
505 | arg = int(parameter_s) |
|
499 | arg = int(parameter_s) | |
506 | else: |
|
500 | else: | |
507 | arg = 'toggle' |
|
501 | arg = 'toggle' | |
508 |
|
502 | |||
509 | if not arg in (0,1,2,'toggle'): |
|
503 | if not arg in (0,1,2,'toggle'): | |
510 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
504 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
511 | return |
|
505 | return | |
512 |
|
506 | |||
513 | if arg in (0,1,2): |
|
507 | if arg in (0,1,2): | |
514 | self.shell.autocall = arg |
|
508 | self.shell.autocall = arg | |
515 | else: # toggle |
|
509 | else: # toggle | |
516 | if self.shell.autocall: |
|
510 | if self.shell.autocall: | |
517 | self._magic_state.autocall_save = self.shell.autocall |
|
511 | self._magic_state.autocall_save = self.shell.autocall | |
518 | self.shell.autocall = 0 |
|
512 | self.shell.autocall = 0 | |
519 | else: |
|
513 | else: | |
520 | try: |
|
514 | try: | |
521 | self.shell.autocall = self._magic_state.autocall_save |
|
515 | self.shell.autocall = self._magic_state.autocall_save | |
522 | except AttributeError: |
|
516 | except AttributeError: | |
523 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
517 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
524 |
|
518 | |||
525 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
519 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
526 |
|
520 | |||
527 |
|
521 | |||
528 | def magic_page(self, parameter_s=''): |
|
522 | def magic_page(self, parameter_s=''): | |
529 | """Pretty print the object and display it through a pager. |
|
523 | """Pretty print the object and display it through a pager. | |
530 |
|
524 | |||
531 | %page [options] OBJECT |
|
525 | %page [options] OBJECT | |
532 |
|
526 | |||
533 | If no object is given, use _ (last output). |
|
527 | If no object is given, use _ (last output). | |
534 |
|
528 | |||
535 | Options: |
|
529 | Options: | |
536 |
|
530 | |||
537 | -r: page str(object), don't pretty-print it.""" |
|
531 | -r: page str(object), don't pretty-print it.""" | |
538 |
|
532 | |||
539 | # After a function contributed by Olivier Aubert, slightly modified. |
|
533 | # After a function contributed by Olivier Aubert, slightly modified. | |
540 |
|
534 | |||
541 | # Process options/args |
|
535 | # Process options/args | |
542 | opts,args = self.parse_options(parameter_s,'r') |
|
536 | opts,args = self.parse_options(parameter_s,'r') | |
543 | raw = 'r' in opts |
|
537 | raw = 'r' in opts | |
544 |
|
538 | |||
545 | oname = args and args or '_' |
|
539 | oname = args and args or '_' | |
546 | info = self._ofind(oname) |
|
540 | info = self._ofind(oname) | |
547 | if info['found']: |
|
541 | if info['found']: | |
548 | txt = (raw and str or pformat)( info['obj'] ) |
|
542 | txt = (raw and str or pformat)( info['obj'] ) | |
549 | page.page(txt) |
|
543 | page.page(txt) | |
550 | else: |
|
544 | else: | |
551 | print 'Object `%s` not found' % oname |
|
545 | print 'Object `%s` not found' % oname | |
552 |
|
546 | |||
553 | def magic_profile(self, parameter_s=''): |
|
547 | def magic_profile(self, parameter_s=''): | |
554 | """Print your currently active IPython profile.""" |
|
548 | """Print your currently active IPython profile.""" | |
555 | if self.shell.profile: |
|
549 | if self.shell.profile: | |
556 | printpl('Current IPython profile: $self.shell.profile.') |
|
550 | printpl('Current IPython profile: $self.shell.profile.') | |
557 | else: |
|
551 | else: | |
558 | print 'No profile active.' |
|
552 | print 'No profile active.' | |
559 |
|
553 | |||
560 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
554 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
561 | """Provide detailed information about an object. |
|
555 | """Provide detailed information about an object. | |
562 |
|
556 | |||
563 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
557 | '%pinfo object' is just a synonym for object? or ?object.""" | |
564 |
|
558 | |||
565 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
559 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
566 |
|
560 | |||
567 |
|
561 | |||
568 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
562 | # detail_level: 0 -> obj? , 1 -> obj?? | |
569 | detail_level = 0 |
|
563 | detail_level = 0 | |
570 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
564 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
571 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
565 | # happen if the user types 'pinfo foo?' at the cmd line. | |
572 | pinfo,qmark1,oname,qmark2 = \ |
|
566 | pinfo,qmark1,oname,qmark2 = \ | |
573 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
567 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
574 | if pinfo or qmark1 or qmark2: |
|
568 | if pinfo or qmark1 or qmark2: | |
575 | detail_level = 1 |
|
569 | detail_level = 1 | |
576 | if "*" in oname: |
|
570 | if "*" in oname: | |
577 | self.magic_psearch(oname) |
|
571 | self.magic_psearch(oname) | |
578 | else: |
|
572 | else: | |
579 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
573 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
580 | namespaces=namespaces) |
|
574 | namespaces=namespaces) | |
581 |
|
575 | |||
582 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
576 | def magic_pdef(self, parameter_s='', namespaces=None): | |
583 | """Print the definition header for any callable object. |
|
577 | """Print the definition header for any callable object. | |
584 |
|
578 | |||
585 | If the object is a class, print the constructor information.""" |
|
579 | If the object is a class, print the constructor information.""" | |
586 | self._inspect('pdef',parameter_s, namespaces) |
|
580 | self._inspect('pdef',parameter_s, namespaces) | |
587 |
|
581 | |||
588 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
582 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
589 | """Print the docstring for an object. |
|
583 | """Print the docstring for an object. | |
590 |
|
584 | |||
591 | If the given object is a class, it will print both the class and the |
|
585 | If the given object is a class, it will print both the class and the | |
592 | constructor docstrings.""" |
|
586 | constructor docstrings.""" | |
593 | self._inspect('pdoc',parameter_s, namespaces) |
|
587 | self._inspect('pdoc',parameter_s, namespaces) | |
594 |
|
588 | |||
595 | def magic_psource(self, parameter_s='', namespaces=None): |
|
589 | def magic_psource(self, parameter_s='', namespaces=None): | |
596 | """Print (or run through pager) the source code for an object.""" |
|
590 | """Print (or run through pager) the source code for an object.""" | |
597 | self._inspect('psource',parameter_s, namespaces) |
|
591 | self._inspect('psource',parameter_s, namespaces) | |
598 |
|
592 | |||
599 | def magic_pfile(self, parameter_s=''): |
|
593 | def magic_pfile(self, parameter_s=''): | |
600 | """Print (or run through pager) the file where an object is defined. |
|
594 | """Print (or run through pager) the file where an object is defined. | |
601 |
|
595 | |||
602 | The file opens at the line where the object definition begins. IPython |
|
596 | The file opens at the line where the object definition begins. IPython | |
603 | will honor the environment variable PAGER if set, and otherwise will |
|
597 | will honor the environment variable PAGER if set, and otherwise will | |
604 | do its best to print the file in a convenient form. |
|
598 | do its best to print the file in a convenient form. | |
605 |
|
599 | |||
606 | If the given argument is not an object currently defined, IPython will |
|
600 | If the given argument is not an object currently defined, IPython will | |
607 | try to interpret it as a filename (automatically adding a .py extension |
|
601 | try to interpret it as a filename (automatically adding a .py extension | |
608 | if needed). You can thus use %pfile as a syntax highlighting code |
|
602 | if needed). You can thus use %pfile as a syntax highlighting code | |
609 | viewer.""" |
|
603 | viewer.""" | |
610 |
|
604 | |||
611 | # first interpret argument as an object name |
|
605 | # first interpret argument as an object name | |
612 | out = self._inspect('pfile',parameter_s) |
|
606 | out = self._inspect('pfile',parameter_s) | |
613 | # if not, try the input as a filename |
|
607 | # if not, try the input as a filename | |
614 | if out == 'not found': |
|
608 | if out == 'not found': | |
615 | try: |
|
609 | try: | |
616 | filename = get_py_filename(parameter_s) |
|
610 | filename = get_py_filename(parameter_s) | |
617 | except IOError,msg: |
|
611 | except IOError,msg: | |
618 | print msg |
|
612 | print msg | |
619 | return |
|
613 | return | |
620 | page.page(self.shell.inspector.format(file(filename).read())) |
|
614 | page.page(self.shell.inspector.format(file(filename).read())) | |
621 |
|
615 | |||
622 | def magic_psearch(self, parameter_s=''): |
|
616 | def magic_psearch(self, parameter_s=''): | |
623 | """Search for object in namespaces by wildcard. |
|
617 | """Search for object in namespaces by wildcard. | |
624 |
|
618 | |||
625 | %psearch [options] PATTERN [OBJECT TYPE] |
|
619 | %psearch [options] PATTERN [OBJECT TYPE] | |
626 |
|
620 | |||
627 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
621 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
628 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
622 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
629 | rest of the command line must be unchanged (options come first), so |
|
623 | rest of the command line must be unchanged (options come first), so | |
630 | for example the following forms are equivalent |
|
624 | for example the following forms are equivalent | |
631 |
|
625 | |||
632 | %psearch -i a* function |
|
626 | %psearch -i a* function | |
633 | -i a* function? |
|
627 | -i a* function? | |
634 | ?-i a* function |
|
628 | ?-i a* function | |
635 |
|
629 | |||
636 | Arguments: |
|
630 | Arguments: | |
637 |
|
631 | |||
638 | PATTERN |
|
632 | PATTERN | |
639 |
|
633 | |||
640 | where PATTERN is a string containing * as a wildcard similar to its |
|
634 | where PATTERN is a string containing * as a wildcard similar to its | |
641 | use in a shell. The pattern is matched in all namespaces on the |
|
635 | use in a shell. The pattern is matched in all namespaces on the | |
642 | search path. By default objects starting with a single _ are not |
|
636 | search path. By default objects starting with a single _ are not | |
643 | matched, many IPython generated objects have a single |
|
637 | matched, many IPython generated objects have a single | |
644 | underscore. The default is case insensitive matching. Matching is |
|
638 | underscore. The default is case insensitive matching. Matching is | |
645 | also done on the attributes of objects and not only on the objects |
|
639 | also done on the attributes of objects and not only on the objects | |
646 | in a module. |
|
640 | in a module. | |
647 |
|
641 | |||
648 | [OBJECT TYPE] |
|
642 | [OBJECT TYPE] | |
649 |
|
643 | |||
650 | Is the name of a python type from the types module. The name is |
|
644 | Is the name of a python type from the types module. The name is | |
651 | given in lowercase without the ending type, ex. StringType is |
|
645 | given in lowercase without the ending type, ex. StringType is | |
652 | written string. By adding a type here only objects matching the |
|
646 | written string. By adding a type here only objects matching the | |
653 | given type are matched. Using all here makes the pattern match all |
|
647 | given type are matched. Using all here makes the pattern match all | |
654 | types (this is the default). |
|
648 | types (this is the default). | |
655 |
|
649 | |||
656 | Options: |
|
650 | Options: | |
657 |
|
651 | |||
658 | -a: makes the pattern match even objects whose names start with a |
|
652 | -a: makes the pattern match even objects whose names start with a | |
659 | single underscore. These names are normally ommitted from the |
|
653 | single underscore. These names are normally ommitted from the | |
660 | search. |
|
654 | search. | |
661 |
|
655 | |||
662 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
656 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
663 | these options is given, the default is read from your ipythonrc |
|
657 | these options is given, the default is read from your ipythonrc | |
664 | file. The option name which sets this value is |
|
658 | file. The option name which sets this value is | |
665 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
659 | 'wildcards_case_sensitive'. If this option is not specified in your | |
666 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
660 | ipythonrc file, IPython's internal default is to do a case sensitive | |
667 | search. |
|
661 | search. | |
668 |
|
662 | |||
669 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
663 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
670 | specifiy can be searched in any of the following namespaces: |
|
664 | specifiy can be searched in any of the following namespaces: | |
671 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
665 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
672 | 'builtin' and 'user' are the search defaults. Note that you should |
|
666 | 'builtin' and 'user' are the search defaults. Note that you should | |
673 | not use quotes when specifying namespaces. |
|
667 | not use quotes when specifying namespaces. | |
674 |
|
668 | |||
675 | 'Builtin' contains the python module builtin, 'user' contains all |
|
669 | 'Builtin' contains the python module builtin, 'user' contains all | |
676 | user data, 'alias' only contain the shell aliases and no python |
|
670 | user data, 'alias' only contain the shell aliases and no python | |
677 | objects, 'internal' contains objects used by IPython. The |
|
671 | objects, 'internal' contains objects used by IPython. The | |
678 | 'user_global' namespace is only used by embedded IPython instances, |
|
672 | 'user_global' namespace is only used by embedded IPython instances, | |
679 | and it contains module-level globals. You can add namespaces to the |
|
673 | and it contains module-level globals. You can add namespaces to the | |
680 | search with -s or exclude them with -e (these options can be given |
|
674 | search with -s or exclude them with -e (these options can be given | |
681 | more than once). |
|
675 | more than once). | |
682 |
|
676 | |||
683 | Examples: |
|
677 | Examples: | |
684 |
|
678 | |||
685 | %psearch a* -> objects beginning with an a |
|
679 | %psearch a* -> objects beginning with an a | |
686 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
680 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
687 | %psearch a* function -> all functions beginning with an a |
|
681 | %psearch a* function -> all functions beginning with an a | |
688 | %psearch re.e* -> objects beginning with an e in module re |
|
682 | %psearch re.e* -> objects beginning with an e in module re | |
689 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
683 | %psearch r*.e* -> objects that start with e in modules starting in r | |
690 | %psearch r*.* string -> all strings in modules beginning with r |
|
684 | %psearch r*.* string -> all strings in modules beginning with r | |
691 |
|
685 | |||
692 | Case sensitve search: |
|
686 | Case sensitve search: | |
693 |
|
687 | |||
694 | %psearch -c a* list all object beginning with lower case a |
|
688 | %psearch -c a* list all object beginning with lower case a | |
695 |
|
689 | |||
696 | Show objects beginning with a single _: |
|
690 | Show objects beginning with a single _: | |
697 |
|
691 | |||
698 | %psearch -a _* list objects beginning with a single underscore""" |
|
692 | %psearch -a _* list objects beginning with a single underscore""" | |
699 | try: |
|
693 | try: | |
700 | parameter_s = parameter_s.encode('ascii') |
|
694 | parameter_s = parameter_s.encode('ascii') | |
701 | except UnicodeEncodeError: |
|
695 | except UnicodeEncodeError: | |
702 | print 'Python identifiers can only contain ascii characters.' |
|
696 | print 'Python identifiers can only contain ascii characters.' | |
703 | return |
|
697 | return | |
704 |
|
698 | |||
705 | # default namespaces to be searched |
|
699 | # default namespaces to be searched | |
706 | def_search = ['user','builtin'] |
|
700 | def_search = ['user','builtin'] | |
707 |
|
701 | |||
708 | # Process options/args |
|
702 | # Process options/args | |
709 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
703 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
710 | opt = opts.get |
|
704 | opt = opts.get | |
711 | shell = self.shell |
|
705 | shell = self.shell | |
712 | psearch = shell.inspector.psearch |
|
706 | psearch = shell.inspector.psearch | |
713 |
|
707 | |||
714 | # select case options |
|
708 | # select case options | |
715 | if opts.has_key('i'): |
|
709 | if opts.has_key('i'): | |
716 | ignore_case = True |
|
710 | ignore_case = True | |
717 | elif opts.has_key('c'): |
|
711 | elif opts.has_key('c'): | |
718 | ignore_case = False |
|
712 | ignore_case = False | |
719 | else: |
|
713 | else: | |
720 | ignore_case = not shell.wildcards_case_sensitive |
|
714 | ignore_case = not shell.wildcards_case_sensitive | |
721 |
|
715 | |||
722 | # Build list of namespaces to search from user options |
|
716 | # Build list of namespaces to search from user options | |
723 | def_search.extend(opt('s',[])) |
|
717 | def_search.extend(opt('s',[])) | |
724 | ns_exclude = ns_exclude=opt('e',[]) |
|
718 | ns_exclude = ns_exclude=opt('e',[]) | |
725 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
719 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
726 |
|
720 | |||
727 | # Call the actual search |
|
721 | # Call the actual search | |
728 | try: |
|
722 | try: | |
729 | psearch(args,shell.ns_table,ns_search, |
|
723 | psearch(args,shell.ns_table,ns_search, | |
730 | show_all=opt('a'),ignore_case=ignore_case) |
|
724 | show_all=opt('a'),ignore_case=ignore_case) | |
731 | except: |
|
725 | except: | |
732 | shell.showtraceback() |
|
726 | shell.showtraceback() | |
733 |
|
727 | |||
734 | def magic_who_ls(self, parameter_s=''): |
|
728 | def magic_who_ls(self, parameter_s=''): | |
735 | """Return a sorted list of all interactive variables. |
|
729 | """Return a sorted list of all interactive variables. | |
736 |
|
730 | |||
737 | If arguments are given, only variables of types matching these |
|
731 | If arguments are given, only variables of types matching these | |
738 | arguments are returned.""" |
|
732 | arguments are returned.""" | |
739 |
|
733 | |||
740 | user_ns = self.shell.user_ns |
|
734 | user_ns = self.shell.user_ns | |
741 | internal_ns = self.shell.internal_ns |
|
735 | internal_ns = self.shell.internal_ns | |
742 | user_ns_hidden = self.shell.user_ns_hidden |
|
736 | user_ns_hidden = self.shell.user_ns_hidden | |
743 | out = [ i for i in user_ns |
|
737 | out = [ i for i in user_ns | |
744 | if not i.startswith('_') \ |
|
738 | if not i.startswith('_') \ | |
745 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
739 | and not (i in internal_ns or i in user_ns_hidden) ] | |
746 |
|
740 | |||
747 | typelist = parameter_s.split() |
|
741 | typelist = parameter_s.split() | |
748 | if typelist: |
|
742 | if typelist: | |
749 | typeset = set(typelist) |
|
743 | typeset = set(typelist) | |
750 | out = [i for i in out if type(i).__name__ in typeset] |
|
744 | out = [i for i in out if type(i).__name__ in typeset] | |
751 |
|
745 | |||
752 | out.sort() |
|
746 | out.sort() | |
753 | return out |
|
747 | return out | |
754 |
|
748 | |||
755 | def magic_who(self, parameter_s=''): |
|
749 | def magic_who(self, parameter_s=''): | |
756 | """Print all interactive variables, with some minimal formatting. |
|
750 | """Print all interactive variables, with some minimal formatting. | |
757 |
|
751 | |||
758 | If any arguments are given, only variables whose type matches one of |
|
752 | If any arguments are given, only variables whose type matches one of | |
759 | these are printed. For example: |
|
753 | these are printed. For example: | |
760 |
|
754 | |||
761 | %who function str |
|
755 | %who function str | |
762 |
|
756 | |||
763 | will only list functions and strings, excluding all other types of |
|
757 | will only list functions and strings, excluding all other types of | |
764 | variables. To find the proper type names, simply use type(var) at a |
|
758 | variables. To find the proper type names, simply use type(var) at a | |
765 | command line to see how python prints type names. For example: |
|
759 | command line to see how python prints type names. For example: | |
766 |
|
760 | |||
767 | In [1]: type('hello')\\ |
|
761 | In [1]: type('hello')\\ | |
768 | Out[1]: <type 'str'> |
|
762 | Out[1]: <type 'str'> | |
769 |
|
763 | |||
770 | indicates that the type name for strings is 'str'. |
|
764 | indicates that the type name for strings is 'str'. | |
771 |
|
765 | |||
772 | %who always excludes executed names loaded through your configuration |
|
766 | %who always excludes executed names loaded through your configuration | |
773 | file and things which are internal to IPython. |
|
767 | file and things which are internal to IPython. | |
774 |
|
768 | |||
775 | This is deliberate, as typically you may load many modules and the |
|
769 | This is deliberate, as typically you may load many modules and the | |
776 | purpose of %who is to show you only what you've manually defined.""" |
|
770 | purpose of %who is to show you only what you've manually defined.""" | |
777 |
|
771 | |||
778 | varlist = self.magic_who_ls(parameter_s) |
|
772 | varlist = self.magic_who_ls(parameter_s) | |
779 | if not varlist: |
|
773 | if not varlist: | |
780 | if parameter_s: |
|
774 | if parameter_s: | |
781 | print 'No variables match your requested type.' |
|
775 | print 'No variables match your requested type.' | |
782 | else: |
|
776 | else: | |
783 | print 'Interactive namespace is empty.' |
|
777 | print 'Interactive namespace is empty.' | |
784 | return |
|
778 | return | |
785 |
|
779 | |||
786 | # if we have variables, move on... |
|
780 | # if we have variables, move on... | |
787 | count = 0 |
|
781 | count = 0 | |
788 | for i in varlist: |
|
782 | for i in varlist: | |
789 | print i+'\t', |
|
783 | print i+'\t', | |
790 | count += 1 |
|
784 | count += 1 | |
791 | if count > 8: |
|
785 | if count > 8: | |
792 | count = 0 |
|
786 | count = 0 | |
793 |
|
787 | |||
794 |
|
788 | |||
795 |
|
789 | |||
796 | def magic_whos(self, parameter_s=''): |
|
790 | def magic_whos(self, parameter_s=''): | |
797 | """Like %who, but gives some extra information about each variable. |
|
791 | """Like %who, but gives some extra information about each variable. | |
798 |
|
792 | |||
799 | The same type filtering of %who can be applied here. |
|
793 | The same type filtering of %who can be applied here. | |
800 |
|
794 | |||
801 | For all variables, the type is printed. Additionally it prints: |
|
795 | For all variables, the type is printed. Additionally it prints: | |
802 |
|
796 | |||
803 | - For {},[],(): their length. |
|
797 | - For {},[],(): their length. | |
804 |
|
798 | |||
805 | - For numpy and Numeric arrays, a summary with shape, number of |
|
799 | - For numpy and Numeric arrays, a summary with shape, number of | |
806 | elements, typecode and size in memory. |
|
800 | elements, typecode and size in memory. | |
807 |
|
801 | |||
808 | - Everything else: a string representation, snipping their middle if |
|
802 | - Everything else: a string representation, snipping their middle if | |
809 | too long.""" |
|
803 | too long.""" | |
810 |
|
804 | |||
811 | varnames = self.magic_who_ls(parameter_s) |
|
805 | varnames = self.magic_who_ls(parameter_s) | |
812 | if not varnames: |
|
806 | if not varnames: | |
813 | if parameter_s: |
|
807 | if parameter_s: | |
814 | print 'No variables match your requested type.' |
|
808 | print 'No variables match your requested type.' | |
815 | else: |
|
809 | else: | |
816 | print 'Interactive namespace is empty.' |
|
810 | print 'Interactive namespace is empty.' | |
817 | return |
|
811 | return | |
818 |
|
812 | |||
819 | # if we have variables, move on... |
|
813 | # if we have variables, move on... | |
820 |
|
814 | |||
821 | # for these types, show len() instead of data: |
|
815 | # for these types, show len() instead of data: | |
822 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
816 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
823 |
|
817 | |||
824 | # for numpy/Numeric arrays, display summary info |
|
818 | # for numpy/Numeric arrays, display summary info | |
825 | try: |
|
819 | try: | |
826 | import numpy |
|
820 | import numpy | |
827 | except ImportError: |
|
821 | except ImportError: | |
828 | ndarray_type = None |
|
822 | ndarray_type = None | |
829 | else: |
|
823 | else: | |
830 | ndarray_type = numpy.ndarray.__name__ |
|
824 | ndarray_type = numpy.ndarray.__name__ | |
831 | try: |
|
825 | try: | |
832 | import Numeric |
|
826 | import Numeric | |
833 | except ImportError: |
|
827 | except ImportError: | |
834 | array_type = None |
|
828 | array_type = None | |
835 | else: |
|
829 | else: | |
836 | array_type = Numeric.ArrayType.__name__ |
|
830 | array_type = Numeric.ArrayType.__name__ | |
837 |
|
831 | |||
838 | # Find all variable names and types so we can figure out column sizes |
|
832 | # Find all variable names and types so we can figure out column sizes | |
839 | def get_vars(i): |
|
833 | def get_vars(i): | |
840 | return self.shell.user_ns[i] |
|
834 | return self.shell.user_ns[i] | |
841 |
|
835 | |||
842 | # some types are well known and can be shorter |
|
836 | # some types are well known and can be shorter | |
843 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
837 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
844 | def type_name(v): |
|
838 | def type_name(v): | |
845 | tn = type(v).__name__ |
|
839 | tn = type(v).__name__ | |
846 | return abbrevs.get(tn,tn) |
|
840 | return abbrevs.get(tn,tn) | |
847 |
|
841 | |||
848 | varlist = map(get_vars,varnames) |
|
842 | varlist = map(get_vars,varnames) | |
849 |
|
843 | |||
850 | typelist = [] |
|
844 | typelist = [] | |
851 | for vv in varlist: |
|
845 | for vv in varlist: | |
852 | tt = type_name(vv) |
|
846 | tt = type_name(vv) | |
853 |
|
847 | |||
854 | if tt=='instance': |
|
848 | if tt=='instance': | |
855 | typelist.append( abbrevs.get(str(vv.__class__), |
|
849 | typelist.append( abbrevs.get(str(vv.__class__), | |
856 | str(vv.__class__))) |
|
850 | str(vv.__class__))) | |
857 | else: |
|
851 | else: | |
858 | typelist.append(tt) |
|
852 | typelist.append(tt) | |
859 |
|
853 | |||
860 | # column labels and # of spaces as separator |
|
854 | # column labels and # of spaces as separator | |
861 | varlabel = 'Variable' |
|
855 | varlabel = 'Variable' | |
862 | typelabel = 'Type' |
|
856 | typelabel = 'Type' | |
863 | datalabel = 'Data/Info' |
|
857 | datalabel = 'Data/Info' | |
864 | colsep = 3 |
|
858 | colsep = 3 | |
865 | # variable format strings |
|
859 | # variable format strings | |
866 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
860 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
867 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
861 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
868 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
862 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
869 | # find the size of the columns to format the output nicely |
|
863 | # find the size of the columns to format the output nicely | |
870 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
864 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
871 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
865 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
872 | # table header |
|
866 | # table header | |
873 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
867 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
874 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
868 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
875 | # and the table itself |
|
869 | # and the table itself | |
876 | kb = 1024 |
|
870 | kb = 1024 | |
877 | Mb = 1048576 # kb**2 |
|
871 | Mb = 1048576 # kb**2 | |
878 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
872 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
879 | print itpl(vformat), |
|
873 | print itpl(vformat), | |
880 | if vtype in seq_types: |
|
874 | if vtype in seq_types: | |
881 | print len(var) |
|
875 | print len(var) | |
882 | elif vtype in [array_type,ndarray_type]: |
|
876 | elif vtype in [array_type,ndarray_type]: | |
883 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
877 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
884 | if vtype==ndarray_type: |
|
878 | if vtype==ndarray_type: | |
885 | # numpy |
|
879 | # numpy | |
886 | vsize = var.size |
|
880 | vsize = var.size | |
887 | vbytes = vsize*var.itemsize |
|
881 | vbytes = vsize*var.itemsize | |
888 | vdtype = var.dtype |
|
882 | vdtype = var.dtype | |
889 | else: |
|
883 | else: | |
890 | # Numeric |
|
884 | # Numeric | |
891 | vsize = Numeric.size(var) |
|
885 | vsize = Numeric.size(var) | |
892 | vbytes = vsize*var.itemsize() |
|
886 | vbytes = vsize*var.itemsize() | |
893 | vdtype = var.typecode() |
|
887 | vdtype = var.typecode() | |
894 |
|
888 | |||
895 | if vbytes < 100000: |
|
889 | if vbytes < 100000: | |
896 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
890 | print aformat % (vshape,vsize,vdtype,vbytes) | |
897 | else: |
|
891 | else: | |
898 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
892 | print aformat % (vshape,vsize,vdtype,vbytes), | |
899 | if vbytes < Mb: |
|
893 | if vbytes < Mb: | |
900 | print '(%s kb)' % (vbytes/kb,) |
|
894 | print '(%s kb)' % (vbytes/kb,) | |
901 | else: |
|
895 | else: | |
902 | print '(%s Mb)' % (vbytes/Mb,) |
|
896 | print '(%s Mb)' % (vbytes/Mb,) | |
903 | else: |
|
897 | else: | |
904 | try: |
|
898 | try: | |
905 | vstr = str(var) |
|
899 | vstr = str(var) | |
906 | except UnicodeEncodeError: |
|
900 | except UnicodeEncodeError: | |
907 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
901 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
908 | 'backslashreplace') |
|
902 | 'backslashreplace') | |
909 | vstr = vstr.replace('\n','\\n') |
|
903 | vstr = vstr.replace('\n','\\n') | |
910 | if len(vstr) < 50: |
|
904 | if len(vstr) < 50: | |
911 | print vstr |
|
905 | print vstr | |
912 | else: |
|
906 | else: | |
913 | printpl(vfmt_short) |
|
907 | printpl(vfmt_short) | |
914 |
|
908 | |||
915 | def magic_reset(self, parameter_s=''): |
|
909 | def magic_reset(self, parameter_s=''): | |
916 | """Resets the namespace by removing all names defined by the user. |
|
910 | """Resets the namespace by removing all names defined by the user. | |
917 |
|
911 | |||
918 | Input/Output history are left around in case you need them. |
|
912 | Input/Output history are left around in case you need them. | |
919 |
|
913 | |||
920 | Parameters |
|
914 | Parameters | |
921 | ---------- |
|
915 | ---------- | |
922 | -y : force reset without asking for confirmation. |
|
916 | -y : force reset without asking for confirmation. | |
923 |
|
917 | |||
924 | Examples |
|
918 | Examples | |
925 | -------- |
|
919 | -------- | |
926 | In [6]: a = 1 |
|
920 | In [6]: a = 1 | |
927 |
|
921 | |||
928 | In [7]: a |
|
922 | In [7]: a | |
929 | Out[7]: 1 |
|
923 | Out[7]: 1 | |
930 |
|
924 | |||
931 | In [8]: 'a' in _ip.user_ns |
|
925 | In [8]: 'a' in _ip.user_ns | |
932 | Out[8]: True |
|
926 | Out[8]: True | |
933 |
|
927 | |||
934 | In [9]: %reset -f |
|
928 | In [9]: %reset -f | |
935 |
|
929 | |||
936 | In [10]: 'a' in _ip.user_ns |
|
930 | In [10]: 'a' in _ip.user_ns | |
937 | Out[10]: False |
|
931 | Out[10]: False | |
938 | """ |
|
932 | """ | |
939 |
|
933 | |||
940 | if parameter_s == '-f': |
|
934 | if parameter_s == '-f': | |
941 | ans = True |
|
935 | ans = True | |
942 | else: |
|
936 | else: | |
943 | ans = self.shell.ask_yes_no( |
|
937 | ans = self.shell.ask_yes_no( | |
944 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
938 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
945 | if not ans: |
|
939 | if not ans: | |
946 | print 'Nothing done.' |
|
940 | print 'Nothing done.' | |
947 | return |
|
941 | return | |
948 | user_ns = self.shell.user_ns |
|
942 | user_ns = self.shell.user_ns | |
949 | for i in self.magic_who_ls(): |
|
943 | for i in self.magic_who_ls(): | |
950 | del(user_ns[i]) |
|
944 | del(user_ns[i]) | |
951 |
|
945 | |||
952 | # Also flush the private list of module references kept for script |
|
946 | # Also flush the private list of module references kept for script | |
953 | # execution protection |
|
947 | # execution protection | |
954 | self.shell.clear_main_mod_cache() |
|
948 | self.shell.clear_main_mod_cache() | |
955 |
|
949 | |||
956 | def magic_reset_selective(self, parameter_s=''): |
|
950 | def magic_reset_selective(self, parameter_s=''): | |
957 | """Resets the namespace by removing names defined by the user. |
|
951 | """Resets the namespace by removing names defined by the user. | |
958 |
|
952 | |||
959 | Input/Output history are left around in case you need them. |
|
953 | Input/Output history are left around in case you need them. | |
960 |
|
954 | |||
961 | %reset_selective [-f] regex |
|
955 | %reset_selective [-f] regex | |
962 |
|
956 | |||
963 | No action is taken if regex is not included |
|
957 | No action is taken if regex is not included | |
964 |
|
958 | |||
965 | Options |
|
959 | Options | |
966 | -f : force reset without asking for confirmation. |
|
960 | -f : force reset without asking for confirmation. | |
967 |
|
961 | |||
968 | Examples |
|
962 | Examples | |
969 | -------- |
|
963 | -------- | |
970 |
|
964 | |||
971 | We first fully reset the namespace so your output looks identical to |
|
965 | We first fully reset the namespace so your output looks identical to | |
972 | this example for pedagogical reasons; in practice you do not need a |
|
966 | this example for pedagogical reasons; in practice you do not need a | |
973 | full reset. |
|
967 | full reset. | |
974 |
|
968 | |||
975 | In [1]: %reset -f |
|
969 | In [1]: %reset -f | |
976 |
|
970 | |||
977 | Now, with a clean namespace we can make a few variables and use |
|
971 | Now, with a clean namespace we can make a few variables and use | |
978 | %reset_selective to only delete names that match our regexp: |
|
972 | %reset_selective to only delete names that match our regexp: | |
979 |
|
973 | |||
980 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
974 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
981 |
|
975 | |||
982 | In [3]: who_ls |
|
976 | In [3]: who_ls | |
983 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
977 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
984 |
|
978 | |||
985 | In [4]: %reset_selective -f b[2-3]m |
|
979 | In [4]: %reset_selective -f b[2-3]m | |
986 |
|
980 | |||
987 | In [5]: who_ls |
|
981 | In [5]: who_ls | |
988 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
982 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
989 |
|
983 | |||
990 | In [6]: %reset_selective -f d |
|
984 | In [6]: %reset_selective -f d | |
991 |
|
985 | |||
992 | In [7]: who_ls |
|
986 | In [7]: who_ls | |
993 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
987 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
994 |
|
988 | |||
995 | In [8]: %reset_selective -f c |
|
989 | In [8]: %reset_selective -f c | |
996 |
|
990 | |||
997 | In [9]: who_ls |
|
991 | In [9]: who_ls | |
998 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
992 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
999 |
|
993 | |||
1000 | In [10]: %reset_selective -f b |
|
994 | In [10]: %reset_selective -f b | |
1001 |
|
995 | |||
1002 | In [11]: who_ls |
|
996 | In [11]: who_ls | |
1003 | Out[11]: ['a'] |
|
997 | Out[11]: ['a'] | |
1004 | """ |
|
998 | """ | |
1005 |
|
999 | |||
1006 | opts, regex = self.parse_options(parameter_s,'f') |
|
1000 | opts, regex = self.parse_options(parameter_s,'f') | |
1007 |
|
1001 | |||
1008 | if opts.has_key('f'): |
|
1002 | if opts.has_key('f'): | |
1009 | ans = True |
|
1003 | ans = True | |
1010 | else: |
|
1004 | else: | |
1011 | ans = self.shell.ask_yes_no( |
|
1005 | ans = self.shell.ask_yes_no( | |
1012 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1006 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1013 | if not ans: |
|
1007 | if not ans: | |
1014 | print 'Nothing done.' |
|
1008 | print 'Nothing done.' | |
1015 | return |
|
1009 | return | |
1016 | user_ns = self.shell.user_ns |
|
1010 | user_ns = self.shell.user_ns | |
1017 | if not regex: |
|
1011 | if not regex: | |
1018 | print 'No regex pattern specified. Nothing done.' |
|
1012 | print 'No regex pattern specified. Nothing done.' | |
1019 | return |
|
1013 | return | |
1020 | else: |
|
1014 | else: | |
1021 | try: |
|
1015 | try: | |
1022 | m = re.compile(regex) |
|
1016 | m = re.compile(regex) | |
1023 | except TypeError: |
|
1017 | except TypeError: | |
1024 | raise TypeError('regex must be a string or compiled pattern') |
|
1018 | raise TypeError('regex must be a string or compiled pattern') | |
1025 | for i in self.magic_who_ls(): |
|
1019 | for i in self.magic_who_ls(): | |
1026 | if m.search(i): |
|
1020 | if m.search(i): | |
1027 | del(user_ns[i]) |
|
1021 | del(user_ns[i]) | |
1028 |
|
1022 | |||
1029 | def magic_logstart(self,parameter_s=''): |
|
1023 | def magic_logstart(self,parameter_s=''): | |
1030 | """Start logging anywhere in a session. |
|
1024 | """Start logging anywhere in a session. | |
1031 |
|
1025 | |||
1032 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1026 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1033 |
|
1027 | |||
1034 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1028 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1035 | current directory, in 'rotate' mode (see below). |
|
1029 | current directory, in 'rotate' mode (see below). | |
1036 |
|
1030 | |||
1037 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1031 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1038 | history up to that point and then continues logging. |
|
1032 | history up to that point and then continues logging. | |
1039 |
|
1033 | |||
1040 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1034 | %logstart takes a second optional parameter: logging mode. This can be one | |
1041 | of (note that the modes are given unquoted):\\ |
|
1035 | of (note that the modes are given unquoted):\\ | |
1042 | append: well, that says it.\\ |
|
1036 | append: well, that says it.\\ | |
1043 | backup: rename (if exists) to name~ and start name.\\ |
|
1037 | backup: rename (if exists) to name~ and start name.\\ | |
1044 | global: single logfile in your home dir, appended to.\\ |
|
1038 | global: single logfile in your home dir, appended to.\\ | |
1045 | over : overwrite existing log.\\ |
|
1039 | over : overwrite existing log.\\ | |
1046 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1040 | rotate: create rotating logs name.1~, name.2~, etc. | |
1047 |
|
1041 | |||
1048 | Options: |
|
1042 | Options: | |
1049 |
|
1043 | |||
1050 | -o: log also IPython's output. In this mode, all commands which |
|
1044 | -o: log also IPython's output. In this mode, all commands which | |
1051 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1045 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1052 | their corresponding input line. The output lines are always |
|
1046 | their corresponding input line. The output lines are always | |
1053 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1047 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1054 | Python code. |
|
1048 | Python code. | |
1055 |
|
1049 | |||
1056 | Since this marker is always the same, filtering only the output from |
|
1050 | Since this marker is always the same, filtering only the output from | |
1057 | a log is very easy, using for example a simple awk call: |
|
1051 | a log is very easy, using for example a simple awk call: | |
1058 |
|
1052 | |||
1059 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1053 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1060 |
|
1054 | |||
1061 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1055 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1062 | input, so that user lines are logged in their final form, converted |
|
1056 | input, so that user lines are logged in their final form, converted | |
1063 | into valid Python. For example, %Exit is logged as |
|
1057 | into valid Python. For example, %Exit is logged as | |
1064 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1058 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1065 | exactly as typed, with no transformations applied. |
|
1059 | exactly as typed, with no transformations applied. | |
1066 |
|
1060 | |||
1067 | -t: put timestamps before each input line logged (these are put in |
|
1061 | -t: put timestamps before each input line logged (these are put in | |
1068 | comments).""" |
|
1062 | comments).""" | |
1069 |
|
1063 | |||
1070 | opts,par = self.parse_options(parameter_s,'ort') |
|
1064 | opts,par = self.parse_options(parameter_s,'ort') | |
1071 | log_output = 'o' in opts |
|
1065 | log_output = 'o' in opts | |
1072 | log_raw_input = 'r' in opts |
|
1066 | log_raw_input = 'r' in opts | |
1073 | timestamp = 't' in opts |
|
1067 | timestamp = 't' in opts | |
1074 |
|
1068 | |||
1075 | logger = self.shell.logger |
|
1069 | logger = self.shell.logger | |
1076 |
|
1070 | |||
1077 | # if no args are given, the defaults set in the logger constructor by |
|
1071 | # if no args are given, the defaults set in the logger constructor by | |
1078 | # ipytohn remain valid |
|
1072 | # ipytohn remain valid | |
1079 | if par: |
|
1073 | if par: | |
1080 | try: |
|
1074 | try: | |
1081 | logfname,logmode = par.split() |
|
1075 | logfname,logmode = par.split() | |
1082 | except: |
|
1076 | except: | |
1083 | logfname = par |
|
1077 | logfname = par | |
1084 | logmode = 'backup' |
|
1078 | logmode = 'backup' | |
1085 | else: |
|
1079 | else: | |
1086 | logfname = logger.logfname |
|
1080 | logfname = logger.logfname | |
1087 | logmode = logger.logmode |
|
1081 | logmode = logger.logmode | |
1088 | # put logfname into rc struct as if it had been called on the command |
|
1082 | # put logfname into rc struct as if it had been called on the command | |
1089 | # line, so it ends up saved in the log header Save it in case we need |
|
1083 | # line, so it ends up saved in the log header Save it in case we need | |
1090 | # to restore it... |
|
1084 | # to restore it... | |
1091 | old_logfile = self.shell.logfile |
|
1085 | old_logfile = self.shell.logfile | |
1092 | if logfname: |
|
1086 | if logfname: | |
1093 | logfname = os.path.expanduser(logfname) |
|
1087 | logfname = os.path.expanduser(logfname) | |
1094 | self.shell.logfile = logfname |
|
1088 | self.shell.logfile = logfname | |
1095 |
|
1089 | |||
1096 | loghead = '# IPython log file\n\n' |
|
1090 | loghead = '# IPython log file\n\n' | |
1097 | try: |
|
1091 | try: | |
1098 | started = logger.logstart(logfname,loghead,logmode, |
|
1092 | started = logger.logstart(logfname,loghead,logmode, | |
1099 | log_output,timestamp,log_raw_input) |
|
1093 | log_output,timestamp,log_raw_input) | |
1100 | except: |
|
1094 | except: | |
1101 | self.shell.logfile = old_logfile |
|
1095 | self.shell.logfile = old_logfile | |
1102 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1096 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1103 | else: |
|
1097 | else: | |
1104 | # log input history up to this point, optionally interleaving |
|
1098 | # log input history up to this point, optionally interleaving | |
1105 | # output if requested |
|
1099 | # output if requested | |
1106 |
|
1100 | |||
1107 | if timestamp: |
|
1101 | if timestamp: | |
1108 | # disable timestamping for the previous history, since we've |
|
1102 | # disable timestamping for the previous history, since we've | |
1109 | # lost those already (no time machine here). |
|
1103 | # lost those already (no time machine here). | |
1110 | logger.timestamp = False |
|
1104 | logger.timestamp = False | |
1111 |
|
1105 | |||
1112 | if log_raw_input: |
|
1106 | if log_raw_input: | |
1113 | input_hist = self.shell.input_hist_raw |
|
1107 | input_hist = self.shell.input_hist_raw | |
1114 | else: |
|
1108 | else: | |
1115 | input_hist = self.shell.input_hist |
|
1109 | input_hist = self.shell.input_hist | |
1116 |
|
1110 | |||
1117 | if log_output: |
|
1111 | if log_output: | |
1118 | log_write = logger.log_write |
|
1112 | log_write = logger.log_write | |
1119 | output_hist = self.shell.output_hist |
|
1113 | output_hist = self.shell.output_hist | |
1120 | for n in range(1,len(input_hist)-1): |
|
1114 | for n in range(1,len(input_hist)-1): | |
1121 | log_write(input_hist[n].rstrip()) |
|
1115 | log_write(input_hist[n].rstrip()) | |
1122 | if n in output_hist: |
|
1116 | if n in output_hist: | |
1123 | log_write(repr(output_hist[n]),'output') |
|
1117 | log_write(repr(output_hist[n]),'output') | |
1124 | else: |
|
1118 | else: | |
1125 | logger.log_write(input_hist[1:]) |
|
1119 | logger.log_write(input_hist[1:]) | |
1126 | if timestamp: |
|
1120 | if timestamp: | |
1127 | # re-enable timestamping |
|
1121 | # re-enable timestamping | |
1128 | logger.timestamp = True |
|
1122 | logger.timestamp = True | |
1129 |
|
1123 | |||
1130 | print ('Activating auto-logging. ' |
|
1124 | print ('Activating auto-logging. ' | |
1131 | 'Current session state plus future input saved.') |
|
1125 | 'Current session state plus future input saved.') | |
1132 | logger.logstate() |
|
1126 | logger.logstate() | |
1133 |
|
1127 | |||
1134 | def magic_logstop(self,parameter_s=''): |
|
1128 | def magic_logstop(self,parameter_s=''): | |
1135 | """Fully stop logging and close log file. |
|
1129 | """Fully stop logging and close log file. | |
1136 |
|
1130 | |||
1137 | In order to start logging again, a new %logstart call needs to be made, |
|
1131 | In order to start logging again, a new %logstart call needs to be made, | |
1138 | possibly (though not necessarily) with a new filename, mode and other |
|
1132 | possibly (though not necessarily) with a new filename, mode and other | |
1139 | options.""" |
|
1133 | options.""" | |
1140 | self.logger.logstop() |
|
1134 | self.logger.logstop() | |
1141 |
|
1135 | |||
1142 | def magic_logoff(self,parameter_s=''): |
|
1136 | def magic_logoff(self,parameter_s=''): | |
1143 | """Temporarily stop logging. |
|
1137 | """Temporarily stop logging. | |
1144 |
|
1138 | |||
1145 | You must have previously started logging.""" |
|
1139 | You must have previously started logging.""" | |
1146 | self.shell.logger.switch_log(0) |
|
1140 | self.shell.logger.switch_log(0) | |
1147 |
|
1141 | |||
1148 | def magic_logon(self,parameter_s=''): |
|
1142 | def magic_logon(self,parameter_s=''): | |
1149 | """Restart logging. |
|
1143 | """Restart logging. | |
1150 |
|
1144 | |||
1151 | This function is for restarting logging which you've temporarily |
|
1145 | This function is for restarting logging which you've temporarily | |
1152 | stopped with %logoff. For starting logging for the first time, you |
|
1146 | stopped with %logoff. For starting logging for the first time, you | |
1153 | must use the %logstart function, which allows you to specify an |
|
1147 | must use the %logstart function, which allows you to specify an | |
1154 | optional log filename.""" |
|
1148 | optional log filename.""" | |
1155 |
|
1149 | |||
1156 | self.shell.logger.switch_log(1) |
|
1150 | self.shell.logger.switch_log(1) | |
1157 |
|
1151 | |||
1158 | def magic_logstate(self,parameter_s=''): |
|
1152 | def magic_logstate(self,parameter_s=''): | |
1159 | """Print the status of the logging system.""" |
|
1153 | """Print the status of the logging system.""" | |
1160 |
|
1154 | |||
1161 | self.shell.logger.logstate() |
|
1155 | self.shell.logger.logstate() | |
1162 |
|
1156 | |||
1163 | def magic_pdb(self, parameter_s=''): |
|
1157 | def magic_pdb(self, parameter_s=''): | |
1164 | """Control the automatic calling of the pdb interactive debugger. |
|
1158 | """Control the automatic calling of the pdb interactive debugger. | |
1165 |
|
1159 | |||
1166 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1160 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1167 | argument it works as a toggle. |
|
1161 | argument it works as a toggle. | |
1168 |
|
1162 | |||
1169 | When an exception is triggered, IPython can optionally call the |
|
1163 | When an exception is triggered, IPython can optionally call the | |
1170 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1164 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1171 | this feature on and off. |
|
1165 | this feature on and off. | |
1172 |
|
1166 | |||
1173 | The initial state of this feature is set in your ipythonrc |
|
1167 | The initial state of this feature is set in your ipythonrc | |
1174 | configuration file (the variable is called 'pdb'). |
|
1168 | configuration file (the variable is called 'pdb'). | |
1175 |
|
1169 | |||
1176 | If you want to just activate the debugger AFTER an exception has fired, |
|
1170 | If you want to just activate the debugger AFTER an exception has fired, | |
1177 | without having to type '%pdb on' and rerunning your code, you can use |
|
1171 | without having to type '%pdb on' and rerunning your code, you can use | |
1178 | the %debug magic.""" |
|
1172 | the %debug magic.""" | |
1179 |
|
1173 | |||
1180 | par = parameter_s.strip().lower() |
|
1174 | par = parameter_s.strip().lower() | |
1181 |
|
1175 | |||
1182 | if par: |
|
1176 | if par: | |
1183 | try: |
|
1177 | try: | |
1184 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1178 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1185 | except KeyError: |
|
1179 | except KeyError: | |
1186 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1180 | print ('Incorrect argument. Use on/1, off/0, ' | |
1187 | 'or nothing for a toggle.') |
|
1181 | 'or nothing for a toggle.') | |
1188 | return |
|
1182 | return | |
1189 | else: |
|
1183 | else: | |
1190 | # toggle |
|
1184 | # toggle | |
1191 | new_pdb = not self.shell.call_pdb |
|
1185 | new_pdb = not self.shell.call_pdb | |
1192 |
|
1186 | |||
1193 | # set on the shell |
|
1187 | # set on the shell | |
1194 | self.shell.call_pdb = new_pdb |
|
1188 | self.shell.call_pdb = new_pdb | |
1195 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1189 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1196 |
|
1190 | |||
1197 | def magic_debug(self, parameter_s=''): |
|
1191 | def magic_debug(self, parameter_s=''): | |
1198 | """Activate the interactive debugger in post-mortem mode. |
|
1192 | """Activate the interactive debugger in post-mortem mode. | |
1199 |
|
1193 | |||
1200 | If an exception has just occurred, this lets you inspect its stack |
|
1194 | If an exception has just occurred, this lets you inspect its stack | |
1201 | frames interactively. Note that this will always work only on the last |
|
1195 | frames interactively. Note that this will always work only on the last | |
1202 | traceback that occurred, so you must call this quickly after an |
|
1196 | traceback that occurred, so you must call this quickly after an | |
1203 | exception that you wish to inspect has fired, because if another one |
|
1197 | exception that you wish to inspect has fired, because if another one | |
1204 | occurs, it clobbers the previous one. |
|
1198 | occurs, it clobbers the previous one. | |
1205 |
|
1199 | |||
1206 | If you want IPython to automatically do this on every exception, see |
|
1200 | If you want IPython to automatically do this on every exception, see | |
1207 | the %pdb magic for more details. |
|
1201 | the %pdb magic for more details. | |
1208 | """ |
|
1202 | """ | |
1209 | self.shell.debugger(force=True) |
|
1203 | self.shell.debugger(force=True) | |
1210 |
|
1204 | |||
1211 | @testdec.skip_doctest |
|
1205 | @testdec.skip_doctest | |
1212 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1206 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1213 | opts=None,arg_lst=None,prog_ns=None): |
|
1207 | opts=None,arg_lst=None,prog_ns=None): | |
1214 |
|
1208 | |||
1215 | """Run a statement through the python code profiler. |
|
1209 | """Run a statement through the python code profiler. | |
1216 |
|
1210 | |||
1217 | Usage: |
|
1211 | Usage: | |
1218 | %prun [options] statement |
|
1212 | %prun [options] statement | |
1219 |
|
1213 | |||
1220 | The given statement (which doesn't require quote marks) is run via the |
|
1214 | The given statement (which doesn't require quote marks) is run via the | |
1221 | python profiler in a manner similar to the profile.run() function. |
|
1215 | python profiler in a manner similar to the profile.run() function. | |
1222 | Namespaces are internally managed to work correctly; profile.run |
|
1216 | Namespaces are internally managed to work correctly; profile.run | |
1223 | cannot be used in IPython because it makes certain assumptions about |
|
1217 | cannot be used in IPython because it makes certain assumptions about | |
1224 | namespaces which do not hold under IPython. |
|
1218 | namespaces which do not hold under IPython. | |
1225 |
|
1219 | |||
1226 | Options: |
|
1220 | Options: | |
1227 |
|
1221 | |||
1228 | -l <limit>: you can place restrictions on what or how much of the |
|
1222 | -l <limit>: you can place restrictions on what or how much of the | |
1229 | profile gets printed. The limit value can be: |
|
1223 | profile gets printed. The limit value can be: | |
1230 |
|
1224 | |||
1231 | * A string: only information for function names containing this string |
|
1225 | * A string: only information for function names containing this string | |
1232 | is printed. |
|
1226 | is printed. | |
1233 |
|
1227 | |||
1234 | * An integer: only these many lines are printed. |
|
1228 | * An integer: only these many lines are printed. | |
1235 |
|
1229 | |||
1236 | * A float (between 0 and 1): this fraction of the report is printed |
|
1230 | * A float (between 0 and 1): this fraction of the report is printed | |
1237 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1231 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1238 |
|
1232 | |||
1239 | You can combine several limits with repeated use of the option. For |
|
1233 | You can combine several limits with repeated use of the option. For | |
1240 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1234 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1241 | information about class constructors. |
|
1235 | information about class constructors. | |
1242 |
|
1236 | |||
1243 | -r: return the pstats.Stats object generated by the profiling. This |
|
1237 | -r: return the pstats.Stats object generated by the profiling. This | |
1244 | object has all the information about the profile in it, and you can |
|
1238 | object has all the information about the profile in it, and you can | |
1245 | later use it for further analysis or in other functions. |
|
1239 | later use it for further analysis or in other functions. | |
1246 |
|
1240 | |||
1247 | -s <key>: sort profile by given key. You can provide more than one key |
|
1241 | -s <key>: sort profile by given key. You can provide more than one key | |
1248 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1242 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1249 | default sorting key is 'time'. |
|
1243 | default sorting key is 'time'. | |
1250 |
|
1244 | |||
1251 | The following is copied verbatim from the profile documentation |
|
1245 | The following is copied verbatim from the profile documentation | |
1252 | referenced below: |
|
1246 | referenced below: | |
1253 |
|
1247 | |||
1254 | When more than one key is provided, additional keys are used as |
|
1248 | When more than one key is provided, additional keys are used as | |
1255 | secondary criteria when the there is equality in all keys selected |
|
1249 | secondary criteria when the there is equality in all keys selected | |
1256 | before them. |
|
1250 | before them. | |
1257 |
|
1251 | |||
1258 | Abbreviations can be used for any key names, as long as the |
|
1252 | Abbreviations can be used for any key names, as long as the | |
1259 | abbreviation is unambiguous. The following are the keys currently |
|
1253 | abbreviation is unambiguous. The following are the keys currently | |
1260 | defined: |
|
1254 | defined: | |
1261 |
|
1255 | |||
1262 | Valid Arg Meaning |
|
1256 | Valid Arg Meaning | |
1263 | "calls" call count |
|
1257 | "calls" call count | |
1264 | "cumulative" cumulative time |
|
1258 | "cumulative" cumulative time | |
1265 | "file" file name |
|
1259 | "file" file name | |
1266 | "module" file name |
|
1260 | "module" file name | |
1267 | "pcalls" primitive call count |
|
1261 | "pcalls" primitive call count | |
1268 | "line" line number |
|
1262 | "line" line number | |
1269 | "name" function name |
|
1263 | "name" function name | |
1270 | "nfl" name/file/line |
|
1264 | "nfl" name/file/line | |
1271 | "stdname" standard name |
|
1265 | "stdname" standard name | |
1272 | "time" internal time |
|
1266 | "time" internal time | |
1273 |
|
1267 | |||
1274 | Note that all sorts on statistics are in descending order (placing |
|
1268 | Note that all sorts on statistics are in descending order (placing | |
1275 | most time consuming items first), where as name, file, and line number |
|
1269 | most time consuming items first), where as name, file, and line number | |
1276 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1270 | searches are in ascending order (i.e., alphabetical). The subtle | |
1277 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1271 | distinction between "nfl" and "stdname" is that the standard name is a | |
1278 | sort of the name as printed, which means that the embedded line |
|
1272 | sort of the name as printed, which means that the embedded line | |
1279 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1273 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1280 | would (if the file names were the same) appear in the string order |
|
1274 | would (if the file names were the same) appear in the string order | |
1281 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1275 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1282 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1276 | line numbers. In fact, sort_stats("nfl") is the same as | |
1283 | sort_stats("name", "file", "line"). |
|
1277 | sort_stats("name", "file", "line"). | |
1284 |
|
1278 | |||
1285 | -T <filename>: save profile results as shown on screen to a text |
|
1279 | -T <filename>: save profile results as shown on screen to a text | |
1286 | file. The profile is still shown on screen. |
|
1280 | file. The profile is still shown on screen. | |
1287 |
|
1281 | |||
1288 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1282 | -D <filename>: save (via dump_stats) profile statistics to given | |
1289 | filename. This data is in a format understod by the pstats module, and |
|
1283 | filename. This data is in a format understod by the pstats module, and | |
1290 | is generated by a call to the dump_stats() method of profile |
|
1284 | is generated by a call to the dump_stats() method of profile | |
1291 | objects. The profile is still shown on screen. |
|
1285 | objects. The profile is still shown on screen. | |
1292 |
|
1286 | |||
1293 | If you want to run complete programs under the profiler's control, use |
|
1287 | If you want to run complete programs under the profiler's control, use | |
1294 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1288 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1295 | contains profiler specific options as described here. |
|
1289 | contains profiler specific options as described here. | |
1296 |
|
1290 | |||
1297 | You can read the complete documentation for the profile module with:: |
|
1291 | You can read the complete documentation for the profile module with:: | |
1298 |
|
1292 | |||
1299 | In [1]: import profile; profile.help() |
|
1293 | In [1]: import profile; profile.help() | |
1300 | """ |
|
1294 | """ | |
1301 |
|
1295 | |||
1302 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1296 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1303 | # protect user quote marks |
|
1297 | # protect user quote marks | |
1304 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1298 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1305 |
|
1299 | |||
1306 | if user_mode: # regular user call |
|
1300 | if user_mode: # regular user call | |
1307 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1301 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1308 | list_all=1) |
|
1302 | list_all=1) | |
1309 | namespace = self.shell.user_ns |
|
1303 | namespace = self.shell.user_ns | |
1310 | else: # called to run a program by %run -p |
|
1304 | else: # called to run a program by %run -p | |
1311 | try: |
|
1305 | try: | |
1312 | filename = get_py_filename(arg_lst[0]) |
|
1306 | filename = get_py_filename(arg_lst[0]) | |
1313 | except IOError,msg: |
|
1307 | except IOError,msg: | |
1314 | error(msg) |
|
1308 | error(msg) | |
1315 | return |
|
1309 | return | |
1316 |
|
1310 | |||
1317 | arg_str = 'execfile(filename,prog_ns)' |
|
1311 | arg_str = 'execfile(filename,prog_ns)' | |
1318 | namespace = locals() |
|
1312 | namespace = locals() | |
1319 |
|
1313 | |||
1320 | opts.merge(opts_def) |
|
1314 | opts.merge(opts_def) | |
1321 |
|
1315 | |||
1322 | prof = profile.Profile() |
|
1316 | prof = profile.Profile() | |
1323 | try: |
|
1317 | try: | |
1324 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1318 | prof = prof.runctx(arg_str,namespace,namespace) | |
1325 | sys_exit = '' |
|
1319 | sys_exit = '' | |
1326 | except SystemExit: |
|
1320 | except SystemExit: | |
1327 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1321 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1328 |
|
1322 | |||
1329 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1323 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1330 |
|
1324 | |||
1331 | lims = opts.l |
|
1325 | lims = opts.l | |
1332 | if lims: |
|
1326 | if lims: | |
1333 | lims = [] # rebuild lims with ints/floats/strings |
|
1327 | lims = [] # rebuild lims with ints/floats/strings | |
1334 | for lim in opts.l: |
|
1328 | for lim in opts.l: | |
1335 | try: |
|
1329 | try: | |
1336 | lims.append(int(lim)) |
|
1330 | lims.append(int(lim)) | |
1337 | except ValueError: |
|
1331 | except ValueError: | |
1338 | try: |
|
1332 | try: | |
1339 | lims.append(float(lim)) |
|
1333 | lims.append(float(lim)) | |
1340 | except ValueError: |
|
1334 | except ValueError: | |
1341 | lims.append(lim) |
|
1335 | lims.append(lim) | |
1342 |
|
1336 | |||
1343 | # Trap output. |
|
1337 | # Trap output. | |
1344 | stdout_trap = StringIO() |
|
1338 | stdout_trap = StringIO() | |
1345 |
|
1339 | |||
1346 | if hasattr(stats,'stream'): |
|
1340 | if hasattr(stats,'stream'): | |
1347 | # In newer versions of python, the stats object has a 'stream' |
|
1341 | # In newer versions of python, the stats object has a 'stream' | |
1348 | # attribute to write into. |
|
1342 | # attribute to write into. | |
1349 | stats.stream = stdout_trap |
|
1343 | stats.stream = stdout_trap | |
1350 | stats.print_stats(*lims) |
|
1344 | stats.print_stats(*lims) | |
1351 | else: |
|
1345 | else: | |
1352 | # For older versions, we manually redirect stdout during printing |
|
1346 | # For older versions, we manually redirect stdout during printing | |
1353 | sys_stdout = sys.stdout |
|
1347 | sys_stdout = sys.stdout | |
1354 | try: |
|
1348 | try: | |
1355 | sys.stdout = stdout_trap |
|
1349 | sys.stdout = stdout_trap | |
1356 | stats.print_stats(*lims) |
|
1350 | stats.print_stats(*lims) | |
1357 | finally: |
|
1351 | finally: | |
1358 | sys.stdout = sys_stdout |
|
1352 | sys.stdout = sys_stdout | |
1359 |
|
1353 | |||
1360 | output = stdout_trap.getvalue() |
|
1354 | output = stdout_trap.getvalue() | |
1361 | output = output.rstrip() |
|
1355 | output = output.rstrip() | |
1362 |
|
1356 | |||
1363 | page.page(output) |
|
1357 | page.page(output) | |
1364 | print sys_exit, |
|
1358 | print sys_exit, | |
1365 |
|
1359 | |||
1366 | dump_file = opts.D[0] |
|
1360 | dump_file = opts.D[0] | |
1367 | text_file = opts.T[0] |
|
1361 | text_file = opts.T[0] | |
1368 | if dump_file: |
|
1362 | if dump_file: | |
1369 | prof.dump_stats(dump_file) |
|
1363 | prof.dump_stats(dump_file) | |
1370 | print '\n*** Profile stats marshalled to file',\ |
|
1364 | print '\n*** Profile stats marshalled to file',\ | |
1371 | `dump_file`+'.',sys_exit |
|
1365 | `dump_file`+'.',sys_exit | |
1372 | if text_file: |
|
1366 | if text_file: | |
1373 | pfile = file(text_file,'w') |
|
1367 | pfile = file(text_file,'w') | |
1374 | pfile.write(output) |
|
1368 | pfile.write(output) | |
1375 | pfile.close() |
|
1369 | pfile.close() | |
1376 | print '\n*** Profile printout saved to text file',\ |
|
1370 | print '\n*** Profile printout saved to text file',\ | |
1377 | `text_file`+'.',sys_exit |
|
1371 | `text_file`+'.',sys_exit | |
1378 |
|
1372 | |||
1379 | if opts.has_key('r'): |
|
1373 | if opts.has_key('r'): | |
1380 | return stats |
|
1374 | return stats | |
1381 | else: |
|
1375 | else: | |
1382 | return None |
|
1376 | return None | |
1383 |
|
1377 | |||
1384 | @testdec.skip_doctest |
|
1378 | @testdec.skip_doctest | |
1385 | def magic_run(self, parameter_s ='',runner=None, |
|
1379 | def magic_run(self, parameter_s ='',runner=None, | |
1386 | file_finder=get_py_filename): |
|
1380 | file_finder=get_py_filename): | |
1387 | """Run the named file inside IPython as a program. |
|
1381 | """Run the named file inside IPython as a program. | |
1388 |
|
1382 | |||
1389 | Usage:\\ |
|
1383 | Usage:\\ | |
1390 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1384 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1391 |
|
1385 | |||
1392 | Parameters after the filename are passed as command-line arguments to |
|
1386 | Parameters after the filename are passed as command-line arguments to | |
1393 | the program (put in sys.argv). Then, control returns to IPython's |
|
1387 | the program (put in sys.argv). Then, control returns to IPython's | |
1394 | prompt. |
|
1388 | prompt. | |
1395 |
|
1389 | |||
1396 | This is similar to running at a system prompt:\\ |
|
1390 | This is similar to running at a system prompt:\\ | |
1397 | $ python file args\\ |
|
1391 | $ python file args\\ | |
1398 | but with the advantage of giving you IPython's tracebacks, and of |
|
1392 | but with the advantage of giving you IPython's tracebacks, and of | |
1399 | loading all variables into your interactive namespace for further use |
|
1393 | loading all variables into your interactive namespace for further use | |
1400 | (unless -p is used, see below). |
|
1394 | (unless -p is used, see below). | |
1401 |
|
1395 | |||
1402 | The file is executed in a namespace initially consisting only of |
|
1396 | The file is executed in a namespace initially consisting only of | |
1403 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1397 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1404 | sees its environment as if it were being run as a stand-alone program |
|
1398 | sees its environment as if it were being run as a stand-alone program | |
1405 | (except for sharing global objects such as previously imported |
|
1399 | (except for sharing global objects such as previously imported | |
1406 | modules). But after execution, the IPython interactive namespace gets |
|
1400 | modules). But after execution, the IPython interactive namespace gets | |
1407 | updated with all variables defined in the program (except for __name__ |
|
1401 | updated with all variables defined in the program (except for __name__ | |
1408 | and sys.argv). This allows for very convenient loading of code for |
|
1402 | and sys.argv). This allows for very convenient loading of code for | |
1409 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1403 | interactive work, while giving each program a 'clean sheet' to run in. | |
1410 |
|
1404 | |||
1411 | Options: |
|
1405 | Options: | |
1412 |
|
1406 | |||
1413 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1407 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1414 | without extension (as python does under import). This allows running |
|
1408 | without extension (as python does under import). This allows running | |
1415 | scripts and reloading the definitions in them without calling code |
|
1409 | scripts and reloading the definitions in them without calling code | |
1416 | protected by an ' if __name__ == "__main__" ' clause. |
|
1410 | protected by an ' if __name__ == "__main__" ' clause. | |
1417 |
|
1411 | |||
1418 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1412 | -i: run the file in IPython's namespace instead of an empty one. This | |
1419 | is useful if you are experimenting with code written in a text editor |
|
1413 | is useful if you are experimenting with code written in a text editor | |
1420 | which depends on variables defined interactively. |
|
1414 | which depends on variables defined interactively. | |
1421 |
|
1415 | |||
1422 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1416 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1423 | being run. This is particularly useful if IPython is being used to |
|
1417 | being run. This is particularly useful if IPython is being used to | |
1424 | run unittests, which always exit with a sys.exit() call. In such |
|
1418 | run unittests, which always exit with a sys.exit() call. In such | |
1425 | cases you are interested in the output of the test results, not in |
|
1419 | cases you are interested in the output of the test results, not in | |
1426 | seeing a traceback of the unittest module. |
|
1420 | seeing a traceback of the unittest module. | |
1427 |
|
1421 | |||
1428 | -t: print timing information at the end of the run. IPython will give |
|
1422 | -t: print timing information at the end of the run. IPython will give | |
1429 | you an estimated CPU time consumption for your script, which under |
|
1423 | you an estimated CPU time consumption for your script, which under | |
1430 | Unix uses the resource module to avoid the wraparound problems of |
|
1424 | Unix uses the resource module to avoid the wraparound problems of | |
1431 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1425 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1432 | is also given (for Windows platforms this is reported as 0.0). |
|
1426 | is also given (for Windows platforms this is reported as 0.0). | |
1433 |
|
1427 | |||
1434 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1428 | If -t is given, an additional -N<N> option can be given, where <N> | |
1435 | must be an integer indicating how many times you want the script to |
|
1429 | must be an integer indicating how many times you want the script to | |
1436 | run. The final timing report will include total and per run results. |
|
1430 | run. The final timing report will include total and per run results. | |
1437 |
|
1431 | |||
1438 | For example (testing the script uniq_stable.py): |
|
1432 | For example (testing the script uniq_stable.py): | |
1439 |
|
1433 | |||
1440 | In [1]: run -t uniq_stable |
|
1434 | In [1]: run -t uniq_stable | |
1441 |
|
1435 | |||
1442 | IPython CPU timings (estimated):\\ |
|
1436 | IPython CPU timings (estimated):\\ | |
1443 | User : 0.19597 s.\\ |
|
1437 | User : 0.19597 s.\\ | |
1444 | System: 0.0 s.\\ |
|
1438 | System: 0.0 s.\\ | |
1445 |
|
1439 | |||
1446 | In [2]: run -t -N5 uniq_stable |
|
1440 | In [2]: run -t -N5 uniq_stable | |
1447 |
|
1441 | |||
1448 | IPython CPU timings (estimated):\\ |
|
1442 | IPython CPU timings (estimated):\\ | |
1449 | Total runs performed: 5\\ |
|
1443 | Total runs performed: 5\\ | |
1450 | Times : Total Per run\\ |
|
1444 | Times : Total Per run\\ | |
1451 | User : 0.910862 s, 0.1821724 s.\\ |
|
1445 | User : 0.910862 s, 0.1821724 s.\\ | |
1452 | System: 0.0 s, 0.0 s. |
|
1446 | System: 0.0 s, 0.0 s. | |
1453 |
|
1447 | |||
1454 | -d: run your program under the control of pdb, the Python debugger. |
|
1448 | -d: run your program under the control of pdb, the Python debugger. | |
1455 | This allows you to execute your program step by step, watch variables, |
|
1449 | This allows you to execute your program step by step, watch variables, | |
1456 | etc. Internally, what IPython does is similar to calling: |
|
1450 | etc. Internally, what IPython does is similar to calling: | |
1457 |
|
1451 | |||
1458 | pdb.run('execfile("YOURFILENAME")') |
|
1452 | pdb.run('execfile("YOURFILENAME")') | |
1459 |
|
1453 | |||
1460 | with a breakpoint set on line 1 of your file. You can change the line |
|
1454 | with a breakpoint set on line 1 of your file. You can change the line | |
1461 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1455 | number for this automatic breakpoint to be <N> by using the -bN option | |
1462 | (where N must be an integer). For example: |
|
1456 | (where N must be an integer). For example: | |
1463 |
|
1457 | |||
1464 | %run -d -b40 myscript |
|
1458 | %run -d -b40 myscript | |
1465 |
|
1459 | |||
1466 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1460 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1467 | the first breakpoint must be set on a line which actually does |
|
1461 | the first breakpoint must be set on a line which actually does | |
1468 | something (not a comment or docstring) for it to stop execution. |
|
1462 | something (not a comment or docstring) for it to stop execution. | |
1469 |
|
1463 | |||
1470 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1464 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1471 | first enter 'c' (without qoutes) to start execution up to the first |
|
1465 | first enter 'c' (without qoutes) to start execution up to the first | |
1472 | breakpoint. |
|
1466 | breakpoint. | |
1473 |
|
1467 | |||
1474 | Entering 'help' gives information about the use of the debugger. You |
|
1468 | Entering 'help' gives information about the use of the debugger. You | |
1475 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1469 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1476 | at a prompt. |
|
1470 | at a prompt. | |
1477 |
|
1471 | |||
1478 | -p: run program under the control of the Python profiler module (which |
|
1472 | -p: run program under the control of the Python profiler module (which | |
1479 | prints a detailed report of execution times, function calls, etc). |
|
1473 | prints a detailed report of execution times, function calls, etc). | |
1480 |
|
1474 | |||
1481 | You can pass other options after -p which affect the behavior of the |
|
1475 | You can pass other options after -p which affect the behavior of the | |
1482 | profiler itself. See the docs for %prun for details. |
|
1476 | profiler itself. See the docs for %prun for details. | |
1483 |
|
1477 | |||
1484 | In this mode, the program's variables do NOT propagate back to the |
|
1478 | In this mode, the program's variables do NOT propagate back to the | |
1485 | IPython interactive namespace (because they remain in the namespace |
|
1479 | IPython interactive namespace (because they remain in the namespace | |
1486 | where the profiler executes them). |
|
1480 | where the profiler executes them). | |
1487 |
|
1481 | |||
1488 | Internally this triggers a call to %prun, see its documentation for |
|
1482 | Internally this triggers a call to %prun, see its documentation for | |
1489 | details on the options available specifically for profiling. |
|
1483 | details on the options available specifically for profiling. | |
1490 |
|
1484 | |||
1491 | There is one special usage for which the text above doesn't apply: |
|
1485 | There is one special usage for which the text above doesn't apply: | |
1492 | if the filename ends with .ipy, the file is run as ipython script, |
|
1486 | if the filename ends with .ipy, the file is run as ipython script, | |
1493 | just as if the commands were written on IPython prompt. |
|
1487 | just as if the commands were written on IPython prompt. | |
1494 | """ |
|
1488 | """ | |
1495 |
|
1489 | |||
1496 | # get arguments and set sys.argv for program to be run. |
|
1490 | # get arguments and set sys.argv for program to be run. | |
1497 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1491 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1498 | mode='list',list_all=1) |
|
1492 | mode='list',list_all=1) | |
1499 |
|
1493 | |||
1500 | try: |
|
1494 | try: | |
1501 | filename = file_finder(arg_lst[0]) |
|
1495 | filename = file_finder(arg_lst[0]) | |
1502 | except IndexError: |
|
1496 | except IndexError: | |
1503 | warn('you must provide at least a filename.') |
|
1497 | warn('you must provide at least a filename.') | |
1504 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1498 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1505 | return |
|
1499 | return | |
1506 | except IOError,msg: |
|
1500 | except IOError,msg: | |
1507 | error(msg) |
|
1501 | error(msg) | |
1508 | return |
|
1502 | return | |
1509 |
|
1503 | |||
1510 | if filename.lower().endswith('.ipy'): |
|
1504 | if filename.lower().endswith('.ipy'): | |
1511 | self.shell.safe_execfile_ipy(filename) |
|
1505 | self.shell.safe_execfile_ipy(filename) | |
1512 | return |
|
1506 | return | |
1513 |
|
1507 | |||
1514 | # Control the response to exit() calls made by the script being run |
|
1508 | # Control the response to exit() calls made by the script being run | |
1515 | exit_ignore = opts.has_key('e') |
|
1509 | exit_ignore = opts.has_key('e') | |
1516 |
|
1510 | |||
1517 | # Make sure that the running script gets a proper sys.argv as if it |
|
1511 | # Make sure that the running script gets a proper sys.argv as if it | |
1518 | # were run from a system shell. |
|
1512 | # were run from a system shell. | |
1519 | save_argv = sys.argv # save it for later restoring |
|
1513 | save_argv = sys.argv # save it for later restoring | |
1520 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1514 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1521 |
|
1515 | |||
1522 | if opts.has_key('i'): |
|
1516 | if opts.has_key('i'): | |
1523 | # Run in user's interactive namespace |
|
1517 | # Run in user's interactive namespace | |
1524 | prog_ns = self.shell.user_ns |
|
1518 | prog_ns = self.shell.user_ns | |
1525 | __name__save = self.shell.user_ns['__name__'] |
|
1519 | __name__save = self.shell.user_ns['__name__'] | |
1526 | prog_ns['__name__'] = '__main__' |
|
1520 | prog_ns['__name__'] = '__main__' | |
1527 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1521 | main_mod = self.shell.new_main_mod(prog_ns) | |
1528 | else: |
|
1522 | else: | |
1529 | # Run in a fresh, empty namespace |
|
1523 | # Run in a fresh, empty namespace | |
1530 | if opts.has_key('n'): |
|
1524 | if opts.has_key('n'): | |
1531 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1525 | name = os.path.splitext(os.path.basename(filename))[0] | |
1532 | else: |
|
1526 | else: | |
1533 | name = '__main__' |
|
1527 | name = '__main__' | |
1534 |
|
1528 | |||
1535 | main_mod = self.shell.new_main_mod() |
|
1529 | main_mod = self.shell.new_main_mod() | |
1536 | prog_ns = main_mod.__dict__ |
|
1530 | prog_ns = main_mod.__dict__ | |
1537 | prog_ns['__name__'] = name |
|
1531 | prog_ns['__name__'] = name | |
1538 |
|
1532 | |||
1539 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1533 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1540 | # set the __file__ global in the script's namespace |
|
1534 | # set the __file__ global in the script's namespace | |
1541 | prog_ns['__file__'] = filename |
|
1535 | prog_ns['__file__'] = filename | |
1542 |
|
1536 | |||
1543 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1537 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1544 | # that, if we overwrite __main__, we replace it at the end |
|
1538 | # that, if we overwrite __main__, we replace it at the end | |
1545 | main_mod_name = prog_ns['__name__'] |
|
1539 | main_mod_name = prog_ns['__name__'] | |
1546 |
|
1540 | |||
1547 | if main_mod_name == '__main__': |
|
1541 | if main_mod_name == '__main__': | |
1548 | restore_main = sys.modules['__main__'] |
|
1542 | restore_main = sys.modules['__main__'] | |
1549 | else: |
|
1543 | else: | |
1550 | restore_main = False |
|
1544 | restore_main = False | |
1551 |
|
1545 | |||
1552 | # This needs to be undone at the end to prevent holding references to |
|
1546 | # This needs to be undone at the end to prevent holding references to | |
1553 | # every single object ever created. |
|
1547 | # every single object ever created. | |
1554 | sys.modules[main_mod_name] = main_mod |
|
1548 | sys.modules[main_mod_name] = main_mod | |
1555 |
|
1549 | |||
1556 | stats = None |
|
1550 | stats = None | |
1557 | try: |
|
1551 | try: | |
1558 | self.shell.savehist() |
|
1552 | self.shell.savehist() | |
1559 |
|
1553 | |||
1560 | if opts.has_key('p'): |
|
1554 | if opts.has_key('p'): | |
1561 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1555 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1562 | else: |
|
1556 | else: | |
1563 | if opts.has_key('d'): |
|
1557 | if opts.has_key('d'): | |
1564 | deb = debugger.Pdb(self.shell.colors) |
|
1558 | deb = debugger.Pdb(self.shell.colors) | |
1565 | # reset Breakpoint state, which is moronically kept |
|
1559 | # reset Breakpoint state, which is moronically kept | |
1566 | # in a class |
|
1560 | # in a class | |
1567 | bdb.Breakpoint.next = 1 |
|
1561 | bdb.Breakpoint.next = 1 | |
1568 | bdb.Breakpoint.bplist = {} |
|
1562 | bdb.Breakpoint.bplist = {} | |
1569 | bdb.Breakpoint.bpbynumber = [None] |
|
1563 | bdb.Breakpoint.bpbynumber = [None] | |
1570 | # Set an initial breakpoint to stop execution |
|
1564 | # Set an initial breakpoint to stop execution | |
1571 | maxtries = 10 |
|
1565 | maxtries = 10 | |
1572 | bp = int(opts.get('b',[1])[0]) |
|
1566 | bp = int(opts.get('b',[1])[0]) | |
1573 | checkline = deb.checkline(filename,bp) |
|
1567 | checkline = deb.checkline(filename,bp) | |
1574 | if not checkline: |
|
1568 | if not checkline: | |
1575 | for bp in range(bp+1,bp+maxtries+1): |
|
1569 | for bp in range(bp+1,bp+maxtries+1): | |
1576 | if deb.checkline(filename,bp): |
|
1570 | if deb.checkline(filename,bp): | |
1577 | break |
|
1571 | break | |
1578 | else: |
|
1572 | else: | |
1579 | msg = ("\nI failed to find a valid line to set " |
|
1573 | msg = ("\nI failed to find a valid line to set " | |
1580 | "a breakpoint\n" |
|
1574 | "a breakpoint\n" | |
1581 | "after trying up to line: %s.\n" |
|
1575 | "after trying up to line: %s.\n" | |
1582 | "Please set a valid breakpoint manually " |
|
1576 | "Please set a valid breakpoint manually " | |
1583 | "with the -b option." % bp) |
|
1577 | "with the -b option." % bp) | |
1584 | error(msg) |
|
1578 | error(msg) | |
1585 | return |
|
1579 | return | |
1586 | # if we find a good linenumber, set the breakpoint |
|
1580 | # if we find a good linenumber, set the breakpoint | |
1587 | deb.do_break('%s:%s' % (filename,bp)) |
|
1581 | deb.do_break('%s:%s' % (filename,bp)) | |
1588 | # Start file run |
|
1582 | # Start file run | |
1589 | print "NOTE: Enter 'c' at the", |
|
1583 | print "NOTE: Enter 'c' at the", | |
1590 | print "%s prompt to start your script." % deb.prompt |
|
1584 | print "%s prompt to start your script." % deb.prompt | |
1591 | try: |
|
1585 | try: | |
1592 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1586 | deb.run('execfile("%s")' % filename,prog_ns) | |
1593 |
|
1587 | |||
1594 | except: |
|
1588 | except: | |
1595 | etype, value, tb = sys.exc_info() |
|
1589 | etype, value, tb = sys.exc_info() | |
1596 | # Skip three frames in the traceback: the %run one, |
|
1590 | # Skip three frames in the traceback: the %run one, | |
1597 | # one inside bdb.py, and the command-line typed by the |
|
1591 | # one inside bdb.py, and the command-line typed by the | |
1598 | # user (run by exec in pdb itself). |
|
1592 | # user (run by exec in pdb itself). | |
1599 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1593 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1600 | else: |
|
1594 | else: | |
1601 | if runner is None: |
|
1595 | if runner is None: | |
1602 | runner = self.shell.safe_execfile |
|
1596 | runner = self.shell.safe_execfile | |
1603 | if opts.has_key('t'): |
|
1597 | if opts.has_key('t'): | |
1604 | # timed execution |
|
1598 | # timed execution | |
1605 | try: |
|
1599 | try: | |
1606 | nruns = int(opts['N'][0]) |
|
1600 | nruns = int(opts['N'][0]) | |
1607 | if nruns < 1: |
|
1601 | if nruns < 1: | |
1608 | error('Number of runs must be >=1') |
|
1602 | error('Number of runs must be >=1') | |
1609 | return |
|
1603 | return | |
1610 | except (KeyError): |
|
1604 | except (KeyError): | |
1611 | nruns = 1 |
|
1605 | nruns = 1 | |
1612 | if nruns == 1: |
|
1606 | if nruns == 1: | |
1613 | t0 = clock2() |
|
1607 | t0 = clock2() | |
1614 | runner(filename,prog_ns,prog_ns, |
|
1608 | runner(filename,prog_ns,prog_ns, | |
1615 | exit_ignore=exit_ignore) |
|
1609 | exit_ignore=exit_ignore) | |
1616 | t1 = clock2() |
|
1610 | t1 = clock2() | |
1617 | t_usr = t1[0]-t0[0] |
|
1611 | t_usr = t1[0]-t0[0] | |
1618 | t_sys = t1[1]-t0[1] |
|
1612 | t_sys = t1[1]-t0[1] | |
1619 | print "\nIPython CPU timings (estimated):" |
|
1613 | print "\nIPython CPU timings (estimated):" | |
1620 | print " User : %10s s." % t_usr |
|
1614 | print " User : %10s s." % t_usr | |
1621 | print " System: %10s s." % t_sys |
|
1615 | print " System: %10s s." % t_sys | |
1622 | else: |
|
1616 | else: | |
1623 | runs = range(nruns) |
|
1617 | runs = range(nruns) | |
1624 | t0 = clock2() |
|
1618 | t0 = clock2() | |
1625 | for nr in runs: |
|
1619 | for nr in runs: | |
1626 | runner(filename,prog_ns,prog_ns, |
|
1620 | runner(filename,prog_ns,prog_ns, | |
1627 | exit_ignore=exit_ignore) |
|
1621 | exit_ignore=exit_ignore) | |
1628 | t1 = clock2() |
|
1622 | t1 = clock2() | |
1629 | t_usr = t1[0]-t0[0] |
|
1623 | t_usr = t1[0]-t0[0] | |
1630 | t_sys = t1[1]-t0[1] |
|
1624 | t_sys = t1[1]-t0[1] | |
1631 | print "\nIPython CPU timings (estimated):" |
|
1625 | print "\nIPython CPU timings (estimated):" | |
1632 | print "Total runs performed:",nruns |
|
1626 | print "Total runs performed:",nruns | |
1633 | print " Times : %10s %10s" % ('Total','Per run') |
|
1627 | print " Times : %10s %10s" % ('Total','Per run') | |
1634 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1628 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1635 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1629 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1636 |
|
1630 | |||
1637 | else: |
|
1631 | else: | |
1638 | # regular execution |
|
1632 | # regular execution | |
1639 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1633 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1640 |
|
1634 | |||
1641 | if opts.has_key('i'): |
|
1635 | if opts.has_key('i'): | |
1642 | self.shell.user_ns['__name__'] = __name__save |
|
1636 | self.shell.user_ns['__name__'] = __name__save | |
1643 | else: |
|
1637 | else: | |
1644 | # The shell MUST hold a reference to prog_ns so after %run |
|
1638 | # The shell MUST hold a reference to prog_ns so after %run | |
1645 | # exits, the python deletion mechanism doesn't zero it out |
|
1639 | # exits, the python deletion mechanism doesn't zero it out | |
1646 | # (leaving dangling references). |
|
1640 | # (leaving dangling references). | |
1647 | self.shell.cache_main_mod(prog_ns,filename) |
|
1641 | self.shell.cache_main_mod(prog_ns,filename) | |
1648 | # update IPython interactive namespace |
|
1642 | # update IPython interactive namespace | |
1649 |
|
1643 | |||
1650 | # Some forms of read errors on the file may mean the |
|
1644 | # Some forms of read errors on the file may mean the | |
1651 | # __name__ key was never set; using pop we don't have to |
|
1645 | # __name__ key was never set; using pop we don't have to | |
1652 | # worry about a possible KeyError. |
|
1646 | # worry about a possible KeyError. | |
1653 | prog_ns.pop('__name__', None) |
|
1647 | prog_ns.pop('__name__', None) | |
1654 |
|
1648 | |||
1655 | self.shell.user_ns.update(prog_ns) |
|
1649 | self.shell.user_ns.update(prog_ns) | |
1656 | finally: |
|
1650 | finally: | |
1657 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1651 | # It's a bit of a mystery why, but __builtins__ can change from | |
1658 | # being a module to becoming a dict missing some key data after |
|
1652 | # being a module to becoming a dict missing some key data after | |
1659 | # %run. As best I can see, this is NOT something IPython is doing |
|
1653 | # %run. As best I can see, this is NOT something IPython is doing | |
1660 | # at all, and similar problems have been reported before: |
|
1654 | # at all, and similar problems have been reported before: | |
1661 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1655 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1662 | # Since this seems to be done by the interpreter itself, the best |
|
1656 | # Since this seems to be done by the interpreter itself, the best | |
1663 | # we can do is to at least restore __builtins__ for the user on |
|
1657 | # we can do is to at least restore __builtins__ for the user on | |
1664 | # exit. |
|
1658 | # exit. | |
1665 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1659 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1666 |
|
1660 | |||
1667 | # Ensure key global structures are restored |
|
1661 | # Ensure key global structures are restored | |
1668 | sys.argv = save_argv |
|
1662 | sys.argv = save_argv | |
1669 | if restore_main: |
|
1663 | if restore_main: | |
1670 | sys.modules['__main__'] = restore_main |
|
1664 | sys.modules['__main__'] = restore_main | |
1671 | else: |
|
1665 | else: | |
1672 | # Remove from sys.modules the reference to main_mod we'd |
|
1666 | # Remove from sys.modules the reference to main_mod we'd | |
1673 | # added. Otherwise it will trap references to objects |
|
1667 | # added. Otherwise it will trap references to objects | |
1674 | # contained therein. |
|
1668 | # contained therein. | |
1675 | del sys.modules[main_mod_name] |
|
1669 | del sys.modules[main_mod_name] | |
1676 |
|
1670 | |||
1677 | self.shell.reloadhist() |
|
1671 | self.shell.reloadhist() | |
1678 |
|
1672 | |||
1679 | return stats |
|
1673 | return stats | |
1680 |
|
1674 | |||
1681 | @testdec.skip_doctest |
|
1675 | @testdec.skip_doctest | |
1682 | def magic_timeit(self, parameter_s =''): |
|
1676 | def magic_timeit(self, parameter_s =''): | |
1683 | """Time execution of a Python statement or expression |
|
1677 | """Time execution of a Python statement or expression | |
1684 |
|
1678 | |||
1685 | Usage:\\ |
|
1679 | Usage:\\ | |
1686 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1680 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1687 |
|
1681 | |||
1688 | Time execution of a Python statement or expression using the timeit |
|
1682 | Time execution of a Python statement or expression using the timeit | |
1689 | module. |
|
1683 | module. | |
1690 |
|
1684 | |||
1691 | Options: |
|
1685 | Options: | |
1692 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1686 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1693 | is not given, a fitting value is chosen. |
|
1687 | is not given, a fitting value is chosen. | |
1694 |
|
1688 | |||
1695 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1689 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1696 | Default: 3 |
|
1690 | Default: 3 | |
1697 |
|
1691 | |||
1698 | -t: use time.time to measure the time, which is the default on Unix. |
|
1692 | -t: use time.time to measure the time, which is the default on Unix. | |
1699 | This function measures wall time. |
|
1693 | This function measures wall time. | |
1700 |
|
1694 | |||
1701 | -c: use time.clock to measure the time, which is the default on |
|
1695 | -c: use time.clock to measure the time, which is the default on | |
1702 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1696 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1703 | instead and returns the CPU user time. |
|
1697 | instead and returns the CPU user time. | |
1704 |
|
1698 | |||
1705 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1699 | -p<P>: use a precision of <P> digits to display the timing result. | |
1706 | Default: 3 |
|
1700 | Default: 3 | |
1707 |
|
1701 | |||
1708 |
|
1702 | |||
1709 | Examples: |
|
1703 | Examples: | |
1710 |
|
1704 | |||
1711 | In [1]: %timeit pass |
|
1705 | In [1]: %timeit pass | |
1712 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1706 | 10000000 loops, best of 3: 53.3 ns per loop | |
1713 |
|
1707 | |||
1714 | In [2]: u = None |
|
1708 | In [2]: u = None | |
1715 |
|
1709 | |||
1716 | In [3]: %timeit u is None |
|
1710 | In [3]: %timeit u is None | |
1717 | 10000000 loops, best of 3: 184 ns per loop |
|
1711 | 10000000 loops, best of 3: 184 ns per loop | |
1718 |
|
1712 | |||
1719 | In [4]: %timeit -r 4 u == None |
|
1713 | In [4]: %timeit -r 4 u == None | |
1720 | 1000000 loops, best of 4: 242 ns per loop |
|
1714 | 1000000 loops, best of 4: 242 ns per loop | |
1721 |
|
1715 | |||
1722 | In [5]: import time |
|
1716 | In [5]: import time | |
1723 |
|
1717 | |||
1724 | In [6]: %timeit -n1 time.sleep(2) |
|
1718 | In [6]: %timeit -n1 time.sleep(2) | |
1725 | 1 loops, best of 3: 2 s per loop |
|
1719 | 1 loops, best of 3: 2 s per loop | |
1726 |
|
1720 | |||
1727 |
|
1721 | |||
1728 | The times reported by %timeit will be slightly higher than those |
|
1722 | The times reported by %timeit will be slightly higher than those | |
1729 | reported by the timeit.py script when variables are accessed. This is |
|
1723 | reported by the timeit.py script when variables are accessed. This is | |
1730 | due to the fact that %timeit executes the statement in the namespace |
|
1724 | due to the fact that %timeit executes the statement in the namespace | |
1731 | of the shell, compared with timeit.py, which uses a single setup |
|
1725 | of the shell, compared with timeit.py, which uses a single setup | |
1732 | statement to import function or create variables. Generally, the bias |
|
1726 | statement to import function or create variables. Generally, the bias | |
1733 | does not matter as long as results from timeit.py are not mixed with |
|
1727 | does not matter as long as results from timeit.py are not mixed with | |
1734 | those from %timeit.""" |
|
1728 | those from %timeit.""" | |
1735 |
|
1729 | |||
1736 | import timeit |
|
1730 | import timeit | |
1737 | import math |
|
1731 | import math | |
1738 |
|
1732 | |||
1739 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1733 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1740 | # certain terminals. Until we figure out a robust way of |
|
1734 | # certain terminals. Until we figure out a robust way of | |
1741 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1735 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1742 | # microseconds. I am really NOT happy about disabling the proper |
|
1736 | # microseconds. I am really NOT happy about disabling the proper | |
1743 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1737 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1744 | # right solution for this is, I'm all ears... |
|
1738 | # right solution for this is, I'm all ears... | |
1745 | # |
|
1739 | # | |
1746 | # Note: using |
|
1740 | # Note: using | |
1747 | # |
|
1741 | # | |
1748 | # s = u'\xb5' |
|
1742 | # s = u'\xb5' | |
1749 | # s.encode(sys.getdefaultencoding()) |
|
1743 | # s.encode(sys.getdefaultencoding()) | |
1750 | # |
|
1744 | # | |
1751 | # is not sufficient, as I've seen terminals where that fails but |
|
1745 | # is not sufficient, as I've seen terminals where that fails but | |
1752 | # print s |
|
1746 | # print s | |
1753 | # |
|
1747 | # | |
1754 | # succeeds |
|
1748 | # succeeds | |
1755 | # |
|
1749 | # | |
1756 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1750 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1757 |
|
1751 | |||
1758 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1752 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1759 | units = [u"s", u"ms",u'us',"ns"] |
|
1753 | units = [u"s", u"ms",u'us',"ns"] | |
1760 |
|
1754 | |||
1761 | scaling = [1, 1e3, 1e6, 1e9] |
|
1755 | scaling = [1, 1e3, 1e6, 1e9] | |
1762 |
|
1756 | |||
1763 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1757 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1764 | posix=False) |
|
1758 | posix=False) | |
1765 | if stmt == "": |
|
1759 | if stmt == "": | |
1766 | return |
|
1760 | return | |
1767 | timefunc = timeit.default_timer |
|
1761 | timefunc = timeit.default_timer | |
1768 | number = int(getattr(opts, "n", 0)) |
|
1762 | number = int(getattr(opts, "n", 0)) | |
1769 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1763 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1770 | precision = int(getattr(opts, "p", 3)) |
|
1764 | precision = int(getattr(opts, "p", 3)) | |
1771 | if hasattr(opts, "t"): |
|
1765 | if hasattr(opts, "t"): | |
1772 | timefunc = time.time |
|
1766 | timefunc = time.time | |
1773 | if hasattr(opts, "c"): |
|
1767 | if hasattr(opts, "c"): | |
1774 | timefunc = clock |
|
1768 | timefunc = clock | |
1775 |
|
1769 | |||
1776 | timer = timeit.Timer(timer=timefunc) |
|
1770 | timer = timeit.Timer(timer=timefunc) | |
1777 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1771 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1778 | # but is there a better way to achieve that the code stmt has access |
|
1772 | # but is there a better way to achieve that the code stmt has access | |
1779 | # to the shell namespace? |
|
1773 | # to the shell namespace? | |
1780 |
|
1774 | |||
1781 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1775 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1782 | 'setup': "pass"} |
|
1776 | 'setup': "pass"} | |
1783 | # Track compilation time so it can be reported if too long |
|
1777 | # Track compilation time so it can be reported if too long | |
1784 | # Minimum time above which compilation time will be reported |
|
1778 | # Minimum time above which compilation time will be reported | |
1785 | tc_min = 0.1 |
|
1779 | tc_min = 0.1 | |
1786 |
|
1780 | |||
1787 | t0 = clock() |
|
1781 | t0 = clock() | |
1788 | code = compile(src, "<magic-timeit>", "exec") |
|
1782 | code = compile(src, "<magic-timeit>", "exec") | |
1789 | tc = clock()-t0 |
|
1783 | tc = clock()-t0 | |
1790 |
|
1784 | |||
1791 | ns = {} |
|
1785 | ns = {} | |
1792 | exec code in self.shell.user_ns, ns |
|
1786 | exec code in self.shell.user_ns, ns | |
1793 | timer.inner = ns["inner"] |
|
1787 | timer.inner = ns["inner"] | |
1794 |
|
1788 | |||
1795 | if number == 0: |
|
1789 | if number == 0: | |
1796 | # determine number so that 0.2 <= total time < 2.0 |
|
1790 | # determine number so that 0.2 <= total time < 2.0 | |
1797 | number = 1 |
|
1791 | number = 1 | |
1798 | for i in range(1, 10): |
|
1792 | for i in range(1, 10): | |
1799 | if timer.timeit(number) >= 0.2: |
|
1793 | if timer.timeit(number) >= 0.2: | |
1800 | break |
|
1794 | break | |
1801 | number *= 10 |
|
1795 | number *= 10 | |
1802 |
|
1796 | |||
1803 | best = min(timer.repeat(repeat, number)) / number |
|
1797 | best = min(timer.repeat(repeat, number)) / number | |
1804 |
|
1798 | |||
1805 | if best > 0.0 and best < 1000.0: |
|
1799 | if best > 0.0 and best < 1000.0: | |
1806 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1800 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1807 | elif best >= 1000.0: |
|
1801 | elif best >= 1000.0: | |
1808 | order = 0 |
|
1802 | order = 0 | |
1809 | else: |
|
1803 | else: | |
1810 | order = 3 |
|
1804 | order = 3 | |
1811 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1805 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1812 | precision, |
|
1806 | precision, | |
1813 | best * scaling[order], |
|
1807 | best * scaling[order], | |
1814 | units[order]) |
|
1808 | units[order]) | |
1815 | if tc > tc_min: |
|
1809 | if tc > tc_min: | |
1816 | print "Compiler time: %.2f s" % tc |
|
1810 | print "Compiler time: %.2f s" % tc | |
1817 |
|
1811 | |||
1818 | @testdec.skip_doctest |
|
1812 | @testdec.skip_doctest | |
1819 | def magic_time(self,parameter_s = ''): |
|
1813 | def magic_time(self,parameter_s = ''): | |
1820 | """Time execution of a Python statement or expression. |
|
1814 | """Time execution of a Python statement or expression. | |
1821 |
|
1815 | |||
1822 | The CPU and wall clock times are printed, and the value of the |
|
1816 | The CPU and wall clock times are printed, and the value of the | |
1823 | expression (if any) is returned. Note that under Win32, system time |
|
1817 | expression (if any) is returned. Note that under Win32, system time | |
1824 | is always reported as 0, since it can not be measured. |
|
1818 | is always reported as 0, since it can not be measured. | |
1825 |
|
1819 | |||
1826 | This function provides very basic timing functionality. In Python |
|
1820 | This function provides very basic timing functionality. In Python | |
1827 | 2.3, the timeit module offers more control and sophistication, so this |
|
1821 | 2.3, the timeit module offers more control and sophistication, so this | |
1828 | could be rewritten to use it (patches welcome). |
|
1822 | could be rewritten to use it (patches welcome). | |
1829 |
|
1823 | |||
1830 | Some examples: |
|
1824 | Some examples: | |
1831 |
|
1825 | |||
1832 | In [1]: time 2**128 |
|
1826 | In [1]: time 2**128 | |
1833 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1827 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1834 | Wall time: 0.00 |
|
1828 | Wall time: 0.00 | |
1835 | Out[1]: 340282366920938463463374607431768211456L |
|
1829 | Out[1]: 340282366920938463463374607431768211456L | |
1836 |
|
1830 | |||
1837 | In [2]: n = 1000000 |
|
1831 | In [2]: n = 1000000 | |
1838 |
|
1832 | |||
1839 | In [3]: time sum(range(n)) |
|
1833 | In [3]: time sum(range(n)) | |
1840 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1834 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1841 | Wall time: 1.37 |
|
1835 | Wall time: 1.37 | |
1842 | Out[3]: 499999500000L |
|
1836 | Out[3]: 499999500000L | |
1843 |
|
1837 | |||
1844 | In [4]: time print 'hello world' |
|
1838 | In [4]: time print 'hello world' | |
1845 | hello world |
|
1839 | hello world | |
1846 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1840 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1847 | Wall time: 0.00 |
|
1841 | Wall time: 0.00 | |
1848 |
|
1842 | |||
1849 | Note that the time needed by Python to compile the given expression |
|
1843 | Note that the time needed by Python to compile the given expression | |
1850 | will be reported if it is more than 0.1s. In this example, the |
|
1844 | will be reported if it is more than 0.1s. In this example, the | |
1851 | actual exponentiation is done by Python at compilation time, so while |
|
1845 | actual exponentiation is done by Python at compilation time, so while | |
1852 | the expression can take a noticeable amount of time to compute, that |
|
1846 | the expression can take a noticeable amount of time to compute, that | |
1853 | time is purely due to the compilation: |
|
1847 | time is purely due to the compilation: | |
1854 |
|
1848 | |||
1855 | In [5]: time 3**9999; |
|
1849 | In [5]: time 3**9999; | |
1856 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1850 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1857 | Wall time: 0.00 s |
|
1851 | Wall time: 0.00 s | |
1858 |
|
1852 | |||
1859 | In [6]: time 3**999999; |
|
1853 | In [6]: time 3**999999; | |
1860 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1854 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1861 | Wall time: 0.00 s |
|
1855 | Wall time: 0.00 s | |
1862 | Compiler : 0.78 s |
|
1856 | Compiler : 0.78 s | |
1863 | """ |
|
1857 | """ | |
1864 |
|
1858 | |||
1865 | # fail immediately if the given expression can't be compiled |
|
1859 | # fail immediately if the given expression can't be compiled | |
1866 |
|
1860 | |||
1867 | expr = self.shell.prefilter(parameter_s,False) |
|
1861 | expr = self.shell.prefilter(parameter_s,False) | |
1868 |
|
1862 | |||
1869 | # Minimum time above which compilation time will be reported |
|
1863 | # Minimum time above which compilation time will be reported | |
1870 | tc_min = 0.1 |
|
1864 | tc_min = 0.1 | |
1871 |
|
1865 | |||
1872 | try: |
|
1866 | try: | |
1873 | mode = 'eval' |
|
1867 | mode = 'eval' | |
1874 | t0 = clock() |
|
1868 | t0 = clock() | |
1875 | code = compile(expr,'<timed eval>',mode) |
|
1869 | code = compile(expr,'<timed eval>',mode) | |
1876 | tc = clock()-t0 |
|
1870 | tc = clock()-t0 | |
1877 | except SyntaxError: |
|
1871 | except SyntaxError: | |
1878 | mode = 'exec' |
|
1872 | mode = 'exec' | |
1879 | t0 = clock() |
|
1873 | t0 = clock() | |
1880 | code = compile(expr,'<timed exec>',mode) |
|
1874 | code = compile(expr,'<timed exec>',mode) | |
1881 | tc = clock()-t0 |
|
1875 | tc = clock()-t0 | |
1882 | # skew measurement as little as possible |
|
1876 | # skew measurement as little as possible | |
1883 | glob = self.shell.user_ns |
|
1877 | glob = self.shell.user_ns | |
1884 | clk = clock2 |
|
1878 | clk = clock2 | |
1885 | wtime = time.time |
|
1879 | wtime = time.time | |
1886 | # time execution |
|
1880 | # time execution | |
1887 | wall_st = wtime() |
|
1881 | wall_st = wtime() | |
1888 | if mode=='eval': |
|
1882 | if mode=='eval': | |
1889 | st = clk() |
|
1883 | st = clk() | |
1890 | out = eval(code,glob) |
|
1884 | out = eval(code,glob) | |
1891 | end = clk() |
|
1885 | end = clk() | |
1892 | else: |
|
1886 | else: | |
1893 | st = clk() |
|
1887 | st = clk() | |
1894 | exec code in glob |
|
1888 | exec code in glob | |
1895 | end = clk() |
|
1889 | end = clk() | |
1896 | out = None |
|
1890 | out = None | |
1897 | wall_end = wtime() |
|
1891 | wall_end = wtime() | |
1898 | # Compute actual times and report |
|
1892 | # Compute actual times and report | |
1899 | wall_time = wall_end-wall_st |
|
1893 | wall_time = wall_end-wall_st | |
1900 | cpu_user = end[0]-st[0] |
|
1894 | cpu_user = end[0]-st[0] | |
1901 | cpu_sys = end[1]-st[1] |
|
1895 | cpu_sys = end[1]-st[1] | |
1902 | cpu_tot = cpu_user+cpu_sys |
|
1896 | cpu_tot = cpu_user+cpu_sys | |
1903 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1897 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1904 | (cpu_user,cpu_sys,cpu_tot) |
|
1898 | (cpu_user,cpu_sys,cpu_tot) | |
1905 | print "Wall time: %.2f s" % wall_time |
|
1899 | print "Wall time: %.2f s" % wall_time | |
1906 | if tc > tc_min: |
|
1900 | if tc > tc_min: | |
1907 | print "Compiler : %.2f s" % tc |
|
1901 | print "Compiler : %.2f s" % tc | |
1908 | return out |
|
1902 | return out | |
1909 |
|
1903 | |||
1910 | @testdec.skip_doctest |
|
1904 | @testdec.skip_doctest | |
1911 | def magic_macro(self,parameter_s = ''): |
|
1905 | def magic_macro(self,parameter_s = ''): | |
1912 | """Define a set of input lines as a macro for future re-execution. |
|
1906 | """Define a set of input lines as a macro for future re-execution. | |
1913 |
|
1907 | |||
1914 | Usage:\\ |
|
1908 | Usage:\\ | |
1915 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1909 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1916 |
|
1910 | |||
1917 | Options: |
|
1911 | Options: | |
1918 |
|
1912 | |||
1919 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1913 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1920 | so that magics are loaded in their transformed version to valid |
|
1914 | so that magics are loaded in their transformed version to valid | |
1921 | Python. If this option is given, the raw input as typed as the |
|
1915 | Python. If this option is given, the raw input as typed as the | |
1922 | command line is used instead. |
|
1916 | command line is used instead. | |
1923 |
|
1917 | |||
1924 | This will define a global variable called `name` which is a string |
|
1918 | This will define a global variable called `name` which is a string | |
1925 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1919 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1926 | above) from your input history into a single string. This variable |
|
1920 | above) from your input history into a single string. This variable | |
1927 | acts like an automatic function which re-executes those lines as if |
|
1921 | acts like an automatic function which re-executes those lines as if | |
1928 | you had typed them. You just type 'name' at the prompt and the code |
|
1922 | you had typed them. You just type 'name' at the prompt and the code | |
1929 | executes. |
|
1923 | executes. | |
1930 |
|
1924 | |||
1931 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1925 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1932 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1926 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1933 | using the lines numbered 5,6 and 7. |
|
1927 | using the lines numbered 5,6 and 7. | |
1934 |
|
1928 | |||
1935 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1929 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1936 | notation, where N:M means numbers N through M-1. |
|
1930 | notation, where N:M means numbers N through M-1. | |
1937 |
|
1931 | |||
1938 | For example, if your history contains (%hist prints it): |
|
1932 | For example, if your history contains (%hist prints it): | |
1939 |
|
1933 | |||
1940 | 44: x=1 |
|
1934 | 44: x=1 | |
1941 | 45: y=3 |
|
1935 | 45: y=3 | |
1942 | 46: z=x+y |
|
1936 | 46: z=x+y | |
1943 | 47: print x |
|
1937 | 47: print x | |
1944 | 48: a=5 |
|
1938 | 48: a=5 | |
1945 | 49: print 'x',x,'y',y |
|
1939 | 49: print 'x',x,'y',y | |
1946 |
|
1940 | |||
1947 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1941 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1948 | called my_macro with: |
|
1942 | called my_macro with: | |
1949 |
|
1943 | |||
1950 | In [55]: %macro my_macro 44-47 49 |
|
1944 | In [55]: %macro my_macro 44-47 49 | |
1951 |
|
1945 | |||
1952 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1946 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1953 | in one pass. |
|
1947 | in one pass. | |
1954 |
|
1948 | |||
1955 | You don't need to give the line-numbers in order, and any given line |
|
1949 | You don't need to give the line-numbers in order, and any given line | |
1956 | number can appear multiple times. You can assemble macros with any |
|
1950 | number can appear multiple times. You can assemble macros with any | |
1957 | lines from your input history in any order. |
|
1951 | lines from your input history in any order. | |
1958 |
|
1952 | |||
1959 | The macro is a simple object which holds its value in an attribute, |
|
1953 | The macro is a simple object which holds its value in an attribute, | |
1960 | but IPython's display system checks for macros and executes them as |
|
1954 | but IPython's display system checks for macros and executes them as | |
1961 | code instead of printing them when you type their name. |
|
1955 | code instead of printing them when you type their name. | |
1962 |
|
1956 | |||
1963 | You can view a macro's contents by explicitly printing it with: |
|
1957 | You can view a macro's contents by explicitly printing it with: | |
1964 |
|
1958 | |||
1965 | 'print macro_name'. |
|
1959 | 'print macro_name'. | |
1966 |
|
1960 | |||
1967 | For one-off cases which DON'T contain magic function calls in them you |
|
1961 | For one-off cases which DON'T contain magic function calls in them you | |
1968 | can obtain similar results by explicitly executing slices from your |
|
1962 | can obtain similar results by explicitly executing slices from your | |
1969 | input history with: |
|
1963 | input history with: | |
1970 |
|
1964 | |||
1971 | In [60]: exec In[44:48]+In[49]""" |
|
1965 | In [60]: exec In[44:48]+In[49]""" | |
1972 |
|
1966 | |||
1973 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1967 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1974 | if not args: |
|
1968 | if not args: | |
1975 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
1969 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
1976 | macs.sort() |
|
1970 | macs.sort() | |
1977 | return macs |
|
1971 | return macs | |
1978 | if len(args) == 1: |
|
1972 | if len(args) == 1: | |
1979 | raise UsageError( |
|
1973 | raise UsageError( | |
1980 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1974 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
1981 | name,ranges = args[0], args[1:] |
|
1975 | name,ranges = args[0], args[1:] | |
1982 |
|
1976 | |||
1983 | #print 'rng',ranges # dbg |
|
1977 | #print 'rng',ranges # dbg | |
1984 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1978 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
1985 | macro = Macro(lines) |
|
1979 | macro = Macro(lines) | |
1986 | self.shell.define_macro(name, macro) |
|
1980 | self.shell.define_macro(name, macro) | |
1987 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1981 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1988 | print 'Macro contents:' |
|
1982 | print 'Macro contents:' | |
1989 | print macro, |
|
1983 | print macro, | |
1990 |
|
1984 | |||
1991 | def magic_save(self,parameter_s = ''): |
|
1985 | def magic_save(self,parameter_s = ''): | |
1992 | """Save a set of lines to a given filename. |
|
1986 | """Save a set of lines to a given filename. | |
1993 |
|
1987 | |||
1994 | Usage:\\ |
|
1988 | Usage:\\ | |
1995 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1989 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
1996 |
|
1990 | |||
1997 | Options: |
|
1991 | Options: | |
1998 |
|
1992 | |||
1999 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1993 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2000 | so that magics are loaded in their transformed version to valid |
|
1994 | so that magics are loaded in their transformed version to valid | |
2001 | Python. If this option is given, the raw input as typed as the |
|
1995 | Python. If this option is given, the raw input as typed as the | |
2002 | command line is used instead. |
|
1996 | command line is used instead. | |
2003 |
|
1997 | |||
2004 | This function uses the same syntax as %macro for line extraction, but |
|
1998 | This function uses the same syntax as %macro for line extraction, but | |
2005 | instead of creating a macro it saves the resulting string to the |
|
1999 | instead of creating a macro it saves the resulting string to the | |
2006 | filename you specify. |
|
2000 | filename you specify. | |
2007 |
|
2001 | |||
2008 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2002 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2009 | it asks for confirmation before overwriting existing files.""" |
|
2003 | it asks for confirmation before overwriting existing files.""" | |
2010 |
|
2004 | |||
2011 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2005 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2012 | fname,ranges = args[0], args[1:] |
|
2006 | fname,ranges = args[0], args[1:] | |
2013 | if not fname.endswith('.py'): |
|
2007 | if not fname.endswith('.py'): | |
2014 | fname += '.py' |
|
2008 | fname += '.py' | |
2015 | if os.path.isfile(fname): |
|
2009 | if os.path.isfile(fname): | |
2016 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2010 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2017 | if ans.lower() not in ['y','yes']: |
|
2011 | if ans.lower() not in ['y','yes']: | |
2018 | print 'Operation cancelled.' |
|
2012 | print 'Operation cancelled.' | |
2019 | return |
|
2013 | return | |
2020 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2014 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2021 | f = file(fname,'w') |
|
2015 | f = file(fname,'w') | |
2022 | f.write(cmds) |
|
2016 | f.write(cmds) | |
2023 | f.close() |
|
2017 | f.close() | |
2024 | print 'The following commands were written to file `%s`:' % fname |
|
2018 | print 'The following commands were written to file `%s`:' % fname | |
2025 | print cmds |
|
2019 | print cmds | |
2026 |
|
2020 | |||
2027 | def _edit_macro(self,mname,macro): |
|
2021 | def _edit_macro(self,mname,macro): | |
2028 | """open an editor with the macro data in a file""" |
|
2022 | """open an editor with the macro data in a file""" | |
2029 | filename = self.shell.mktempfile(macro.value) |
|
2023 | filename = self.shell.mktempfile(macro.value) | |
2030 | self.shell.hooks.editor(filename) |
|
2024 | self.shell.hooks.editor(filename) | |
2031 |
|
2025 | |||
2032 | # and make a new macro object, to replace the old one |
|
2026 | # and make a new macro object, to replace the old one | |
2033 | mfile = open(filename) |
|
2027 | mfile = open(filename) | |
2034 | mvalue = mfile.read() |
|
2028 | mvalue = mfile.read() | |
2035 | mfile.close() |
|
2029 | mfile.close() | |
2036 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2030 | self.shell.user_ns[mname] = Macro(mvalue) | |
2037 |
|
2031 | |||
2038 | def magic_ed(self,parameter_s=''): |
|
2032 | def magic_ed(self,parameter_s=''): | |
2039 | """Alias to %edit.""" |
|
2033 | """Alias to %edit.""" | |
2040 | return self.magic_edit(parameter_s) |
|
2034 | return self.magic_edit(parameter_s) | |
2041 |
|
2035 | |||
2042 | @testdec.skip_doctest |
|
2036 | @testdec.skip_doctest | |
2043 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2037 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2044 | """Bring up an editor and execute the resulting code. |
|
2038 | """Bring up an editor and execute the resulting code. | |
2045 |
|
2039 | |||
2046 | Usage: |
|
2040 | Usage: | |
2047 | %edit [options] [args] |
|
2041 | %edit [options] [args] | |
2048 |
|
2042 | |||
2049 | %edit runs IPython's editor hook. The default version of this hook is |
|
2043 | %edit runs IPython's editor hook. The default version of this hook is | |
2050 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2044 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2051 | environment variable $EDITOR. If this isn't found, it will default to |
|
2045 | environment variable $EDITOR. If this isn't found, it will default to | |
2052 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2046 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2053 | docstring for how to change the editor hook. |
|
2047 | docstring for how to change the editor hook. | |
2054 |
|
2048 | |||
2055 | You can also set the value of this editor via the command line option |
|
2049 | You can also set the value of this editor via the command line option | |
2056 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2050 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2057 | specifically for IPython an editor different from your typical default |
|
2051 | specifically for IPython an editor different from your typical default | |
2058 | (and for Windows users who typically don't set environment variables). |
|
2052 | (and for Windows users who typically don't set environment variables). | |
2059 |
|
2053 | |||
2060 | This command allows you to conveniently edit multi-line code right in |
|
2054 | This command allows you to conveniently edit multi-line code right in | |
2061 | your IPython session. |
|
2055 | your IPython session. | |
2062 |
|
2056 | |||
2063 | If called without arguments, %edit opens up an empty editor with a |
|
2057 | If called without arguments, %edit opens up an empty editor with a | |
2064 | temporary file and will execute the contents of this file when you |
|
2058 | temporary file and will execute the contents of this file when you | |
2065 | close it (don't forget to save it!). |
|
2059 | close it (don't forget to save it!). | |
2066 |
|
2060 | |||
2067 |
|
2061 | |||
2068 | Options: |
|
2062 | Options: | |
2069 |
|
2063 | |||
2070 | -n <number>: open the editor at a specified line number. By default, |
|
2064 | -n <number>: open the editor at a specified line number. By default, | |
2071 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2065 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2072 | you can configure this by providing your own modified hook if your |
|
2066 | you can configure this by providing your own modified hook if your | |
2073 | favorite editor supports line-number specifications with a different |
|
2067 | favorite editor supports line-number specifications with a different | |
2074 | syntax. |
|
2068 | syntax. | |
2075 |
|
2069 | |||
2076 | -p: this will call the editor with the same data as the previous time |
|
2070 | -p: this will call the editor with the same data as the previous time | |
2077 | it was used, regardless of how long ago (in your current session) it |
|
2071 | it was used, regardless of how long ago (in your current session) it | |
2078 | was. |
|
2072 | was. | |
2079 |
|
2073 | |||
2080 | -r: use 'raw' input. This option only applies to input taken from the |
|
2074 | -r: use 'raw' input. This option only applies to input taken from the | |
2081 | user's history. By default, the 'processed' history is used, so that |
|
2075 | user's history. By default, the 'processed' history is used, so that | |
2082 | magics are loaded in their transformed version to valid Python. If |
|
2076 | magics are loaded in their transformed version to valid Python. If | |
2083 | this option is given, the raw input as typed as the command line is |
|
2077 | this option is given, the raw input as typed as the command line is | |
2084 | used instead. When you exit the editor, it will be executed by |
|
2078 | used instead. When you exit the editor, it will be executed by | |
2085 | IPython's own processor. |
|
2079 | IPython's own processor. | |
2086 |
|
2080 | |||
2087 | -x: do not execute the edited code immediately upon exit. This is |
|
2081 | -x: do not execute the edited code immediately upon exit. This is | |
2088 | mainly useful if you are editing programs which need to be called with |
|
2082 | mainly useful if you are editing programs which need to be called with | |
2089 | command line arguments, which you can then do using %run. |
|
2083 | command line arguments, which you can then do using %run. | |
2090 |
|
2084 | |||
2091 |
|
2085 | |||
2092 | Arguments: |
|
2086 | Arguments: | |
2093 |
|
2087 | |||
2094 | If arguments are given, the following possibilites exist: |
|
2088 | If arguments are given, the following possibilites exist: | |
2095 |
|
2089 | |||
2096 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2090 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2097 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2091 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2098 | loaded into the editor. The syntax is the same of the %macro command. |
|
2092 | loaded into the editor. The syntax is the same of the %macro command. | |
2099 |
|
2093 | |||
2100 | - If the argument doesn't start with a number, it is evaluated as a |
|
2094 | - If the argument doesn't start with a number, it is evaluated as a | |
2101 | variable and its contents loaded into the editor. You can thus edit |
|
2095 | variable and its contents loaded into the editor. You can thus edit | |
2102 | any string which contains python code (including the result of |
|
2096 | any string which contains python code (including the result of | |
2103 | previous edits). |
|
2097 | previous edits). | |
2104 |
|
2098 | |||
2105 | - If the argument is the name of an object (other than a string), |
|
2099 | - If the argument is the name of an object (other than a string), | |
2106 | IPython will try to locate the file where it was defined and open the |
|
2100 | IPython will try to locate the file where it was defined and open the | |
2107 | editor at the point where it is defined. You can use `%edit function` |
|
2101 | editor at the point where it is defined. You can use `%edit function` | |
2108 | to load an editor exactly at the point where 'function' is defined, |
|
2102 | to load an editor exactly at the point where 'function' is defined, | |
2109 | edit it and have the file be executed automatically. |
|
2103 | edit it and have the file be executed automatically. | |
2110 |
|
2104 | |||
2111 | If the object is a macro (see %macro for details), this opens up your |
|
2105 | If the object is a macro (see %macro for details), this opens up your | |
2112 | specified editor with a temporary file containing the macro's data. |
|
2106 | specified editor with a temporary file containing the macro's data. | |
2113 | Upon exit, the macro is reloaded with the contents of the file. |
|
2107 | Upon exit, the macro is reloaded with the contents of the file. | |
2114 |
|
2108 | |||
2115 | Note: opening at an exact line is only supported under Unix, and some |
|
2109 | Note: opening at an exact line is only supported under Unix, and some | |
2116 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2110 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2117 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2111 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2118 | (X)Emacs, vi, jed, pico and joe all do. |
|
2112 | (X)Emacs, vi, jed, pico and joe all do. | |
2119 |
|
2113 | |||
2120 | - If the argument is not found as a variable, IPython will look for a |
|
2114 | - If the argument is not found as a variable, IPython will look for a | |
2121 | file with that name (adding .py if necessary) and load it into the |
|
2115 | file with that name (adding .py if necessary) and load it into the | |
2122 | editor. It will execute its contents with execfile() when you exit, |
|
2116 | editor. It will execute its contents with execfile() when you exit, | |
2123 | loading any code in the file into your interactive namespace. |
|
2117 | loading any code in the file into your interactive namespace. | |
2124 |
|
2118 | |||
2125 | After executing your code, %edit will return as output the code you |
|
2119 | After executing your code, %edit will return as output the code you | |
2126 | typed in the editor (except when it was an existing file). This way |
|
2120 | typed in the editor (except when it was an existing file). This way | |
2127 | you can reload the code in further invocations of %edit as a variable, |
|
2121 | you can reload the code in further invocations of %edit as a variable, | |
2128 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2122 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2129 | the output. |
|
2123 | the output. | |
2130 |
|
2124 | |||
2131 | Note that %edit is also available through the alias %ed. |
|
2125 | Note that %edit is also available through the alias %ed. | |
2132 |
|
2126 | |||
2133 | This is an example of creating a simple function inside the editor and |
|
2127 | This is an example of creating a simple function inside the editor and | |
2134 | then modifying it. First, start up the editor: |
|
2128 | then modifying it. First, start up the editor: | |
2135 |
|
2129 | |||
2136 | In [1]: ed |
|
2130 | In [1]: ed | |
2137 | Editing... done. Executing edited code... |
|
2131 | Editing... done. Executing edited code... | |
2138 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2132 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2139 |
|
2133 | |||
2140 | We can then call the function foo(): |
|
2134 | We can then call the function foo(): | |
2141 |
|
2135 | |||
2142 | In [2]: foo() |
|
2136 | In [2]: foo() | |
2143 | foo() was defined in an editing session |
|
2137 | foo() was defined in an editing session | |
2144 |
|
2138 | |||
2145 | Now we edit foo. IPython automatically loads the editor with the |
|
2139 | Now we edit foo. IPython automatically loads the editor with the | |
2146 | (temporary) file where foo() was previously defined: |
|
2140 | (temporary) file where foo() was previously defined: | |
2147 |
|
2141 | |||
2148 | In [3]: ed foo |
|
2142 | In [3]: ed foo | |
2149 | Editing... done. Executing edited code... |
|
2143 | Editing... done. Executing edited code... | |
2150 |
|
2144 | |||
2151 | And if we call foo() again we get the modified version: |
|
2145 | And if we call foo() again we get the modified version: | |
2152 |
|
2146 | |||
2153 | In [4]: foo() |
|
2147 | In [4]: foo() | |
2154 | foo() has now been changed! |
|
2148 | foo() has now been changed! | |
2155 |
|
2149 | |||
2156 | Here is an example of how to edit a code snippet successive |
|
2150 | Here is an example of how to edit a code snippet successive | |
2157 | times. First we call the editor: |
|
2151 | times. First we call the editor: | |
2158 |
|
2152 | |||
2159 | In [5]: ed |
|
2153 | In [5]: ed | |
2160 | Editing... done. Executing edited code... |
|
2154 | Editing... done. Executing edited code... | |
2161 | hello |
|
2155 | hello | |
2162 | Out[5]: "print 'hello'n" |
|
2156 | Out[5]: "print 'hello'n" | |
2163 |
|
2157 | |||
2164 | Now we call it again with the previous output (stored in _): |
|
2158 | Now we call it again with the previous output (stored in _): | |
2165 |
|
2159 | |||
2166 | In [6]: ed _ |
|
2160 | In [6]: ed _ | |
2167 | Editing... done. Executing edited code... |
|
2161 | Editing... done. Executing edited code... | |
2168 | hello world |
|
2162 | hello world | |
2169 | Out[6]: "print 'hello world'n" |
|
2163 | Out[6]: "print 'hello world'n" | |
2170 |
|
2164 | |||
2171 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2165 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2172 |
|
2166 | |||
2173 | In [7]: ed _8 |
|
2167 | In [7]: ed _8 | |
2174 | Editing... done. Executing edited code... |
|
2168 | Editing... done. Executing edited code... | |
2175 | hello again |
|
2169 | hello again | |
2176 | Out[7]: "print 'hello again'n" |
|
2170 | Out[7]: "print 'hello again'n" | |
2177 |
|
2171 | |||
2178 |
|
2172 | |||
2179 | Changing the default editor hook: |
|
2173 | Changing the default editor hook: | |
2180 |
|
2174 | |||
2181 | If you wish to write your own editor hook, you can put it in a |
|
2175 | If you wish to write your own editor hook, you can put it in a | |
2182 | configuration file which you load at startup time. The default hook |
|
2176 | configuration file which you load at startup time. The default hook | |
2183 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2177 | is defined in the IPython.core.hooks module, and you can use that as a | |
2184 | starting example for further modifications. That file also has |
|
2178 | starting example for further modifications. That file also has | |
2185 | general instructions on how to set a new hook for use once you've |
|
2179 | general instructions on how to set a new hook for use once you've | |
2186 | defined it.""" |
|
2180 | defined it.""" | |
2187 |
|
2181 | |||
2188 | # FIXME: This function has become a convoluted mess. It needs a |
|
2182 | # FIXME: This function has become a convoluted mess. It needs a | |
2189 | # ground-up rewrite with clean, simple logic. |
|
2183 | # ground-up rewrite with clean, simple logic. | |
2190 |
|
2184 | |||
2191 | def make_filename(arg): |
|
2185 | def make_filename(arg): | |
2192 | "Make a filename from the given args" |
|
2186 | "Make a filename from the given args" | |
2193 | try: |
|
2187 | try: | |
2194 | filename = get_py_filename(arg) |
|
2188 | filename = get_py_filename(arg) | |
2195 | except IOError: |
|
2189 | except IOError: | |
2196 | if args.endswith('.py'): |
|
2190 | if args.endswith('.py'): | |
2197 | filename = arg |
|
2191 | filename = arg | |
2198 | else: |
|
2192 | else: | |
2199 | filename = None |
|
2193 | filename = None | |
2200 | return filename |
|
2194 | return filename | |
2201 |
|
2195 | |||
2202 | # custom exceptions |
|
2196 | # custom exceptions | |
2203 | class DataIsObject(Exception): pass |
|
2197 | class DataIsObject(Exception): pass | |
2204 |
|
2198 | |||
2205 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2199 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2206 | # Set a few locals from the options for convenience: |
|
2200 | # Set a few locals from the options for convenience: | |
2207 | opts_p = opts.has_key('p') |
|
2201 | opts_p = opts.has_key('p') | |
2208 | opts_r = opts.has_key('r') |
|
2202 | opts_r = opts.has_key('r') | |
2209 |
|
2203 | |||
2210 | # Default line number value |
|
2204 | # Default line number value | |
2211 | lineno = opts.get('n',None) |
|
2205 | lineno = opts.get('n',None) | |
2212 |
|
2206 | |||
2213 | if opts_p: |
|
2207 | if opts_p: | |
2214 | args = '_%s' % last_call[0] |
|
2208 | args = '_%s' % last_call[0] | |
2215 | if not self.shell.user_ns.has_key(args): |
|
2209 | if not self.shell.user_ns.has_key(args): | |
2216 | args = last_call[1] |
|
2210 | args = last_call[1] | |
2217 |
|
2211 | |||
2218 | # use last_call to remember the state of the previous call, but don't |
|
2212 | # use last_call to remember the state of the previous call, but don't | |
2219 | # let it be clobbered by successive '-p' calls. |
|
2213 | # let it be clobbered by successive '-p' calls. | |
2220 | try: |
|
2214 | try: | |
2221 | last_call[0] = self.shell.displayhook.prompt_count |
|
2215 | last_call[0] = self.shell.displayhook.prompt_count | |
2222 | if not opts_p: |
|
2216 | if not opts_p: | |
2223 | last_call[1] = parameter_s |
|
2217 | last_call[1] = parameter_s | |
2224 | except: |
|
2218 | except: | |
2225 | pass |
|
2219 | pass | |
2226 |
|
2220 | |||
2227 | # by default this is done with temp files, except when the given |
|
2221 | # by default this is done with temp files, except when the given | |
2228 | # arg is a filename |
|
2222 | # arg is a filename | |
2229 | use_temp = 1 |
|
2223 | use_temp = 1 | |
2230 |
|
2224 | |||
2231 | if re.match(r'\d',args): |
|
2225 | if re.match(r'\d',args): | |
2232 | # Mode where user specifies ranges of lines, like in %macro. |
|
2226 | # Mode where user specifies ranges of lines, like in %macro. | |
2233 | # This means that you can't edit files whose names begin with |
|
2227 | # This means that you can't edit files whose names begin with | |
2234 | # numbers this way. Tough. |
|
2228 | # numbers this way. Tough. | |
2235 | ranges = args.split() |
|
2229 | ranges = args.split() | |
2236 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2230 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2237 | elif args.endswith('.py'): |
|
2231 | elif args.endswith('.py'): | |
2238 | filename = make_filename(args) |
|
2232 | filename = make_filename(args) | |
2239 | data = '' |
|
2233 | data = '' | |
2240 | use_temp = 0 |
|
2234 | use_temp = 0 | |
2241 | elif args: |
|
2235 | elif args: | |
2242 | try: |
|
2236 | try: | |
2243 | # Load the parameter given as a variable. If not a string, |
|
2237 | # Load the parameter given as a variable. If not a string, | |
2244 | # process it as an object instead (below) |
|
2238 | # process it as an object instead (below) | |
2245 |
|
2239 | |||
2246 | #print '*** args',args,'type',type(args) # dbg |
|
2240 | #print '*** args',args,'type',type(args) # dbg | |
2247 | data = eval(args,self.shell.user_ns) |
|
2241 | data = eval(args,self.shell.user_ns) | |
2248 | if not type(data) in StringTypes: |
|
2242 | if not type(data) in StringTypes: | |
2249 | raise DataIsObject |
|
2243 | raise DataIsObject | |
2250 |
|
2244 | |||
2251 | except (NameError,SyntaxError): |
|
2245 | except (NameError,SyntaxError): | |
2252 | # given argument is not a variable, try as a filename |
|
2246 | # given argument is not a variable, try as a filename | |
2253 | filename = make_filename(args) |
|
2247 | filename = make_filename(args) | |
2254 | if filename is None: |
|
2248 | if filename is None: | |
2255 | warn("Argument given (%s) can't be found as a variable " |
|
2249 | warn("Argument given (%s) can't be found as a variable " | |
2256 | "or as a filename." % args) |
|
2250 | "or as a filename." % args) | |
2257 | return |
|
2251 | return | |
2258 |
|
2252 | |||
2259 | data = '' |
|
2253 | data = '' | |
2260 | use_temp = 0 |
|
2254 | use_temp = 0 | |
2261 | except DataIsObject: |
|
2255 | except DataIsObject: | |
2262 |
|
2256 | |||
2263 | # macros have a special edit function |
|
2257 | # macros have a special edit function | |
2264 | if isinstance(data,Macro): |
|
2258 | if isinstance(data,Macro): | |
2265 | self._edit_macro(args,data) |
|
2259 | self._edit_macro(args,data) | |
2266 | return |
|
2260 | return | |
2267 |
|
2261 | |||
2268 | # For objects, try to edit the file where they are defined |
|
2262 | # For objects, try to edit the file where they are defined | |
2269 | try: |
|
2263 | try: | |
2270 | filename = inspect.getabsfile(data) |
|
2264 | filename = inspect.getabsfile(data) | |
2271 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2265 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2272 | # class created by %edit? Try to find source |
|
2266 | # class created by %edit? Try to find source | |
2273 | # by looking for method definitions instead, the |
|
2267 | # by looking for method definitions instead, the | |
2274 | # __module__ in those classes is FakeModule. |
|
2268 | # __module__ in those classes is FakeModule. | |
2275 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2269 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2276 | for attr in attrs: |
|
2270 | for attr in attrs: | |
2277 | if not inspect.ismethod(attr): |
|
2271 | if not inspect.ismethod(attr): | |
2278 | continue |
|
2272 | continue | |
2279 | filename = inspect.getabsfile(attr) |
|
2273 | filename = inspect.getabsfile(attr) | |
2280 | if filename and 'fakemodule' not in filename.lower(): |
|
2274 | if filename and 'fakemodule' not in filename.lower(): | |
2281 | # change the attribute to be the edit target instead |
|
2275 | # change the attribute to be the edit target instead | |
2282 | data = attr |
|
2276 | data = attr | |
2283 | break |
|
2277 | break | |
2284 |
|
2278 | |||
2285 | datafile = 1 |
|
2279 | datafile = 1 | |
2286 | except TypeError: |
|
2280 | except TypeError: | |
2287 | filename = make_filename(args) |
|
2281 | filename = make_filename(args) | |
2288 | datafile = 1 |
|
2282 | datafile = 1 | |
2289 | warn('Could not find file where `%s` is defined.\n' |
|
2283 | warn('Could not find file where `%s` is defined.\n' | |
2290 | 'Opening a file named `%s`' % (args,filename)) |
|
2284 | 'Opening a file named `%s`' % (args,filename)) | |
2291 | # Now, make sure we can actually read the source (if it was in |
|
2285 | # Now, make sure we can actually read the source (if it was in | |
2292 | # a temp file it's gone by now). |
|
2286 | # a temp file it's gone by now). | |
2293 | if datafile: |
|
2287 | if datafile: | |
2294 | try: |
|
2288 | try: | |
2295 | if lineno is None: |
|
2289 | if lineno is None: | |
2296 | lineno = inspect.getsourcelines(data)[1] |
|
2290 | lineno = inspect.getsourcelines(data)[1] | |
2297 | except IOError: |
|
2291 | except IOError: | |
2298 | filename = make_filename(args) |
|
2292 | filename = make_filename(args) | |
2299 | if filename is None: |
|
2293 | if filename is None: | |
2300 | warn('The file `%s` where `%s` was defined cannot ' |
|
2294 | warn('The file `%s` where `%s` was defined cannot ' | |
2301 | 'be read.' % (filename,data)) |
|
2295 | 'be read.' % (filename,data)) | |
2302 | return |
|
2296 | return | |
2303 | use_temp = 0 |
|
2297 | use_temp = 0 | |
2304 | else: |
|
2298 | else: | |
2305 | data = '' |
|
2299 | data = '' | |
2306 |
|
2300 | |||
2307 | if use_temp: |
|
2301 | if use_temp: | |
2308 | filename = self.shell.mktempfile(data) |
|
2302 | filename = self.shell.mktempfile(data) | |
2309 | print 'IPython will make a temporary file named:',filename |
|
2303 | print 'IPython will make a temporary file named:',filename | |
2310 |
|
2304 | |||
2311 | # do actual editing here |
|
2305 | # do actual editing here | |
2312 | print 'Editing...', |
|
2306 | print 'Editing...', | |
2313 | sys.stdout.flush() |
|
2307 | sys.stdout.flush() | |
2314 | try: |
|
2308 | try: | |
2315 | # Quote filenames that may have spaces in them |
|
2309 | # Quote filenames that may have spaces in them | |
2316 | if ' ' in filename: |
|
2310 | if ' ' in filename: | |
2317 | filename = "%s" % filename |
|
2311 | filename = "%s" % filename | |
2318 | self.shell.hooks.editor(filename,lineno) |
|
2312 | self.shell.hooks.editor(filename,lineno) | |
2319 | except TryNext: |
|
2313 | except TryNext: | |
2320 | warn('Could not open editor') |
|
2314 | warn('Could not open editor') | |
2321 | return |
|
2315 | return | |
2322 |
|
2316 | |||
2323 | # XXX TODO: should this be generalized for all string vars? |
|
2317 | # XXX TODO: should this be generalized for all string vars? | |
2324 | # For now, this is special-cased to blocks created by cpaste |
|
2318 | # For now, this is special-cased to blocks created by cpaste | |
2325 | if args.strip() == 'pasted_block': |
|
2319 | if args.strip() == 'pasted_block': | |
2326 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2320 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2327 |
|
2321 | |||
2328 | if opts.has_key('x'): # -x prevents actual execution |
|
2322 | if opts.has_key('x'): # -x prevents actual execution | |
2329 |
|
2323 | |||
2330 | else: |
|
2324 | else: | |
2331 | print 'done. Executing edited code...' |
|
2325 | print 'done. Executing edited code...' | |
2332 | if opts_r: |
|
2326 | if opts_r: | |
2333 | self.shell.runlines(file_read(filename)) |
|
2327 | self.shell.runlines(file_read(filename)) | |
2334 | else: |
|
2328 | else: | |
2335 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2329 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2336 | self.shell.user_ns) |
|
2330 | self.shell.user_ns) | |
2337 |
|
2331 | |||
2338 |
|
2332 | |||
2339 | if use_temp: |
|
2333 | if use_temp: | |
2340 | try: |
|
2334 | try: | |
2341 | return open(filename).read() |
|
2335 | return open(filename).read() | |
2342 | except IOError,msg: |
|
2336 | except IOError,msg: | |
2343 | if msg.filename == filename: |
|
2337 | if msg.filename == filename: | |
2344 | warn('File not found. Did you forget to save?') |
|
2338 | warn('File not found. Did you forget to save?') | |
2345 | return |
|
2339 | return | |
2346 | else: |
|
2340 | else: | |
2347 | self.shell.showtraceback() |
|
2341 | self.shell.showtraceback() | |
2348 |
|
2342 | |||
2349 | def magic_xmode(self,parameter_s = ''): |
|
2343 | def magic_xmode(self,parameter_s = ''): | |
2350 | """Switch modes for the exception handlers. |
|
2344 | """Switch modes for the exception handlers. | |
2351 |
|
2345 | |||
2352 | Valid modes: Plain, Context and Verbose. |
|
2346 | Valid modes: Plain, Context and Verbose. | |
2353 |
|
2347 | |||
2354 | If called without arguments, acts as a toggle.""" |
|
2348 | If called without arguments, acts as a toggle.""" | |
2355 |
|
2349 | |||
2356 | def xmode_switch_err(name): |
|
2350 | def xmode_switch_err(name): | |
2357 | warn('Error changing %s exception modes.\n%s' % |
|
2351 | warn('Error changing %s exception modes.\n%s' % | |
2358 | (name,sys.exc_info()[1])) |
|
2352 | (name,sys.exc_info()[1])) | |
2359 |
|
2353 | |||
2360 | shell = self.shell |
|
2354 | shell = self.shell | |
2361 | new_mode = parameter_s.strip().capitalize() |
|
2355 | new_mode = parameter_s.strip().capitalize() | |
2362 | try: |
|
2356 | try: | |
2363 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2357 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2364 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2358 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2365 | except: |
|
2359 | except: | |
2366 | xmode_switch_err('user') |
|
2360 | xmode_switch_err('user') | |
2367 |
|
2361 | |||
2368 | def magic_colors(self,parameter_s = ''): |
|
2362 | def magic_colors(self,parameter_s = ''): | |
2369 | """Switch color scheme for prompts, info system and exception handlers. |
|
2363 | """Switch color scheme for prompts, info system and exception handlers. | |
2370 |
|
2364 | |||
2371 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2365 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2372 |
|
2366 | |||
2373 | Color scheme names are not case-sensitive.""" |
|
2367 | Color scheme names are not case-sensitive.""" | |
2374 |
|
2368 | |||
2375 | def color_switch_err(name): |
|
2369 | def color_switch_err(name): | |
2376 | warn('Error changing %s color schemes.\n%s' % |
|
2370 | warn('Error changing %s color schemes.\n%s' % | |
2377 | (name,sys.exc_info()[1])) |
|
2371 | (name,sys.exc_info()[1])) | |
2378 |
|
2372 | |||
2379 |
|
2373 | |||
2380 | new_scheme = parameter_s.strip() |
|
2374 | new_scheme = parameter_s.strip() | |
2381 | if not new_scheme: |
|
2375 | if not new_scheme: | |
2382 | raise UsageError( |
|
2376 | raise UsageError( | |
2383 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2377 | "%colors: you must specify a color scheme. See '%colors?'") | |
2384 | return |
|
2378 | return | |
2385 | # local shortcut |
|
2379 | # local shortcut | |
2386 | shell = self.shell |
|
2380 | shell = self.shell | |
2387 |
|
2381 | |||
2388 | import IPython.utils.rlineimpl as readline |
|
2382 | import IPython.utils.rlineimpl as readline | |
2389 |
|
2383 | |||
2390 | if not readline.have_readline and sys.platform == "win32": |
|
2384 | if not readline.have_readline and sys.platform == "win32": | |
2391 | msg = """\ |
|
2385 | msg = """\ | |
2392 | Proper color support under MS Windows requires the pyreadline library. |
|
2386 | Proper color support under MS Windows requires the pyreadline library. | |
2393 | You can find it at: |
|
2387 | You can find it at: | |
2394 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2388 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2395 | Gary's readline needs the ctypes module, from: |
|
2389 | Gary's readline needs the ctypes module, from: | |
2396 | http://starship.python.net/crew/theller/ctypes |
|
2390 | http://starship.python.net/crew/theller/ctypes | |
2397 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2391 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2398 |
|
2392 | |||
2399 | Defaulting color scheme to 'NoColor'""" |
|
2393 | Defaulting color scheme to 'NoColor'""" | |
2400 | new_scheme = 'NoColor' |
|
2394 | new_scheme = 'NoColor' | |
2401 | warn(msg) |
|
2395 | warn(msg) | |
2402 |
|
2396 | |||
2403 | # readline option is 0 |
|
2397 | # readline option is 0 | |
2404 | if not shell.has_readline: |
|
2398 | if not shell.has_readline: | |
2405 | new_scheme = 'NoColor' |
|
2399 | new_scheme = 'NoColor' | |
2406 |
|
2400 | |||
2407 | # Set prompt colors |
|
2401 | # Set prompt colors | |
2408 | try: |
|
2402 | try: | |
2409 | shell.displayhook.set_colors(new_scheme) |
|
2403 | shell.displayhook.set_colors(new_scheme) | |
2410 | except: |
|
2404 | except: | |
2411 | color_switch_err('prompt') |
|
2405 | color_switch_err('prompt') | |
2412 | else: |
|
2406 | else: | |
2413 | shell.colors = \ |
|
2407 | shell.colors = \ | |
2414 | shell.displayhook.color_table.active_scheme_name |
|
2408 | shell.displayhook.color_table.active_scheme_name | |
2415 | # Set exception colors |
|
2409 | # Set exception colors | |
2416 | try: |
|
2410 | try: | |
2417 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2411 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2418 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2412 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2419 | except: |
|
2413 | except: | |
2420 | color_switch_err('exception') |
|
2414 | color_switch_err('exception') | |
2421 |
|
2415 | |||
2422 | # Set info (for 'object?') colors |
|
2416 | # Set info (for 'object?') colors | |
2423 | if shell.color_info: |
|
2417 | if shell.color_info: | |
2424 | try: |
|
2418 | try: | |
2425 | shell.inspector.set_active_scheme(new_scheme) |
|
2419 | shell.inspector.set_active_scheme(new_scheme) | |
2426 | except: |
|
2420 | except: | |
2427 | color_switch_err('object inspector') |
|
2421 | color_switch_err('object inspector') | |
2428 | else: |
|
2422 | else: | |
2429 | shell.inspector.set_active_scheme('NoColor') |
|
2423 | shell.inspector.set_active_scheme('NoColor') | |
2430 |
|
2424 | |||
2431 | def magic_color_info(self,parameter_s = ''): |
|
|||
2432 | """Toggle color_info. |
|
|||
2433 |
|
||||
2434 | The color_info configuration parameter controls whether colors are |
|
|||
2435 | used for displaying object details (by things like %psource, %pfile or |
|
|||
2436 | the '?' system). This function toggles this value with each call. |
|
|||
2437 |
|
||||
2438 | Note that unless you have a fairly recent pager (less works better |
|
|||
2439 | than more) in your system, using colored object information displays |
|
|||
2440 | will not work properly. Test it and see.""" |
|
|||
2441 |
|
||||
2442 | self.shell.color_info = not self.shell.color_info |
|
|||
2443 | self.magic_colors(self.shell.colors) |
|
|||
2444 | print 'Object introspection functions have now coloring:', |
|
|||
2445 | print ['OFF','ON'][int(self.shell.color_info)] |
|
|||
2446 |
|
||||
2447 | def magic_Pprint(self, parameter_s=''): |
|
2425 | def magic_Pprint(self, parameter_s=''): | |
2448 | """Toggle pretty printing on/off.""" |
|
2426 | """Toggle pretty printing on/off.""" | |
2449 |
|
2427 | |||
2450 | self.shell.pprint = 1 - self.shell.pprint |
|
2428 | self.shell.pprint = 1 - self.shell.pprint | |
2451 | print 'Pretty printing has been turned', \ |
|
2429 | print 'Pretty printing has been turned', \ | |
2452 | ['OFF','ON'][self.shell.pprint] |
|
2430 | ['OFF','ON'][self.shell.pprint] | |
2453 |
|
2431 | |||
2454 | def magic_Exit(self, parameter_s=''): |
|
2432 | def magic_Exit(self, parameter_s=''): | |
2455 | """Exit IPython.""" |
|
2433 | """Exit IPython.""" | |
2456 |
|
2434 | |||
2457 | self.shell.ask_exit() |
|
2435 | self.shell.ask_exit() | |
2458 |
|
2436 | |||
2459 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
2437 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. | |
2460 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
2438 | magic_exit = magic_quit = magic_Quit = magic_Exit | |
2461 |
|
2439 | |||
2462 | #...................................................................... |
|
2440 | #...................................................................... | |
2463 | # Functions to implement unix shell-type things |
|
2441 | # Functions to implement unix shell-type things | |
2464 |
|
2442 | |||
2465 | @testdec.skip_doctest |
|
2443 | @testdec.skip_doctest | |
2466 | def magic_alias(self, parameter_s = ''): |
|
2444 | def magic_alias(self, parameter_s = ''): | |
2467 | """Define an alias for a system command. |
|
2445 | """Define an alias for a system command. | |
2468 |
|
2446 | |||
2469 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2447 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2470 |
|
2448 | |||
2471 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2449 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2472 | params' (from your underlying operating system). |
|
2450 | params' (from your underlying operating system). | |
2473 |
|
2451 | |||
2474 | Aliases have lower precedence than magic functions and Python normal |
|
2452 | Aliases have lower precedence than magic functions and Python normal | |
2475 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2453 | variables, so if 'foo' is both a Python variable and an alias, the | |
2476 | alias can not be executed until 'del foo' removes the Python variable. |
|
2454 | alias can not be executed until 'del foo' removes the Python variable. | |
2477 |
|
2455 | |||
2478 | You can use the %l specifier in an alias definition to represent the |
|
2456 | You can use the %l specifier in an alias definition to represent the | |
2479 | whole line when the alias is called. For example: |
|
2457 | whole line when the alias is called. For example: | |
2480 |
|
2458 | |||
2481 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2459 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2482 | In [3]: bracket hello world |
|
2460 | In [3]: bracket hello world | |
2483 | Input in brackets: <hello world> |
|
2461 | Input in brackets: <hello world> | |
2484 |
|
2462 | |||
2485 | You can also define aliases with parameters using %s specifiers (one |
|
2463 | You can also define aliases with parameters using %s specifiers (one | |
2486 | per parameter): |
|
2464 | per parameter): | |
2487 |
|
2465 | |||
2488 | In [1]: alias parts echo first %s second %s |
|
2466 | In [1]: alias parts echo first %s second %s | |
2489 | In [2]: %parts A B |
|
2467 | In [2]: %parts A B | |
2490 | first A second B |
|
2468 | first A second B | |
2491 | In [3]: %parts A |
|
2469 | In [3]: %parts A | |
2492 | Incorrect number of arguments: 2 expected. |
|
2470 | Incorrect number of arguments: 2 expected. | |
2493 | parts is an alias to: 'echo first %s second %s' |
|
2471 | parts is an alias to: 'echo first %s second %s' | |
2494 |
|
2472 | |||
2495 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2473 | Note that %l and %s are mutually exclusive. You can only use one or | |
2496 | the other in your aliases. |
|
2474 | the other in your aliases. | |
2497 |
|
2475 | |||
2498 | Aliases expand Python variables just like system calls using ! or !! |
|
2476 | Aliases expand Python variables just like system calls using ! or !! | |
2499 | do: all expressions prefixed with '$' get expanded. For details of |
|
2477 | do: all expressions prefixed with '$' get expanded. For details of | |
2500 | the semantic rules, see PEP-215: |
|
2478 | the semantic rules, see PEP-215: | |
2501 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2479 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2502 | IPython for variable expansion. If you want to access a true shell |
|
2480 | IPython for variable expansion. If you want to access a true shell | |
2503 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2481 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2504 |
|
2482 | |||
2505 | In [6]: alias show echo |
|
2483 | In [6]: alias show echo | |
2506 | In [7]: PATH='A Python string' |
|
2484 | In [7]: PATH='A Python string' | |
2507 | In [8]: show $PATH |
|
2485 | In [8]: show $PATH | |
2508 | A Python string |
|
2486 | A Python string | |
2509 | In [9]: show $$PATH |
|
2487 | In [9]: show $$PATH | |
2510 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2488 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2511 |
|
2489 | |||
2512 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2490 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2513 | and %rehashx functions, which automatically create aliases for the |
|
2491 | and %rehashx functions, which automatically create aliases for the | |
2514 | contents of your $PATH. |
|
2492 | contents of your $PATH. | |
2515 |
|
2493 | |||
2516 | If called with no parameters, %alias prints the current alias table.""" |
|
2494 | If called with no parameters, %alias prints the current alias table.""" | |
2517 |
|
2495 | |||
2518 | par = parameter_s.strip() |
|
2496 | par = parameter_s.strip() | |
2519 | if not par: |
|
2497 | if not par: | |
2520 | stored = self.db.get('stored_aliases', {} ) |
|
2498 | stored = self.db.get('stored_aliases', {} ) | |
2521 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2499 | aliases = sorted(self.shell.alias_manager.aliases) | |
2522 | # for k, v in stored: |
|
2500 | # for k, v in stored: | |
2523 | # atab.append(k, v[0]) |
|
2501 | # atab.append(k, v[0]) | |
2524 |
|
2502 | |||
2525 | print "Total number of aliases:", len(aliases) |
|
2503 | print "Total number of aliases:", len(aliases) | |
2526 | return aliases |
|
2504 | return aliases | |
2527 |
|
2505 | |||
2528 | # Now try to define a new one |
|
2506 | # Now try to define a new one | |
2529 | try: |
|
2507 | try: | |
2530 | alias,cmd = par.split(None, 1) |
|
2508 | alias,cmd = par.split(None, 1) | |
2531 | except: |
|
2509 | except: | |
2532 | print oinspect.getdoc(self.magic_alias) |
|
2510 | print oinspect.getdoc(self.magic_alias) | |
2533 | else: |
|
2511 | else: | |
2534 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2512 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2535 | # end magic_alias |
|
2513 | # end magic_alias | |
2536 |
|
2514 | |||
2537 | def magic_unalias(self, parameter_s = ''): |
|
2515 | def magic_unalias(self, parameter_s = ''): | |
2538 | """Remove an alias""" |
|
2516 | """Remove an alias""" | |
2539 |
|
2517 | |||
2540 | aname = parameter_s.strip() |
|
2518 | aname = parameter_s.strip() | |
2541 | self.shell.alias_manager.undefine_alias(aname) |
|
2519 | self.shell.alias_manager.undefine_alias(aname) | |
2542 | stored = self.db.get('stored_aliases', {} ) |
|
2520 | stored = self.db.get('stored_aliases', {} ) | |
2543 | if aname in stored: |
|
2521 | if aname in stored: | |
2544 | print "Removing %stored alias",aname |
|
2522 | print "Removing %stored alias",aname | |
2545 | del stored[aname] |
|
2523 | del stored[aname] | |
2546 | self.db['stored_aliases'] = stored |
|
2524 | self.db['stored_aliases'] = stored | |
2547 |
|
2525 | |||
2548 |
|
||||
2549 | def magic_rehashx(self, parameter_s = ''): |
|
2526 | def magic_rehashx(self, parameter_s = ''): | |
2550 | """Update the alias table with all executable files in $PATH. |
|
2527 | """Update the alias table with all executable files in $PATH. | |
2551 |
|
2528 | |||
2552 | This version explicitly checks that every entry in $PATH is a file |
|
2529 | This version explicitly checks that every entry in $PATH is a file | |
2553 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2530 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2554 |
|
2531 | |||
2555 | Under Windows, it checks executability as a match agains a |
|
2532 | Under Windows, it checks executability as a match agains a | |
2556 | '|'-separated string of extensions, stored in the IPython config |
|
2533 | '|'-separated string of extensions, stored in the IPython config | |
2557 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2534 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2558 |
|
2535 | |||
2559 | This function also resets the root module cache of module completer, |
|
2536 | This function also resets the root module cache of module completer, | |
2560 | used on slow filesystems. |
|
2537 | used on slow filesystems. | |
2561 | """ |
|
2538 | """ | |
2562 | from IPython.core.alias import InvalidAliasError |
|
2539 | from IPython.core.alias import InvalidAliasError | |
2563 |
|
2540 | |||
2564 | # for the benefit of module completer in ipy_completers.py |
|
2541 | # for the benefit of module completer in ipy_completers.py | |
2565 | del self.db['rootmodules'] |
|
2542 | del self.db['rootmodules'] | |
2566 |
|
2543 | |||
2567 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2544 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2568 | os.environ.get('PATH','').split(os.pathsep)] |
|
2545 | os.environ.get('PATH','').split(os.pathsep)] | |
2569 | path = filter(os.path.isdir,path) |
|
2546 | path = filter(os.path.isdir,path) | |
2570 |
|
2547 | |||
2571 | syscmdlist = [] |
|
2548 | syscmdlist = [] | |
2572 | # Now define isexec in a cross platform manner. |
|
2549 | # Now define isexec in a cross platform manner. | |
2573 | if os.name == 'posix': |
|
2550 | if os.name == 'posix': | |
2574 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2551 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2575 | os.access(fname,os.X_OK) |
|
2552 | os.access(fname,os.X_OK) | |
2576 | else: |
|
2553 | else: | |
2577 | try: |
|
2554 | try: | |
2578 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2555 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2579 | except KeyError: |
|
2556 | except KeyError: | |
2580 | winext = 'exe|com|bat|py' |
|
2557 | winext = 'exe|com|bat|py' | |
2581 | if 'py' not in winext: |
|
2558 | if 'py' not in winext: | |
2582 | winext += '|py' |
|
2559 | winext += '|py' | |
2583 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2560 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2584 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2561 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2585 | savedir = os.getcwd() |
|
2562 | savedir = os.getcwd() | |
2586 |
|
2563 | |||
2587 | # Now walk the paths looking for executables to alias. |
|
2564 | # Now walk the paths looking for executables to alias. | |
2588 | try: |
|
2565 | try: | |
2589 | # write the whole loop for posix/Windows so we don't have an if in |
|
2566 | # write the whole loop for posix/Windows so we don't have an if in | |
2590 | # the innermost part |
|
2567 | # the innermost part | |
2591 | if os.name == 'posix': |
|
2568 | if os.name == 'posix': | |
2592 | for pdir in path: |
|
2569 | for pdir in path: | |
2593 | os.chdir(pdir) |
|
2570 | os.chdir(pdir) | |
2594 | for ff in os.listdir(pdir): |
|
2571 | for ff in os.listdir(pdir): | |
2595 | if isexec(ff): |
|
2572 | if isexec(ff): | |
2596 | try: |
|
2573 | try: | |
2597 | # Removes dots from the name since ipython |
|
2574 | # Removes dots from the name since ipython | |
2598 | # will assume names with dots to be python. |
|
2575 | # will assume names with dots to be python. | |
2599 | self.shell.alias_manager.define_alias( |
|
2576 | self.shell.alias_manager.define_alias( | |
2600 | ff.replace('.',''), ff) |
|
2577 | ff.replace('.',''), ff) | |
2601 | except InvalidAliasError: |
|
2578 | except InvalidAliasError: | |
2602 | pass |
|
2579 | pass | |
2603 | else: |
|
2580 | else: | |
2604 | syscmdlist.append(ff) |
|
2581 | syscmdlist.append(ff) | |
2605 | else: |
|
2582 | else: | |
2606 | no_alias = self.shell.alias_manager.no_alias |
|
2583 | no_alias = self.shell.alias_manager.no_alias | |
2607 | for pdir in path: |
|
2584 | for pdir in path: | |
2608 | os.chdir(pdir) |
|
2585 | os.chdir(pdir) | |
2609 | for ff in os.listdir(pdir): |
|
2586 | for ff in os.listdir(pdir): | |
2610 | base, ext = os.path.splitext(ff) |
|
2587 | base, ext = os.path.splitext(ff) | |
2611 | if isexec(ff) and base.lower() not in no_alias: |
|
2588 | if isexec(ff) and base.lower() not in no_alias: | |
2612 | if ext.lower() == '.exe': |
|
2589 | if ext.lower() == '.exe': | |
2613 | ff = base |
|
2590 | ff = base | |
2614 | try: |
|
2591 | try: | |
2615 | # Removes dots from the name since ipython |
|
2592 | # Removes dots from the name since ipython | |
2616 | # will assume names with dots to be python. |
|
2593 | # will assume names with dots to be python. | |
2617 | self.shell.alias_manager.define_alias( |
|
2594 | self.shell.alias_manager.define_alias( | |
2618 | base.lower().replace('.',''), ff) |
|
2595 | base.lower().replace('.',''), ff) | |
2619 | except InvalidAliasError: |
|
2596 | except InvalidAliasError: | |
2620 | pass |
|
2597 | pass | |
2621 | syscmdlist.append(ff) |
|
2598 | syscmdlist.append(ff) | |
2622 | db = self.db |
|
2599 | db = self.db | |
2623 | db['syscmdlist'] = syscmdlist |
|
2600 | db['syscmdlist'] = syscmdlist | |
2624 | finally: |
|
2601 | finally: | |
2625 | os.chdir(savedir) |
|
2602 | os.chdir(savedir) | |
2626 |
|
2603 | |||
2627 | def magic_pwd(self, parameter_s = ''): |
|
2604 | def magic_pwd(self, parameter_s = ''): | |
2628 | """Return the current working directory path.""" |
|
2605 | """Return the current working directory path.""" | |
2629 | return os.getcwd() |
|
2606 | return os.getcwd() | |
2630 |
|
2607 | |||
2631 | def magic_cd(self, parameter_s=''): |
|
2608 | def magic_cd(self, parameter_s=''): | |
2632 | """Change the current working directory. |
|
2609 | """Change the current working directory. | |
2633 |
|
2610 | |||
2634 | This command automatically maintains an internal list of directories |
|
2611 | This command automatically maintains an internal list of directories | |
2635 | you visit during your IPython session, in the variable _dh. The |
|
2612 | you visit during your IPython session, in the variable _dh. The | |
2636 | command %dhist shows this history nicely formatted. You can also |
|
2613 | command %dhist shows this history nicely formatted. You can also | |
2637 | do 'cd -<tab>' to see directory history conveniently. |
|
2614 | do 'cd -<tab>' to see directory history conveniently. | |
2638 |
|
2615 | |||
2639 | Usage: |
|
2616 | Usage: | |
2640 |
|
2617 | |||
2641 | cd 'dir': changes to directory 'dir'. |
|
2618 | cd 'dir': changes to directory 'dir'. | |
2642 |
|
2619 | |||
2643 | cd -: changes to the last visited directory. |
|
2620 | cd -: changes to the last visited directory. | |
2644 |
|
2621 | |||
2645 | cd -<n>: changes to the n-th directory in the directory history. |
|
2622 | cd -<n>: changes to the n-th directory in the directory history. | |
2646 |
|
2623 | |||
2647 | cd --foo: change to directory that matches 'foo' in history |
|
2624 | cd --foo: change to directory that matches 'foo' in history | |
2648 |
|
2625 | |||
2649 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2626 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2650 | (note: cd <bookmark_name> is enough if there is no |
|
2627 | (note: cd <bookmark_name> is enough if there is no | |
2651 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2628 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2652 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2629 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2653 |
|
2630 | |||
2654 | Options: |
|
2631 | Options: | |
2655 |
|
2632 | |||
2656 | -q: quiet. Do not print the working directory after the cd command is |
|
2633 | -q: quiet. Do not print the working directory after the cd command is | |
2657 | executed. By default IPython's cd command does print this directory, |
|
2634 | executed. By default IPython's cd command does print this directory, | |
2658 | since the default prompts do not display path information. |
|
2635 | since the default prompts do not display path information. | |
2659 |
|
2636 | |||
2660 | Note that !cd doesn't work for this purpose because the shell where |
|
2637 | Note that !cd doesn't work for this purpose because the shell where | |
2661 | !command runs is immediately discarded after executing 'command'.""" |
|
2638 | !command runs is immediately discarded after executing 'command'.""" | |
2662 |
|
2639 | |||
2663 | parameter_s = parameter_s.strip() |
|
2640 | parameter_s = parameter_s.strip() | |
2664 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2641 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2665 |
|
2642 | |||
2666 | oldcwd = os.getcwd() |
|
2643 | oldcwd = os.getcwd() | |
2667 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2644 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2668 | # jump in directory history by number |
|
2645 | # jump in directory history by number | |
2669 | if numcd: |
|
2646 | if numcd: | |
2670 | nn = int(numcd.group(2)) |
|
2647 | nn = int(numcd.group(2)) | |
2671 | try: |
|
2648 | try: | |
2672 | ps = self.shell.user_ns['_dh'][nn] |
|
2649 | ps = self.shell.user_ns['_dh'][nn] | |
2673 | except IndexError: |
|
2650 | except IndexError: | |
2674 | print 'The requested directory does not exist in history.' |
|
2651 | print 'The requested directory does not exist in history.' | |
2675 | return |
|
2652 | return | |
2676 | else: |
|
2653 | else: | |
2677 | opts = {} |
|
2654 | opts = {} | |
2678 | elif parameter_s.startswith('--'): |
|
2655 | elif parameter_s.startswith('--'): | |
2679 | ps = None |
|
2656 | ps = None | |
2680 | fallback = None |
|
2657 | fallback = None | |
2681 | pat = parameter_s[2:] |
|
2658 | pat = parameter_s[2:] | |
2682 | dh = self.shell.user_ns['_dh'] |
|
2659 | dh = self.shell.user_ns['_dh'] | |
2683 | # first search only by basename (last component) |
|
2660 | # first search only by basename (last component) | |
2684 | for ent in reversed(dh): |
|
2661 | for ent in reversed(dh): | |
2685 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2662 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2686 | ps = ent |
|
2663 | ps = ent | |
2687 | break |
|
2664 | break | |
2688 |
|
2665 | |||
2689 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2666 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2690 | fallback = ent |
|
2667 | fallback = ent | |
2691 |
|
2668 | |||
2692 | # if we have no last part match, pick the first full path match |
|
2669 | # if we have no last part match, pick the first full path match | |
2693 | if ps is None: |
|
2670 | if ps is None: | |
2694 | ps = fallback |
|
2671 | ps = fallback | |
2695 |
|
2672 | |||
2696 | if ps is None: |
|
2673 | if ps is None: | |
2697 | print "No matching entry in directory history" |
|
2674 | print "No matching entry in directory history" | |
2698 | return |
|
2675 | return | |
2699 | else: |
|
2676 | else: | |
2700 | opts = {} |
|
2677 | opts = {} | |
2701 |
|
2678 | |||
2702 |
|
2679 | |||
2703 | else: |
|
2680 | else: | |
2704 | #turn all non-space-escaping backslashes to slashes, |
|
2681 | #turn all non-space-escaping backslashes to slashes, | |
2705 | # for c:\windows\directory\names\ |
|
2682 | # for c:\windows\directory\names\ | |
2706 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2683 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2707 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2684 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2708 | # jump to previous |
|
2685 | # jump to previous | |
2709 | if ps == '-': |
|
2686 | if ps == '-': | |
2710 | try: |
|
2687 | try: | |
2711 | ps = self.shell.user_ns['_dh'][-2] |
|
2688 | ps = self.shell.user_ns['_dh'][-2] | |
2712 | except IndexError: |
|
2689 | except IndexError: | |
2713 | raise UsageError('%cd -: No previous directory to change to.') |
|
2690 | raise UsageError('%cd -: No previous directory to change to.') | |
2714 | # jump to bookmark if needed |
|
2691 | # jump to bookmark if needed | |
2715 | else: |
|
2692 | else: | |
2716 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2693 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2717 | bkms = self.db.get('bookmarks', {}) |
|
2694 | bkms = self.db.get('bookmarks', {}) | |
2718 |
|
2695 | |||
2719 | if bkms.has_key(ps): |
|
2696 | if bkms.has_key(ps): | |
2720 | target = bkms[ps] |
|
2697 | target = bkms[ps] | |
2721 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2698 | print '(bookmark:%s) -> %s' % (ps,target) | |
2722 | ps = target |
|
2699 | ps = target | |
2723 | else: |
|
2700 | else: | |
2724 | if opts.has_key('b'): |
|
2701 | if opts.has_key('b'): | |
2725 | raise UsageError("Bookmark '%s' not found. " |
|
2702 | raise UsageError("Bookmark '%s' not found. " | |
2726 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2703 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2727 |
|
2704 | |||
2728 | # at this point ps should point to the target dir |
|
2705 | # at this point ps should point to the target dir | |
2729 | if ps: |
|
2706 | if ps: | |
2730 | try: |
|
2707 | try: | |
2731 | os.chdir(os.path.expanduser(ps)) |
|
2708 | os.chdir(os.path.expanduser(ps)) | |
2732 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2709 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2733 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2710 | set_term_title('IPython: ' + abbrev_cwd()) | |
2734 | except OSError: |
|
2711 | except OSError: | |
2735 | print sys.exc_info()[1] |
|
2712 | print sys.exc_info()[1] | |
2736 | else: |
|
2713 | else: | |
2737 | cwd = os.getcwd() |
|
2714 | cwd = os.getcwd() | |
2738 | dhist = self.shell.user_ns['_dh'] |
|
2715 | dhist = self.shell.user_ns['_dh'] | |
2739 | if oldcwd != cwd: |
|
2716 | if oldcwd != cwd: | |
2740 | dhist.append(cwd) |
|
2717 | dhist.append(cwd) | |
2741 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2718 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2742 |
|
2719 | |||
2743 | else: |
|
2720 | else: | |
2744 | os.chdir(self.shell.home_dir) |
|
2721 | os.chdir(self.shell.home_dir) | |
2745 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2722 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2746 | set_term_title('IPython: ' + '~') |
|
2723 | set_term_title('IPython: ' + '~') | |
2747 | cwd = os.getcwd() |
|
2724 | cwd = os.getcwd() | |
2748 | dhist = self.shell.user_ns['_dh'] |
|
2725 | dhist = self.shell.user_ns['_dh'] | |
2749 |
|
2726 | |||
2750 | if oldcwd != cwd: |
|
2727 | if oldcwd != cwd: | |
2751 | dhist.append(cwd) |
|
2728 | dhist.append(cwd) | |
2752 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2729 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2753 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2730 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2754 | print self.shell.user_ns['_dh'][-1] |
|
2731 | print self.shell.user_ns['_dh'][-1] | |
2755 |
|
2732 | |||
2756 |
|
2733 | |||
2757 | def magic_env(self, parameter_s=''): |
|
2734 | def magic_env(self, parameter_s=''): | |
2758 | """List environment variables.""" |
|
2735 | """List environment variables.""" | |
2759 |
|
2736 | |||
2760 | return os.environ.data |
|
2737 | return os.environ.data | |
2761 |
|
2738 | |||
2762 | def magic_pushd(self, parameter_s=''): |
|
2739 | def magic_pushd(self, parameter_s=''): | |
2763 | """Place the current dir on stack and change directory. |
|
2740 | """Place the current dir on stack and change directory. | |
2764 |
|
2741 | |||
2765 | Usage:\\ |
|
2742 | Usage:\\ | |
2766 | %pushd ['dirname'] |
|
2743 | %pushd ['dirname'] | |
2767 | """ |
|
2744 | """ | |
2768 |
|
2745 | |||
2769 | dir_s = self.shell.dir_stack |
|
2746 | dir_s = self.shell.dir_stack | |
2770 | tgt = os.path.expanduser(parameter_s) |
|
2747 | tgt = os.path.expanduser(parameter_s) | |
2771 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2748 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2772 | if tgt: |
|
2749 | if tgt: | |
2773 | self.magic_cd(parameter_s) |
|
2750 | self.magic_cd(parameter_s) | |
2774 | dir_s.insert(0,cwd) |
|
2751 | dir_s.insert(0,cwd) | |
2775 | return self.magic_dirs() |
|
2752 | return self.magic_dirs() | |
2776 |
|
2753 | |||
2777 | def magic_popd(self, parameter_s=''): |
|
2754 | def magic_popd(self, parameter_s=''): | |
2778 | """Change to directory popped off the top of the stack. |
|
2755 | """Change to directory popped off the top of the stack. | |
2779 | """ |
|
2756 | """ | |
2780 | if not self.shell.dir_stack: |
|
2757 | if not self.shell.dir_stack: | |
2781 | raise UsageError("%popd on empty stack") |
|
2758 | raise UsageError("%popd on empty stack") | |
2782 | top = self.shell.dir_stack.pop(0) |
|
2759 | top = self.shell.dir_stack.pop(0) | |
2783 | self.magic_cd(top) |
|
2760 | self.magic_cd(top) | |
2784 | print "popd ->",top |
|
2761 | print "popd ->",top | |
2785 |
|
2762 | |||
2786 | def magic_dirs(self, parameter_s=''): |
|
2763 | def magic_dirs(self, parameter_s=''): | |
2787 | """Return the current directory stack.""" |
|
2764 | """Return the current directory stack.""" | |
2788 |
|
2765 | |||
2789 | return self.shell.dir_stack |
|
2766 | return self.shell.dir_stack | |
2790 |
|
2767 | |||
2791 | def magic_dhist(self, parameter_s=''): |
|
2768 | def magic_dhist(self, parameter_s=''): | |
2792 | """Print your history of visited directories. |
|
2769 | """Print your history of visited directories. | |
2793 |
|
2770 | |||
2794 | %dhist -> print full history\\ |
|
2771 | %dhist -> print full history\\ | |
2795 | %dhist n -> print last n entries only\\ |
|
2772 | %dhist n -> print last n entries only\\ | |
2796 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2773 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2797 |
|
2774 | |||
2798 | This history is automatically maintained by the %cd command, and |
|
2775 | This history is automatically maintained by the %cd command, and | |
2799 | always available as the global list variable _dh. You can use %cd -<n> |
|
2776 | always available as the global list variable _dh. You can use %cd -<n> | |
2800 | to go to directory number <n>. |
|
2777 | to go to directory number <n>. | |
2801 |
|
2778 | |||
2802 | Note that most of time, you should view directory history by entering |
|
2779 | Note that most of time, you should view directory history by entering | |
2803 | cd -<TAB>. |
|
2780 | cd -<TAB>. | |
2804 |
|
2781 | |||
2805 | """ |
|
2782 | """ | |
2806 |
|
2783 | |||
2807 | dh = self.shell.user_ns['_dh'] |
|
2784 | dh = self.shell.user_ns['_dh'] | |
2808 | if parameter_s: |
|
2785 | if parameter_s: | |
2809 | try: |
|
2786 | try: | |
2810 | args = map(int,parameter_s.split()) |
|
2787 | args = map(int,parameter_s.split()) | |
2811 | except: |
|
2788 | except: | |
2812 | self.arg_err(Magic.magic_dhist) |
|
2789 | self.arg_err(Magic.magic_dhist) | |
2813 | return |
|
2790 | return | |
2814 | if len(args) == 1: |
|
2791 | if len(args) == 1: | |
2815 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2792 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2816 | elif len(args) == 2: |
|
2793 | elif len(args) == 2: | |
2817 | ini,fin = args |
|
2794 | ini,fin = args | |
2818 | else: |
|
2795 | else: | |
2819 | self.arg_err(Magic.magic_dhist) |
|
2796 | self.arg_err(Magic.magic_dhist) | |
2820 | return |
|
2797 | return | |
2821 | else: |
|
2798 | else: | |
2822 | ini,fin = 0,len(dh) |
|
2799 | ini,fin = 0,len(dh) | |
2823 | nlprint(dh, |
|
2800 | nlprint(dh, | |
2824 | header = 'Directory history (kept in _dh)', |
|
2801 | header = 'Directory history (kept in _dh)', | |
2825 | start=ini,stop=fin) |
|
2802 | start=ini,stop=fin) | |
2826 |
|
2803 | |||
2827 | @testdec.skip_doctest |
|
2804 | @testdec.skip_doctest | |
2828 | def magic_sc(self, parameter_s=''): |
|
2805 | def magic_sc(self, parameter_s=''): | |
2829 | """Shell capture - execute a shell command and capture its output. |
|
2806 | """Shell capture - execute a shell command and capture its output. | |
2830 |
|
2807 | |||
2831 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2808 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2832 |
|
2809 | |||
2833 | You should use the form 'var = !command' instead. Example: |
|
2810 | You should use the form 'var = !command' instead. Example: | |
2834 |
|
2811 | |||
2835 | "%sc -l myfiles = ls ~" should now be written as |
|
2812 | "%sc -l myfiles = ls ~" should now be written as | |
2836 |
|
2813 | |||
2837 | "myfiles = !ls ~" |
|
2814 | "myfiles = !ls ~" | |
2838 |
|
2815 | |||
2839 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2816 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2840 | below. |
|
2817 | below. | |
2841 |
|
2818 | |||
2842 | -- |
|
2819 | -- | |
2843 | %sc [options] varname=command |
|
2820 | %sc [options] varname=command | |
2844 |
|
2821 | |||
2845 | IPython will run the given command using commands.getoutput(), and |
|
2822 | IPython will run the given command using commands.getoutput(), and | |
2846 | will then update the user's interactive namespace with a variable |
|
2823 | will then update the user's interactive namespace with a variable | |
2847 | called varname, containing the value of the call. Your command can |
|
2824 | called varname, containing the value of the call. Your command can | |
2848 | contain shell wildcards, pipes, etc. |
|
2825 | contain shell wildcards, pipes, etc. | |
2849 |
|
2826 | |||
2850 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2827 | The '=' sign in the syntax is mandatory, and the variable name you | |
2851 | supply must follow Python's standard conventions for valid names. |
|
2828 | supply must follow Python's standard conventions for valid names. | |
2852 |
|
2829 | |||
2853 | (A special format without variable name exists for internal use) |
|
2830 | (A special format without variable name exists for internal use) | |
2854 |
|
2831 | |||
2855 | Options: |
|
2832 | Options: | |
2856 |
|
2833 | |||
2857 | -l: list output. Split the output on newlines into a list before |
|
2834 | -l: list output. Split the output on newlines into a list before | |
2858 | assigning it to the given variable. By default the output is stored |
|
2835 | assigning it to the given variable. By default the output is stored | |
2859 | as a single string. |
|
2836 | as a single string. | |
2860 |
|
2837 | |||
2861 | -v: verbose. Print the contents of the variable. |
|
2838 | -v: verbose. Print the contents of the variable. | |
2862 |
|
2839 | |||
2863 | In most cases you should not need to split as a list, because the |
|
2840 | In most cases you should not need to split as a list, because the | |
2864 | returned value is a special type of string which can automatically |
|
2841 | returned value is a special type of string which can automatically | |
2865 | provide its contents either as a list (split on newlines) or as a |
|
2842 | provide its contents either as a list (split on newlines) or as a | |
2866 | space-separated string. These are convenient, respectively, either |
|
2843 | space-separated string. These are convenient, respectively, either | |
2867 | for sequential processing or to be passed to a shell command. |
|
2844 | for sequential processing or to be passed to a shell command. | |
2868 |
|
2845 | |||
2869 | For example: |
|
2846 | For example: | |
2870 |
|
2847 | |||
2871 | # all-random |
|
2848 | # all-random | |
2872 |
|
2849 | |||
2873 | # Capture into variable a |
|
2850 | # Capture into variable a | |
2874 | In [1]: sc a=ls *py |
|
2851 | In [1]: sc a=ls *py | |
2875 |
|
2852 | |||
2876 | # a is a string with embedded newlines |
|
2853 | # a is a string with embedded newlines | |
2877 | In [2]: a |
|
2854 | In [2]: a | |
2878 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2855 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2879 |
|
2856 | |||
2880 | # which can be seen as a list: |
|
2857 | # which can be seen as a list: | |
2881 | In [3]: a.l |
|
2858 | In [3]: a.l | |
2882 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2859 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2883 |
|
2860 | |||
2884 | # or as a whitespace-separated string: |
|
2861 | # or as a whitespace-separated string: | |
2885 | In [4]: a.s |
|
2862 | In [4]: a.s | |
2886 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2863 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2887 |
|
2864 | |||
2888 | # a.s is useful to pass as a single command line: |
|
2865 | # a.s is useful to pass as a single command line: | |
2889 | In [5]: !wc -l $a.s |
|
2866 | In [5]: !wc -l $a.s | |
2890 | 146 setup.py |
|
2867 | 146 setup.py | |
2891 | 130 win32_manual_post_install.py |
|
2868 | 130 win32_manual_post_install.py | |
2892 | 276 total |
|
2869 | 276 total | |
2893 |
|
2870 | |||
2894 | # while the list form is useful to loop over: |
|
2871 | # while the list form is useful to loop over: | |
2895 | In [6]: for f in a.l: |
|
2872 | In [6]: for f in a.l: | |
2896 | ...: !wc -l $f |
|
2873 | ...: !wc -l $f | |
2897 | ...: |
|
2874 | ...: | |
2898 | 146 setup.py |
|
2875 | 146 setup.py | |
2899 | 130 win32_manual_post_install.py |
|
2876 | 130 win32_manual_post_install.py | |
2900 |
|
2877 | |||
2901 | Similiarly, the lists returned by the -l option are also special, in |
|
2878 | Similiarly, the lists returned by the -l option are also special, in | |
2902 | the sense that you can equally invoke the .s attribute on them to |
|
2879 | the sense that you can equally invoke the .s attribute on them to | |
2903 | automatically get a whitespace-separated string from their contents: |
|
2880 | automatically get a whitespace-separated string from their contents: | |
2904 |
|
2881 | |||
2905 | In [7]: sc -l b=ls *py |
|
2882 | In [7]: sc -l b=ls *py | |
2906 |
|
2883 | |||
2907 | In [8]: b |
|
2884 | In [8]: b | |
2908 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2885 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2909 |
|
2886 | |||
2910 | In [9]: b.s |
|
2887 | In [9]: b.s | |
2911 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2888 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2912 |
|
2889 | |||
2913 | In summary, both the lists and strings used for ouptut capture have |
|
2890 | In summary, both the lists and strings used for ouptut capture have | |
2914 | the following special attributes: |
|
2891 | the following special attributes: | |
2915 |
|
2892 | |||
2916 | .l (or .list) : value as list. |
|
2893 | .l (or .list) : value as list. | |
2917 | .n (or .nlstr): value as newline-separated string. |
|
2894 | .n (or .nlstr): value as newline-separated string. | |
2918 | .s (or .spstr): value as space-separated string. |
|
2895 | .s (or .spstr): value as space-separated string. | |
2919 | """ |
|
2896 | """ | |
2920 |
|
2897 | |||
2921 | opts,args = self.parse_options(parameter_s,'lv') |
|
2898 | opts,args = self.parse_options(parameter_s,'lv') | |
2922 | # Try to get a variable name and command to run |
|
2899 | # Try to get a variable name and command to run | |
2923 | try: |
|
2900 | try: | |
2924 | # the variable name must be obtained from the parse_options |
|
2901 | # the variable name must be obtained from the parse_options | |
2925 | # output, which uses shlex.split to strip options out. |
|
2902 | # output, which uses shlex.split to strip options out. | |
2926 | var,_ = args.split('=',1) |
|
2903 | var,_ = args.split('=',1) | |
2927 | var = var.strip() |
|
2904 | var = var.strip() | |
2928 | # But the the command has to be extracted from the original input |
|
2905 | # But the the command has to be extracted from the original input | |
2929 | # parameter_s, not on what parse_options returns, to avoid the |
|
2906 | # parameter_s, not on what parse_options returns, to avoid the | |
2930 | # quote stripping which shlex.split performs on it. |
|
2907 | # quote stripping which shlex.split performs on it. | |
2931 | _,cmd = parameter_s.split('=',1) |
|
2908 | _,cmd = parameter_s.split('=',1) | |
2932 | except ValueError: |
|
2909 | except ValueError: | |
2933 | var,cmd = '','' |
|
2910 | var,cmd = '','' | |
2934 | # If all looks ok, proceed |
|
2911 | # If all looks ok, proceed | |
2935 | out = self.shell.getoutput(cmd) |
|
2912 | out = self.shell.getoutput(cmd) | |
2936 | if opts.has_key('l'): |
|
2913 | if opts.has_key('l'): | |
2937 | out = SList(out.split('\n')) |
|
2914 | out = SList(out.split('\n')) | |
2938 | else: |
|
2915 | else: | |
2939 | out = LSString(out) |
|
2916 | out = LSString(out) | |
2940 | if opts.has_key('v'): |
|
2917 | if opts.has_key('v'): | |
2941 | print '%s ==\n%s' % (var,pformat(out)) |
|
2918 | print '%s ==\n%s' % (var,pformat(out)) | |
2942 | if var: |
|
2919 | if var: | |
2943 | self.shell.user_ns.update({var:out}) |
|
2920 | self.shell.user_ns.update({var:out}) | |
2944 | else: |
|
2921 | else: | |
2945 | return out |
|
2922 | return out | |
2946 |
|
2923 | |||
2947 | def magic_sx(self, parameter_s=''): |
|
2924 | def magic_sx(self, parameter_s=''): | |
2948 | """Shell execute - run a shell command and capture its output. |
|
2925 | """Shell execute - run a shell command and capture its output. | |
2949 |
|
2926 | |||
2950 | %sx command |
|
2927 | %sx command | |
2951 |
|
2928 | |||
2952 | IPython will run the given command using commands.getoutput(), and |
|
2929 | IPython will run the given command using commands.getoutput(), and | |
2953 | return the result formatted as a list (split on '\\n'). Since the |
|
2930 | return the result formatted as a list (split on '\\n'). Since the | |
2954 | output is _returned_, it will be stored in ipython's regular output |
|
2931 | output is _returned_, it will be stored in ipython's regular output | |
2955 | cache Out[N] and in the '_N' automatic variables. |
|
2932 | cache Out[N] and in the '_N' automatic variables. | |
2956 |
|
2933 | |||
2957 | Notes: |
|
2934 | Notes: | |
2958 |
|
2935 | |||
2959 | 1) If an input line begins with '!!', then %sx is automatically |
|
2936 | 1) If an input line begins with '!!', then %sx is automatically | |
2960 | invoked. That is, while: |
|
2937 | invoked. That is, while: | |
2961 | !ls |
|
2938 | !ls | |
2962 | causes ipython to simply issue system('ls'), typing |
|
2939 | causes ipython to simply issue system('ls'), typing | |
2963 | !!ls |
|
2940 | !!ls | |
2964 | is a shorthand equivalent to: |
|
2941 | is a shorthand equivalent to: | |
2965 | %sx ls |
|
2942 | %sx ls | |
2966 |
|
2943 | |||
2967 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2944 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2968 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2945 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2969 | to process line-oriented shell output via further python commands. |
|
2946 | to process line-oriented shell output via further python commands. | |
2970 | %sc is meant to provide much finer control, but requires more |
|
2947 | %sc is meant to provide much finer control, but requires more | |
2971 | typing. |
|
2948 | typing. | |
2972 |
|
2949 | |||
2973 | 3) Just like %sc -l, this is a list with special attributes: |
|
2950 | 3) Just like %sc -l, this is a list with special attributes: | |
2974 |
|
2951 | |||
2975 | .l (or .list) : value as list. |
|
2952 | .l (or .list) : value as list. | |
2976 | .n (or .nlstr): value as newline-separated string. |
|
2953 | .n (or .nlstr): value as newline-separated string. | |
2977 | .s (or .spstr): value as whitespace-separated string. |
|
2954 | .s (or .spstr): value as whitespace-separated string. | |
2978 |
|
2955 | |||
2979 | This is very useful when trying to use such lists as arguments to |
|
2956 | This is very useful when trying to use such lists as arguments to | |
2980 | system commands.""" |
|
2957 | system commands.""" | |
2981 |
|
2958 | |||
2982 | if parameter_s: |
|
2959 | if parameter_s: | |
2983 | out = self.shell.getoutput(parameter_s) |
|
2960 | out = self.shell.getoutput(parameter_s) | |
2984 | if out is not None: |
|
2961 | if out is not None: | |
2985 | return SList(out.splitlines()) |
|
2962 | return SList(out.splitlines()) | |
2986 |
|
2963 | |||
2987 | def magic_r(self, parameter_s=''): |
|
2964 | def magic_r(self, parameter_s=''): | |
2988 | """Repeat previous input. |
|
2965 | """Repeat previous input. | |
2989 |
|
2966 | |||
2990 | Note: Consider using the more powerfull %rep instead! |
|
2967 | Note: Consider using the more powerfull %rep instead! | |
2991 |
|
2968 | |||
2992 | If given an argument, repeats the previous command which starts with |
|
2969 | If given an argument, repeats the previous command which starts with | |
2993 | the same string, otherwise it just repeats the previous input. |
|
2970 | the same string, otherwise it just repeats the previous input. | |
2994 |
|
2971 | |||
2995 | Shell escaped commands (with ! as first character) are not recognized |
|
2972 | Shell escaped commands (with ! as first character) are not recognized | |
2996 | by this system, only pure python code and magic commands. |
|
2973 | by this system, only pure python code and magic commands. | |
2997 | """ |
|
2974 | """ | |
2998 |
|
2975 | |||
2999 | start = parameter_s.strip() |
|
2976 | start = parameter_s.strip() | |
3000 | esc_magic = ESC_MAGIC |
|
2977 | esc_magic = ESC_MAGIC | |
3001 | # Identify magic commands even if automagic is on (which means |
|
2978 | # Identify magic commands even if automagic is on (which means | |
3002 | # the in-memory version is different from that typed by the user). |
|
2979 | # the in-memory version is different from that typed by the user). | |
3003 | if self.shell.automagic: |
|
2980 | if self.shell.automagic: | |
3004 | start_magic = esc_magic+start |
|
2981 | start_magic = esc_magic+start | |
3005 | else: |
|
2982 | else: | |
3006 | start_magic = start |
|
2983 | start_magic = start | |
3007 | # Look through the input history in reverse |
|
2984 | # Look through the input history in reverse | |
3008 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
2985 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
3009 | input = self.shell.input_hist[n] |
|
2986 | input = self.shell.input_hist[n] | |
3010 | # skip plain 'r' lines so we don't recurse to infinity |
|
2987 | # skip plain 'r' lines so we don't recurse to infinity | |
3011 | if input != '_ip.magic("r")\n' and \ |
|
2988 | if input != '_ip.magic("r")\n' and \ | |
3012 | (input.startswith(start) or input.startswith(start_magic)): |
|
2989 | (input.startswith(start) or input.startswith(start_magic)): | |
3013 | #print 'match',`input` # dbg |
|
2990 | #print 'match',`input` # dbg | |
3014 | print 'Executing:',input, |
|
2991 | print 'Executing:',input, | |
3015 | self.shell.runlines(input) |
|
2992 | self.shell.runlines(input) | |
3016 | return |
|
2993 | return | |
3017 | print 'No previous input matching `%s` found.' % start |
|
2994 | print 'No previous input matching `%s` found.' % start | |
3018 |
|
2995 | |||
3019 |
|
2996 | |||
3020 | def magic_bookmark(self, parameter_s=''): |
|
2997 | def magic_bookmark(self, parameter_s=''): | |
3021 | """Manage IPython's bookmark system. |
|
2998 | """Manage IPython's bookmark system. | |
3022 |
|
2999 | |||
3023 | %bookmark <name> - set bookmark to current dir |
|
3000 | %bookmark <name> - set bookmark to current dir | |
3024 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3001 | %bookmark <name> <dir> - set bookmark to <dir> | |
3025 | %bookmark -l - list all bookmarks |
|
3002 | %bookmark -l - list all bookmarks | |
3026 | %bookmark -d <name> - remove bookmark |
|
3003 | %bookmark -d <name> - remove bookmark | |
3027 | %bookmark -r - remove all bookmarks |
|
3004 | %bookmark -r - remove all bookmarks | |
3028 |
|
3005 | |||
3029 | You can later on access a bookmarked folder with: |
|
3006 | You can later on access a bookmarked folder with: | |
3030 | %cd -b <name> |
|
3007 | %cd -b <name> | |
3031 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3008 | or simply '%cd <name>' if there is no directory called <name> AND | |
3032 | there is such a bookmark defined. |
|
3009 | there is such a bookmark defined. | |
3033 |
|
3010 | |||
3034 | Your bookmarks persist through IPython sessions, but they are |
|
3011 | Your bookmarks persist through IPython sessions, but they are | |
3035 | associated with each profile.""" |
|
3012 | associated with each profile.""" | |
3036 |
|
3013 | |||
3037 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3014 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3038 | if len(args) > 2: |
|
3015 | if len(args) > 2: | |
3039 | raise UsageError("%bookmark: too many arguments") |
|
3016 | raise UsageError("%bookmark: too many arguments") | |
3040 |
|
3017 | |||
3041 | bkms = self.db.get('bookmarks',{}) |
|
3018 | bkms = self.db.get('bookmarks',{}) | |
3042 |
|
3019 | |||
3043 | if opts.has_key('d'): |
|
3020 | if opts.has_key('d'): | |
3044 | try: |
|
3021 | try: | |
3045 | todel = args[0] |
|
3022 | todel = args[0] | |
3046 | except IndexError: |
|
3023 | except IndexError: | |
3047 | raise UsageError( |
|
3024 | raise UsageError( | |
3048 | "%bookmark -d: must provide a bookmark to delete") |
|
3025 | "%bookmark -d: must provide a bookmark to delete") | |
3049 | else: |
|
3026 | else: | |
3050 | try: |
|
3027 | try: | |
3051 | del bkms[todel] |
|
3028 | del bkms[todel] | |
3052 | except KeyError: |
|
3029 | except KeyError: | |
3053 | raise UsageError( |
|
3030 | raise UsageError( | |
3054 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3031 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3055 |
|
3032 | |||
3056 | elif opts.has_key('r'): |
|
3033 | elif opts.has_key('r'): | |
3057 | bkms = {} |
|
3034 | bkms = {} | |
3058 | elif opts.has_key('l'): |
|
3035 | elif opts.has_key('l'): | |
3059 | bks = bkms.keys() |
|
3036 | bks = bkms.keys() | |
3060 | bks.sort() |
|
3037 | bks.sort() | |
3061 | if bks: |
|
3038 | if bks: | |
3062 | size = max(map(len,bks)) |
|
3039 | size = max(map(len,bks)) | |
3063 | else: |
|
3040 | else: | |
3064 | size = 0 |
|
3041 | size = 0 | |
3065 | fmt = '%-'+str(size)+'s -> %s' |
|
3042 | fmt = '%-'+str(size)+'s -> %s' | |
3066 | print 'Current bookmarks:' |
|
3043 | print 'Current bookmarks:' | |
3067 | for bk in bks: |
|
3044 | for bk in bks: | |
3068 | print fmt % (bk,bkms[bk]) |
|
3045 | print fmt % (bk,bkms[bk]) | |
3069 | else: |
|
3046 | else: | |
3070 | if not args: |
|
3047 | if not args: | |
3071 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3048 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3072 | elif len(args)==1: |
|
3049 | elif len(args)==1: | |
3073 | bkms[args[0]] = os.getcwd() |
|
3050 | bkms[args[0]] = os.getcwd() | |
3074 | elif len(args)==2: |
|
3051 | elif len(args)==2: | |
3075 | bkms[args[0]] = args[1] |
|
3052 | bkms[args[0]] = args[1] | |
3076 | self.db['bookmarks'] = bkms |
|
3053 | self.db['bookmarks'] = bkms | |
3077 |
|
3054 | |||
3078 | def magic_pycat(self, parameter_s=''): |
|
3055 | def magic_pycat(self, parameter_s=''): | |
3079 | """Show a syntax-highlighted file through a pager. |
|
3056 | """Show a syntax-highlighted file through a pager. | |
3080 |
|
3057 | |||
3081 | This magic is similar to the cat utility, but it will assume the file |
|
3058 | This magic is similar to the cat utility, but it will assume the file | |
3082 | to be Python source and will show it with syntax highlighting. """ |
|
3059 | to be Python source and will show it with syntax highlighting. """ | |
3083 |
|
3060 | |||
3084 | try: |
|
3061 | try: | |
3085 | filename = get_py_filename(parameter_s) |
|
3062 | filename = get_py_filename(parameter_s) | |
3086 | cont = file_read(filename) |
|
3063 | cont = file_read(filename) | |
3087 | except IOError: |
|
3064 | except IOError: | |
3088 | try: |
|
3065 | try: | |
3089 | cont = eval(parameter_s,self.user_ns) |
|
3066 | cont = eval(parameter_s,self.user_ns) | |
3090 | except NameError: |
|
3067 | except NameError: | |
3091 | cont = None |
|
3068 | cont = None | |
3092 | if cont is None: |
|
3069 | if cont is None: | |
3093 | print "Error: no such file or variable" |
|
3070 | print "Error: no such file or variable" | |
3094 | return |
|
3071 | return | |
3095 |
|
3072 | |||
3096 | page.page(self.shell.pycolorize(cont)) |
|
3073 | page.page(self.shell.pycolorize(cont)) | |
3097 |
|
3074 | |||
3098 | def _rerun_pasted(self): |
|
3075 | def _rerun_pasted(self): | |
3099 | """ Rerun a previously pasted command. |
|
3076 | """ Rerun a previously pasted command. | |
3100 | """ |
|
3077 | """ | |
3101 | b = self.user_ns.get('pasted_block', None) |
|
3078 | b = self.user_ns.get('pasted_block', None) | |
3102 | if b is None: |
|
3079 | if b is None: | |
3103 | raise UsageError('No previous pasted block available') |
|
3080 | raise UsageError('No previous pasted block available') | |
3104 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3081 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3105 | exec b in self.user_ns |
|
3082 | exec b in self.user_ns | |
3106 |
|
3083 | |||
3107 | def _get_pasted_lines(self, sentinel): |
|
3084 | def _get_pasted_lines(self, sentinel): | |
3108 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3085 | """ Yield pasted lines until the user enters the given sentinel value. | |
3109 | """ |
|
3086 | """ | |
3110 | from IPython.core import interactiveshell |
|
3087 | from IPython.core import interactiveshell | |
3111 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3088 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3112 | while True: |
|
3089 | while True: | |
3113 | l = interactiveshell.raw_input_original(':') |
|
3090 | l = interactiveshell.raw_input_original(':') | |
3114 | if l == sentinel: |
|
3091 | if l == sentinel: | |
3115 | return |
|
3092 | return | |
3116 | else: |
|
3093 | else: | |
3117 | yield l |
|
3094 | yield l | |
3118 |
|
3095 | |||
3119 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3096 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3120 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3097 | """ Strip non-code parts of a sequence of lines to return a block of | |
3121 | code. |
|
3098 | code. | |
3122 | """ |
|
3099 | """ | |
3123 | # Regular expressions that declare text we strip from the input: |
|
3100 | # Regular expressions that declare text we strip from the input: | |
3124 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3101 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3125 | r'^\s*(\s?>)+', # Python input prompt |
|
3102 | r'^\s*(\s?>)+', # Python input prompt | |
3126 | r'^\s*\.{3,}', # Continuation prompts |
|
3103 | r'^\s*\.{3,}', # Continuation prompts | |
3127 | r'^\++', |
|
3104 | r'^\++', | |
3128 | ] |
|
3105 | ] | |
3129 |
|
3106 | |||
3130 | strip_from_start = map(re.compile,strip_re) |
|
3107 | strip_from_start = map(re.compile,strip_re) | |
3131 |
|
3108 | |||
3132 | lines = [] |
|
3109 | lines = [] | |
3133 | for l in raw_lines: |
|
3110 | for l in raw_lines: | |
3134 | for pat in strip_from_start: |
|
3111 | for pat in strip_from_start: | |
3135 | l = pat.sub('',l) |
|
3112 | l = pat.sub('',l) | |
3136 | lines.append(l) |
|
3113 | lines.append(l) | |
3137 |
|
3114 | |||
3138 | block = "\n".join(lines) + '\n' |
|
3115 | block = "\n".join(lines) + '\n' | |
3139 | #print "block:\n",block |
|
3116 | #print "block:\n",block | |
3140 | return block |
|
3117 | return block | |
3141 |
|
3118 | |||
3142 | def _execute_block(self, block, par): |
|
3119 | def _execute_block(self, block, par): | |
3143 | """ Execute a block, or store it in a variable, per the user's request. |
|
3120 | """ Execute a block, or store it in a variable, per the user's request. | |
3144 | """ |
|
3121 | """ | |
3145 | if not par: |
|
3122 | if not par: | |
3146 | b = textwrap.dedent(block) |
|
3123 | b = textwrap.dedent(block) | |
3147 | self.user_ns['pasted_block'] = b |
|
3124 | self.user_ns['pasted_block'] = b | |
3148 | exec b in self.user_ns |
|
3125 | exec b in self.user_ns | |
3149 | else: |
|
3126 | else: | |
3150 | self.user_ns[par] = SList(block.splitlines()) |
|
3127 | self.user_ns[par] = SList(block.splitlines()) | |
3151 | print "Block assigned to '%s'" % par |
|
3128 | print "Block assigned to '%s'" % par | |
3152 |
|
3129 | |||
3153 | def magic_cpaste(self, parameter_s=''): |
|
|||
3154 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
|||
3155 |
|
||||
3156 | You must terminate the block with '--' (two minus-signs) alone on the |
|
|||
3157 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
|||
3158 | is the new sentinel for this operation) |
|
|||
3159 |
|
||||
3160 | The block is dedented prior to execution to enable execution of method |
|
|||
3161 | definitions. '>' and '+' characters at the beginning of a line are |
|
|||
3162 | ignored, to allow pasting directly from e-mails, diff files and |
|
|||
3163 | doctests (the '...' continuation prompt is also stripped). The |
|
|||
3164 | executed block is also assigned to variable named 'pasted_block' for |
|
|||
3165 | later editing with '%edit pasted_block'. |
|
|||
3166 |
|
||||
3167 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
|||
3168 | This assigns the pasted block to variable 'foo' as string, without |
|
|||
3169 | dedenting or executing it (preceding >>> and + is still stripped) |
|
|||
3170 |
|
||||
3171 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
|||
3172 |
|
||||
3173 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
|||
3174 | Just press enter and type -- (and press enter again) and the block |
|
|||
3175 | will be what was just pasted. |
|
|||
3176 |
|
||||
3177 | IPython statements (magics, shell escapes) are not supported (yet). |
|
|||
3178 |
|
||||
3179 | See also |
|
|||
3180 | -------- |
|
|||
3181 | paste: automatically pull code from clipboard. |
|
|||
3182 | """ |
|
|||
3183 |
|
||||
3184 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') |
|
|||
3185 | par = args.strip() |
|
|||
3186 | if opts.has_key('r'): |
|
|||
3187 | self._rerun_pasted() |
|
|||
3188 | return |
|
|||
3189 |
|
||||
3190 | sentinel = opts.get('s','--') |
|
|||
3191 |
|
||||
3192 | block = self._strip_pasted_lines_for_code( |
|
|||
3193 | self._get_pasted_lines(sentinel)) |
|
|||
3194 |
|
||||
3195 | self._execute_block(block, par) |
|
|||
3196 |
|
||||
3197 | def magic_paste(self, parameter_s=''): |
|
|||
3198 | """Allows you to paste & execute a pre-formatted code block from clipboard. |
|
|||
3199 |
|
||||
3200 | The text is pulled directly from the clipboard without user |
|
|||
3201 | intervention and printed back on the screen before execution (unless |
|
|||
3202 | the -q flag is given to force quiet mode). |
|
|||
3203 |
|
||||
3204 | The block is dedented prior to execution to enable execution of method |
|
|||
3205 | definitions. '>' and '+' characters at the beginning of a line are |
|
|||
3206 | ignored, to allow pasting directly from e-mails, diff files and |
|
|||
3207 | doctests (the '...' continuation prompt is also stripped). The |
|
|||
3208 | executed block is also assigned to variable named 'pasted_block' for |
|
|||
3209 | later editing with '%edit pasted_block'. |
|
|||
3210 |
|
||||
3211 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
|||
3212 | This assigns the pasted block to variable 'foo' as string, without |
|
|||
3213 | dedenting or executing it (preceding >>> and + is still stripped) |
|
|||
3214 |
|
||||
3215 | Options |
|
|||
3216 | ------- |
|
|||
3217 |
|
||||
3218 | -r: re-executes the block previously entered by cpaste. |
|
|||
3219 |
|
||||
3220 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
|||
3221 |
|
||||
3222 | IPython statements (magics, shell escapes) are not supported (yet). |
|
|||
3223 |
|
||||
3224 | See also |
|
|||
3225 | -------- |
|
|||
3226 | cpaste: manually paste code into terminal until you mark its end. |
|
|||
3227 | """ |
|
|||
3228 | opts,args = self.parse_options(parameter_s,'rq',mode='string') |
|
|||
3229 | par = args.strip() |
|
|||
3230 | if opts.has_key('r'): |
|
|||
3231 | self._rerun_pasted() |
|
|||
3232 | return |
|
|||
3233 |
|
||||
3234 | text = self.shell.hooks.clipboard_get() |
|
|||
3235 | block = self._strip_pasted_lines_for_code(text.splitlines()) |
|
|||
3236 |
|
||||
3237 | # By default, echo back to terminal unless quiet mode is requested |
|
|||
3238 | if not opts.has_key('q'): |
|
|||
3239 | write = self.shell.write |
|
|||
3240 | write(self.shell.pycolorize(block)) |
|
|||
3241 | if not block.endswith('\n'): |
|
|||
3242 | write('\n') |
|
|||
3243 | write("## -- End pasted text --\n") |
|
|||
3244 |
|
||||
3245 | self._execute_block(block, par) |
|
|||
3246 |
|
||||
3247 | def magic_quickref(self,arg): |
|
3130 | def magic_quickref(self,arg): | |
3248 | """ Show a quick reference sheet """ |
|
3131 | """ Show a quick reference sheet """ | |
3249 | import IPython.core.usage |
|
3132 | import IPython.core.usage | |
3250 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3133 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3251 |
|
3134 | |||
3252 | page.page(qr) |
|
3135 | page.page(qr) | |
3253 |
|
3136 | |||
3254 | def magic_doctest_mode(self,parameter_s=''): |
|
3137 | def magic_doctest_mode(self,parameter_s=''): | |
3255 | """Toggle doctest mode on and off. |
|
3138 | """Toggle doctest mode on and off. | |
3256 |
|
3139 | |||
3257 | This mode is intended to make IPython behave as much as possible like a |
|
3140 | This mode is intended to make IPython behave as much as possible like a | |
3258 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3141 | plain Python shell, from the perspective of how its prompts, exceptions | |
3259 | and output look. This makes it easy to copy and paste parts of a |
|
3142 | and output look. This makes it easy to copy and paste parts of a | |
3260 | session into doctests. It does so by: |
|
3143 | session into doctests. It does so by: | |
3261 |
|
3144 | |||
3262 | - Changing the prompts to the classic ``>>>`` ones. |
|
3145 | - Changing the prompts to the classic ``>>>`` ones. | |
3263 | - Changing the exception reporting mode to 'Plain'. |
|
3146 | - Changing the exception reporting mode to 'Plain'. | |
3264 | - Disabling pretty-printing of output. |
|
3147 | - Disabling pretty-printing of output. | |
3265 |
|
3148 | |||
3266 | Note that IPython also supports the pasting of code snippets that have |
|
3149 | Note that IPython also supports the pasting of code snippets that have | |
3267 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3150 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3268 | doctests from files or docstrings (even if they have leading |
|
3151 | doctests from files or docstrings (even if they have leading | |
3269 | whitespace), and the code will execute correctly. You can then use |
|
3152 | whitespace), and the code will execute correctly. You can then use | |
3270 | '%history -t' to see the translated history; this will give you the |
|
3153 | '%history -t' to see the translated history; this will give you the | |
3271 | input after removal of all the leading prompts and whitespace, which |
|
3154 | input after removal of all the leading prompts and whitespace, which | |
3272 | can be pasted back into an editor. |
|
3155 | can be pasted back into an editor. | |
3273 |
|
3156 | |||
3274 | With these features, you can switch into this mode easily whenever you |
|
3157 | With these features, you can switch into this mode easily whenever you | |
3275 | need to do testing and changes to doctests, without having to leave |
|
3158 | need to do testing and changes to doctests, without having to leave | |
3276 | your existing IPython session. |
|
3159 | your existing IPython session. | |
3277 | """ |
|
3160 | """ | |
3278 |
|
3161 | |||
3279 | from IPython.utils.ipstruct import Struct |
|
3162 | from IPython.utils.ipstruct import Struct | |
3280 |
|
3163 | |||
3281 | # Shorthands |
|
3164 | # Shorthands | |
3282 | shell = self.shell |
|
3165 | shell = self.shell | |
3283 | oc = shell.displayhook |
|
3166 | oc = shell.displayhook | |
3284 | meta = shell.meta |
|
3167 | meta = shell.meta | |
3285 | # dstore is a data store kept in the instance metadata bag to track any |
|
3168 | # dstore is a data store kept in the instance metadata bag to track any | |
3286 | # changes we make, so we can undo them later. |
|
3169 | # changes we make, so we can undo them later. | |
3287 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3170 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3288 | save_dstore = dstore.setdefault |
|
3171 | save_dstore = dstore.setdefault | |
3289 |
|
3172 | |||
3290 | # save a few values we'll need to recover later |
|
3173 | # save a few values we'll need to recover later | |
3291 | mode = save_dstore('mode',False) |
|
3174 | mode = save_dstore('mode',False) | |
3292 | save_dstore('rc_pprint',shell.pprint) |
|
3175 | save_dstore('rc_pprint',shell.pprint) | |
3293 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3176 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3294 | save_dstore('rc_separate_out',shell.separate_out) |
|
3177 | save_dstore('rc_separate_out',shell.separate_out) | |
3295 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3178 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3296 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3179 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3297 | save_dstore('rc_separate_in',shell.separate_in) |
|
3180 | save_dstore('rc_separate_in',shell.separate_in) | |
3298 |
|
3181 | |||
3299 | if mode == False: |
|
3182 | if mode == False: | |
3300 | # turn on |
|
3183 | # turn on | |
3301 | oc.prompt1.p_template = '>>> ' |
|
3184 | oc.prompt1.p_template = '>>> ' | |
3302 | oc.prompt2.p_template = '... ' |
|
3185 | oc.prompt2.p_template = '... ' | |
3303 | oc.prompt_out.p_template = '' |
|
3186 | oc.prompt_out.p_template = '' | |
3304 |
|
3187 | |||
3305 | # Prompt separators like plain python |
|
3188 | # Prompt separators like plain python | |
3306 | oc.input_sep = oc.prompt1.sep = '' |
|
3189 | oc.input_sep = oc.prompt1.sep = '' | |
3307 | oc.output_sep = '' |
|
3190 | oc.output_sep = '' | |
3308 | oc.output_sep2 = '' |
|
3191 | oc.output_sep2 = '' | |
3309 |
|
3192 | |||
3310 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3193 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3311 | oc.prompt_out.pad_left = False |
|
3194 | oc.prompt_out.pad_left = False | |
3312 |
|
3195 | |||
3313 | shell.pprint = False |
|
3196 | shell.pprint = False | |
3314 |
|
3197 | |||
3315 | shell.magic_xmode('Plain') |
|
3198 | shell.magic_xmode('Plain') | |
3316 | else: |
|
3199 | else: | |
3317 | # turn off |
|
3200 | # turn off | |
3318 | oc.prompt1.p_template = shell.prompt_in1 |
|
3201 | oc.prompt1.p_template = shell.prompt_in1 | |
3319 | oc.prompt2.p_template = shell.prompt_in2 |
|
3202 | oc.prompt2.p_template = shell.prompt_in2 | |
3320 | oc.prompt_out.p_template = shell.prompt_out |
|
3203 | oc.prompt_out.p_template = shell.prompt_out | |
3321 |
|
3204 | |||
3322 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3205 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3323 |
|
3206 | |||
3324 | oc.output_sep = dstore.rc_separate_out |
|
3207 | oc.output_sep = dstore.rc_separate_out | |
3325 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3208 | oc.output_sep2 = dstore.rc_separate_out2 | |
3326 |
|
3209 | |||
3327 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3210 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3328 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3211 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3329 |
|
3212 | |||
3330 | shell.pprint = dstore.rc_pprint |
|
3213 | shell.pprint = dstore.rc_pprint | |
3331 |
|
3214 | |||
3332 | shell.magic_xmode(dstore.xmode) |
|
3215 | shell.magic_xmode(dstore.xmode) | |
3333 |
|
3216 | |||
3334 | # Store new mode and inform |
|
3217 | # Store new mode and inform | |
3335 | dstore.mode = bool(1-int(mode)) |
|
3218 | dstore.mode = bool(1-int(mode)) | |
3336 | mode_label = ['OFF','ON'][dstore.mode] |
|
3219 | mode_label = ['OFF','ON'][dstore.mode] | |
3337 | print 'Doctest mode is:', mode_label |
|
3220 | print 'Doctest mode is:', mode_label | |
3338 |
|
3221 | |||
3339 | def magic_gui(self, parameter_s=''): |
|
3222 | def magic_gui(self, parameter_s=''): | |
3340 | """Enable or disable IPython GUI event loop integration. |
|
3223 | """Enable or disable IPython GUI event loop integration. | |
3341 |
|
3224 | |||
3342 | %gui [GUINAME] |
|
3225 | %gui [GUINAME] | |
3343 |
|
3226 | |||
3344 | This magic replaces IPython's threaded shells that were activated |
|
3227 | This magic replaces IPython's threaded shells that were activated | |
3345 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3228 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3346 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3229 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3347 | interrupts should work without any problems. The following toolkits |
|
3230 | interrupts should work without any problems. The following toolkits | |
3348 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3231 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3349 |
|
3232 | |||
3350 | %gui wx # enable wxPython event loop integration |
|
3233 | %gui wx # enable wxPython event loop integration | |
3351 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3234 | %gui qt4|qt # enable PyQt4 event loop integration | |
3352 | %gui gtk # enable PyGTK event loop integration |
|
3235 | %gui gtk # enable PyGTK event loop integration | |
3353 | %gui tk # enable Tk event loop integration |
|
3236 | %gui tk # enable Tk event loop integration | |
3354 | %gui # disable all event loop integration |
|
3237 | %gui # disable all event loop integration | |
3355 |
|
3238 | |||
3356 | WARNING: after any of these has been called you can simply create |
|
3239 | WARNING: after any of these has been called you can simply create | |
3357 | an application object, but DO NOT start the event loop yourself, as |
|
3240 | an application object, but DO NOT start the event loop yourself, as | |
3358 | we have already handled that. |
|
3241 | we have already handled that. | |
3359 | """ |
|
3242 | """ | |
3360 | from IPython.lib.inputhook import enable_gui |
|
3243 | from IPython.lib.inputhook import enable_gui | |
3361 | opts, arg = self.parse_options(parameter_s='') |
|
3244 | opts, arg = self.parse_options(parameter_s='') | |
3362 | if arg=='': arg = None |
|
3245 | if arg=='': arg = None | |
3363 | return enable_gui(arg) |
|
3246 | return enable_gui(arg) | |
3364 |
|
3247 | |||
3365 | def magic_load_ext(self, module_str): |
|
3248 | def magic_load_ext(self, module_str): | |
3366 | """Load an IPython extension by its module name.""" |
|
3249 | """Load an IPython extension by its module name.""" | |
3367 | return self.extension_manager.load_extension(module_str) |
|
3250 | return self.extension_manager.load_extension(module_str) | |
3368 |
|
3251 | |||
3369 | def magic_unload_ext(self, module_str): |
|
3252 | def magic_unload_ext(self, module_str): | |
3370 | """Unload an IPython extension by its module name.""" |
|
3253 | """Unload an IPython extension by its module name.""" | |
3371 | self.extension_manager.unload_extension(module_str) |
|
3254 | self.extension_manager.unload_extension(module_str) | |
3372 |
|
3255 | |||
3373 | def magic_reload_ext(self, module_str): |
|
3256 | def magic_reload_ext(self, module_str): | |
3374 | """Reload an IPython extension by its module name.""" |
|
3257 | """Reload an IPython extension by its module name.""" | |
3375 | self.extension_manager.reload_extension(module_str) |
|
3258 | self.extension_manager.reload_extension(module_str) | |
3376 |
|
3259 | |||
3377 | @testdec.skip_doctest |
|
3260 | @testdec.skip_doctest | |
3378 | def magic_install_profiles(self, s): |
|
3261 | def magic_install_profiles(self, s): | |
3379 | """Install the default IPython profiles into the .ipython dir. |
|
3262 | """Install the default IPython profiles into the .ipython dir. | |
3380 |
|
3263 | |||
3381 | If the default profiles have already been installed, they will not |
|
3264 | If the default profiles have already been installed, they will not | |
3382 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3265 | be overwritten. You can force overwriting them by using the ``-o`` | |
3383 | option:: |
|
3266 | option:: | |
3384 |
|
3267 | |||
3385 | In [1]: %install_profiles -o |
|
3268 | In [1]: %install_profiles -o | |
3386 | """ |
|
3269 | """ | |
3387 | if '-o' in s: |
|
3270 | if '-o' in s: | |
3388 | overwrite = True |
|
3271 | overwrite = True | |
3389 | else: |
|
3272 | else: | |
3390 | overwrite = False |
|
3273 | overwrite = False | |
3391 | from IPython.config import profile |
|
3274 | from IPython.config import profile | |
3392 | profile_dir = os.path.split(profile.__file__)[0] |
|
3275 | profile_dir = os.path.split(profile.__file__)[0] | |
3393 | ipython_dir = self.ipython_dir |
|
3276 | ipython_dir = self.ipython_dir | |
3394 | files = os.listdir(profile_dir) |
|
3277 | files = os.listdir(profile_dir) | |
3395 |
|
3278 | |||
3396 | to_install = [] |
|
3279 | to_install = [] | |
3397 | for f in files: |
|
3280 | for f in files: | |
3398 | if f.startswith('ipython_config'): |
|
3281 | if f.startswith('ipython_config'): | |
3399 | src = os.path.join(profile_dir, f) |
|
3282 | src = os.path.join(profile_dir, f) | |
3400 | dst = os.path.join(ipython_dir, f) |
|
3283 | dst = os.path.join(ipython_dir, f) | |
3401 | if (not os.path.isfile(dst)) or overwrite: |
|
3284 | if (not os.path.isfile(dst)) or overwrite: | |
3402 | to_install.append((f, src, dst)) |
|
3285 | to_install.append((f, src, dst)) | |
3403 | if len(to_install)>0: |
|
3286 | if len(to_install)>0: | |
3404 | print "Installing profiles to: ", ipython_dir |
|
3287 | print "Installing profiles to: ", ipython_dir | |
3405 | for (f, src, dst) in to_install: |
|
3288 | for (f, src, dst) in to_install: | |
3406 | shutil.copy(src, dst) |
|
3289 | shutil.copy(src, dst) | |
3407 | print " %s" % f |
|
3290 | print " %s" % f | |
3408 |
|
3291 | |||
3409 | def magic_install_default_config(self, s): |
|
3292 | def magic_install_default_config(self, s): | |
3410 | """Install IPython's default config file into the .ipython dir. |
|
3293 | """Install IPython's default config file into the .ipython dir. | |
3411 |
|
3294 | |||
3412 | If the default config file (:file:`ipython_config.py`) is already |
|
3295 | If the default config file (:file:`ipython_config.py`) is already | |
3413 | installed, it will not be overwritten. You can force overwriting |
|
3296 | installed, it will not be overwritten. You can force overwriting | |
3414 | by using the ``-o`` option:: |
|
3297 | by using the ``-o`` option:: | |
3415 |
|
3298 | |||
3416 | In [1]: %install_default_config |
|
3299 | In [1]: %install_default_config | |
3417 | """ |
|
3300 | """ | |
3418 | if '-o' in s: |
|
3301 | if '-o' in s: | |
3419 | overwrite = True |
|
3302 | overwrite = True | |
3420 | else: |
|
3303 | else: | |
3421 | overwrite = False |
|
3304 | overwrite = False | |
3422 | from IPython.config import default |
|
3305 | from IPython.config import default | |
3423 | config_dir = os.path.split(default.__file__)[0] |
|
3306 | config_dir = os.path.split(default.__file__)[0] | |
3424 | ipython_dir = self.ipython_dir |
|
3307 | ipython_dir = self.ipython_dir | |
3425 | default_config_file_name = 'ipython_config.py' |
|
3308 | default_config_file_name = 'ipython_config.py' | |
3426 | src = os.path.join(config_dir, default_config_file_name) |
|
3309 | src = os.path.join(config_dir, default_config_file_name) | |
3427 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3310 | dst = os.path.join(ipython_dir, default_config_file_name) | |
3428 | if (not os.path.isfile(dst)) or overwrite: |
|
3311 | if (not os.path.isfile(dst)) or overwrite: | |
3429 | shutil.copy(src, dst) |
|
3312 | shutil.copy(src, dst) | |
3430 | print "Installing default config file: %s" % dst |
|
3313 | print "Installing default config file: %s" % dst | |
3431 |
|
3314 | |||
3432 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3315 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3433 | # handling and modify slightly %run |
|
3316 | # handling and modify slightly %run | |
3434 |
|
3317 | |||
3435 | @testdec.skip_doctest |
|
3318 | @testdec.skip_doctest | |
3436 | def _pylab_magic_run(self, parameter_s=''): |
|
3319 | def _pylab_magic_run(self, parameter_s=''): | |
3437 | Magic.magic_run(self, parameter_s, |
|
3320 | Magic.magic_run(self, parameter_s, | |
3438 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3321 | runner=mpl_runner(self.shell.safe_execfile)) | |
3439 |
|
3322 | |||
3440 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3323 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3441 |
|
3324 | |||
3442 | @testdec.skip_doctest |
|
3325 | @testdec.skip_doctest | |
3443 | def magic_pylab(self, s): |
|
3326 | def magic_pylab(self, s): | |
3444 | """Load numpy and matplotlib to work interactively. |
|
3327 | """Load numpy and matplotlib to work interactively. | |
3445 |
|
3328 | |||
3446 | %pylab [GUINAME] |
|
3329 | %pylab [GUINAME] | |
3447 |
|
3330 | |||
3448 | This function lets you activate pylab (matplotlib, numpy and |
|
3331 | This function lets you activate pylab (matplotlib, numpy and | |
3449 | interactive support) at any point during an IPython session. |
|
3332 | interactive support) at any point during an IPython session. | |
3450 |
|
3333 | |||
3451 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3334 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3452 | pylab and mlab, as well as all names from numpy and pylab. |
|
3335 | pylab and mlab, as well as all names from numpy and pylab. | |
3453 |
|
3336 | |||
3454 | Parameters |
|
3337 | Parameters | |
3455 | ---------- |
|
3338 | ---------- | |
3456 | guiname : optional |
|
3339 | guiname : optional | |
3457 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3340 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or | |
3458 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3341 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3459 | otherwise matplotlib's default (which you can override in your |
|
3342 | otherwise matplotlib's default (which you can override in your | |
3460 | matplotlib config file) is used. |
|
3343 | matplotlib config file) is used. | |
3461 |
|
3344 | |||
3462 | Examples |
|
3345 | Examples | |
3463 | -------- |
|
3346 | -------- | |
3464 | In this case, where the MPL default is TkAgg: |
|
3347 | In this case, where the MPL default is TkAgg: | |
3465 | In [2]: %pylab |
|
3348 | In [2]: %pylab | |
3466 |
|
3349 | |||
3467 | Welcome to pylab, a matplotlib-based Python environment. |
|
3350 | Welcome to pylab, a matplotlib-based Python environment. | |
3468 | Backend in use: TkAgg |
|
3351 | Backend in use: TkAgg | |
3469 | For more information, type 'help(pylab)'. |
|
3352 | For more information, type 'help(pylab)'. | |
3470 |
|
3353 | |||
3471 | But you can explicitly request a different backend: |
|
3354 | But you can explicitly request a different backend: | |
3472 | In [3]: %pylab qt |
|
3355 | In [3]: %pylab qt | |
3473 |
|
3356 | |||
3474 | Welcome to pylab, a matplotlib-based Python environment. |
|
3357 | Welcome to pylab, a matplotlib-based Python environment. | |
3475 | Backend in use: Qt4Agg |
|
3358 | Backend in use: Qt4Agg | |
3476 | For more information, type 'help(pylab)'. |
|
3359 | For more information, type 'help(pylab)'. | |
3477 | """ |
|
3360 | """ | |
3478 | self.shell.enable_pylab(s) |
|
3361 | self.shell.enable_pylab(s) | |
3479 |
|
3362 | |||
3480 | def magic_tb(self, s): |
|
3363 | def magic_tb(self, s): | |
3481 | """Print the last traceback with the currently active exception mode. |
|
3364 | """Print the last traceback with the currently active exception mode. | |
3482 |
|
3365 | |||
3483 | See %xmode for changing exception reporting modes.""" |
|
3366 | See %xmode for changing exception reporting modes.""" | |
3484 | self.shell.showtraceback() |
|
3367 | self.shell.showtraceback() | |
3485 |
|
3368 | |||
3486 | # end Magic |
|
3369 | # end Magic |
@@ -1,522 +1,630 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Subclass of InteractiveShell for terminal based frontends.""" |
|
2 | """Subclass of InteractiveShell for terminal based frontends.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2010 The IPython Development Team |
|
7 | # Copyright (C) 2008-2010 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | import __builtin__ |
|
17 | import __builtin__ | |
18 | import bdb |
|
18 | import bdb | |
19 | from contextlib import nested |
|
19 | from contextlib import nested | |
20 | import os |
|
20 | import os | |
21 | import re |
|
21 | import re | |
22 | import sys |
|
22 | import sys | |
23 |
|
23 | |||
24 | from IPython.core.error import TryNext |
|
24 | from IPython.core.error import TryNext | |
25 | from IPython.core.usage import interactive_usage, default_banner |
|
25 | from IPython.core.usage import interactive_usage, default_banner | |
26 | from IPython.core.inputlist import InputList |
|
26 | from IPython.core.inputlist import InputList | |
27 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC |
|
27 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC | |
28 | from IPython.lib.inputhook import enable_gui |
|
28 | from IPython.lib.inputhook import enable_gui | |
29 | from IPython.lib.pylabtools import pylab_activate |
|
29 | from IPython.lib.pylabtools import pylab_activate | |
30 | from IPython.utils.terminal import toggle_set_term_title, set_term_title |
|
30 | from IPython.utils.terminal import toggle_set_term_title, set_term_title | |
31 | from IPython.utils.process import abbrev_cwd |
|
31 | from IPython.utils.process import abbrev_cwd | |
32 | from IPython.utils.warn import warn |
|
32 | from IPython.utils.warn import warn | |
33 | from IPython.utils.text import num_ini_spaces |
|
33 | from IPython.utils.text import num_ini_spaces | |
34 | from IPython.utils.traitlets import Int, Str, CBool |
|
34 | from IPython.utils.traitlets import Int, Str, CBool | |
35 |
|
35 | |||
36 |
|
36 | |||
37 | #----------------------------------------------------------------------------- |
|
37 | #----------------------------------------------------------------------------- | |
38 | # Utilities |
|
38 | # Utilities | |
39 | #----------------------------------------------------------------------------- |
|
39 | #----------------------------------------------------------------------------- | |
40 |
|
40 | |||
41 |
|
41 | |||
42 | def get_default_editor(): |
|
42 | def get_default_editor(): | |
43 | try: |
|
43 | try: | |
44 | ed = os.environ['EDITOR'] |
|
44 | ed = os.environ['EDITOR'] | |
45 | except KeyError: |
|
45 | except KeyError: | |
46 | if os.name == 'posix': |
|
46 | if os.name == 'posix': | |
47 | ed = 'vi' # the only one guaranteed to be there! |
|
47 | ed = 'vi' # the only one guaranteed to be there! | |
48 | else: |
|
48 | else: | |
49 | ed = 'notepad' # same in Windows! |
|
49 | ed = 'notepad' # same in Windows! | |
50 | return ed |
|
50 | return ed | |
51 |
|
51 | |||
52 |
|
52 | |||
53 | # store the builtin raw_input globally, and use this always, in case user code |
|
53 | # store the builtin raw_input globally, and use this always, in case user code | |
54 | # overwrites it (like wx.py.PyShell does) |
|
54 | # overwrites it (like wx.py.PyShell does) | |
55 | raw_input_original = raw_input |
|
55 | raw_input_original = raw_input | |
56 |
|
56 | |||
57 |
|
57 | |||
58 | #----------------------------------------------------------------------------- |
|
58 | #----------------------------------------------------------------------------- | |
59 | # Main class |
|
59 | # Main class | |
60 | #----------------------------------------------------------------------------- |
|
60 | #----------------------------------------------------------------------------- | |
61 |
|
61 | |||
62 |
|
62 | |||
63 | class TerminalInteractiveShell(InteractiveShell): |
|
63 | class TerminalInteractiveShell(InteractiveShell): | |
64 |
|
64 | |||
65 | autoedit_syntax = CBool(False, config=True) |
|
65 | autoedit_syntax = CBool(False, config=True) | |
66 | banner = Str('') |
|
66 | banner = Str('') | |
67 | banner1 = Str(default_banner, config=True) |
|
67 | banner1 = Str(default_banner, config=True) | |
68 | banner2 = Str('', config=True) |
|
68 | banner2 = Str('', config=True) | |
69 | confirm_exit = CBool(True, config=True) |
|
69 | confirm_exit = CBool(True, config=True) | |
70 | # This display_banner only controls whether or not self.show_banner() |
|
70 | # This display_banner only controls whether or not self.show_banner() | |
71 | # is called when mainloop/interact are called. The default is False |
|
71 | # is called when mainloop/interact are called. The default is False | |
72 | # because for the terminal based application, the banner behavior |
|
72 | # because for the terminal based application, the banner behavior | |
73 | # is controlled by Global.display_banner, which IPythonApp looks at |
|
73 | # is controlled by Global.display_banner, which IPythonApp looks at | |
74 | # to determine if *it* should call show_banner() by hand or not. |
|
74 | # to determine if *it* should call show_banner() by hand or not. | |
75 | display_banner = CBool(False) # This isn't configurable! |
|
75 | display_banner = CBool(False) # This isn't configurable! | |
76 | embedded = CBool(False) |
|
76 | embedded = CBool(False) | |
77 | embedded_active = CBool(False) |
|
77 | embedded_active = CBool(False) | |
78 | editor = Str(get_default_editor(), config=True) |
|
78 | editor = Str(get_default_editor(), config=True) | |
79 | pager = Str('less', config=True) |
|
79 | pager = Str('less', config=True) | |
80 |
|
80 | |||
81 | screen_length = Int(0, config=True) |
|
81 | screen_length = Int(0, config=True) | |
82 | term_title = CBool(False, config=True) |
|
82 | term_title = CBool(False, config=True) | |
83 |
|
83 | |||
84 | def __init__(self, config=None, ipython_dir=None, user_ns=None, |
|
84 | def __init__(self, config=None, ipython_dir=None, user_ns=None, | |
85 | user_global_ns=None, custom_exceptions=((),None), |
|
85 | user_global_ns=None, custom_exceptions=((),None), | |
86 | usage=None, banner1=None, banner2=None, |
|
86 | usage=None, banner1=None, banner2=None, | |
87 | display_banner=None): |
|
87 | display_banner=None): | |
88 |
|
88 | |||
89 | super(TerminalInteractiveShell, self).__init__( |
|
89 | super(TerminalInteractiveShell, self).__init__( | |
90 | config=config, ipython_dir=ipython_dir, user_ns=user_ns, |
|
90 | config=config, ipython_dir=ipython_dir, user_ns=user_ns, | |
91 | user_global_ns=user_global_ns, custom_exceptions=custom_exceptions |
|
91 | user_global_ns=user_global_ns, custom_exceptions=custom_exceptions | |
92 | ) |
|
92 | ) | |
93 | self.init_term_title() |
|
93 | self.init_term_title() | |
94 | self.init_usage(usage) |
|
94 | self.init_usage(usage) | |
95 | self.init_banner(banner1, banner2, display_banner) |
|
95 | self.init_banner(banner1, banner2, display_banner) | |
96 |
|
96 | |||
97 | #------------------------------------------------------------------------- |
|
97 | #------------------------------------------------------------------------- | |
98 | # Things related to the terminal |
|
98 | # Things related to the terminal | |
99 | #------------------------------------------------------------------------- |
|
99 | #------------------------------------------------------------------------- | |
100 |
|
100 | |||
101 | @property |
|
101 | @property | |
102 | def usable_screen_length(self): |
|
102 | def usable_screen_length(self): | |
103 | if self.screen_length == 0: |
|
103 | if self.screen_length == 0: | |
104 | return 0 |
|
104 | return 0 | |
105 | else: |
|
105 | else: | |
106 | num_lines_bot = self.separate_in.count('\n')+1 |
|
106 | num_lines_bot = self.separate_in.count('\n')+1 | |
107 | return self.screen_length - num_lines_bot |
|
107 | return self.screen_length - num_lines_bot | |
108 |
|
108 | |||
109 | def init_term_title(self): |
|
109 | def init_term_title(self): | |
110 | # Enable or disable the terminal title. |
|
110 | # Enable or disable the terminal title. | |
111 | if self.term_title: |
|
111 | if self.term_title: | |
112 | toggle_set_term_title(True) |
|
112 | toggle_set_term_title(True) | |
113 | set_term_title('IPython: ' + abbrev_cwd()) |
|
113 | set_term_title('IPython: ' + abbrev_cwd()) | |
114 | else: |
|
114 | else: | |
115 | toggle_set_term_title(False) |
|
115 | toggle_set_term_title(False) | |
116 |
|
116 | |||
117 | #------------------------------------------------------------------------- |
|
117 | #------------------------------------------------------------------------- | |
118 | # Things related to the banner and usage |
|
118 | # Things related to the banner and usage | |
119 | #------------------------------------------------------------------------- |
|
119 | #------------------------------------------------------------------------- | |
120 |
|
120 | |||
121 | def _banner1_changed(self): |
|
121 | def _banner1_changed(self): | |
122 | self.compute_banner() |
|
122 | self.compute_banner() | |
123 |
|
123 | |||
124 | def _banner2_changed(self): |
|
124 | def _banner2_changed(self): | |
125 | self.compute_banner() |
|
125 | self.compute_banner() | |
126 |
|
126 | |||
127 | def _term_title_changed(self, name, new_value): |
|
127 | def _term_title_changed(self, name, new_value): | |
128 | self.init_term_title() |
|
128 | self.init_term_title() | |
129 |
|
129 | |||
130 | def init_banner(self, banner1, banner2, display_banner): |
|
130 | def init_banner(self, banner1, banner2, display_banner): | |
131 | if banner1 is not None: |
|
131 | if banner1 is not None: | |
132 | self.banner1 = banner1 |
|
132 | self.banner1 = banner1 | |
133 | if banner2 is not None: |
|
133 | if banner2 is not None: | |
134 | self.banner2 = banner2 |
|
134 | self.banner2 = banner2 | |
135 | if display_banner is not None: |
|
135 | if display_banner is not None: | |
136 | self.display_banner = display_banner |
|
136 | self.display_banner = display_banner | |
137 | self.compute_banner() |
|
137 | self.compute_banner() | |
138 |
|
138 | |||
139 | def show_banner(self, banner=None): |
|
139 | def show_banner(self, banner=None): | |
140 | if banner is None: |
|
140 | if banner is None: | |
141 | banner = self.banner |
|
141 | banner = self.banner | |
142 | self.write(banner) |
|
142 | self.write(banner) | |
143 |
|
143 | |||
144 | def compute_banner(self): |
|
144 | def compute_banner(self): | |
145 | self.banner = self.banner1 + '\n' |
|
145 | self.banner = self.banner1 + '\n' | |
146 | if self.profile: |
|
146 | if self.profile: | |
147 | self.banner += '\nIPython profile: %s\n' % self.profile |
|
147 | self.banner += '\nIPython profile: %s\n' % self.profile | |
148 | if self.banner2: |
|
148 | if self.banner2: | |
149 | self.banner += '\n' + self.banner2 + '\n' |
|
149 | self.banner += '\n' + self.banner2 + '\n' | |
150 |
|
150 | |||
151 | def init_usage(self, usage=None): |
|
151 | def init_usage(self, usage=None): | |
152 | if usage is None: |
|
152 | if usage is None: | |
153 | self.usage = interactive_usage |
|
153 | self.usage = interactive_usage | |
154 | else: |
|
154 | else: | |
155 | self.usage = usage |
|
155 | self.usage = usage | |
156 |
|
156 | |||
157 | #------------------------------------------------------------------------- |
|
157 | #------------------------------------------------------------------------- | |
158 | # Mainloop and code execution logic |
|
158 | # Mainloop and code execution logic | |
159 | #------------------------------------------------------------------------- |
|
159 | #------------------------------------------------------------------------- | |
160 |
|
160 | |||
161 | def mainloop(self, display_banner=None): |
|
161 | def mainloop(self, display_banner=None): | |
162 | """Start the mainloop. |
|
162 | """Start the mainloop. | |
163 |
|
163 | |||
164 | If an optional banner argument is given, it will override the |
|
164 | If an optional banner argument is given, it will override the | |
165 | internally created default banner. |
|
165 | internally created default banner. | |
166 | """ |
|
166 | """ | |
167 |
|
167 | |||
168 | with nested(self.builtin_trap, self.display_trap): |
|
168 | with nested(self.builtin_trap, self.display_trap): | |
169 |
|
169 | |||
170 | # if you run stuff with -c <cmd>, raw hist is not updated |
|
170 | # if you run stuff with -c <cmd>, raw hist is not updated | |
171 | # ensure that it's in sync |
|
171 | # ensure that it's in sync | |
172 | if len(self.input_hist) != len (self.input_hist_raw): |
|
172 | if len(self.input_hist) != len (self.input_hist_raw): | |
173 | self.input_hist_raw = InputList(self.input_hist) |
|
173 | self.input_hist_raw = InputList(self.input_hist) | |
174 |
|
174 | |||
175 | while 1: |
|
175 | while 1: | |
176 | try: |
|
176 | try: | |
177 | self.interact(display_banner=display_banner) |
|
177 | self.interact(display_banner=display_banner) | |
178 | #self.interact_with_readline() |
|
178 | #self.interact_with_readline() | |
179 | # XXX for testing of a readline-decoupled repl loop, call |
|
179 | # XXX for testing of a readline-decoupled repl loop, call | |
180 | # interact_with_readline above |
|
180 | # interact_with_readline above | |
181 | break |
|
181 | break | |
182 | except KeyboardInterrupt: |
|
182 | except KeyboardInterrupt: | |
183 | # this should not be necessary, but KeyboardInterrupt |
|
183 | # this should not be necessary, but KeyboardInterrupt | |
184 | # handling seems rather unpredictable... |
|
184 | # handling seems rather unpredictable... | |
185 | self.write("\nKeyboardInterrupt in interact()\n") |
|
185 | self.write("\nKeyboardInterrupt in interact()\n") | |
186 |
|
186 | |||
187 | def interact(self, display_banner=None): |
|
187 | def interact(self, display_banner=None): | |
188 | """Closely emulate the interactive Python console.""" |
|
188 | """Closely emulate the interactive Python console.""" | |
189 |
|
189 | |||
190 | # batch run -> do not interact |
|
190 | # batch run -> do not interact | |
191 | if self.exit_now: |
|
191 | if self.exit_now: | |
192 | return |
|
192 | return | |
193 |
|
193 | |||
194 | if display_banner is None: |
|
194 | if display_banner is None: | |
195 | display_banner = self.display_banner |
|
195 | display_banner = self.display_banner | |
196 | if display_banner: |
|
196 | if display_banner: | |
197 | self.show_banner() |
|
197 | self.show_banner() | |
198 |
|
198 | |||
199 | more = 0 |
|
199 | more = 0 | |
200 |
|
200 | |||
201 | # Mark activity in the builtins |
|
201 | # Mark activity in the builtins | |
202 | __builtin__.__dict__['__IPYTHON__active'] += 1 |
|
202 | __builtin__.__dict__['__IPYTHON__active'] += 1 | |
203 |
|
203 | |||
204 | if self.has_readline: |
|
204 | if self.has_readline: | |
205 | self.readline_startup_hook(self.pre_readline) |
|
205 | self.readline_startup_hook(self.pre_readline) | |
206 | # exit_now is set by a call to %Exit or %Quit, through the |
|
206 | # exit_now is set by a call to %Exit or %Quit, through the | |
207 | # ask_exit callback. |
|
207 | # ask_exit callback. | |
208 |
|
208 | |||
209 | while not self.exit_now: |
|
209 | while not self.exit_now: | |
210 | self.hooks.pre_prompt_hook() |
|
210 | self.hooks.pre_prompt_hook() | |
211 | if more: |
|
211 | if more: | |
212 | try: |
|
212 | try: | |
213 | prompt = self.hooks.generate_prompt(True) |
|
213 | prompt = self.hooks.generate_prompt(True) | |
214 | except: |
|
214 | except: | |
215 | self.showtraceback() |
|
215 | self.showtraceback() | |
216 | if self.autoindent: |
|
216 | if self.autoindent: | |
217 | self.rl_do_indent = True |
|
217 | self.rl_do_indent = True | |
218 |
|
218 | |||
219 | else: |
|
219 | else: | |
220 | try: |
|
220 | try: | |
221 | prompt = self.hooks.generate_prompt(False) |
|
221 | prompt = self.hooks.generate_prompt(False) | |
222 | except: |
|
222 | except: | |
223 | self.showtraceback() |
|
223 | self.showtraceback() | |
224 | try: |
|
224 | try: | |
225 | line = self.raw_input(prompt, more) |
|
225 | line = self.raw_input(prompt, more) | |
226 | if self.exit_now: |
|
226 | if self.exit_now: | |
227 | # quick exit on sys.std[in|out] close |
|
227 | # quick exit on sys.std[in|out] close | |
228 | break |
|
228 | break | |
229 | if self.autoindent: |
|
229 | if self.autoindent: | |
230 | self.rl_do_indent = False |
|
230 | self.rl_do_indent = False | |
231 |
|
231 | |||
232 | except KeyboardInterrupt: |
|
232 | except KeyboardInterrupt: | |
233 | #double-guard against keyboardinterrupts during kbdint handling |
|
233 | #double-guard against keyboardinterrupts during kbdint handling | |
234 | try: |
|
234 | try: | |
235 | self.write('\nKeyboardInterrupt\n') |
|
235 | self.write('\nKeyboardInterrupt\n') | |
236 | self.resetbuffer() |
|
236 | self.resetbuffer() | |
237 | # keep cache in sync with the prompt counter: |
|
237 | # keep cache in sync with the prompt counter: | |
238 | self.displayhook.prompt_count -= 1 |
|
238 | self.displayhook.prompt_count -= 1 | |
239 |
|
239 | |||
240 | if self.autoindent: |
|
240 | if self.autoindent: | |
241 | self.indent_current_nsp = 0 |
|
241 | self.indent_current_nsp = 0 | |
242 | more = 0 |
|
242 | more = 0 | |
243 | except KeyboardInterrupt: |
|
243 | except KeyboardInterrupt: | |
244 | pass |
|
244 | pass | |
245 | except EOFError: |
|
245 | except EOFError: | |
246 | if self.autoindent: |
|
246 | if self.autoindent: | |
247 | self.rl_do_indent = False |
|
247 | self.rl_do_indent = False | |
248 | if self.has_readline: |
|
248 | if self.has_readline: | |
249 | self.readline_startup_hook(None) |
|
249 | self.readline_startup_hook(None) | |
250 | self.write('\n') |
|
250 | self.write('\n') | |
251 | self.exit() |
|
251 | self.exit() | |
252 | except bdb.BdbQuit: |
|
252 | except bdb.BdbQuit: | |
253 | warn('The Python debugger has exited with a BdbQuit exception.\n' |
|
253 | warn('The Python debugger has exited with a BdbQuit exception.\n' | |
254 | 'Because of how pdb handles the stack, it is impossible\n' |
|
254 | 'Because of how pdb handles the stack, it is impossible\n' | |
255 | 'for IPython to properly format this particular exception.\n' |
|
255 | 'for IPython to properly format this particular exception.\n' | |
256 | 'IPython will resume normal operation.') |
|
256 | 'IPython will resume normal operation.') | |
257 | except: |
|
257 | except: | |
258 | # exceptions here are VERY RARE, but they can be triggered |
|
258 | # exceptions here are VERY RARE, but they can be triggered | |
259 | # asynchronously by signal handlers, for example. |
|
259 | # asynchronously by signal handlers, for example. | |
260 | self.showtraceback() |
|
260 | self.showtraceback() | |
261 | else: |
|
261 | else: | |
262 | more = self.push_line(line) |
|
262 | more = self.push_line(line) | |
263 | if (self.SyntaxTB.last_syntax_error and |
|
263 | if (self.SyntaxTB.last_syntax_error and | |
264 | self.autoedit_syntax): |
|
264 | self.autoedit_syntax): | |
265 | self.edit_syntax_error() |
|
265 | self.edit_syntax_error() | |
266 |
|
266 | |||
267 | # We are off again... |
|
267 | # We are off again... | |
268 | __builtin__.__dict__['__IPYTHON__active'] -= 1 |
|
268 | __builtin__.__dict__['__IPYTHON__active'] -= 1 | |
269 |
|
269 | |||
270 | # Turn off the exit flag, so the mainloop can be restarted if desired |
|
270 | # Turn off the exit flag, so the mainloop can be restarted if desired | |
271 | self.exit_now = False |
|
271 | self.exit_now = False | |
272 |
|
272 | |||
273 | def raw_input(self,prompt='',continue_prompt=False): |
|
273 | def raw_input(self,prompt='',continue_prompt=False): | |
274 | """Write a prompt and read a line. |
|
274 | """Write a prompt and read a line. | |
275 |
|
275 | |||
276 | The returned line does not include the trailing newline. |
|
276 | The returned line does not include the trailing newline. | |
277 | When the user enters the EOF key sequence, EOFError is raised. |
|
277 | When the user enters the EOF key sequence, EOFError is raised. | |
278 |
|
278 | |||
279 | Optional inputs: |
|
279 | Optional inputs: | |
280 |
|
280 | |||
281 | - prompt(''): a string to be printed to prompt the user. |
|
281 | - prompt(''): a string to be printed to prompt the user. | |
282 |
|
282 | |||
283 | - continue_prompt(False): whether this line is the first one or a |
|
283 | - continue_prompt(False): whether this line is the first one or a | |
284 | continuation in a sequence of inputs. |
|
284 | continuation in a sequence of inputs. | |
285 | """ |
|
285 | """ | |
286 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) |
|
286 | # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt)) | |
287 |
|
287 | |||
288 | # Code run by the user may have modified the readline completer state. |
|
288 | # Code run by the user may have modified the readline completer state. | |
289 | # We must ensure that our completer is back in place. |
|
289 | # We must ensure that our completer is back in place. | |
290 |
|
290 | |||
291 | if self.has_readline: |
|
291 | if self.has_readline: | |
292 | self.set_readline_completer() |
|
292 | self.set_readline_completer() | |
293 |
|
293 | |||
294 | try: |
|
294 | try: | |
295 | line = raw_input_original(prompt).decode(self.stdin_encoding) |
|
295 | line = raw_input_original(prompt).decode(self.stdin_encoding) | |
296 | except ValueError: |
|
296 | except ValueError: | |
297 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" |
|
297 | warn("\n********\nYou or a %run:ed script called sys.stdin.close()" | |
298 | " or sys.stdout.close()!\nExiting IPython!") |
|
298 | " or sys.stdout.close()!\nExiting IPython!") | |
299 | self.ask_exit() |
|
299 | self.ask_exit() | |
300 | return "" |
|
300 | return "" | |
301 |
|
301 | |||
302 | # Try to be reasonably smart about not re-indenting pasted input more |
|
302 | # Try to be reasonably smart about not re-indenting pasted input more | |
303 | # than necessary. We do this by trimming out the auto-indent initial |
|
303 | # than necessary. We do this by trimming out the auto-indent initial | |
304 | # spaces, if the user's actual input started itself with whitespace. |
|
304 | # spaces, if the user's actual input started itself with whitespace. | |
305 | #debugx('self.buffer[-1]') |
|
305 | #debugx('self.buffer[-1]') | |
306 |
|
306 | |||
307 | if self.autoindent: |
|
307 | if self.autoindent: | |
308 | if num_ini_spaces(line) > self.indent_current_nsp: |
|
308 | if num_ini_spaces(line) > self.indent_current_nsp: | |
309 | line = line[self.indent_current_nsp:] |
|
309 | line = line[self.indent_current_nsp:] | |
310 | self.indent_current_nsp = 0 |
|
310 | self.indent_current_nsp = 0 | |
311 |
|
311 | |||
312 | # store the unfiltered input before the user has any chance to modify |
|
312 | # store the unfiltered input before the user has any chance to modify | |
313 | # it. |
|
313 | # it. | |
314 | if line.strip(): |
|
314 | if line.strip(): | |
315 | if continue_prompt: |
|
315 | if continue_prompt: | |
316 | self.input_hist_raw[-1] += '%s\n' % line |
|
316 | self.input_hist_raw[-1] += '%s\n' % line | |
317 | if self.has_readline and self.readline_use: |
|
317 | if self.has_readline and self.readline_use: | |
318 | try: |
|
318 | try: | |
319 | histlen = self.readline.get_current_history_length() |
|
319 | histlen = self.readline.get_current_history_length() | |
320 | if histlen > 1: |
|
320 | if histlen > 1: | |
321 | newhist = self.input_hist_raw[-1].rstrip() |
|
321 | newhist = self.input_hist_raw[-1].rstrip() | |
322 | self.readline.remove_history_item(histlen-1) |
|
322 | self.readline.remove_history_item(histlen-1) | |
323 | self.readline.replace_history_item(histlen-2, |
|
323 | self.readline.replace_history_item(histlen-2, | |
324 | newhist.encode(self.stdin_encoding)) |
|
324 | newhist.encode(self.stdin_encoding)) | |
325 | except AttributeError: |
|
325 | except AttributeError: | |
326 | pass # re{move,place}_history_item are new in 2.4. |
|
326 | pass # re{move,place}_history_item are new in 2.4. | |
327 | else: |
|
327 | else: | |
328 | self.input_hist_raw.append('%s\n' % line) |
|
328 | self.input_hist_raw.append('%s\n' % line) | |
329 | # only entries starting at first column go to shadow history |
|
329 | # only entries starting at first column go to shadow history | |
330 | if line.lstrip() == line: |
|
330 | if line.lstrip() == line: | |
331 | self.shadowhist.add(line.strip()) |
|
331 | self.shadowhist.add(line.strip()) | |
332 | elif not continue_prompt: |
|
332 | elif not continue_prompt: | |
333 | self.input_hist_raw.append('\n') |
|
333 | self.input_hist_raw.append('\n') | |
334 | try: |
|
334 | try: | |
335 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) |
|
335 | lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt) | |
336 | except: |
|
336 | except: | |
337 | # blanket except, in case a user-defined prefilter crashes, so it |
|
337 | # blanket except, in case a user-defined prefilter crashes, so it | |
338 | # can't take all of ipython with it. |
|
338 | # can't take all of ipython with it. | |
339 | self.showtraceback() |
|
339 | self.showtraceback() | |
340 | return '' |
|
340 | return '' | |
341 | else: |
|
341 | else: | |
342 | return lineout |
|
342 | return lineout | |
343 |
|
343 | |||
344 | # TODO: The following three methods are an early attempt to refactor |
|
344 | # TODO: The following three methods are an early attempt to refactor | |
345 | # the main code execution logic. We don't use them, but they may be |
|
345 | # the main code execution logic. We don't use them, but they may be | |
346 | # helpful when we refactor the code execution logic further. |
|
346 | # helpful when we refactor the code execution logic further. | |
347 | # def interact_prompt(self): |
|
347 | # def interact_prompt(self): | |
348 | # """ Print the prompt (in read-eval-print loop) |
|
348 | # """ Print the prompt (in read-eval-print loop) | |
349 | # |
|
349 | # | |
350 | # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
350 | # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
351 | # used in standard IPython flow. |
|
351 | # used in standard IPython flow. | |
352 | # """ |
|
352 | # """ | |
353 | # if self.more: |
|
353 | # if self.more: | |
354 | # try: |
|
354 | # try: | |
355 | # prompt = self.hooks.generate_prompt(True) |
|
355 | # prompt = self.hooks.generate_prompt(True) | |
356 | # except: |
|
356 | # except: | |
357 | # self.showtraceback() |
|
357 | # self.showtraceback() | |
358 | # if self.autoindent: |
|
358 | # if self.autoindent: | |
359 | # self.rl_do_indent = True |
|
359 | # self.rl_do_indent = True | |
360 | # |
|
360 | # | |
361 | # else: |
|
361 | # else: | |
362 | # try: |
|
362 | # try: | |
363 | # prompt = self.hooks.generate_prompt(False) |
|
363 | # prompt = self.hooks.generate_prompt(False) | |
364 | # except: |
|
364 | # except: | |
365 | # self.showtraceback() |
|
365 | # self.showtraceback() | |
366 | # self.write(prompt) |
|
366 | # self.write(prompt) | |
367 | # |
|
367 | # | |
368 | # def interact_handle_input(self,line): |
|
368 | # def interact_handle_input(self,line): | |
369 | # """ Handle the input line (in read-eval-print loop) |
|
369 | # """ Handle the input line (in read-eval-print loop) | |
370 | # |
|
370 | # | |
371 | # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not |
|
371 | # Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not | |
372 | # used in standard IPython flow. |
|
372 | # used in standard IPython flow. | |
373 | # """ |
|
373 | # """ | |
374 | # if line.lstrip() == line: |
|
374 | # if line.lstrip() == line: | |
375 | # self.shadowhist.add(line.strip()) |
|
375 | # self.shadowhist.add(line.strip()) | |
376 | # lineout = self.prefilter_manager.prefilter_lines(line,self.more) |
|
376 | # lineout = self.prefilter_manager.prefilter_lines(line,self.more) | |
377 | # |
|
377 | # | |
378 | # if line.strip(): |
|
378 | # if line.strip(): | |
379 | # if self.more: |
|
379 | # if self.more: | |
380 | # self.input_hist_raw[-1] += '%s\n' % line |
|
380 | # self.input_hist_raw[-1] += '%s\n' % line | |
381 | # else: |
|
381 | # else: | |
382 | # self.input_hist_raw.append('%s\n' % line) |
|
382 | # self.input_hist_raw.append('%s\n' % line) | |
383 | # |
|
383 | # | |
384 | # |
|
384 | # | |
385 | # self.more = self.push_line(lineout) |
|
385 | # self.more = self.push_line(lineout) | |
386 | # if (self.SyntaxTB.last_syntax_error and |
|
386 | # if (self.SyntaxTB.last_syntax_error and | |
387 | # self.autoedit_syntax): |
|
387 | # self.autoedit_syntax): | |
388 | # self.edit_syntax_error() |
|
388 | # self.edit_syntax_error() | |
389 | # |
|
389 | # | |
390 | # def interact_with_readline(self): |
|
390 | # def interact_with_readline(self): | |
391 | # """ Demo of using interact_handle_input, interact_prompt |
|
391 | # """ Demo of using interact_handle_input, interact_prompt | |
392 | # |
|
392 | # | |
393 | # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), |
|
393 | # This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI), | |
394 | # it should work like this. |
|
394 | # it should work like this. | |
395 | # """ |
|
395 | # """ | |
396 | # self.readline_startup_hook(self.pre_readline) |
|
396 | # self.readline_startup_hook(self.pre_readline) | |
397 | # while not self.exit_now: |
|
397 | # while not self.exit_now: | |
398 | # self.interact_prompt() |
|
398 | # self.interact_prompt() | |
399 | # if self.more: |
|
399 | # if self.more: | |
400 | # self.rl_do_indent = True |
|
400 | # self.rl_do_indent = True | |
401 | # else: |
|
401 | # else: | |
402 | # self.rl_do_indent = False |
|
402 | # self.rl_do_indent = False | |
403 | # line = raw_input_original().decode(self.stdin_encoding) |
|
403 | # line = raw_input_original().decode(self.stdin_encoding) | |
404 | # self.interact_handle_input(line) |
|
404 | # self.interact_handle_input(line) | |
405 |
|
405 | |||
406 | #------------------------------------------------------------------------- |
|
406 | #------------------------------------------------------------------------- | |
407 | # Methods to support auto-editing of SyntaxErrors. |
|
407 | # Methods to support auto-editing of SyntaxErrors. | |
408 | #------------------------------------------------------------------------- |
|
408 | #------------------------------------------------------------------------- | |
409 |
|
409 | |||
410 | def edit_syntax_error(self): |
|
410 | def edit_syntax_error(self): | |
411 | """The bottom half of the syntax error handler called in the main loop. |
|
411 | """The bottom half of the syntax error handler called in the main loop. | |
412 |
|
412 | |||
413 | Loop until syntax error is fixed or user cancels. |
|
413 | Loop until syntax error is fixed or user cancels. | |
414 | """ |
|
414 | """ | |
415 |
|
415 | |||
416 | while self.SyntaxTB.last_syntax_error: |
|
416 | while self.SyntaxTB.last_syntax_error: | |
417 | # copy and clear last_syntax_error |
|
417 | # copy and clear last_syntax_error | |
418 | err = self.SyntaxTB.clear_err_state() |
|
418 | err = self.SyntaxTB.clear_err_state() | |
419 | if not self._should_recompile(err): |
|
419 | if not self._should_recompile(err): | |
420 | return |
|
420 | return | |
421 | try: |
|
421 | try: | |
422 | # may set last_syntax_error again if a SyntaxError is raised |
|
422 | # may set last_syntax_error again if a SyntaxError is raised | |
423 | self.safe_execfile(err.filename,self.user_ns) |
|
423 | self.safe_execfile(err.filename,self.user_ns) | |
424 | except: |
|
424 | except: | |
425 | self.showtraceback() |
|
425 | self.showtraceback() | |
426 | else: |
|
426 | else: | |
427 | try: |
|
427 | try: | |
428 | f = file(err.filename) |
|
428 | f = file(err.filename) | |
429 | try: |
|
429 | try: | |
430 | # This should be inside a display_trap block and I |
|
430 | # This should be inside a display_trap block and I | |
431 | # think it is. |
|
431 | # think it is. | |
432 | sys.displayhook(f.read()) |
|
432 | sys.displayhook(f.read()) | |
433 | finally: |
|
433 | finally: | |
434 | f.close() |
|
434 | f.close() | |
435 | except: |
|
435 | except: | |
436 | self.showtraceback() |
|
436 | self.showtraceback() | |
437 |
|
437 | |||
438 | def _should_recompile(self,e): |
|
438 | def _should_recompile(self,e): | |
439 | """Utility routine for edit_syntax_error""" |
|
439 | """Utility routine for edit_syntax_error""" | |
440 |
|
440 | |||
441 | if e.filename in ('<ipython console>','<input>','<string>', |
|
441 | if e.filename in ('<ipython console>','<input>','<string>', | |
442 | '<console>','<BackgroundJob compilation>', |
|
442 | '<console>','<BackgroundJob compilation>', | |
443 | None): |
|
443 | None): | |
444 |
|
444 | |||
445 | return False |
|
445 | return False | |
446 | try: |
|
446 | try: | |
447 | if (self.autoedit_syntax and |
|
447 | if (self.autoedit_syntax and | |
448 | not self.ask_yes_no('Return to editor to correct syntax error? ' |
|
448 | not self.ask_yes_no('Return to editor to correct syntax error? ' | |
449 | '[Y/n] ','y')): |
|
449 | '[Y/n] ','y')): | |
450 | return False |
|
450 | return False | |
451 | except EOFError: |
|
451 | except EOFError: | |
452 | return False |
|
452 | return False | |
453 |
|
453 | |||
454 | def int0(x): |
|
454 | def int0(x): | |
455 | try: |
|
455 | try: | |
456 | return int(x) |
|
456 | return int(x) | |
457 | except TypeError: |
|
457 | except TypeError: | |
458 | return 0 |
|
458 | return 0 | |
459 | # always pass integer line and offset values to editor hook |
|
459 | # always pass integer line and offset values to editor hook | |
460 | try: |
|
460 | try: | |
461 | self.hooks.fix_error_editor(e.filename, |
|
461 | self.hooks.fix_error_editor(e.filename, | |
462 | int0(e.lineno),int0(e.offset),e.msg) |
|
462 | int0(e.lineno),int0(e.offset),e.msg) | |
463 | except TryNext: |
|
463 | except TryNext: | |
464 | warn('Could not open editor') |
|
464 | warn('Could not open editor') | |
465 | return False |
|
465 | return False | |
466 | return True |
|
466 | return True | |
467 |
|
467 | |||
468 | #------------------------------------------------------------------------- |
|
468 | #------------------------------------------------------------------------- | |
469 | # Things related to GUI support and pylab |
|
469 | # Things related to GUI support and pylab | |
470 | #------------------------------------------------------------------------- |
|
470 | #------------------------------------------------------------------------- | |
471 |
|
471 | |||
472 | def enable_pylab(self, gui=None): |
|
472 | def enable_pylab(self, gui=None): | |
473 | """Activate pylab support at runtime. |
|
473 | """Activate pylab support at runtime. | |
474 |
|
474 | |||
475 | This turns on support for matplotlib, preloads into the interactive |
|
475 | This turns on support for matplotlib, preloads into the interactive | |
476 | namespace all of numpy and pylab, and configures IPython to correcdtly |
|
476 | namespace all of numpy and pylab, and configures IPython to correcdtly | |
477 | interact with the GUI event loop. The GUI backend to be used can be |
|
477 | interact with the GUI event loop. The GUI backend to be used can be | |
478 | optionally selected with the optional :param:`gui` argument. |
|
478 | optionally selected with the optional :param:`gui` argument. | |
479 |
|
479 | |||
480 | Parameters |
|
480 | Parameters | |
481 | ---------- |
|
481 | ---------- | |
482 | gui : optional, string |
|
482 | gui : optional, string | |
483 |
|
483 | |||
484 | If given, dictates the choice of matplotlib GUI backend to use |
|
484 | If given, dictates the choice of matplotlib GUI backend to use | |
485 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or |
|
485 | (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or | |
486 | 'gtk'), otherwise we use the default chosen by matplotlib (as |
|
486 | 'gtk'), otherwise we use the default chosen by matplotlib (as | |
487 | dictated by the matplotlib build-time options plus the user's |
|
487 | dictated by the matplotlib build-time options plus the user's | |
488 | matplotlibrc configuration file). |
|
488 | matplotlibrc configuration file). | |
489 | """ |
|
489 | """ | |
490 | # We want to prevent the loading of pylab to pollute the user's |
|
490 | # We want to prevent the loading of pylab to pollute the user's | |
491 | # namespace as shown by the %who* magics, so we execute the activation |
|
491 | # namespace as shown by the %who* magics, so we execute the activation | |
492 | # code in an empty namespace, and we update *both* user_ns and |
|
492 | # code in an empty namespace, and we update *both* user_ns and | |
493 | # user_ns_hidden with this information. |
|
493 | # user_ns_hidden with this information. | |
494 | ns = {} |
|
494 | ns = {} | |
495 | gui = pylab_activate(ns, gui) |
|
495 | gui = pylab_activate(ns, gui) | |
496 | self.user_ns.update(ns) |
|
496 | self.user_ns.update(ns) | |
497 | self.user_ns_hidden.update(ns) |
|
497 | self.user_ns_hidden.update(ns) | |
498 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
498 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
499 | # plot updates into account |
|
499 | # plot updates into account | |
500 | enable_gui(gui) |
|
500 | enable_gui(gui) | |
501 | self.magic_run = self._pylab_magic_run |
|
501 | self.magic_run = self._pylab_magic_run | |
502 |
|
502 | |||
503 | #------------------------------------------------------------------------- |
|
503 | #------------------------------------------------------------------------- | |
504 | # Things related to exiting |
|
504 | # Things related to exiting | |
505 | #------------------------------------------------------------------------- |
|
505 | #------------------------------------------------------------------------- | |
506 |
|
506 | |||
507 | def ask_exit(self): |
|
507 | def ask_exit(self): | |
508 | """ Ask the shell to exit. Can be overiden and used as a callback. """ |
|
508 | """ Ask the shell to exit. Can be overiden and used as a callback. """ | |
509 | self.exit_now = True |
|
509 | self.exit_now = True | |
510 |
|
510 | |||
511 | def exit(self): |
|
511 | def exit(self): | |
512 | """Handle interactive exit. |
|
512 | """Handle interactive exit. | |
513 |
|
513 | |||
514 | This method calls the ask_exit callback.""" |
|
514 | This method calls the ask_exit callback.""" | |
515 | if self.confirm_exit: |
|
515 | if self.confirm_exit: | |
516 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): |
|
516 | if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'): | |
517 | self.ask_exit() |
|
517 | self.ask_exit() | |
518 | else: |
|
518 | else: | |
519 | self.ask_exit() |
|
519 | self.ask_exit() | |
520 |
|
520 | |||
|
521 | #------------------------------------------------------------------------ | |||
|
522 | # Magic overrides | |||
|
523 | #------------------------------------------------------------------------ | |||
|
524 | # Once the base class stops inheriting from magic, this code needs to be | |||
|
525 | # moved into a separate machinery as well. For now, at least isolate here | |||
|
526 | # the magics which this class needs to implement differently from the base | |||
|
527 | # class, or that are unique to it. | |||
|
528 | ||||
|
529 | def magic_autoindent(self, parameter_s = ''): | |||
|
530 | """Toggle autoindent on/off (if available).""" | |||
|
531 | ||||
|
532 | self.shell.set_autoindent() | |||
|
533 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |||
|
534 | ||||
|
535 | def magic_cpaste(self, parameter_s=''): | |||
|
536 | """Paste & execute a pre-formatted code block from clipboard. | |||
|
537 | ||||
|
538 | You must terminate the block with '--' (two minus-signs) alone on the | |||
|
539 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |||
|
540 | is the new sentinel for this operation) | |||
|
541 | ||||
|
542 | The block is dedented prior to execution to enable execution of method | |||
|
543 | definitions. '>' and '+' characters at the beginning of a line are | |||
|
544 | ignored, to allow pasting directly from e-mails, diff files and | |||
|
545 | doctests (the '...' continuation prompt is also stripped). The | |||
|
546 | executed block is also assigned to variable named 'pasted_block' for | |||
|
547 | later editing with '%edit pasted_block'. | |||
|
548 | ||||
|
549 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |||
|
550 | This assigns the pasted block to variable 'foo' as string, without | |||
|
551 | dedenting or executing it (preceding >>> and + is still stripped) | |||
|
552 | ||||
|
553 | '%cpaste -r' re-executes the block previously entered by cpaste. | |||
|
554 | ||||
|
555 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |||
|
556 | Just press enter and type -- (and press enter again) and the block | |||
|
557 | will be what was just pasted. | |||
|
558 | ||||
|
559 | IPython statements (magics, shell escapes) are not supported (yet). | |||
|
560 | ||||
|
561 | See also | |||
|
562 | -------- | |||
|
563 | paste: automatically pull code from clipboard. | |||
|
564 | """ | |||
|
565 | ||||
|
566 | opts,args = self.parse_options(parameter_s,'rs:',mode='string') | |||
|
567 | par = args.strip() | |||
|
568 | if opts.has_key('r'): | |||
|
569 | self._rerun_pasted() | |||
|
570 | return | |||
|
571 | ||||
|
572 | sentinel = opts.get('s','--') | |||
|
573 | ||||
|
574 | block = self._strip_pasted_lines_for_code( | |||
|
575 | self._get_pasted_lines(sentinel)) | |||
|
576 | ||||
|
577 | self._execute_block(block, par) | |||
|
578 | ||||
|
579 | def magic_paste(self, parameter_s=''): | |||
|
580 | """Paste & execute a pre-formatted code block from clipboard. | |||
|
581 | ||||
|
582 | The text is pulled directly from the clipboard without user | |||
|
583 | intervention and printed back on the screen before execution (unless | |||
|
584 | the -q flag is given to force quiet mode). | |||
|
585 | ||||
|
586 | The block is dedented prior to execution to enable execution of method | |||
|
587 | definitions. '>' and '+' characters at the beginning of a line are | |||
|
588 | ignored, to allow pasting directly from e-mails, diff files and | |||
|
589 | doctests (the '...' continuation prompt is also stripped). The | |||
|
590 | executed block is also assigned to variable named 'pasted_block' for | |||
|
591 | later editing with '%edit pasted_block'. | |||
|
592 | ||||
|
593 | You can also pass a variable name as an argument, e.g. '%paste foo'. | |||
|
594 | This assigns the pasted block to variable 'foo' as string, without | |||
|
595 | dedenting or executing it (preceding >>> and + is still stripped) | |||
|
596 | ||||
|
597 | Options | |||
|
598 | ------- | |||
|
599 | ||||
|
600 | -r: re-executes the block previously entered by cpaste. | |||
|
601 | ||||
|
602 | -q: quiet mode: do not echo the pasted text back to the terminal. | |||
|
603 | ||||
|
604 | IPython statements (magics, shell escapes) are not supported (yet). | |||
|
605 | ||||
|
606 | See also | |||
|
607 | -------- | |||
|
608 | cpaste: manually paste code into terminal until you mark its end. | |||
|
609 | """ | |||
|
610 | opts,args = self.parse_options(parameter_s,'rq',mode='string') | |||
|
611 | par = args.strip() | |||
|
612 | if opts.has_key('r'): | |||
|
613 | self._rerun_pasted() | |||
|
614 | return | |||
|
615 | ||||
|
616 | text = self.shell.hooks.clipboard_get() | |||
|
617 | block = self._strip_pasted_lines_for_code(text.splitlines()) | |||
|
618 | ||||
|
619 | # By default, echo back to terminal unless quiet mode is requested | |||
|
620 | if not opts.has_key('q'): | |||
|
621 | write = self.shell.write | |||
|
622 | write(self.shell.pycolorize(block)) | |||
|
623 | if not block.endswith('\n'): | |||
|
624 | write('\n') | |||
|
625 | write("## -- End pasted text --\n") | |||
|
626 | ||||
|
627 | self._execute_block(block, par) | |||
|
628 | ||||
521 |
|
629 | |||
522 | InteractiveShellABC.register(TerminalInteractiveShell) |
|
630 | InteractiveShellABC.register(TerminalInteractiveShell) |
@@ -1,477 +1,489 b'' | |||||
1 | """A ZMQ-based subclass of InteractiveShell. |
|
1 | """A ZMQ-based subclass of InteractiveShell. | |
2 |
|
2 | |||
3 | This code is meant to ease the refactoring of the base InteractiveShell into |
|
3 | This code is meant to ease the refactoring of the base InteractiveShell into | |
4 | something with a cleaner architecture for 2-process use, without actually |
|
4 | something with a cleaner architecture for 2-process use, without actually | |
5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where |
|
5 | breaking InteractiveShell itself. So we're doing something a bit ugly, where | |
6 | we subclass and override what we want to fix. Once this is working well, we |
|
6 | we subclass and override what we want to fix. Once this is working well, we | |
7 | can go back to the base class and refactor the code for a cleaner inheritance |
|
7 | can go back to the base class and refactor the code for a cleaner inheritance | |
8 | implementation that doesn't rely on so much monkeypatching. |
|
8 | implementation that doesn't rely on so much monkeypatching. | |
9 |
|
9 | |||
10 | But this lets us maintain a fully working IPython as we develop the new |
|
10 | But this lets us maintain a fully working IPython as we develop the new | |
11 | machinery. This should thus be thought of as scaffolding. |
|
11 | machinery. This should thus be thought of as scaffolding. | |
12 | """ |
|
12 | """ | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | from __future__ import print_function |
|
16 | from __future__ import print_function | |
17 |
|
17 | |||
18 | # Stdlib |
|
18 | # Stdlib | |
19 | import inspect |
|
19 | import inspect | |
20 | import os |
|
20 | import os | |
21 | import re |
|
21 | import re | |
22 |
|
22 | |||
23 | # Our own |
|
23 | # Our own | |
24 | from IPython.core.interactiveshell import ( |
|
24 | from IPython.core.interactiveshell import ( | |
25 | InteractiveShell, InteractiveShellABC |
|
25 | InteractiveShell, InteractiveShellABC | |
26 | ) |
|
26 | ) | |
27 | from IPython.core.displayhook import DisplayHook |
|
27 | from IPython.core.displayhook import DisplayHook | |
28 | from IPython.core.macro import Macro |
|
28 | from IPython.core.macro import Macro | |
29 | from IPython.core.payloadpage import install_payload_page |
|
29 | from IPython.core.payloadpage import install_payload_page | |
30 | from IPython.utils import io |
|
30 | from IPython.utils import io | |
31 | from IPython.utils.path import get_py_filename |
|
31 | from IPython.utils.path import get_py_filename | |
32 | from IPython.utils.text import StringTypes |
|
32 | from IPython.utils.text import StringTypes | |
33 | from IPython.utils.traitlets import Instance, Type, Dict |
|
33 | from IPython.utils.traitlets import Instance, Type, Dict | |
34 | from IPython.utils.warn import warn |
|
34 | from IPython.utils.warn import warn | |
35 | from IPython.zmq.session import extract_header |
|
35 | from IPython.zmq.session import extract_header | |
36 | from session import Session |
|
36 | from session import Session | |
37 |
|
37 | |||
38 | #----------------------------------------------------------------------------- |
|
38 | #----------------------------------------------------------------------------- | |
39 | # Globals and side-effects |
|
39 | # Globals and side-effects | |
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 |
|
41 | |||
42 | # Install the payload version of page. |
|
42 | # Install the payload version of page. | |
43 | install_payload_page() |
|
43 | install_payload_page() | |
44 |
|
44 | |||
45 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
46 | # Functions and classes |
|
46 | # Functions and classes | |
47 | #----------------------------------------------------------------------------- |
|
47 | #----------------------------------------------------------------------------- | |
48 |
|
48 | |||
49 | class ZMQDisplayHook(DisplayHook): |
|
49 | class ZMQDisplayHook(DisplayHook): | |
50 |
|
50 | |||
51 | session = Instance(Session) |
|
51 | session = Instance(Session) | |
52 | pub_socket = Instance('zmq.Socket') |
|
52 | pub_socket = Instance('zmq.Socket') | |
53 | parent_header = Dict({}) |
|
53 | parent_header = Dict({}) | |
54 |
|
54 | |||
55 | def set_parent(self, parent): |
|
55 | def set_parent(self, parent): | |
56 | """Set the parent for outbound messages.""" |
|
56 | """Set the parent for outbound messages.""" | |
57 | self.parent_header = extract_header(parent) |
|
57 | self.parent_header = extract_header(parent) | |
58 |
|
58 | |||
59 | def start_displayhook(self): |
|
59 | def start_displayhook(self): | |
60 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) |
|
60 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) | |
61 |
|
61 | |||
62 | def write_output_prompt(self): |
|
62 | def write_output_prompt(self): | |
63 | """Write the output prompt.""" |
|
63 | """Write the output prompt.""" | |
64 | if self.do_full_cache: |
|
64 | if self.do_full_cache: | |
65 | self.msg['content']['execution_count'] = self.prompt_count |
|
65 | self.msg['content']['execution_count'] = self.prompt_count | |
66 |
|
66 | |||
67 | def write_result_repr(self, result_repr): |
|
67 | def write_result_repr(self, result_repr): | |
68 | self.msg['content']['data'] = result_repr |
|
68 | self.msg['content']['data'] = result_repr | |
69 |
|
69 | |||
70 | def finish_displayhook(self): |
|
70 | def finish_displayhook(self): | |
71 | """Finish up all displayhook activities.""" |
|
71 | """Finish up all displayhook activities.""" | |
72 | self.pub_socket.send_json(self.msg) |
|
72 | self.pub_socket.send_json(self.msg) | |
73 | self.msg = None |
|
73 | self.msg = None | |
74 |
|
74 | |||
75 |
|
75 | |||
76 | class ZMQInteractiveShell(InteractiveShell): |
|
76 | class ZMQInteractiveShell(InteractiveShell): | |
77 | """A subclass of InteractiveShell for ZMQ.""" |
|
77 | """A subclass of InteractiveShell for ZMQ.""" | |
78 |
|
78 | |||
79 | displayhook_class = Type(ZMQDisplayHook) |
|
79 | displayhook_class = Type(ZMQDisplayHook) | |
80 |
|
80 | |||
|
81 | ||||
|
82 | def auto_rewrite_input(self, cmd): | |||
|
83 | """Called to show the auto-rewritten input for autocall and friends. | |||
|
84 | ||||
|
85 | FIXME: this payload is currently not correctly processed by the | |||
|
86 | frontend. | |||
|
87 | """ | |||
|
88 | new = self.displayhook.prompt1.auto_rewrite() + cmd | |||
|
89 | payload = dict( | |||
|
90 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', | |||
|
91 | transformed_input=new, | |||
|
92 | ) | |||
|
93 | self.payload_manager.write_payload(payload) | |||
|
94 | ||||
|
95 | def ask_exit(self): | |||
|
96 | """Engage the exit actions.""" | |||
|
97 | payload = dict( | |||
|
98 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', | |||
|
99 | exit=True, | |||
|
100 | ) | |||
|
101 | self.payload_manager.write_payload(payload) | |||
|
102 | ||||
|
103 | def _showtraceback(self, etype, evalue, stb): | |||
|
104 | ||||
|
105 | exc_content = { | |||
|
106 | u'traceback' : stb, | |||
|
107 | u'ename' : unicode(etype.__name__), | |||
|
108 | u'evalue' : unicode(evalue) | |||
|
109 | } | |||
|
110 | ||||
|
111 | dh = self.displayhook | |||
|
112 | exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header) | |||
|
113 | # Send exception info over pub socket for other clients than the caller | |||
|
114 | # to pick up | |||
|
115 | dh.pub_socket.send_json(exc_msg) | |||
|
116 | ||||
|
117 | # FIXME - Hack: store exception info in shell object. Right now, the | |||
|
118 | # caller is reading this info after the fact, we need to fix this logic | |||
|
119 | # to remove this hack. Even uglier, we need to store the error status | |||
|
120 | # here, because in the main loop, the logic that sets it is being | |||
|
121 | # skipped because runlines swallows the exceptions. | |||
|
122 | exc_content[u'status'] = u'error' | |||
|
123 | self._reply_content = exc_content | |||
|
124 | # /FIXME | |||
|
125 | ||||
|
126 | return exc_content | |||
|
127 | ||||
|
128 | #------------------------------------------------------------------------ | |||
|
129 | # Magic overrides | |||
|
130 | #------------------------------------------------------------------------ | |||
|
131 | # Once the base class stops inheriting from magic, this code needs to be | |||
|
132 | # moved into a separate machinery as well. For now, at least isolate here | |||
|
133 | # the magics which this class needs to implement differently from the base | |||
|
134 | # class, or that are unique to it. | |||
|
135 | ||||
81 | def magic_doctest_mode(self,parameter_s=''): |
|
136 | def magic_doctest_mode(self,parameter_s=''): | |
82 | """Toggle doctest mode on and off. |
|
137 | """Toggle doctest mode on and off. | |
83 |
|
138 | |||
84 | This mode is intended to make IPython behave as much as possible like a |
|
139 | This mode is intended to make IPython behave as much as possible like a | |
85 | plain Python shell, from the perspective of how its prompts, exceptions |
|
140 | plain Python shell, from the perspective of how its prompts, exceptions | |
86 | and output look. This makes it easy to copy and paste parts of a |
|
141 | and output look. This makes it easy to copy and paste parts of a | |
87 | session into doctests. It does so by: |
|
142 | session into doctests. It does so by: | |
88 |
|
143 | |||
89 | - Changing the prompts to the classic ``>>>`` ones. |
|
144 | - Changing the prompts to the classic ``>>>`` ones. | |
90 | - Changing the exception reporting mode to 'Plain'. |
|
145 | - Changing the exception reporting mode to 'Plain'. | |
91 | - Disabling pretty-printing of output. |
|
146 | - Disabling pretty-printing of output. | |
92 |
|
147 | |||
93 | Note that IPython also supports the pasting of code snippets that have |
|
148 | Note that IPython also supports the pasting of code snippets that have | |
94 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
149 | leading '>>>' and '...' prompts in them. This means that you can paste | |
95 | doctests from files or docstrings (even if they have leading |
|
150 | doctests from files or docstrings (even if they have leading | |
96 | whitespace), and the code will execute correctly. You can then use |
|
151 | whitespace), and the code will execute correctly. You can then use | |
97 | '%history -t' to see the translated history; this will give you the |
|
152 | '%history -t' to see the translated history; this will give you the | |
98 | input after removal of all the leading prompts and whitespace, which |
|
153 | input after removal of all the leading prompts and whitespace, which | |
99 | can be pasted back into an editor. |
|
154 | can be pasted back into an editor. | |
100 |
|
155 | |||
101 | With these features, you can switch into this mode easily whenever you |
|
156 | With these features, you can switch into this mode easily whenever you | |
102 | need to do testing and changes to doctests, without having to leave |
|
157 | need to do testing and changes to doctests, without having to leave | |
103 | your existing IPython session. |
|
158 | your existing IPython session. | |
104 | """ |
|
159 | """ | |
105 |
|
160 | |||
106 | from IPython.utils.ipstruct import Struct |
|
161 | from IPython.utils.ipstruct import Struct | |
107 |
|
162 | |||
108 | # Shorthands |
|
163 | # Shorthands | |
109 | shell = self.shell |
|
164 | shell = self.shell | |
110 | # dstore is a data store kept in the instance metadata bag to track any |
|
165 | # dstore is a data store kept in the instance metadata bag to track any | |
111 | # changes we make, so we can undo them later. |
|
166 | # changes we make, so we can undo them later. | |
112 | dstore = shell.meta.setdefault('doctest_mode', Struct()) |
|
167 | dstore = shell.meta.setdefault('doctest_mode', Struct()) | |
113 | save_dstore = dstore.setdefault |
|
168 | save_dstore = dstore.setdefault | |
114 |
|
169 | |||
115 | # save a few values we'll need to recover later |
|
170 | # save a few values we'll need to recover later | |
116 | mode = save_dstore('mode', False) |
|
171 | mode = save_dstore('mode', False) | |
117 | save_dstore('rc_pprint', shell.pprint) |
|
172 | save_dstore('rc_pprint', shell.pprint) | |
118 | save_dstore('xmode', shell.InteractiveTB.mode) |
|
173 | save_dstore('xmode', shell.InteractiveTB.mode) | |
119 |
|
174 | |||
120 | if mode == False: |
|
175 | if mode == False: | |
121 | # turn on |
|
176 | # turn on | |
122 | shell.pprint = False |
|
177 | shell.pprint = False | |
123 | shell.magic_xmode('Plain') |
|
178 | shell.magic_xmode('Plain') | |
124 | else: |
|
179 | else: | |
125 | # turn off |
|
180 | # turn off | |
126 | shell.pprint = dstore.rc_pprint |
|
181 | shell.pprint = dstore.rc_pprint | |
127 | shell.magic_xmode(dstore.xmode) |
|
182 | shell.magic_xmode(dstore.xmode) | |
128 |
|
183 | |||
129 | # Store new mode and inform on console |
|
184 | # Store new mode and inform on console | |
130 | dstore.mode = bool(1-int(mode)) |
|
185 | dstore.mode = bool(1-int(mode)) | |
131 | mode_label = ['OFF','ON'][dstore.mode] |
|
186 | mode_label = ['OFF','ON'][dstore.mode] | |
132 | print('Doctest mode is:', mode_label) |
|
187 | print('Doctest mode is:', mode_label) | |
133 |
|
188 | |||
134 | # Send the payload back so that clients can modify their prompt display |
|
189 | # Send the payload back so that clients can modify their prompt display | |
135 | payload = dict( |
|
190 | payload = dict( | |
136 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode', |
|
191 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode', | |
137 | mode=dstore.mode) |
|
192 | mode=dstore.mode) | |
138 | self.payload_manager.write_payload(payload) |
|
193 | self.payload_manager.write_payload(payload) | |
139 |
|
194 | |||
140 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
195 | def magic_edit(self,parameter_s='',last_call=['','']): | |
141 | """Bring up an editor and execute the resulting code. |
|
196 | """Bring up an editor and execute the resulting code. | |
142 |
|
197 | |||
143 | Usage: |
|
198 | Usage: | |
144 | %edit [options] [args] |
|
199 | %edit [options] [args] | |
145 |
|
200 | |||
146 | %edit runs IPython's editor hook. The default version of this hook is |
|
201 | %edit runs IPython's editor hook. The default version of this hook is | |
147 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
202 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
148 | environment variable $EDITOR. If this isn't found, it will default to |
|
203 | environment variable $EDITOR. If this isn't found, it will default to | |
149 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
204 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
150 | docstring for how to change the editor hook. |
|
205 | docstring for how to change the editor hook. | |
151 |
|
206 | |||
152 | You can also set the value of this editor via the command line option |
|
207 | You can also set the value of this editor via the command line option | |
153 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
208 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
154 | specifically for IPython an editor different from your typical default |
|
209 | specifically for IPython an editor different from your typical default | |
155 | (and for Windows users who typically don't set environment variables). |
|
210 | (and for Windows users who typically don't set environment variables). | |
156 |
|
211 | |||
157 | This command allows you to conveniently edit multi-line code right in |
|
212 | This command allows you to conveniently edit multi-line code right in | |
158 | your IPython session. |
|
213 | your IPython session. | |
159 |
|
214 | |||
160 | If called without arguments, %edit opens up an empty editor with a |
|
215 | If called without arguments, %edit opens up an empty editor with a | |
161 | temporary file and will execute the contents of this file when you |
|
216 | temporary file and will execute the contents of this file when you | |
162 | close it (don't forget to save it!). |
|
217 | close it (don't forget to save it!). | |
163 |
|
218 | |||
164 |
|
219 | |||
165 | Options: |
|
220 | Options: | |
166 |
|
221 | |||
167 | -n <number>: open the editor at a specified line number. By default, |
|
222 | -n <number>: open the editor at a specified line number. By default, | |
168 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
223 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
169 | you can configure this by providing your own modified hook if your |
|
224 | you can configure this by providing your own modified hook if your | |
170 | favorite editor supports line-number specifications with a different |
|
225 | favorite editor supports line-number specifications with a different | |
171 | syntax. |
|
226 | syntax. | |
172 |
|
227 | |||
173 | -p: this will call the editor with the same data as the previous time |
|
228 | -p: this will call the editor with the same data as the previous time | |
174 | it was used, regardless of how long ago (in your current session) it |
|
229 | it was used, regardless of how long ago (in your current session) it | |
175 | was. |
|
230 | was. | |
176 |
|
231 | |||
177 | -r: use 'raw' input. This option only applies to input taken from the |
|
232 | -r: use 'raw' input. This option only applies to input taken from the | |
178 | user's history. By default, the 'processed' history is used, so that |
|
233 | user's history. By default, the 'processed' history is used, so that | |
179 | magics are loaded in their transformed version to valid Python. If |
|
234 | magics are loaded in their transformed version to valid Python. If | |
180 | this option is given, the raw input as typed as the command line is |
|
235 | this option is given, the raw input as typed as the command line is | |
181 | used instead. When you exit the editor, it will be executed by |
|
236 | used instead. When you exit the editor, it will be executed by | |
182 | IPython's own processor. |
|
237 | IPython's own processor. | |
183 |
|
238 | |||
184 | -x: do not execute the edited code immediately upon exit. This is |
|
239 | -x: do not execute the edited code immediately upon exit. This is | |
185 | mainly useful if you are editing programs which need to be called with |
|
240 | mainly useful if you are editing programs which need to be called with | |
186 | command line arguments, which you can then do using %run. |
|
241 | command line arguments, which you can then do using %run. | |
187 |
|
242 | |||
188 |
|
243 | |||
189 | Arguments: |
|
244 | Arguments: | |
190 |
|
245 | |||
191 | If arguments are given, the following possibilites exist: |
|
246 | If arguments are given, the following possibilites exist: | |
192 |
|
247 | |||
193 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
248 | - The arguments are numbers or pairs of colon-separated numbers (like | |
194 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
249 | 1 4:8 9). These are interpreted as lines of previous input to be | |
195 | loaded into the editor. The syntax is the same of the %macro command. |
|
250 | loaded into the editor. The syntax is the same of the %macro command. | |
196 |
|
251 | |||
197 | - If the argument doesn't start with a number, it is evaluated as a |
|
252 | - If the argument doesn't start with a number, it is evaluated as a | |
198 | variable and its contents loaded into the editor. You can thus edit |
|
253 | variable and its contents loaded into the editor. You can thus edit | |
199 | any string which contains python code (including the result of |
|
254 | any string which contains python code (including the result of | |
200 | previous edits). |
|
255 | previous edits). | |
201 |
|
256 | |||
202 | - If the argument is the name of an object (other than a string), |
|
257 | - If the argument is the name of an object (other than a string), | |
203 | IPython will try to locate the file where it was defined and open the |
|
258 | IPython will try to locate the file where it was defined and open the | |
204 | editor at the point where it is defined. You can use `%edit function` |
|
259 | editor at the point where it is defined. You can use `%edit function` | |
205 | to load an editor exactly at the point where 'function' is defined, |
|
260 | to load an editor exactly at the point where 'function' is defined, | |
206 | edit it and have the file be executed automatically. |
|
261 | edit it and have the file be executed automatically. | |
207 |
|
262 | |||
208 | If the object is a macro (see %macro for details), this opens up your |
|
263 | If the object is a macro (see %macro for details), this opens up your | |
209 | specified editor with a temporary file containing the macro's data. |
|
264 | specified editor with a temporary file containing the macro's data. | |
210 | Upon exit, the macro is reloaded with the contents of the file. |
|
265 | Upon exit, the macro is reloaded with the contents of the file. | |
211 |
|
266 | |||
212 | Note: opening at an exact line is only supported under Unix, and some |
|
267 | Note: opening at an exact line is only supported under Unix, and some | |
213 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
268 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
214 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
269 | '+NUMBER' parameter necessary for this feature. Good editors like | |
215 | (X)Emacs, vi, jed, pico and joe all do. |
|
270 | (X)Emacs, vi, jed, pico and joe all do. | |
216 |
|
271 | |||
217 | - If the argument is not found as a variable, IPython will look for a |
|
272 | - If the argument is not found as a variable, IPython will look for a | |
218 | file with that name (adding .py if necessary) and load it into the |
|
273 | file with that name (adding .py if necessary) and load it into the | |
219 | editor. It will execute its contents with execfile() when you exit, |
|
274 | editor. It will execute its contents with execfile() when you exit, | |
220 | loading any code in the file into your interactive namespace. |
|
275 | loading any code in the file into your interactive namespace. | |
221 |
|
276 | |||
222 | After executing your code, %edit will return as output the code you |
|
277 | After executing your code, %edit will return as output the code you | |
223 | typed in the editor (except when it was an existing file). This way |
|
278 | typed in the editor (except when it was an existing file). This way | |
224 | you can reload the code in further invocations of %edit as a variable, |
|
279 | you can reload the code in further invocations of %edit as a variable, | |
225 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
280 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
226 | the output. |
|
281 | the output. | |
227 |
|
282 | |||
228 | Note that %edit is also available through the alias %ed. |
|
283 | Note that %edit is also available through the alias %ed. | |
229 |
|
284 | |||
230 | This is an example of creating a simple function inside the editor and |
|
285 | This is an example of creating a simple function inside the editor and | |
231 | then modifying it. First, start up the editor: |
|
286 | then modifying it. First, start up the editor: | |
232 |
|
287 | |||
233 | In [1]: ed |
|
288 | In [1]: ed | |
234 | Editing... done. Executing edited code... |
|
289 | Editing... done. Executing edited code... | |
235 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
290 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
236 |
|
291 | |||
237 | We can then call the function foo(): |
|
292 | We can then call the function foo(): | |
238 |
|
293 | |||
239 | In [2]: foo() |
|
294 | In [2]: foo() | |
240 | foo() was defined in an editing session |
|
295 | foo() was defined in an editing session | |
241 |
|
296 | |||
242 | Now we edit foo. IPython automatically loads the editor with the |
|
297 | Now we edit foo. IPython automatically loads the editor with the | |
243 | (temporary) file where foo() was previously defined: |
|
298 | (temporary) file where foo() was previously defined: | |
244 |
|
299 | |||
245 | In [3]: ed foo |
|
300 | In [3]: ed foo | |
246 | Editing... done. Executing edited code... |
|
301 | Editing... done. Executing edited code... | |
247 |
|
302 | |||
248 | And if we call foo() again we get the modified version: |
|
303 | And if we call foo() again we get the modified version: | |
249 |
|
304 | |||
250 | In [4]: foo() |
|
305 | In [4]: foo() | |
251 | foo() has now been changed! |
|
306 | foo() has now been changed! | |
252 |
|
307 | |||
253 | Here is an example of how to edit a code snippet successive |
|
308 | Here is an example of how to edit a code snippet successive | |
254 | times. First we call the editor: |
|
309 | times. First we call the editor: | |
255 |
|
310 | |||
256 | In [5]: ed |
|
311 | In [5]: ed | |
257 | Editing... done. Executing edited code... |
|
312 | Editing... done. Executing edited code... | |
258 | hello |
|
313 | hello | |
259 | Out[5]: "print 'hello'n" |
|
314 | Out[5]: "print 'hello'n" | |
260 |
|
315 | |||
261 | Now we call it again with the previous output (stored in _): |
|
316 | Now we call it again with the previous output (stored in _): | |
262 |
|
317 | |||
263 | In [6]: ed _ |
|
318 | In [6]: ed _ | |
264 | Editing... done. Executing edited code... |
|
319 | Editing... done. Executing edited code... | |
265 | hello world |
|
320 | hello world | |
266 | Out[6]: "print 'hello world'n" |
|
321 | Out[6]: "print 'hello world'n" | |
267 |
|
322 | |||
268 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
323 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
269 |
|
324 | |||
270 | In [7]: ed _8 |
|
325 | In [7]: ed _8 | |
271 | Editing... done. Executing edited code... |
|
326 | Editing... done. Executing edited code... | |
272 | hello again |
|
327 | hello again | |
273 | Out[7]: "print 'hello again'n" |
|
328 | Out[7]: "print 'hello again'n" | |
274 |
|
329 | |||
275 |
|
330 | |||
276 | Changing the default editor hook: |
|
331 | Changing the default editor hook: | |
277 |
|
332 | |||
278 | If you wish to write your own editor hook, you can put it in a |
|
333 | If you wish to write your own editor hook, you can put it in a | |
279 | configuration file which you load at startup time. The default hook |
|
334 | configuration file which you load at startup time. The default hook | |
280 | is defined in the IPython.core.hooks module, and you can use that as a |
|
335 | is defined in the IPython.core.hooks module, and you can use that as a | |
281 | starting example for further modifications. That file also has |
|
336 | starting example for further modifications. That file also has | |
282 | general instructions on how to set a new hook for use once you've |
|
337 | general instructions on how to set a new hook for use once you've | |
283 | defined it.""" |
|
338 | defined it.""" | |
284 |
|
339 | |||
285 | # FIXME: This function has become a convoluted mess. It needs a |
|
340 | # FIXME: This function has become a convoluted mess. It needs a | |
286 | # ground-up rewrite with clean, simple logic. |
|
341 | # ground-up rewrite with clean, simple logic. | |
287 |
|
342 | |||
288 | def make_filename(arg): |
|
343 | def make_filename(arg): | |
289 | "Make a filename from the given args" |
|
344 | "Make a filename from the given args" | |
290 | try: |
|
345 | try: | |
291 | filename = get_py_filename(arg) |
|
346 | filename = get_py_filename(arg) | |
292 | except IOError: |
|
347 | except IOError: | |
293 | if args.endswith('.py'): |
|
348 | if args.endswith('.py'): | |
294 | filename = arg |
|
349 | filename = arg | |
295 | else: |
|
350 | else: | |
296 | filename = None |
|
351 | filename = None | |
297 | return filename |
|
352 | return filename | |
298 |
|
353 | |||
299 | # custom exceptions |
|
354 | # custom exceptions | |
300 | class DataIsObject(Exception): pass |
|
355 | class DataIsObject(Exception): pass | |
301 |
|
356 | |||
302 | opts,args = self.parse_options(parameter_s,'prn:') |
|
357 | opts,args = self.parse_options(parameter_s,'prn:') | |
303 | # Set a few locals from the options for convenience: |
|
358 | # Set a few locals from the options for convenience: | |
304 | opts_p = opts.has_key('p') |
|
359 | opts_p = opts.has_key('p') | |
305 | opts_r = opts.has_key('r') |
|
360 | opts_r = opts.has_key('r') | |
306 |
|
361 | |||
307 | # Default line number value |
|
362 | # Default line number value | |
308 | lineno = opts.get('n',None) |
|
363 | lineno = opts.get('n',None) | |
309 | if lineno is not None: |
|
364 | if lineno is not None: | |
310 | try: |
|
365 | try: | |
311 | lineno = int(lineno) |
|
366 | lineno = int(lineno) | |
312 | except: |
|
367 | except: | |
313 | warn("The -n argument must be an integer.") |
|
368 | warn("The -n argument must be an integer.") | |
314 | return |
|
369 | return | |
315 |
|
370 | |||
316 | if opts_p: |
|
371 | if opts_p: | |
317 | args = '_%s' % last_call[0] |
|
372 | args = '_%s' % last_call[0] | |
318 | if not self.shell.user_ns.has_key(args): |
|
373 | if not self.shell.user_ns.has_key(args): | |
319 | args = last_call[1] |
|
374 | args = last_call[1] | |
320 |
|
375 | |||
321 | # use last_call to remember the state of the previous call, but don't |
|
376 | # use last_call to remember the state of the previous call, but don't | |
322 | # let it be clobbered by successive '-p' calls. |
|
377 | # let it be clobbered by successive '-p' calls. | |
323 | try: |
|
378 | try: | |
324 | last_call[0] = self.shell.displayhook.prompt_count |
|
379 | last_call[0] = self.shell.displayhook.prompt_count | |
325 | if not opts_p: |
|
380 | if not opts_p: | |
326 | last_call[1] = parameter_s |
|
381 | last_call[1] = parameter_s | |
327 | except: |
|
382 | except: | |
328 | pass |
|
383 | pass | |
329 |
|
384 | |||
330 | # by default this is done with temp files, except when the given |
|
385 | # by default this is done with temp files, except when the given | |
331 | # arg is a filename |
|
386 | # arg is a filename | |
332 | use_temp = 1 |
|
387 | use_temp = 1 | |
333 |
|
388 | |||
334 | if re.match(r'\d',args): |
|
389 | if re.match(r'\d',args): | |
335 | # Mode where user specifies ranges of lines, like in %macro. |
|
390 | # Mode where user specifies ranges of lines, like in %macro. | |
336 | # This means that you can't edit files whose names begin with |
|
391 | # This means that you can't edit files whose names begin with | |
337 | # numbers this way. Tough. |
|
392 | # numbers this way. Tough. | |
338 | ranges = args.split() |
|
393 | ranges = args.split() | |
339 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
394 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
340 | elif args.endswith('.py'): |
|
395 | elif args.endswith('.py'): | |
341 | filename = make_filename(args) |
|
396 | filename = make_filename(args) | |
342 | data = '' |
|
397 | data = '' | |
343 | use_temp = 0 |
|
398 | use_temp = 0 | |
344 | elif args: |
|
399 | elif args: | |
345 | try: |
|
400 | try: | |
346 | # Load the parameter given as a variable. If not a string, |
|
401 | # Load the parameter given as a variable. If not a string, | |
347 | # process it as an object instead (below) |
|
402 | # process it as an object instead (below) | |
348 |
|
403 | |||
349 | #print '*** args',args,'type',type(args) # dbg |
|
404 | #print '*** args',args,'type',type(args) # dbg | |
350 | data = eval(args,self.shell.user_ns) |
|
405 | data = eval(args,self.shell.user_ns) | |
351 | if not type(data) in StringTypes: |
|
406 | if not type(data) in StringTypes: | |
352 | raise DataIsObject |
|
407 | raise DataIsObject | |
353 |
|
408 | |||
354 | except (NameError,SyntaxError): |
|
409 | except (NameError,SyntaxError): | |
355 | # given argument is not a variable, try as a filename |
|
410 | # given argument is not a variable, try as a filename | |
356 | filename = make_filename(args) |
|
411 | filename = make_filename(args) | |
357 | if filename is None: |
|
412 | if filename is None: | |
358 | warn("Argument given (%s) can't be found as a variable " |
|
413 | warn("Argument given (%s) can't be found as a variable " | |
359 | "or as a filename." % args) |
|
414 | "or as a filename." % args) | |
360 | return |
|
415 | return | |
361 |
|
416 | |||
362 | data = '' |
|
417 | data = '' | |
363 | use_temp = 0 |
|
418 | use_temp = 0 | |
364 | except DataIsObject: |
|
419 | except DataIsObject: | |
365 |
|
420 | |||
366 | # macros have a special edit function |
|
421 | # macros have a special edit function | |
367 | if isinstance(data,Macro): |
|
422 | if isinstance(data,Macro): | |
368 | self._edit_macro(args,data) |
|
423 | self._edit_macro(args,data) | |
369 | return |
|
424 | return | |
370 |
|
425 | |||
371 | # For objects, try to edit the file where they are defined |
|
426 | # For objects, try to edit the file where they are defined | |
372 | try: |
|
427 | try: | |
373 | filename = inspect.getabsfile(data) |
|
428 | filename = inspect.getabsfile(data) | |
374 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
429 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
375 | # class created by %edit? Try to find source |
|
430 | # class created by %edit? Try to find source | |
376 | # by looking for method definitions instead, the |
|
431 | # by looking for method definitions instead, the | |
377 | # __module__ in those classes is FakeModule. |
|
432 | # __module__ in those classes is FakeModule. | |
378 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
433 | attrs = [getattr(data, aname) for aname in dir(data)] | |
379 | for attr in attrs: |
|
434 | for attr in attrs: | |
380 | if not inspect.ismethod(attr): |
|
435 | if not inspect.ismethod(attr): | |
381 | continue |
|
436 | continue | |
382 | filename = inspect.getabsfile(attr) |
|
437 | filename = inspect.getabsfile(attr) | |
383 | if filename and 'fakemodule' not in filename.lower(): |
|
438 | if filename and 'fakemodule' not in filename.lower(): | |
384 | # change the attribute to be the edit target instead |
|
439 | # change the attribute to be the edit target instead | |
385 | data = attr |
|
440 | data = attr | |
386 | break |
|
441 | break | |
387 |
|
442 | |||
388 | datafile = 1 |
|
443 | datafile = 1 | |
389 | except TypeError: |
|
444 | except TypeError: | |
390 | filename = make_filename(args) |
|
445 | filename = make_filename(args) | |
391 | datafile = 1 |
|
446 | datafile = 1 | |
392 | warn('Could not find file where `%s` is defined.\n' |
|
447 | warn('Could not find file where `%s` is defined.\n' | |
393 | 'Opening a file named `%s`' % (args,filename)) |
|
448 | 'Opening a file named `%s`' % (args,filename)) | |
394 | # Now, make sure we can actually read the source (if it was in |
|
449 | # Now, make sure we can actually read the source (if it was in | |
395 | # a temp file it's gone by now). |
|
450 | # a temp file it's gone by now). | |
396 | if datafile: |
|
451 | if datafile: | |
397 | try: |
|
452 | try: | |
398 | if lineno is None: |
|
453 | if lineno is None: | |
399 | lineno = inspect.getsourcelines(data)[1] |
|
454 | lineno = inspect.getsourcelines(data)[1] | |
400 | except IOError: |
|
455 | except IOError: | |
401 | filename = make_filename(args) |
|
456 | filename = make_filename(args) | |
402 | if filename is None: |
|
457 | if filename is None: | |
403 | warn('The file `%s` where `%s` was defined cannot ' |
|
458 | warn('The file `%s` where `%s` was defined cannot ' | |
404 | 'be read.' % (filename,data)) |
|
459 | 'be read.' % (filename,data)) | |
405 | return |
|
460 | return | |
406 | use_temp = 0 |
|
461 | use_temp = 0 | |
407 | else: |
|
462 | else: | |
408 | data = '' |
|
463 | data = '' | |
409 |
|
464 | |||
410 | if use_temp: |
|
465 | if use_temp: | |
411 | filename = self.shell.mktempfile(data) |
|
466 | filename = self.shell.mktempfile(data) | |
412 | print('IPython will make a temporary file named:', filename) |
|
467 | print('IPython will make a temporary file named:', filename) | |
413 |
|
468 | |||
414 | # Make sure we send to the client an absolute path, in case the working |
|
469 | # Make sure we send to the client an absolute path, in case the working | |
415 | # directory of client and kernel don't match |
|
470 | # directory of client and kernel don't match | |
416 | filename = os.path.abspath(filename) |
|
471 | filename = os.path.abspath(filename) | |
417 |
|
472 | |||
418 | payload = { |
|
473 | payload = { | |
419 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', |
|
474 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', | |
420 | 'filename' : filename, |
|
475 | 'filename' : filename, | |
421 | 'line_number' : lineno |
|
476 | 'line_number' : lineno | |
422 | } |
|
477 | } | |
423 | self.payload_manager.write_payload(payload) |
|
478 | self.payload_manager.write_payload(payload) | |
424 |
|
479 | |||
425 | def magic_gui(self, *args, **kwargs): |
|
480 | def magic_gui(self, *args, **kwargs): | |
426 | raise NotImplementedError('GUI support must be enabled in command line options.') |
|
481 | raise NotImplementedError( | |
|
482 | 'GUI support must be enabled in command line options.') | |||
427 |
|
483 | |||
428 | def magic_pylab(self, *args, **kwargs): |
|
484 | def magic_pylab(self, *args, **kwargs): | |
429 | raise NotImplementedError('pylab support must be enabled in commandl in options.') |
|
485 | raise NotImplementedError( | |
430 |
|
486 | 'pylab support must be enabled in command line options.') | ||
431 | def auto_rewrite_input(self, cmd): |
|
|||
432 | """Called to show the auto-rewritten input for autocall and friends. |
|
|||
433 |
|
||||
434 | FIXME: this payload is currently not correctly processed by the |
|
|||
435 | frontend. |
|
|||
436 | """ |
|
|||
437 | new = self.displayhook.prompt1.auto_rewrite() + cmd |
|
|||
438 | payload = dict( |
|
|||
439 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', |
|
|||
440 | transformed_input=new, |
|
|||
441 | ) |
|
|||
442 | self.payload_manager.write_payload(payload) |
|
|||
443 |
|
||||
444 | def ask_exit(self): |
|
|||
445 | """Engage the exit actions.""" |
|
|||
446 | payload = dict( |
|
|||
447 | source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', |
|
|||
448 | exit=True, |
|
|||
449 | ) |
|
|||
450 | self.payload_manager.write_payload(payload) |
|
|||
451 |
|
||||
452 | def _showtraceback(self, etype, evalue, stb): |
|
|||
453 |
|
||||
454 | exc_content = { |
|
|||
455 | u'traceback' : stb, |
|
|||
456 | u'ename' : unicode(etype.__name__), |
|
|||
457 | u'evalue' : unicode(evalue) |
|
|||
458 | } |
|
|||
459 |
|
487 | |||
460 | dh = self.displayhook |
|
|||
461 | exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header) |
|
|||
462 | # Send exception info over pub socket for other clients than the caller |
|
|||
463 | # to pick up |
|
|||
464 | dh.pub_socket.send_json(exc_msg) |
|
|||
465 |
|
||||
466 | # FIXME - Hack: store exception info in shell object. Right now, the |
|
|||
467 | # caller is reading this info after the fact, we need to fix this logic |
|
|||
468 | # to remove this hack. Even uglier, we need to store the error status |
|
|||
469 | # here, because in the main loop, the logic that sets it is being |
|
|||
470 | # skipped because runlines swallows the exceptions. |
|
|||
471 | exc_content[u'status'] = u'error' |
|
|||
472 | self._reply_content = exc_content |
|
|||
473 | # /FIXME |
|
|||
474 |
|
||||
475 | return exc_content |
|
|||
476 |
|
488 | |||
477 | InteractiveShellABC.register(ZMQInteractiveShell) |
|
489 | InteractiveShellABC.register(ZMQInteractiveShell) |
General Comments 0
You need to be logged in to leave comments.
Login now