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