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