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