Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,252 +1,62 b'' | |||||
1 | """ Legacy stuff |
|
1 | """ Legacy stuff | |
2 |
|
2 | |||
3 | Various stuff that are there for historical / familiarity reasons. |
|
3 | Various stuff that are there for historical / familiarity reasons. | |
4 |
|
4 | |||
5 | This is automatically imported by default profile, though not other profiles |
|
5 | This is automatically imported by default profile, though not other profiles | |
6 | (e.g. 'sh' profile). |
|
6 | (e.g. 'sh' profile). | |
7 |
|
7 | |||
8 | Stuff that is considered obsolete / redundant is gradually moved here. |
|
8 | Stuff that is considered obsolete / redundant is gradually moved here. | |
9 |
|
9 | |||
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | import IPython.ipapi |
|
12 | import IPython.ipapi | |
13 | ip = IPython.ipapi.get() |
|
13 | ip = IPython.ipapi.get() | |
14 |
|
14 | |||
15 | import os,sys |
|
15 | import os,sys | |
16 |
|
16 | |||
17 | from IPython.genutils import * |
|
17 | from IPython.genutils import * | |
18 |
|
18 | |||
19 | # use ? |
|
|||
20 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
|||
21 | """Print the definition header for any callable object. |
|
|||
22 |
|
||||
23 | If the object is a class, print the constructor information.""" |
|
|||
24 | self._inspect('pdef',parameter_s, namespaces) |
|
|||
25 |
|
||||
26 | ip.expose_magic("pdef", magic_pdef) |
|
|||
27 |
|
||||
28 | # use ? |
|
|||
29 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
|||
30 | """Print the docstring for an object. |
|
|||
31 |
|
||||
32 | If the given object is a class, it will print both the class and the |
|
|||
33 | constructor docstrings.""" |
|
|||
34 | self._inspect('pdoc',parameter_s, namespaces) |
|
|||
35 |
|
||||
36 | ip.expose_magic("pdoc", magic_pdoc) |
|
|||
37 |
|
||||
38 | # use ?? |
|
|||
39 | def magic_psource(self, parameter_s='', namespaces=None): |
|
|||
40 | """Print (or run through pager) the source code for an object.""" |
|
|||
41 | self._inspect('psource',parameter_s, namespaces) |
|
|||
42 |
|
||||
43 | ip.expose_magic("pdoc", magic_psource) |
|
|||
44 |
|
||||
45 | # use ? |
|
|||
46 | def magic_pfile(self, parameter_s=''): |
|
|||
47 | """Print (or run through pager) the file where an object is defined. |
|
|||
48 |
|
||||
49 | The file opens at the line where the object definition begins. IPython |
|
|||
50 | will honor the environment variable PAGER if set, and otherwise will |
|
|||
51 | do its best to print the file in a convenient form. |
|
|||
52 |
|
||||
53 | If the given argument is not an object currently defined, IPython will |
|
|||
54 | try to interpret it as a filename (automatically adding a .py extension |
|
|||
55 | if needed). You can thus use %pfile as a syntax highlighting code |
|
|||
56 | viewer.""" |
|
|||
57 |
|
||||
58 | # first interpret argument as an object name |
|
|||
59 | out = self._inspect('pfile',parameter_s) |
|
|||
60 | # if not, try the input as a filename |
|
|||
61 | if out == 'not found': |
|
|||
62 | try: |
|
|||
63 | filename = get_py_filename(parameter_s) |
|
|||
64 | except IOError,msg: |
|
|||
65 | print msg |
|
|||
66 | return |
|
|||
67 | page(self.shell.inspector.format(file(filename).read())) |
|
|||
68 |
|
||||
69 | ip.expose_magic("pfile", magic_pfile) |
|
|||
70 |
|
||||
71 | # use rehashx |
|
19 | # use rehashx | |
72 |
|
20 | |||
73 | def magic_rehash(self, parameter_s = ''): |
|
21 | def magic_rehash(self, parameter_s = ''): | |
74 | """Update the alias table with all entries in $PATH. |
|
22 | """Update the alias table with all entries in $PATH. | |
75 |
|
23 | |||
76 | This version does no checks on execute permissions or whether the |
|
24 | This version does no checks on execute permissions or whether the | |
77 | contents of $PATH are truly files (instead of directories or something |
|
25 | contents of $PATH are truly files (instead of directories or something | |
78 | else). For such a safer (but slower) version, use %rehashx.""" |
|
26 | else). For such a safer (but slower) version, use %rehashx.""" | |
79 |
|
27 | |||
80 | # This function (and rehashx) manipulate the alias_table directly |
|
28 | # This function (and rehashx) manipulate the alias_table directly | |
81 | # rather than calling magic_alias, for speed reasons. A rehash on a |
|
29 | # rather than calling magic_alias, for speed reasons. A rehash on a | |
82 | # typical Linux box involves several thousand entries, so efficiency |
|
30 | # typical Linux box involves several thousand entries, so efficiency | |
83 | # here is a top concern. |
|
31 | # here is a top concern. | |
84 |
|
32 | |||
85 | path = filter(os.path.isdir,os.environ.get('PATH','').split(os.pathsep)) |
|
33 | path = filter(os.path.isdir,os.environ.get('PATH','').split(os.pathsep)) | |
86 | alias_table = self.shell.alias_table |
|
34 | alias_table = self.shell.alias_table | |
87 | for pdir in path: |
|
35 | for pdir in path: | |
88 | for ff in os.listdir(pdir): |
|
36 | for ff in os.listdir(pdir): | |
89 | # each entry in the alias table must be (N,name), where |
|
37 | # each entry in the alias table must be (N,name), where | |
90 | # N is the number of positional arguments of the alias. |
|
38 | # N is the number of positional arguments of the alias. | |
91 | alias_table[ff] = (0,ff) |
|
39 | alias_table[ff] = (0,ff) | |
92 | # Make sure the alias table doesn't contain keywords or builtins |
|
40 | # Make sure the alias table doesn't contain keywords or builtins | |
93 | self.shell.alias_table_validate() |
|
41 | self.shell.alias_table_validate() | |
94 | # Call again init_auto_alias() so we get 'rm -i' and other modified |
|
42 | # Call again init_auto_alias() so we get 'rm -i' and other modified | |
95 | # aliases since %rehash will probably clobber them |
|
43 | # aliases since %rehash will probably clobber them | |
96 | self.shell.init_auto_alias() |
|
44 | self.shell.init_auto_alias() | |
97 |
|
45 | |||
98 | ip.expose_magic("rehash", magic_rehash) |
|
46 | ip.expose_magic("rehash", magic_rehash) | |
99 |
|
47 | |||
100 | #use cd -<tab> |
|
|||
101 | def magic_dhist(self, parameter_s=''): |
|
|||
102 | """Print your history of visited directories. |
|
|||
103 |
|
||||
104 | %dhist -> print full history\\ |
|
|||
105 | %dhist n -> print last n entries only\\ |
|
|||
106 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
|||
107 |
|
||||
108 | This history is automatically maintained by the %cd command, and |
|
|||
109 | always available as the global list variable _dh. You can use %cd -<n> |
|
|||
110 | to go to directory number <n>.""" |
|
|||
111 |
|
||||
112 | dh = self.shell.user_ns['_dh'] |
|
|||
113 | if parameter_s: |
|
|||
114 | try: |
|
|||
115 | args = map(int,parameter_s.split()) |
|
|||
116 | except: |
|
|||
117 | self.arg_err(Magic.magic_dhist) |
|
|||
118 | return |
|
|||
119 | if len(args) == 1: |
|
|||
120 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
|||
121 | elif len(args) == 2: |
|
|||
122 | ini,fin = args |
|
|||
123 | else: |
|
|||
124 | self.arg_err(Magic.magic_dhist) |
|
|||
125 | return |
|
|||
126 | else: |
|
|||
127 | ini,fin = 0,len(dh) |
|
|||
128 | nlprint(dh, |
|
|||
129 | header = 'Directory history (kept in _dh)', |
|
|||
130 | start=ini,stop=fin) |
|
|||
131 |
|
||||
132 | ip.expose_magic("dhist", magic_dhist) |
|
|||
133 |
|
||||
134 | # Exit |
|
48 | # Exit | |
135 | def magic_Quit(self, parameter_s=''): |
|
49 | def magic_Quit(self, parameter_s=''): | |
136 | """Exit IPython without confirmation (like %Exit).""" |
|
50 | """Exit IPython without confirmation (like %Exit).""" | |
137 |
|
51 | |||
138 | self.shell.exit_now = True |
|
52 | self.shell.exit_now = True | |
139 |
|
53 | |||
140 | ip.expose_magic("Quit", magic_Quit) |
|
54 | ip.expose_magic("Quit", magic_Quit) | |
141 |
|
55 | |||
142 |
|
56 | |||
143 | # make it autocallable fn if you really need it |
|
57 | # make it autocallable fn if you really need it | |
144 | def magic_p(self, parameter_s=''): |
|
58 | def magic_p(self, parameter_s=''): | |
145 | """Just a short alias for Python's 'print'.""" |
|
59 | """Just a short alias for Python's 'print'.""" | |
146 | exec 'print ' + parameter_s in self.shell.user_ns |
|
60 | exec 'print ' + parameter_s in self.shell.user_ns | |
147 |
|
61 | |||
148 | ip.expose_magic("p", magic_p) |
|
62 | ip.expose_magic("p", magic_p) | |
149 |
|
||||
150 | # up + enter. One char magic. |
|
|||
151 | def magic_r(self, parameter_s=''): |
|
|||
152 | """Repeat previous input. |
|
|||
153 |
|
||||
154 | If given an argument, repeats the previous command which starts with |
|
|||
155 | the same string, otherwise it just repeats the previous input. |
|
|||
156 |
|
||||
157 | Shell escaped commands (with ! as first character) are not recognized |
|
|||
158 | by this system, only pure python code and magic commands. |
|
|||
159 | """ |
|
|||
160 |
|
||||
161 | start = parameter_s.strip() |
|
|||
162 | esc_magic = self.shell.ESC_MAGIC |
|
|||
163 | # Identify magic commands even if automagic is on (which means |
|
|||
164 | # the in-memory version is different from that typed by the user). |
|
|||
165 | if self.shell.rc.automagic: |
|
|||
166 | start_magic = esc_magic+start |
|
|||
167 | else: |
|
|||
168 | start_magic = start |
|
|||
169 | # Look through the input history in reverse |
|
|||
170 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
|||
171 | input = self.shell.input_hist[n] |
|
|||
172 | # skip plain 'r' lines so we don't recurse to infinity |
|
|||
173 | if input != '_ip.magic("r")\n' and \ |
|
|||
174 | (input.startswith(start) or input.startswith(start_magic)): |
|
|||
175 | #print 'match',`input` # dbg |
|
|||
176 | print 'Executing:',input, |
|
|||
177 | self.shell.runlines(input) |
|
|||
178 | return |
|
|||
179 | print 'No previous input matching `%s` found.' % start |
|
|||
180 |
|
||||
181 | ip.expose_magic("r", magic_r) |
|
|||
182 |
|
||||
183 |
|
||||
184 | # use _ip.option.automagic |
|
|||
185 |
|
||||
186 | def magic_automagic(self, parameter_s = ''): |
|
|||
187 | """Make magic functions callable without having to type the initial %. |
|
|||
188 |
|
||||
189 | Without argumentsl toggles on/off (when off, you must call it as |
|
|||
190 | %automagic, of course). With arguments it sets the value, and you can |
|
|||
191 | use any of (case insensitive): |
|
|||
192 |
|
||||
193 | - on,1,True: to activate |
|
|||
194 |
|
||||
195 | - off,0,False: to deactivate. |
|
|||
196 |
|
||||
197 | Note that magic functions have lowest priority, so if there's a |
|
|||
198 | variable whose name collides with that of a magic fn, automagic won't |
|
|||
199 | work for that function (you get the variable instead). However, if you |
|
|||
200 | delete the variable (del var), the previously shadowed magic function |
|
|||
201 | becomes visible to automagic again.""" |
|
|||
202 |
|
||||
203 | rc = self.shell.rc |
|
|||
204 | arg = parameter_s.lower() |
|
|||
205 | if parameter_s in ('on','1','true'): |
|
|||
206 | rc.automagic = True |
|
|||
207 | elif parameter_s in ('off','0','false'): |
|
|||
208 | rc.automagic = False |
|
|||
209 | else: |
|
|||
210 | rc.automagic = not rc.automagic |
|
|||
211 | print '\n' + Magic.auto_status[rc.automagic] |
|
|||
212 |
|
||||
213 | ip.expose_magic("automagic", magic_automagic) |
|
|||
214 |
|
||||
215 | # use _ip.options.autocall |
|
|||
216 | def magic_autocall(self, parameter_s = ''): |
|
|||
217 | """Make functions callable without having to type parentheses. |
|
|||
218 |
|
||||
219 | Usage: |
|
|||
220 |
|
||||
221 | %autocall [mode] |
|
|||
222 |
|
||||
223 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
|||
224 | value is toggled on and off (remembering the previous state).""" |
|
|||
225 |
|
||||
226 | rc = self.shell.rc |
|
|||
227 |
|
||||
228 | if parameter_s: |
|
|||
229 | arg = int(parameter_s) |
|
|||
230 | else: |
|
|||
231 | arg = 'toggle' |
|
|||
232 |
|
||||
233 | if not arg in (0,1,2,'toggle'): |
|
|||
234 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
|||
235 | return |
|
|||
236 |
|
||||
237 | if arg in (0,1,2): |
|
|||
238 | rc.autocall = arg |
|
|||
239 | else: # toggle |
|
|||
240 | if rc.autocall: |
|
|||
241 | self._magic_state.autocall_save = rc.autocall |
|
|||
242 | rc.autocall = 0 |
|
|||
243 | else: |
|
|||
244 | try: |
|
|||
245 | rc.autocall = self._magic_state.autocall_save |
|
|||
246 | except AttributeError: |
|
|||
247 | rc.autocall = self._magic_state.autocall_save = 1 |
|
|||
248 |
|
||||
249 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] |
|
|||
250 |
|
||||
251 | ip.expose_magic("autocall", magic_autocall) |
|
|||
252 |
|
@@ -1,51 +1,52 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Class which mimics a module. |
|
3 | Class which mimics a module. | |
4 |
|
4 | |||
5 | Needed to allow pickle to correctly resolve namespaces during IPython |
|
5 | Needed to allow pickle to correctly resolve namespaces during IPython | |
6 | sessions. |
|
6 | sessions. | |
7 |
|
7 | |||
8 |
$Id: FakeModule.py 2 |
|
8 | $Id: FakeModule.py 2723 2007-09-07 07:44:16Z fperez $""" | |
9 |
|
9 | |||
10 | #***************************************************************************** |
|
10 | #***************************************************************************** | |
11 | # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu> |
|
11 | # Copyright (C) 2002-2004 Fernando Perez. <fperez@colorado.edu> | |
12 | # |
|
12 | # | |
13 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | # Distributed under the terms of the BSD License. The full license is in | |
14 | # the file COPYING, distributed as part of this software. |
|
14 | # the file COPYING, distributed as part of this software. | |
15 | #***************************************************************************** |
|
15 | #***************************************************************************** | |
16 |
|
16 | |||
17 | class FakeModule: |
|
17 | import types | |
|
18 | ||||
|
19 | class FakeModule(types.ModuleType): | |||
18 | """Simple class with attribute access to fake a module. |
|
20 | """Simple class with attribute access to fake a module. | |
19 |
|
21 | |||
20 | This is not meant to replace a module, but to allow inserting a fake |
|
22 | This is not meant to replace a module, but to allow inserting a fake | |
21 | module in sys.modules so that systems which rely on run-time module |
|
23 | module in sys.modules so that systems which rely on run-time module | |
22 | importing (like shelve and pickle) work correctly in interactive IPython |
|
24 | importing (like shelve and pickle) work correctly in interactive IPython | |
23 | sessions. |
|
25 | sessions. | |
24 |
|
26 | |||
25 | Do NOT use this code for anything other than this IPython private hack.""" |
|
27 | Do NOT use this code for anything other than this IPython private hack.""" | |
26 |
|
||||
27 | def __init__(self,adict): |
|
28 | def __init__(self,adict): | |
28 |
|
29 | |||
29 | # It seems pydoc (and perhaps others) needs any module instance to |
|
30 | # It seems pydoc (and perhaps others) needs any module instance to | |
30 | # implement a __nonzero__ method, so we add it if missing: |
|
31 | # implement a __nonzero__ method, so we add it if missing: | |
31 | if '__nonzero__' not in adict: |
|
32 | if '__nonzero__' not in adict: | |
32 | def __nonzero__(): |
|
33 | def __nonzero__(): | |
33 | return 1 |
|
34 | return 1 | |
34 | adict['__nonzero__'] = __nonzero__ |
|
35 | adict['__nonzero__'] = __nonzero__ | |
35 |
|
36 | |||
36 |
self. |
|
37 | self._dict_ = adict | |
37 |
|
38 | |||
38 | # modules should have a __file__ attribute |
|
39 | # modules should have a __file__ attribute | |
39 | adict.setdefault('__file__',__file__) |
|
40 | adict.setdefault('__file__',__file__) | |
40 |
|
41 | |||
41 | def __getattr__(self,key): |
|
42 | def __getattr__(self,key): | |
42 | try: |
|
43 | try: | |
43 |
return self. |
|
44 | return self._dict_[key] | |
44 | except KeyError, e: |
|
45 | except KeyError, e: | |
45 | raise AttributeError("FakeModule object has no attribute %s" % e) |
|
46 | raise AttributeError("FakeModule object has no attribute %s" % e) | |
46 |
|
47 | |||
47 | def __str__(self): |
|
48 | def __str__(self): | |
48 | return "<IPython.FakeModule instance>" |
|
49 | return "<IPython.FakeModule instance>" | |
49 |
|
50 | |||
50 | def __repr__(self): |
|
51 | def __repr__(self): | |
51 | return str(self) |
|
52 | return str(self) |
@@ -1,3016 +1,3212 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 |
|
3 | |||
4 |
$Id: Magic.py 27 |
|
4 | $Id: Magic.py 2723 2007-09-07 07:44:16Z fperez $""" | |
5 |
|
5 | |||
6 | #***************************************************************************** |
|
6 | #***************************************************************************** | |
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> |
|
8 | # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu> | |
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 | # Modules and globals |
|
15 | # Modules and globals | |
16 |
|
16 | |||
17 | from IPython import Release |
|
17 | from IPython import Release | |
18 | __author__ = '%s <%s>\n%s <%s>' % \ |
|
18 | __author__ = '%s <%s>\n%s <%s>' % \ | |
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) |
|
19 | ( Release.authors['Janko'] + Release.authors['Fernando'] ) | |
20 | __license__ = Release.license |
|
20 | __license__ = Release.license | |
21 |
|
21 | |||
22 | # Python standard modules |
|
22 | # Python standard modules | |
23 | import __builtin__ |
|
23 | import __builtin__ | |
24 | import bdb |
|
24 | import bdb | |
25 | import inspect |
|
25 | import inspect | |
26 | import os |
|
26 | import os | |
27 | import pdb |
|
27 | import pdb | |
28 | import pydoc |
|
28 | import pydoc | |
29 | import sys |
|
29 | import sys | |
30 | import re |
|
30 | import re | |
31 | import tempfile |
|
31 | import tempfile | |
32 | import time |
|
32 | import time | |
33 | import cPickle as pickle |
|
33 | import cPickle as pickle | |
34 | import textwrap |
|
34 | import textwrap | |
35 | from cStringIO import StringIO |
|
35 | from cStringIO import StringIO | |
36 | from getopt import getopt,GetoptError |
|
36 | from getopt import getopt,GetoptError | |
37 | from pprint import pprint, pformat |
|
37 | from pprint import pprint, pformat | |
38 | from sets import Set |
|
38 | from sets import Set | |
39 |
|
39 | |||
40 | # cProfile was added in Python2.5 |
|
40 | # cProfile was added in Python2.5 | |
41 | try: |
|
41 | try: | |
42 | import cProfile as profile |
|
42 | import cProfile as profile | |
43 | import pstats |
|
43 | import pstats | |
44 | except ImportError: |
|
44 | except ImportError: | |
45 | # profile isn't bundled by default in Debian for license reasons |
|
45 | # profile isn't bundled by default in Debian for license reasons | |
46 | try: |
|
46 | try: | |
47 | import profile,pstats |
|
47 | import profile,pstats | |
48 | except ImportError: |
|
48 | except ImportError: | |
49 | profile = pstats = None |
|
49 | profile = pstats = None | |
50 |
|
50 | |||
51 | # Homebrewed |
|
51 | # Homebrewed | |
52 | import IPython |
|
52 | import IPython | |
53 | from IPython import Debugger, OInspect, wildcard |
|
53 | from IPython import Debugger, OInspect, wildcard | |
54 | from IPython.FakeModule import FakeModule |
|
54 | from IPython.FakeModule import FakeModule | |
55 | from IPython.Itpl import Itpl, itpl, printpl,itplns |
|
55 | from IPython.Itpl import Itpl, itpl, printpl,itplns | |
56 | from IPython.PyColorize import Parser |
|
56 | from IPython.PyColorize import Parser | |
57 | from IPython.ipstruct import Struct |
|
57 | from IPython.ipstruct import Struct | |
58 | from IPython.macro import Macro |
|
58 | from IPython.macro import Macro | |
59 | from IPython.genutils import * |
|
59 | from IPython.genutils import * | |
60 | from IPython import platutils |
|
60 | from IPython import platutils | |
61 | import IPython.generics |
|
61 | import IPython.generics | |
62 | import IPython.ipapi |
|
62 | import IPython.ipapi | |
63 |
|
63 | |||
64 | #*************************************************************************** |
|
64 | #*************************************************************************** | |
65 | # Utility functions |
|
65 | # Utility functions | |
66 | def on_off(tag): |
|
66 | def on_off(tag): | |
67 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
67 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
68 | return ['OFF','ON'][tag] |
|
68 | return ['OFF','ON'][tag] | |
69 |
|
69 | |||
70 | class Bunch: pass |
|
70 | class Bunch: pass | |
71 |
|
71 | |||
72 | def compress_dhist(dh): |
|
72 | def compress_dhist(dh): | |
73 | head, tail = dh[:-10], dh[-10:] |
|
73 | head, tail = dh[:-10], dh[-10:] | |
74 |
|
74 | |||
75 | newhead = [] |
|
75 | newhead = [] | |
76 | done = Set() |
|
76 | done = Set() | |
77 | for h in head: |
|
77 | for h in head: | |
78 | if h in done: |
|
78 | if h in done: | |
79 | continue |
|
79 | continue | |
80 | newhead.append(h) |
|
80 | newhead.append(h) | |
81 | done.add(h) |
|
81 | done.add(h) | |
82 |
|
82 | |||
83 | return newhead + tail |
|
83 | return newhead + tail | |
84 |
|
84 | |||
85 |
|
85 | |||
86 | #*************************************************************************** |
|
86 | #*************************************************************************** | |
87 | # Main class implementing Magic functionality |
|
87 | # Main class implementing Magic functionality | |
88 | class Magic: |
|
88 | class Magic: | |
89 | """Magic functions for InteractiveShell. |
|
89 | """Magic functions for InteractiveShell. | |
90 |
|
90 | |||
91 | Shell functions which can be reached as %function_name. All magic |
|
91 | Shell functions which can be reached as %function_name. All magic | |
92 | functions should accept a string, which they can parse for their own |
|
92 | functions should accept a string, which they can parse for their own | |
93 | needs. This can make some functions easier to type, eg `%cd ../` |
|
93 | needs. This can make some functions easier to type, eg `%cd ../` | |
94 | vs. `%cd("../")` |
|
94 | vs. `%cd("../")` | |
95 |
|
95 | |||
96 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
96 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
97 | at the command line, but it is is needed in the definition. """ |
|
97 | at the command line, but it is is needed in the definition. """ | |
98 |
|
98 | |||
99 | # class globals |
|
99 | # class globals | |
100 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
100 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
101 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
101 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
102 |
|
102 | |||
103 | #...................................................................... |
|
103 | #...................................................................... | |
104 | # some utility functions |
|
104 | # some utility functions | |
105 |
|
105 | |||
106 | def __init__(self,shell): |
|
106 | def __init__(self,shell): | |
107 |
|
107 | |||
108 | self.options_table = {} |
|
108 | self.options_table = {} | |
109 | if profile is None: |
|
109 | if profile is None: | |
110 | self.magic_prun = self.profile_missing_notice |
|
110 | self.magic_prun = self.profile_missing_notice | |
111 | self.shell = shell |
|
111 | self.shell = shell | |
112 |
|
112 | |||
113 | # namespace for holding state we may need |
|
113 | # namespace for holding state we may need | |
114 | self._magic_state = Bunch() |
|
114 | self._magic_state = Bunch() | |
115 |
|
115 | |||
116 | def profile_missing_notice(self, *args, **kwargs): |
|
116 | def profile_missing_notice(self, *args, **kwargs): | |
117 | error("""\ |
|
117 | error("""\ | |
118 | The profile module could not be found. If you are a Debian user, |
|
118 | The profile module could not be found. If you are a Debian user, | |
119 | it has been removed from the standard Debian package because of its non-free |
|
119 | it has been removed from the standard Debian package because of its non-free | |
120 | license. To use profiling, please install"python2.3-profiler" from non-free.""") |
|
120 | license. To use profiling, please install"python2.3-profiler" from non-free.""") | |
121 |
|
121 | |||
122 | def default_option(self,fn,optstr): |
|
122 | def default_option(self,fn,optstr): | |
123 | """Make an entry in the options_table for fn, with value optstr""" |
|
123 | """Make an entry in the options_table for fn, with value optstr""" | |
124 |
|
124 | |||
125 | if fn not in self.lsmagic(): |
|
125 | if fn not in self.lsmagic(): | |
126 | error("%s is not a magic function" % fn) |
|
126 | error("%s is not a magic function" % fn) | |
127 | self.options_table[fn] = optstr |
|
127 | self.options_table[fn] = optstr | |
128 |
|
128 | |||
129 | def lsmagic(self): |
|
129 | def lsmagic(self): | |
130 | """Return a list of currently available magic functions. |
|
130 | """Return a list of currently available magic functions. | |
131 |
|
131 | |||
132 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
132 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
133 | ['magic_ls','magic_cd',...]""" |
|
133 | ['magic_ls','magic_cd',...]""" | |
134 |
|
134 | |||
135 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
135 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
136 |
|
136 | |||
137 | # magics in class definition |
|
137 | # magics in class definition | |
138 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
138 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
139 | callable(Magic.__dict__[fn]) |
|
139 | callable(Magic.__dict__[fn]) | |
140 | # in instance namespace (run-time user additions) |
|
140 | # in instance namespace (run-time user additions) | |
141 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
141 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
142 | callable(self.__dict__[fn]) |
|
142 | callable(self.__dict__[fn]) | |
143 | # and bound magics by user (so they can access self): |
|
143 | # and bound magics by user (so they can access self): | |
144 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
144 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
145 | callable(self.__class__.__dict__[fn]) |
|
145 | callable(self.__class__.__dict__[fn]) | |
146 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
146 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
147 | filter(inst_magic,self.__dict__.keys()) + \ |
|
147 | filter(inst_magic,self.__dict__.keys()) + \ | |
148 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
148 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
149 | out = [] |
|
149 | out = [] | |
150 | for fn in magics: |
|
150 | for fn in magics: | |
151 | out.append(fn.replace('magic_','',1)) |
|
151 | out.append(fn.replace('magic_','',1)) | |
152 | out.sort() |
|
152 | out.sort() | |
153 | return out |
|
153 | return out | |
154 |
|
154 | |||
155 | def extract_input_slices(self,slices,raw=False): |
|
155 | def extract_input_slices(self,slices,raw=False): | |
156 | """Return as a string a set of input history slices. |
|
156 | """Return as a string a set of input history slices. | |
157 |
|
157 | |||
158 | Inputs: |
|
158 | Inputs: | |
159 |
|
159 | |||
160 | - slices: the set of slices is given as a list of strings (like |
|
160 | - slices: the set of slices is given as a list of strings (like | |
161 | ['1','4:8','9'], since this function is for use by magic functions |
|
161 | ['1','4:8','9'], since this function is for use by magic functions | |
162 | which get their arguments as strings. |
|
162 | which get their arguments as strings. | |
163 |
|
163 | |||
164 | Optional inputs: |
|
164 | Optional inputs: | |
165 |
|
165 | |||
166 | - raw(False): by default, the processed input is used. If this is |
|
166 | - raw(False): by default, the processed input is used. If this is | |
167 | true, the raw input history is used instead. |
|
167 | true, the raw input history is used instead. | |
168 |
|
168 | |||
169 | Note that slices can be called with two notations: |
|
169 | Note that slices can be called with two notations: | |
170 |
|
170 | |||
171 | N:M -> standard python form, means including items N...(M-1). |
|
171 | N:M -> standard python form, means including items N...(M-1). | |
172 |
|
172 | |||
173 | N-M -> include items N..M (closed endpoint).""" |
|
173 | N-M -> include items N..M (closed endpoint).""" | |
174 |
|
174 | |||
175 | if raw: |
|
175 | if raw: | |
176 | hist = self.shell.input_hist_raw |
|
176 | hist = self.shell.input_hist_raw | |
177 | else: |
|
177 | else: | |
178 | hist = self.shell.input_hist |
|
178 | hist = self.shell.input_hist | |
179 |
|
179 | |||
180 | cmds = [] |
|
180 | cmds = [] | |
181 | for chunk in slices: |
|
181 | for chunk in slices: | |
182 | if ':' in chunk: |
|
182 | if ':' in chunk: | |
183 | ini,fin = map(int,chunk.split(':')) |
|
183 | ini,fin = map(int,chunk.split(':')) | |
184 | elif '-' in chunk: |
|
184 | elif '-' in chunk: | |
185 | ini,fin = map(int,chunk.split('-')) |
|
185 | ini,fin = map(int,chunk.split('-')) | |
186 | fin += 1 |
|
186 | fin += 1 | |
187 | else: |
|
187 | else: | |
188 | ini = int(chunk) |
|
188 | ini = int(chunk) | |
189 | fin = ini+1 |
|
189 | fin = ini+1 | |
190 | cmds.append(hist[ini:fin]) |
|
190 | cmds.append(hist[ini:fin]) | |
191 | return cmds |
|
191 | return cmds | |
192 |
|
192 | |||
193 | def _ofind(self, oname, namespaces=None): |
|
193 | def _ofind(self, oname, namespaces=None): | |
194 | """Find an object in the available namespaces. |
|
194 | """Find an object in the available namespaces. | |
195 |
|
195 | |||
196 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
196 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
197 |
|
197 | |||
198 | Has special code to detect magic functions. |
|
198 | Has special code to detect magic functions. | |
199 | """ |
|
199 | """ | |
200 |
|
200 | |||
201 | oname = oname.strip() |
|
201 | oname = oname.strip() | |
202 |
|
202 | |||
203 | alias_ns = None |
|
203 | alias_ns = None | |
204 | if namespaces is None: |
|
204 | if namespaces is None: | |
205 | # Namespaces to search in: |
|
205 | # Namespaces to search in: | |
206 | # Put them in a list. The order is important so that we |
|
206 | # Put them in a list. The order is important so that we | |
207 | # find things in the same order that Python finds them. |
|
207 | # find things in the same order that Python finds them. | |
208 | namespaces = [ ('Interactive', self.shell.user_ns), |
|
208 | namespaces = [ ('Interactive', self.shell.user_ns), | |
209 | ('IPython internal', self.shell.internal_ns), |
|
209 | ('IPython internal', self.shell.internal_ns), | |
210 | ('Python builtin', __builtin__.__dict__), |
|
210 | ('Python builtin', __builtin__.__dict__), | |
211 | ('Alias', self.shell.alias_table), |
|
211 | ('Alias', self.shell.alias_table), | |
212 | ] |
|
212 | ] | |
213 | alias_ns = self.shell.alias_table |
|
213 | alias_ns = self.shell.alias_table | |
214 |
|
214 | |||
215 | # initialize results to 'null' |
|
215 | # initialize results to 'null' | |
216 | found = 0; obj = None; ospace = None; ds = None; |
|
216 | found = 0; obj = None; ospace = None; ds = None; | |
217 | ismagic = 0; isalias = 0; parent = None |
|
217 | ismagic = 0; isalias = 0; parent = None | |
218 |
|
218 | |||
219 | # Look for the given name by splitting it in parts. If the head is |
|
219 | # Look for the given name by splitting it in parts. If the head is | |
220 | # found, then we look for all the remaining parts as members, and only |
|
220 | # found, then we look for all the remaining parts as members, and only | |
221 | # declare success if we can find them all. |
|
221 | # declare success if we can find them all. | |
222 | oname_parts = oname.split('.') |
|
222 | oname_parts = oname.split('.') | |
223 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
223 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
224 | for nsname,ns in namespaces: |
|
224 | for nsname,ns in namespaces: | |
225 | try: |
|
225 | try: | |
226 | obj = ns[oname_head] |
|
226 | obj = ns[oname_head] | |
227 | except KeyError: |
|
227 | except KeyError: | |
228 | continue |
|
228 | continue | |
229 | else: |
|
229 | else: | |
230 | #print 'oname_rest:', oname_rest # dbg |
|
230 | #print 'oname_rest:', oname_rest # dbg | |
231 | for part in oname_rest: |
|
231 | for part in oname_rest: | |
232 | try: |
|
232 | try: | |
233 | parent = obj |
|
233 | parent = obj | |
234 | obj = getattr(obj,part) |
|
234 | obj = getattr(obj,part) | |
235 | except: |
|
235 | except: | |
236 | # Blanket except b/c some badly implemented objects |
|
236 | # Blanket except b/c some badly implemented objects | |
237 | # allow __getattr__ to raise exceptions other than |
|
237 | # allow __getattr__ to raise exceptions other than | |
238 | # AttributeError, which then crashes IPython. |
|
238 | # AttributeError, which then crashes IPython. | |
239 | break |
|
239 | break | |
240 | else: |
|
240 | else: | |
241 | # If we finish the for loop (no break), we got all members |
|
241 | # If we finish the for loop (no break), we got all members | |
242 | found = 1 |
|
242 | found = 1 | |
243 | ospace = nsname |
|
243 | ospace = nsname | |
244 | if ns == alias_ns: |
|
244 | if ns == alias_ns: | |
245 | isalias = 1 |
|
245 | isalias = 1 | |
246 | break # namespace loop |
|
246 | break # namespace loop | |
247 |
|
247 | |||
248 | # Try to see if it's magic |
|
248 | # Try to see if it's magic | |
249 | if not found: |
|
249 | if not found: | |
250 | if oname.startswith(self.shell.ESC_MAGIC): |
|
250 | if oname.startswith(self.shell.ESC_MAGIC): | |
251 | oname = oname[1:] |
|
251 | oname = oname[1:] | |
252 | obj = getattr(self,'magic_'+oname,None) |
|
252 | obj = getattr(self,'magic_'+oname,None) | |
253 | if obj is not None: |
|
253 | if obj is not None: | |
254 | found = 1 |
|
254 | found = 1 | |
255 | ospace = 'IPython internal' |
|
255 | ospace = 'IPython internal' | |
256 | ismagic = 1 |
|
256 | ismagic = 1 | |
257 |
|
257 | |||
258 | # Last try: special-case some literals like '', [], {}, etc: |
|
258 | # Last try: special-case some literals like '', [], {}, etc: | |
259 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
259 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
260 | obj = eval(oname_head) |
|
260 | obj = eval(oname_head) | |
261 | found = 1 |
|
261 | found = 1 | |
262 | ospace = 'Interactive' |
|
262 | ospace = 'Interactive' | |
263 |
|
263 | |||
264 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
264 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
265 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
265 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
266 |
|
266 | |||
267 | def arg_err(self,func): |
|
267 | def arg_err(self,func): | |
268 | """Print docstring if incorrect arguments were passed""" |
|
268 | """Print docstring if incorrect arguments were passed""" | |
269 | print 'Error in arguments:' |
|
269 | print 'Error in arguments:' | |
270 | print OInspect.getdoc(func) |
|
270 | print OInspect.getdoc(func) | |
271 |
|
271 | |||
272 | def format_latex(self,strng): |
|
272 | def format_latex(self,strng): | |
273 | """Format a string for latex inclusion.""" |
|
273 | """Format a string for latex inclusion.""" | |
274 |
|
274 | |||
275 | # Characters that need to be escaped for latex: |
|
275 | # Characters that need to be escaped for latex: | |
276 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
276 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
277 | # Magic command names as headers: |
|
277 | # Magic command names as headers: | |
278 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, |
|
278 | cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC, | |
279 | re.MULTILINE) |
|
279 | re.MULTILINE) | |
280 | # Magic commands |
|
280 | # Magic commands | |
281 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, |
|
281 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC, | |
282 | re.MULTILINE) |
|
282 | re.MULTILINE) | |
283 | # Paragraph continue |
|
283 | # Paragraph continue | |
284 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
284 | par_re = re.compile(r'\\$',re.MULTILINE) | |
285 |
|
285 | |||
286 | # The "\n" symbol |
|
286 | # The "\n" symbol | |
287 | newline_re = re.compile(r'\\n') |
|
287 | newline_re = re.compile(r'\\n') | |
288 |
|
288 | |||
289 | # Now build the string for output: |
|
289 | # Now build the string for output: | |
290 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
290 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
291 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
291 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
292 | strng) |
|
292 | strng) | |
293 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
293 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
294 | strng = par_re.sub(r'\\\\',strng) |
|
294 | strng = par_re.sub(r'\\\\',strng) | |
295 | strng = escape_re.sub(r'\\\1',strng) |
|
295 | strng = escape_re.sub(r'\\\1',strng) | |
296 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
296 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
297 | return strng |
|
297 | return strng | |
298 |
|
298 | |||
299 | def format_screen(self,strng): |
|
299 | def format_screen(self,strng): | |
300 | """Format a string for screen printing. |
|
300 | """Format a string for screen printing. | |
301 |
|
301 | |||
302 | This removes some latex-type format codes.""" |
|
302 | This removes some latex-type format codes.""" | |
303 | # Paragraph continue |
|
303 | # Paragraph continue | |
304 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
304 | par_re = re.compile(r'\\$',re.MULTILINE) | |
305 | strng = par_re.sub('',strng) |
|
305 | strng = par_re.sub('',strng) | |
306 | return strng |
|
306 | return strng | |
307 |
|
307 | |||
308 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
308 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
309 | """Parse options passed to an argument string. |
|
309 | """Parse options passed to an argument string. | |
310 |
|
310 | |||
311 | The interface is similar to that of getopt(), but it returns back a |
|
311 | The interface is similar to that of getopt(), but it returns back a | |
312 | Struct with the options as keys and the stripped argument string still |
|
312 | Struct with the options as keys and the stripped argument string still | |
313 | as a string. |
|
313 | as a string. | |
314 |
|
314 | |||
315 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
315 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
316 | This allows us to easily expand variables, glob files, quote |
|
316 | This allows us to easily expand variables, glob files, quote | |
317 | arguments, etc. |
|
317 | arguments, etc. | |
318 |
|
318 | |||
319 | Options: |
|
319 | Options: | |
320 | -mode: default 'string'. If given as 'list', the argument string is |
|
320 | -mode: default 'string'. If given as 'list', the argument string is | |
321 | returned as a list (split on whitespace) instead of a string. |
|
321 | returned as a list (split on whitespace) instead of a string. | |
322 |
|
322 | |||
323 | -list_all: put all option values in lists. Normally only options |
|
323 | -list_all: put all option values in lists. Normally only options | |
324 | appearing more than once are put in a list. |
|
324 | appearing more than once are put in a list. | |
325 |
|
325 | |||
326 | -posix (True): whether to split the input line in POSIX mode or not, |
|
326 | -posix (True): whether to split the input line in POSIX mode or not, | |
327 | as per the conventions outlined in the shlex module from the |
|
327 | as per the conventions outlined in the shlex module from the | |
328 | standard library.""" |
|
328 | standard library.""" | |
329 |
|
329 | |||
330 | # inject default options at the beginning of the input line |
|
330 | # inject default options at the beginning of the input line | |
331 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
331 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
332 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
332 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
333 |
|
333 | |||
334 | mode = kw.get('mode','string') |
|
334 | mode = kw.get('mode','string') | |
335 | if mode not in ['string','list']: |
|
335 | if mode not in ['string','list']: | |
336 | raise ValueError,'incorrect mode given: %s' % mode |
|
336 | raise ValueError,'incorrect mode given: %s' % mode | |
337 | # Get options |
|
337 | # Get options | |
338 | list_all = kw.get('list_all',0) |
|
338 | list_all = kw.get('list_all',0) | |
339 | posix = kw.get('posix',True) |
|
339 | posix = kw.get('posix',True) | |
340 |
|
340 | |||
341 | # Check if we have more than one argument to warrant extra processing: |
|
341 | # Check if we have more than one argument to warrant extra processing: | |
342 | odict = {} # Dictionary with options |
|
342 | odict = {} # Dictionary with options | |
343 | args = arg_str.split() |
|
343 | args = arg_str.split() | |
344 | if len(args) >= 1: |
|
344 | if len(args) >= 1: | |
345 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
345 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
346 | # need to look for options |
|
346 | # need to look for options | |
347 | argv = arg_split(arg_str,posix) |
|
347 | argv = arg_split(arg_str,posix) | |
348 | # Do regular option processing |
|
348 | # Do regular option processing | |
349 | try: |
|
349 | try: | |
350 | opts,args = getopt(argv,opt_str,*long_opts) |
|
350 | opts,args = getopt(argv,opt_str,*long_opts) | |
351 | except GetoptError,e: |
|
351 | except GetoptError,e: | |
352 | raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
352 | raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
353 | " ".join(long_opts))) |
|
353 | " ".join(long_opts))) | |
354 | for o,a in opts: |
|
354 | for o,a in opts: | |
355 | if o.startswith('--'): |
|
355 | if o.startswith('--'): | |
356 | o = o[2:] |
|
356 | o = o[2:] | |
357 | else: |
|
357 | else: | |
358 | o = o[1:] |
|
358 | o = o[1:] | |
359 | try: |
|
359 | try: | |
360 | odict[o].append(a) |
|
360 | odict[o].append(a) | |
361 | except AttributeError: |
|
361 | except AttributeError: | |
362 | odict[o] = [odict[o],a] |
|
362 | odict[o] = [odict[o],a] | |
363 | except KeyError: |
|
363 | except KeyError: | |
364 | if list_all: |
|
364 | if list_all: | |
365 | odict[o] = [a] |
|
365 | odict[o] = [a] | |
366 | else: |
|
366 | else: | |
367 | odict[o] = a |
|
367 | odict[o] = a | |
368 |
|
368 | |||
369 | # Prepare opts,args for return |
|
369 | # Prepare opts,args for return | |
370 | opts = Struct(odict) |
|
370 | opts = Struct(odict) | |
371 | if mode == 'string': |
|
371 | if mode == 'string': | |
372 | args = ' '.join(args) |
|
372 | args = ' '.join(args) | |
373 |
|
373 | |||
374 | return opts,args |
|
374 | return opts,args | |
375 |
|
375 | |||
376 | #...................................................................... |
|
376 | #...................................................................... | |
377 | # And now the actual magic functions |
|
377 | # And now the actual magic functions | |
378 |
|
378 | |||
379 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
379 | # Functions for IPython shell work (vars,funcs, config, etc) | |
380 | def magic_lsmagic(self, parameter_s = ''): |
|
380 | def magic_lsmagic(self, parameter_s = ''): | |
381 | """List currently available magic functions.""" |
|
381 | """List currently available magic functions.""" | |
382 | mesc = self.shell.ESC_MAGIC |
|
382 | mesc = self.shell.ESC_MAGIC | |
383 | print 'Available magic functions:\n'+mesc+\ |
|
383 | print 'Available magic functions:\n'+mesc+\ | |
384 | (' '+mesc).join(self.lsmagic()) |
|
384 | (' '+mesc).join(self.lsmagic()) | |
385 | print '\n' + Magic.auto_status[self.shell.rc.automagic] |
|
385 | print '\n' + Magic.auto_status[self.shell.rc.automagic] | |
386 | return None |
|
386 | return None | |
387 |
|
387 | |||
388 | def magic_magic(self, parameter_s = ''): |
|
388 | def magic_magic(self, parameter_s = ''): | |
389 | """Print information about the magic function system.""" |
|
389 | """Print information about the magic function system.""" | |
390 |
|
390 | |||
391 | mode = '' |
|
391 | mode = '' | |
392 | try: |
|
392 | try: | |
393 | if parameter_s.split()[0] == '-latex': |
|
393 | if parameter_s.split()[0] == '-latex': | |
394 | mode = 'latex' |
|
394 | mode = 'latex' | |
395 | if parameter_s.split()[0] == '-brief': |
|
395 | if parameter_s.split()[0] == '-brief': | |
396 | mode = 'brief' |
|
396 | mode = 'brief' | |
397 | except: |
|
397 | except: | |
398 | pass |
|
398 | pass | |
399 |
|
399 | |||
400 | magic_docs = [] |
|
400 | magic_docs = [] | |
401 | for fname in self.lsmagic(): |
|
401 | for fname in self.lsmagic(): | |
402 | mname = 'magic_' + fname |
|
402 | mname = 'magic_' + fname | |
403 | for space in (Magic,self,self.__class__): |
|
403 | for space in (Magic,self,self.__class__): | |
404 | try: |
|
404 | try: | |
405 | fn = space.__dict__[mname] |
|
405 | fn = space.__dict__[mname] | |
406 | except KeyError: |
|
406 | except KeyError: | |
407 | pass |
|
407 | pass | |
408 | else: |
|
408 | else: | |
409 | break |
|
409 | break | |
410 | if mode == 'brief': |
|
410 | if mode == 'brief': | |
411 | # only first line |
|
411 | # only first line | |
412 | fndoc = fn.__doc__.split('\n',1)[0] |
|
412 | fndoc = fn.__doc__.split('\n',1)[0] | |
413 | else: |
|
413 | else: | |
414 | fndoc = fn.__doc__ |
|
414 | fndoc = fn.__doc__ | |
415 |
|
415 | |||
416 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, |
|
416 | magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC, | |
417 | fname,fndoc)) |
|
417 | fname,fndoc)) | |
418 | magic_docs = ''.join(magic_docs) |
|
418 | magic_docs = ''.join(magic_docs) | |
419 |
|
419 | |||
420 | if mode == 'latex': |
|
420 | if mode == 'latex': | |
421 | print self.format_latex(magic_docs) |
|
421 | print self.format_latex(magic_docs) | |
422 | return |
|
422 | return | |
423 | else: |
|
423 | else: | |
424 | magic_docs = self.format_screen(magic_docs) |
|
424 | magic_docs = self.format_screen(magic_docs) | |
425 | if mode == 'brief': |
|
425 | if mode == 'brief': | |
426 | return magic_docs |
|
426 | return magic_docs | |
427 |
|
427 | |||
428 | outmsg = """ |
|
428 | outmsg = """ | |
429 | IPython's 'magic' functions |
|
429 | IPython's 'magic' functions | |
430 | =========================== |
|
430 | =========================== | |
431 |
|
431 | |||
432 | The magic function system provides a series of functions which allow you to |
|
432 | The magic function system provides a series of functions which allow you to | |
433 | control the behavior of IPython itself, plus a lot of system-type |
|
433 | control the behavior of IPython itself, plus a lot of system-type | |
434 | features. All these functions are prefixed with a % character, but parameters |
|
434 | features. All these functions are prefixed with a % character, but parameters | |
435 | are given without parentheses or quotes. |
|
435 | are given without parentheses or quotes. | |
436 |
|
436 | |||
437 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
437 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
438 | %automagic function), you don't need to type in the % explicitly. By default, |
|
438 | %automagic function), you don't need to type in the % explicitly. By default, | |
439 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
439 | IPython ships with automagic on, so you should only rarely need the % escape. | |
440 |
|
440 | |||
441 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
441 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
442 | to 'mydir', if it exists. |
|
442 | to 'mydir', if it exists. | |
443 |
|
443 | |||
444 | You can define your own magic functions to extend the system. See the supplied |
|
444 | You can define your own magic functions to extend the system. See the supplied | |
445 | ipythonrc and example-magic.py files for details (in your ipython |
|
445 | ipythonrc and example-magic.py files for details (in your ipython | |
446 | configuration directory, typically $HOME/.ipython/). |
|
446 | configuration directory, typically $HOME/.ipython/). | |
447 |
|
447 | |||
448 | You can also define your own aliased names for magic functions. In your |
|
448 | You can also define your own aliased names for magic functions. In your | |
449 | ipythonrc file, placing a line like: |
|
449 | ipythonrc file, placing a line like: | |
450 |
|
450 | |||
451 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
451 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
452 |
|
452 | |||
453 | will define %pf as a new name for %profile. |
|
453 | will define %pf as a new name for %profile. | |
454 |
|
454 | |||
455 | You can also call magics in code using the ipmagic() function, which IPython |
|
455 | You can also call magics in code using the ipmagic() function, which IPython | |
456 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. |
|
456 | automatically adds to the builtin namespace. Type 'ipmagic?' for details. | |
457 |
|
457 | |||
458 | For a list of the available magic functions, use %lsmagic. For a description |
|
458 | For a list of the available magic functions, use %lsmagic. For a description | |
459 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
459 | of any of them, type %magic_name?, e.g. '%cd?'. | |
460 |
|
460 | |||
461 | Currently the magic system has the following functions:\n""" |
|
461 | Currently the magic system has the following functions:\n""" | |
462 |
|
462 | |||
463 | mesc = self.shell.ESC_MAGIC |
|
463 | mesc = self.shell.ESC_MAGIC | |
464 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
464 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
465 | "\n\n%s%s\n\n%s" % (outmsg, |
|
465 | "\n\n%s%s\n\n%s" % (outmsg, | |
466 | magic_docs,mesc,mesc, |
|
466 | magic_docs,mesc,mesc, | |
467 | (' '+mesc).join(self.lsmagic()), |
|
467 | (' '+mesc).join(self.lsmagic()), | |
468 | Magic.auto_status[self.shell.rc.automagic] ) ) |
|
468 | Magic.auto_status[self.shell.rc.automagic] ) ) | |
469 |
|
469 | |||
470 | page(outmsg,screen_lines=self.shell.rc.screen_length) |
|
470 | page(outmsg,screen_lines=self.shell.rc.screen_length) | |
471 |
|
471 | |||
472 |
|
472 | |||
473 | def magic_autoindent(self, parameter_s = ''): |
|
473 | def magic_autoindent(self, parameter_s = ''): | |
474 | """Toggle autoindent on/off (if available).""" |
|
474 | """Toggle autoindent on/off (if available).""" | |
475 |
|
475 | |||
476 | self.shell.set_autoindent() |
|
476 | self.shell.set_autoindent() | |
477 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] |
|
477 | print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent] | |
478 |
|
478 | |||
|
479 | ||||
|
480 | def magic_automagic(self, parameter_s = ''): | |||
|
481 | """Make magic functions callable without having to type the initial %. | |||
|
482 | ||||
|
483 | Without argumentsl toggles on/off (when off, you must call it as | |||
|
484 | %automagic, of course). With arguments it sets the value, and you can | |||
|
485 | use any of (case insensitive): | |||
|
486 | ||||
|
487 | - on,1,True: to activate | |||
|
488 | ||||
|
489 | - off,0,False: to deactivate. | |||
|
490 | ||||
|
491 | Note that magic functions have lowest priority, so if there's a | |||
|
492 | variable whose name collides with that of a magic fn, automagic won't | |||
|
493 | work for that function (you get the variable instead). However, if you | |||
|
494 | delete the variable (del var), the previously shadowed magic function | |||
|
495 | becomes visible to automagic again.""" | |||
|
496 | ||||
|
497 | rc = self.shell.rc | |||
|
498 | arg = parameter_s.lower() | |||
|
499 | if parameter_s in ('on','1','true'): | |||
|
500 | rc.automagic = True | |||
|
501 | elif parameter_s in ('off','0','false'): | |||
|
502 | rc.automagic = False | |||
|
503 | else: | |||
|
504 | rc.automagic = not rc.automagic | |||
|
505 | print '\n' + Magic.auto_status[rc.automagic] | |||
|
506 | ||||
|
507 | ||||
|
508 | def magic_autocall(self, parameter_s = ''): | |||
|
509 | """Make functions callable without having to type parentheses. | |||
|
510 | ||||
|
511 | Usage: | |||
|
512 | ||||
|
513 | %autocall [mode] | |||
|
514 | ||||
|
515 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |||
|
516 | value is toggled on and off (remembering the previous state). | |||
|
517 | ||||
|
518 | In more detail, these values mean: | |||
|
519 | ||||
|
520 | 0 -> fully disabled | |||
|
521 | ||||
|
522 | 1 -> active, but do not apply if there are no arguments on the line. | |||
|
523 | ||||
|
524 | In this mode, you get: | |||
|
525 | ||||
|
526 | In [1]: callable | |||
|
527 | Out[1]: <built-in function callable> | |||
|
528 | ||||
|
529 | In [2]: callable 'hello' | |||
|
530 | ------> callable('hello') | |||
|
531 | Out[2]: False | |||
|
532 | ||||
|
533 | 2 -> Active always. Even if no arguments are present, the callable | |||
|
534 | object is called: | |||
|
535 | ||||
|
536 | In [4]: callable | |||
|
537 | ------> callable() | |||
|
538 | ||||
|
539 | Note that even with autocall off, you can still use '/' at the start of | |||
|
540 | a line to treat the first argument on the command line as a function | |||
|
541 | and add parentheses to it: | |||
|
542 | ||||
|
543 | In [8]: /str 43 | |||
|
544 | ------> str(43) | |||
|
545 | Out[8]: '43' | |||
|
546 | """ | |||
|
547 | ||||
|
548 | rc = self.shell.rc | |||
|
549 | ||||
|
550 | if parameter_s: | |||
|
551 | arg = int(parameter_s) | |||
|
552 | else: | |||
|
553 | arg = 'toggle' | |||
|
554 | ||||
|
555 | if not arg in (0,1,2,'toggle'): | |||
|
556 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |||
|
557 | return | |||
|
558 | ||||
|
559 | if arg in (0,1,2): | |||
|
560 | rc.autocall = arg | |||
|
561 | else: # toggle | |||
|
562 | if rc.autocall: | |||
|
563 | self._magic_state.autocall_save = rc.autocall | |||
|
564 | rc.autocall = 0 | |||
|
565 | else: | |||
|
566 | try: | |||
|
567 | rc.autocall = self._magic_state.autocall_save | |||
|
568 | except AttributeError: | |||
|
569 | rc.autocall = self._magic_state.autocall_save = 1 | |||
|
570 | ||||
|
571 | print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall] | |||
|
572 | ||||
479 | def magic_system_verbose(self, parameter_s = ''): |
|
573 | def magic_system_verbose(self, parameter_s = ''): | |
480 | """Set verbose printing of system calls. |
|
574 | """Set verbose printing of system calls. | |
481 |
|
575 | |||
482 | If called without an argument, act as a toggle""" |
|
576 | If called without an argument, act as a toggle""" | |
483 |
|
577 | |||
484 | if parameter_s: |
|
578 | if parameter_s: | |
485 | val = bool(eval(parameter_s)) |
|
579 | val = bool(eval(parameter_s)) | |
486 | else: |
|
580 | else: | |
487 | val = None |
|
581 | val = None | |
488 |
|
582 | |||
489 | self.shell.rc_set_toggle('system_verbose',val) |
|
583 | self.shell.rc_set_toggle('system_verbose',val) | |
490 | print "System verbose printing is:",\ |
|
584 | print "System verbose printing is:",\ | |
491 | ['OFF','ON'][self.shell.rc.system_verbose] |
|
585 | ['OFF','ON'][self.shell.rc.system_verbose] | |
492 |
|
586 | |||
493 |
|
587 | |||
494 | def magic_page(self, parameter_s=''): |
|
588 | def magic_page(self, parameter_s=''): | |
495 | """Pretty print the object and display it through a pager. |
|
589 | """Pretty print the object and display it through a pager. | |
496 |
|
590 | |||
497 | %page [options] OBJECT |
|
591 | %page [options] OBJECT | |
498 |
|
592 | |||
499 | If no object is given, use _ (last output). |
|
593 | If no object is given, use _ (last output). | |
500 |
|
594 | |||
501 | Options: |
|
595 | Options: | |
502 |
|
596 | |||
503 | -r: page str(object), don't pretty-print it.""" |
|
597 | -r: page str(object), don't pretty-print it.""" | |
504 |
|
598 | |||
505 | # After a function contributed by Olivier Aubert, slightly modified. |
|
599 | # After a function contributed by Olivier Aubert, slightly modified. | |
506 |
|
600 | |||
507 | # Process options/args |
|
601 | # Process options/args | |
508 | opts,args = self.parse_options(parameter_s,'r') |
|
602 | opts,args = self.parse_options(parameter_s,'r') | |
509 | raw = 'r' in opts |
|
603 | raw = 'r' in opts | |
510 |
|
604 | |||
511 | oname = args and args or '_' |
|
605 | oname = args and args or '_' | |
512 | info = self._ofind(oname) |
|
606 | info = self._ofind(oname) | |
513 | if info['found']: |
|
607 | if info['found']: | |
514 | txt = (raw and str or pformat)( info['obj'] ) |
|
608 | txt = (raw and str or pformat)( info['obj'] ) | |
515 | page(txt) |
|
609 | page(txt) | |
516 | else: |
|
610 | else: | |
517 | print 'Object `%s` not found' % oname |
|
611 | print 'Object `%s` not found' % oname | |
518 |
|
612 | |||
519 | def magic_profile(self, parameter_s=''): |
|
613 | def magic_profile(self, parameter_s=''): | |
520 | """Print your currently active IPyhton profile.""" |
|
614 | """Print your currently active IPyhton profile.""" | |
521 | if self.shell.rc.profile: |
|
615 | if self.shell.rc.profile: | |
522 | printpl('Current IPython profile: $self.shell.rc.profile.') |
|
616 | printpl('Current IPython profile: $self.shell.rc.profile.') | |
523 | else: |
|
617 | else: | |
524 | print 'No profile active.' |
|
618 | print 'No profile active.' | |
525 |
|
619 | |||
526 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
620 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
527 | """Provide detailed information about an object. |
|
621 | """Provide detailed information about an object. | |
528 |
|
622 | |||
529 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
623 | '%pinfo object' is just a synonym for object? or ?object.""" | |
530 |
|
624 | |||
531 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
625 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
532 |
|
626 | |||
533 |
|
627 | |||
534 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
628 | # detail_level: 0 -> obj? , 1 -> obj?? | |
535 | detail_level = 0 |
|
629 | detail_level = 0 | |
536 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
630 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
537 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
631 | # happen if the user types 'pinfo foo?' at the cmd line. | |
538 | pinfo,qmark1,oname,qmark2 = \ |
|
632 | pinfo,qmark1,oname,qmark2 = \ | |
539 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
633 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
540 | if pinfo or qmark1 or qmark2: |
|
634 | if pinfo or qmark1 or qmark2: | |
541 | detail_level = 1 |
|
635 | detail_level = 1 | |
542 | if "*" in oname: |
|
636 | if "*" in oname: | |
543 | self.magic_psearch(oname) |
|
637 | self.magic_psearch(oname) | |
544 | else: |
|
638 | else: | |
545 | self._inspect('pinfo', oname, detail_level=detail_level, |
|
639 | self._inspect('pinfo', oname, detail_level=detail_level, | |
546 | namespaces=namespaces) |
|
640 | namespaces=namespaces) | |
547 |
|
641 | |||
|
642 | def magic_pdef(self, parameter_s='', namespaces=None): | |||
|
643 | """Print the definition header for any callable object. | |||
|
644 | ||||
|
645 | If the object is a class, print the constructor information.""" | |||
|
646 | self._inspect('pdef',parameter_s, namespaces) | |||
|
647 | ||||
|
648 | def magic_pdoc(self, parameter_s='', namespaces=None): | |||
|
649 | """Print the docstring for an object. | |||
|
650 | ||||
|
651 | If the given object is a class, it will print both the class and the | |||
|
652 | constructor docstrings.""" | |||
|
653 | self._inspect('pdoc',parameter_s, namespaces) | |||
|
654 | ||||
|
655 | def magic_psource(self, parameter_s='', namespaces=None): | |||
|
656 | """Print (or run through pager) the source code for an object.""" | |||
|
657 | self._inspect('psource',parameter_s, namespaces) | |||
|
658 | ||||
|
659 | def magic_pfile(self, parameter_s=''): | |||
|
660 | """Print (or run through pager) the file where an object is defined. | |||
|
661 | ||||
|
662 | The file opens at the line where the object definition begins. IPython | |||
|
663 | will honor the environment variable PAGER if set, and otherwise will | |||
|
664 | do its best to print the file in a convenient form. | |||
|
665 | ||||
|
666 | If the given argument is not an object currently defined, IPython will | |||
|
667 | try to interpret it as a filename (automatically adding a .py extension | |||
|
668 | if needed). You can thus use %pfile as a syntax highlighting code | |||
|
669 | viewer.""" | |||
|
670 | ||||
|
671 | # first interpret argument as an object name | |||
|
672 | out = self._inspect('pfile',parameter_s) | |||
|
673 | # if not, try the input as a filename | |||
|
674 | if out == 'not found': | |||
|
675 | try: | |||
|
676 | filename = get_py_filename(parameter_s) | |||
|
677 | except IOError,msg: | |||
|
678 | print msg | |||
|
679 | return | |||
|
680 | page(self.shell.inspector.format(file(filename).read())) | |||
|
681 | ||||
548 | def _inspect(self,meth,oname,namespaces=None,**kw): |
|
682 | def _inspect(self,meth,oname,namespaces=None,**kw): | |
549 | """Generic interface to the inspector system. |
|
683 | """Generic interface to the inspector system. | |
550 |
|
684 | |||
551 | This function is meant to be called by pdef, pdoc & friends.""" |
|
685 | This function is meant to be called by pdef, pdoc & friends.""" | |
552 |
|
686 | |||
553 | #oname = oname.strip() |
|
687 | #oname = oname.strip() | |
554 | #print '1- oname: <%r>' % oname # dbg |
|
688 | #print '1- oname: <%r>' % oname # dbg | |
555 | try: |
|
689 | try: | |
556 | oname = oname.strip().encode('ascii') |
|
690 | oname = oname.strip().encode('ascii') | |
557 | #print '2- oname: <%r>' % oname # dbg |
|
691 | #print '2- oname: <%r>' % oname # dbg | |
558 | except UnicodeEncodeError: |
|
692 | except UnicodeEncodeError: | |
559 | print 'Python identifiers can only contain ascii characters.' |
|
693 | print 'Python identifiers can only contain ascii characters.' | |
560 | return 'not found' |
|
694 | return 'not found' | |
561 |
|
695 | |||
562 | info = Struct(self._ofind(oname, namespaces)) |
|
696 | info = Struct(self._ofind(oname, namespaces)) | |
563 |
|
697 | |||
564 | if info.found: |
|
698 | if info.found: | |
565 | try: |
|
699 | try: | |
566 | IPython.generics.inspect_object(info.obj) |
|
700 | IPython.generics.inspect_object(info.obj) | |
567 | return |
|
701 | return | |
568 | except IPython.ipapi.TryNext: |
|
702 | except IPython.ipapi.TryNext: | |
569 | pass |
|
703 | pass | |
570 | # Get the docstring of the class property if it exists. |
|
704 | # Get the docstring of the class property if it exists. | |
571 | path = oname.split('.') |
|
705 | path = oname.split('.') | |
572 | root = '.'.join(path[:-1]) |
|
706 | root = '.'.join(path[:-1]) | |
573 | if info.parent is not None: |
|
707 | if info.parent is not None: | |
574 | try: |
|
708 | try: | |
575 | target = getattr(info.parent, '__class__') |
|
709 | target = getattr(info.parent, '__class__') | |
576 | # The object belongs to a class instance. |
|
710 | # The object belongs to a class instance. | |
577 | try: |
|
711 | try: | |
578 | target = getattr(target, path[-1]) |
|
712 | target = getattr(target, path[-1]) | |
579 | # The class defines the object. |
|
713 | # The class defines the object. | |
580 | if isinstance(target, property): |
|
714 | if isinstance(target, property): | |
581 | oname = root + '.__class__.' + path[-1] |
|
715 | oname = root + '.__class__.' + path[-1] | |
582 | info = Struct(self._ofind(oname)) |
|
716 | info = Struct(self._ofind(oname)) | |
583 | except AttributeError: pass |
|
717 | except AttributeError: pass | |
584 | except AttributeError: pass |
|
718 | except AttributeError: pass | |
585 |
|
719 | |||
586 | pmethod = getattr(self.shell.inspector,meth) |
|
720 | pmethod = getattr(self.shell.inspector,meth) | |
587 | formatter = info.ismagic and self.format_screen or None |
|
721 | formatter = info.ismagic and self.format_screen or None | |
588 | if meth == 'pdoc': |
|
722 | if meth == 'pdoc': | |
589 | pmethod(info.obj,oname,formatter) |
|
723 | pmethod(info.obj,oname,formatter) | |
590 | elif meth == 'pinfo': |
|
724 | elif meth == 'pinfo': | |
591 | pmethod(info.obj,oname,formatter,info,**kw) |
|
725 | pmethod(info.obj,oname,formatter,info,**kw) | |
592 | else: |
|
726 | else: | |
593 | pmethod(info.obj,oname) |
|
727 | pmethod(info.obj,oname) | |
594 | else: |
|
728 | else: | |
595 | print 'Object `%s` not found.' % oname |
|
729 | print 'Object `%s` not found.' % oname | |
596 | return 'not found' # so callers can take other action |
|
730 | return 'not found' # so callers can take other action | |
597 |
|
731 | |||
598 | def magic_psearch(self, parameter_s=''): |
|
732 | def magic_psearch(self, parameter_s=''): | |
599 | """Search for object in namespaces by wildcard. |
|
733 | """Search for object in namespaces by wildcard. | |
600 |
|
734 | |||
601 | %psearch [options] PATTERN [OBJECT TYPE] |
|
735 | %psearch [options] PATTERN [OBJECT TYPE] | |
602 |
|
736 | |||
603 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
737 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
604 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
738 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
605 | rest of the command line must be unchanged (options come first), so |
|
739 | rest of the command line must be unchanged (options come first), so | |
606 | for example the following forms are equivalent |
|
740 | for example the following forms are equivalent | |
607 |
|
741 | |||
608 | %psearch -i a* function |
|
742 | %psearch -i a* function | |
609 | -i a* function? |
|
743 | -i a* function? | |
610 | ?-i a* function |
|
744 | ?-i a* function | |
611 |
|
745 | |||
612 | Arguments: |
|
746 | Arguments: | |
613 |
|
747 | |||
614 | PATTERN |
|
748 | PATTERN | |
615 |
|
749 | |||
616 | where PATTERN is a string containing * as a wildcard similar to its |
|
750 | where PATTERN is a string containing * as a wildcard similar to its | |
617 | use in a shell. The pattern is matched in all namespaces on the |
|
751 | use in a shell. The pattern is matched in all namespaces on the | |
618 | search path. By default objects starting with a single _ are not |
|
752 | search path. By default objects starting with a single _ are not | |
619 | matched, many IPython generated objects have a single |
|
753 | matched, many IPython generated objects have a single | |
620 | underscore. The default is case insensitive matching. Matching is |
|
754 | underscore. The default is case insensitive matching. Matching is | |
621 | also done on the attributes of objects and not only on the objects |
|
755 | also done on the attributes of objects and not only on the objects | |
622 | in a module. |
|
756 | in a module. | |
623 |
|
757 | |||
624 | [OBJECT TYPE] |
|
758 | [OBJECT TYPE] | |
625 |
|
759 | |||
626 | Is the name of a python type from the types module. The name is |
|
760 | Is the name of a python type from the types module. The name is | |
627 | given in lowercase without the ending type, ex. StringType is |
|
761 | given in lowercase without the ending type, ex. StringType is | |
628 | written string. By adding a type here only objects matching the |
|
762 | written string. By adding a type here only objects matching the | |
629 | given type are matched. Using all here makes the pattern match all |
|
763 | given type are matched. Using all here makes the pattern match all | |
630 | types (this is the default). |
|
764 | types (this is the default). | |
631 |
|
765 | |||
632 | Options: |
|
766 | Options: | |
633 |
|
767 | |||
634 | -a: makes the pattern match even objects whose names start with a |
|
768 | -a: makes the pattern match even objects whose names start with a | |
635 | single underscore. These names are normally ommitted from the |
|
769 | single underscore. These names are normally ommitted from the | |
636 | search. |
|
770 | search. | |
637 |
|
771 | |||
638 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
772 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
639 | these options is given, the default is read from your ipythonrc |
|
773 | these options is given, the default is read from your ipythonrc | |
640 | file. The option name which sets this value is |
|
774 | file. The option name which sets this value is | |
641 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
775 | 'wildcards_case_sensitive'. If this option is not specified in your | |
642 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
776 | ipythonrc file, IPython's internal default is to do a case sensitive | |
643 | search. |
|
777 | search. | |
644 |
|
778 | |||
645 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
779 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
646 | specifiy can be searched in any of the following namespaces: |
|
780 | specifiy can be searched in any of the following namespaces: | |
647 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
781 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
648 | 'builtin' and 'user' are the search defaults. Note that you should |
|
782 | 'builtin' and 'user' are the search defaults. Note that you should | |
649 | not use quotes when specifying namespaces. |
|
783 | not use quotes when specifying namespaces. | |
650 |
|
784 | |||
651 | 'Builtin' contains the python module builtin, 'user' contains all |
|
785 | 'Builtin' contains the python module builtin, 'user' contains all | |
652 | user data, 'alias' only contain the shell aliases and no python |
|
786 | user data, 'alias' only contain the shell aliases and no python | |
653 | objects, 'internal' contains objects used by IPython. The |
|
787 | objects, 'internal' contains objects used by IPython. The | |
654 | 'user_global' namespace is only used by embedded IPython instances, |
|
788 | 'user_global' namespace is only used by embedded IPython instances, | |
655 | and it contains module-level globals. You can add namespaces to the |
|
789 | and it contains module-level globals. You can add namespaces to the | |
656 | search with -s or exclude them with -e (these options can be given |
|
790 | search with -s or exclude them with -e (these options can be given | |
657 | more than once). |
|
791 | more than once). | |
658 |
|
792 | |||
659 | Examples: |
|
793 | Examples: | |
660 |
|
794 | |||
661 | %psearch a* -> objects beginning with an a |
|
795 | %psearch a* -> objects beginning with an a | |
662 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
796 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
663 | %psearch a* function -> all functions beginning with an a |
|
797 | %psearch a* function -> all functions beginning with an a | |
664 | %psearch re.e* -> objects beginning with an e in module re |
|
798 | %psearch re.e* -> objects beginning with an e in module re | |
665 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
799 | %psearch r*.e* -> objects that start with e in modules starting in r | |
666 | %psearch r*.* string -> all strings in modules beginning with r |
|
800 | %psearch r*.* string -> all strings in modules beginning with r | |
667 |
|
801 | |||
668 | Case sensitve search: |
|
802 | Case sensitve search: | |
669 |
|
803 | |||
670 | %psearch -c a* list all object beginning with lower case a |
|
804 | %psearch -c a* list all object beginning with lower case a | |
671 |
|
805 | |||
672 | Show objects beginning with a single _: |
|
806 | Show objects beginning with a single _: | |
673 |
|
807 | |||
674 | %psearch -a _* list objects beginning with a single underscore""" |
|
808 | %psearch -a _* list objects beginning with a single underscore""" | |
675 | try: |
|
809 | try: | |
676 | parameter_s = parameter_s.encode('ascii') |
|
810 | parameter_s = parameter_s.encode('ascii') | |
677 | except UnicodeEncodeError: |
|
811 | except UnicodeEncodeError: | |
678 | print 'Python identifiers can only contain ascii characters.' |
|
812 | print 'Python identifiers can only contain ascii characters.' | |
679 | return |
|
813 | return | |
680 |
|
814 | |||
681 | # default namespaces to be searched |
|
815 | # default namespaces to be searched | |
682 | def_search = ['user','builtin'] |
|
816 | def_search = ['user','builtin'] | |
683 |
|
817 | |||
684 | # Process options/args |
|
818 | # Process options/args | |
685 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
819 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
686 | opt = opts.get |
|
820 | opt = opts.get | |
687 | shell = self.shell |
|
821 | shell = self.shell | |
688 | psearch = shell.inspector.psearch |
|
822 | psearch = shell.inspector.psearch | |
689 |
|
823 | |||
690 | # select case options |
|
824 | # select case options | |
691 | if opts.has_key('i'): |
|
825 | if opts.has_key('i'): | |
692 | ignore_case = True |
|
826 | ignore_case = True | |
693 | elif opts.has_key('c'): |
|
827 | elif opts.has_key('c'): | |
694 | ignore_case = False |
|
828 | ignore_case = False | |
695 | else: |
|
829 | else: | |
696 | ignore_case = not shell.rc.wildcards_case_sensitive |
|
830 | ignore_case = not shell.rc.wildcards_case_sensitive | |
697 |
|
831 | |||
698 | # Build list of namespaces to search from user options |
|
832 | # Build list of namespaces to search from user options | |
699 | def_search.extend(opt('s',[])) |
|
833 | def_search.extend(opt('s',[])) | |
700 | ns_exclude = ns_exclude=opt('e',[]) |
|
834 | ns_exclude = ns_exclude=opt('e',[]) | |
701 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
835 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
702 |
|
836 | |||
703 | # Call the actual search |
|
837 | # Call the actual search | |
704 | try: |
|
838 | try: | |
705 | psearch(args,shell.ns_table,ns_search, |
|
839 | psearch(args,shell.ns_table,ns_search, | |
706 | show_all=opt('a'),ignore_case=ignore_case) |
|
840 | show_all=opt('a'),ignore_case=ignore_case) | |
707 | except: |
|
841 | except: | |
708 | shell.showtraceback() |
|
842 | shell.showtraceback() | |
709 |
|
843 | |||
710 | def magic_who_ls(self, parameter_s=''): |
|
844 | def magic_who_ls(self, parameter_s=''): | |
711 | """Return a sorted list of all interactive variables. |
|
845 | """Return a sorted list of all interactive variables. | |
712 |
|
846 | |||
713 | If arguments are given, only variables of types matching these |
|
847 | If arguments are given, only variables of types matching these | |
714 | arguments are returned.""" |
|
848 | arguments are returned.""" | |
715 |
|
849 | |||
716 | user_ns = self.shell.user_ns |
|
850 | user_ns = self.shell.user_ns | |
717 | internal_ns = self.shell.internal_ns |
|
851 | internal_ns = self.shell.internal_ns | |
718 | user_config_ns = self.shell.user_config_ns |
|
852 | user_config_ns = self.shell.user_config_ns | |
719 | out = [] |
|
853 | out = [] | |
720 | typelist = parameter_s.split() |
|
854 | typelist = parameter_s.split() | |
721 |
|
855 | |||
722 | for i in user_ns: |
|
856 | for i in user_ns: | |
723 | if not (i.startswith('_') or i.startswith('_i')) \ |
|
857 | if not (i.startswith('_') or i.startswith('_i')) \ | |
724 | and not (i in internal_ns or i in user_config_ns): |
|
858 | and not (i in internal_ns or i in user_config_ns): | |
725 | if typelist: |
|
859 | if typelist: | |
726 | if type(user_ns[i]).__name__ in typelist: |
|
860 | if type(user_ns[i]).__name__ in typelist: | |
727 | out.append(i) |
|
861 | out.append(i) | |
728 | else: |
|
862 | else: | |
729 | out.append(i) |
|
863 | out.append(i) | |
730 | out.sort() |
|
864 | out.sort() | |
731 | return out |
|
865 | return out | |
732 |
|
866 | |||
733 | def magic_who(self, parameter_s=''): |
|
867 | def magic_who(self, parameter_s=''): | |
734 | """Print all interactive variables, with some minimal formatting. |
|
868 | """Print all interactive variables, with some minimal formatting. | |
735 |
|
869 | |||
736 | If any arguments are given, only variables whose type matches one of |
|
870 | If any arguments are given, only variables whose type matches one of | |
737 | these are printed. For example: |
|
871 | these are printed. For example: | |
738 |
|
872 | |||
739 | %who function str |
|
873 | %who function str | |
740 |
|
874 | |||
741 | will only list functions and strings, excluding all other types of |
|
875 | will only list functions and strings, excluding all other types of | |
742 | variables. To find the proper type names, simply use type(var) at a |
|
876 | variables. To find the proper type names, simply use type(var) at a | |
743 | command line to see how python prints type names. For example: |
|
877 | command line to see how python prints type names. For example: | |
744 |
|
878 | |||
745 | In [1]: type('hello')\\ |
|
879 | In [1]: type('hello')\\ | |
746 | Out[1]: <type 'str'> |
|
880 | Out[1]: <type 'str'> | |
747 |
|
881 | |||
748 | indicates that the type name for strings is 'str'. |
|
882 | indicates that the type name for strings is 'str'. | |
749 |
|
883 | |||
750 | %who always excludes executed names loaded through your configuration |
|
884 | %who always excludes executed names loaded through your configuration | |
751 | file and things which are internal to IPython. |
|
885 | file and things which are internal to IPython. | |
752 |
|
886 | |||
753 | This is deliberate, as typically you may load many modules and the |
|
887 | This is deliberate, as typically you may load many modules and the | |
754 | purpose of %who is to show you only what you've manually defined.""" |
|
888 | purpose of %who is to show you only what you've manually defined.""" | |
755 |
|
889 | |||
756 | varlist = self.magic_who_ls(parameter_s) |
|
890 | varlist = self.magic_who_ls(parameter_s) | |
757 | if not varlist: |
|
891 | if not varlist: | |
758 | if parameter_s: |
|
892 | if parameter_s: | |
759 | print 'No variables match your requested type.' |
|
893 | print 'No variables match your requested type.' | |
760 | else: |
|
894 | else: | |
761 | print 'Interactive namespace is empty.' |
|
895 | print 'Interactive namespace is empty.' | |
762 | return |
|
896 | return | |
763 |
|
897 | |||
764 | # if we have variables, move on... |
|
898 | # if we have variables, move on... | |
765 | count = 0 |
|
899 | count = 0 | |
766 | for i in varlist: |
|
900 | for i in varlist: | |
767 | print i+'\t', |
|
901 | print i+'\t', | |
768 | count += 1 |
|
902 | count += 1 | |
769 | if count > 8: |
|
903 | if count > 8: | |
770 | count = 0 |
|
904 | count = 0 | |
771 |
|
905 | |||
772 |
|
906 | |||
773 |
|
907 | |||
774 | def magic_whos(self, parameter_s=''): |
|
908 | def magic_whos(self, parameter_s=''): | |
775 | """Like %who, but gives some extra information about each variable. |
|
909 | """Like %who, but gives some extra information about each variable. | |
776 |
|
910 | |||
777 | The same type filtering of %who can be applied here. |
|
911 | The same type filtering of %who can be applied here. | |
778 |
|
912 | |||
779 | For all variables, the type is printed. Additionally it prints: |
|
913 | For all variables, the type is printed. Additionally it prints: | |
780 |
|
914 | |||
781 | - For {},[],(): their length. |
|
915 | - For {},[],(): their length. | |
782 |
|
916 | |||
783 | - For numpy and Numeric arrays, a summary with shape, number of |
|
917 | - For numpy and Numeric arrays, a summary with shape, number of | |
784 | elements, typecode and size in memory. |
|
918 | elements, typecode and size in memory. | |
785 |
|
919 | |||
786 | - Everything else: a string representation, snipping their middle if |
|
920 | - Everything else: a string representation, snipping their middle if | |
787 | too long.""" |
|
921 | too long.""" | |
788 |
|
922 | |||
789 | varnames = self.magic_who_ls(parameter_s) |
|
923 | varnames = self.magic_who_ls(parameter_s) | |
790 | if not varnames: |
|
924 | if not varnames: | |
791 | if parameter_s: |
|
925 | if parameter_s: | |
792 | print 'No variables match your requested type.' |
|
926 | print 'No variables match your requested type.' | |
793 | else: |
|
927 | else: | |
794 | print 'Interactive namespace is empty.' |
|
928 | print 'Interactive namespace is empty.' | |
795 | return |
|
929 | return | |
796 |
|
930 | |||
797 | # if we have variables, move on... |
|
931 | # if we have variables, move on... | |
798 |
|
932 | |||
799 | # for these types, show len() instead of data: |
|
933 | # for these types, show len() instead of data: | |
800 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
934 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
801 |
|
935 | |||
802 | # for numpy/Numeric arrays, display summary info |
|
936 | # for numpy/Numeric arrays, display summary info | |
803 | try: |
|
937 | try: | |
804 | import numpy |
|
938 | import numpy | |
805 | except ImportError: |
|
939 | except ImportError: | |
806 | ndarray_type = None |
|
940 | ndarray_type = None | |
807 | else: |
|
941 | else: | |
808 | ndarray_type = numpy.ndarray.__name__ |
|
942 | ndarray_type = numpy.ndarray.__name__ | |
809 | try: |
|
943 | try: | |
810 | import Numeric |
|
944 | import Numeric | |
811 | except ImportError: |
|
945 | except ImportError: | |
812 | array_type = None |
|
946 | array_type = None | |
813 | else: |
|
947 | else: | |
814 | array_type = Numeric.ArrayType.__name__ |
|
948 | array_type = Numeric.ArrayType.__name__ | |
815 |
|
949 | |||
816 | # Find all variable names and types so we can figure out column sizes |
|
950 | # Find all variable names and types so we can figure out column sizes | |
817 | def get_vars(i): |
|
951 | def get_vars(i): | |
818 | return self.shell.user_ns[i] |
|
952 | return self.shell.user_ns[i] | |
819 |
|
953 | |||
820 | # some types are well known and can be shorter |
|
954 | # some types are well known and can be shorter | |
821 | abbrevs = {'IPython.macro.Macro' : 'Macro'} |
|
955 | abbrevs = {'IPython.macro.Macro' : 'Macro'} | |
822 | def type_name(v): |
|
956 | def type_name(v): | |
823 | tn = type(v).__name__ |
|
957 | tn = type(v).__name__ | |
824 | return abbrevs.get(tn,tn) |
|
958 | return abbrevs.get(tn,tn) | |
825 |
|
959 | |||
826 | varlist = map(get_vars,varnames) |
|
960 | varlist = map(get_vars,varnames) | |
827 |
|
961 | |||
828 | typelist = [] |
|
962 | typelist = [] | |
829 | for vv in varlist: |
|
963 | for vv in varlist: | |
830 | tt = type_name(vv) |
|
964 | tt = type_name(vv) | |
831 |
|
965 | |||
832 | if tt=='instance': |
|
966 | if tt=='instance': | |
833 | typelist.append( abbrevs.get(str(vv.__class__), |
|
967 | typelist.append( abbrevs.get(str(vv.__class__), | |
834 | str(vv.__class__))) |
|
968 | str(vv.__class__))) | |
835 | else: |
|
969 | else: | |
836 | typelist.append(tt) |
|
970 | typelist.append(tt) | |
837 |
|
971 | |||
838 | # column labels and # of spaces as separator |
|
972 | # column labels and # of spaces as separator | |
839 | varlabel = 'Variable' |
|
973 | varlabel = 'Variable' | |
840 | typelabel = 'Type' |
|
974 | typelabel = 'Type' | |
841 | datalabel = 'Data/Info' |
|
975 | datalabel = 'Data/Info' | |
842 | colsep = 3 |
|
976 | colsep = 3 | |
843 | # variable format strings |
|
977 | # variable format strings | |
844 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
978 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
845 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
979 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
846 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
980 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
847 | # find the size of the columns to format the output nicely |
|
981 | # find the size of the columns to format the output nicely | |
848 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
982 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
849 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
983 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
850 | # table header |
|
984 | # table header | |
851 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
985 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
852 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
986 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
853 | # and the table itself |
|
987 | # and the table itself | |
854 | kb = 1024 |
|
988 | kb = 1024 | |
855 | Mb = 1048576 # kb**2 |
|
989 | Mb = 1048576 # kb**2 | |
856 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
990 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
857 | print itpl(vformat), |
|
991 | print itpl(vformat), | |
858 | if vtype in seq_types: |
|
992 | if vtype in seq_types: | |
859 | print len(var) |
|
993 | print len(var) | |
860 | elif vtype in [array_type,ndarray_type]: |
|
994 | elif vtype in [array_type,ndarray_type]: | |
861 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
995 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
862 | if vtype==ndarray_type: |
|
996 | if vtype==ndarray_type: | |
863 | # numpy |
|
997 | # numpy | |
864 | vsize = var.size |
|
998 | vsize = var.size | |
865 | vbytes = vsize*var.itemsize |
|
999 | vbytes = vsize*var.itemsize | |
866 | vdtype = var.dtype |
|
1000 | vdtype = var.dtype | |
867 | else: |
|
1001 | else: | |
868 | # Numeric |
|
1002 | # Numeric | |
869 | vsize = Numeric.size(var) |
|
1003 | vsize = Numeric.size(var) | |
870 | vbytes = vsize*var.itemsize() |
|
1004 | vbytes = vsize*var.itemsize() | |
871 | vdtype = var.typecode() |
|
1005 | vdtype = var.typecode() | |
872 |
|
1006 | |||
873 | if vbytes < 100000: |
|
1007 | if vbytes < 100000: | |
874 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
1008 | print aformat % (vshape,vsize,vdtype,vbytes) | |
875 | else: |
|
1009 | else: | |
876 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
1010 | print aformat % (vshape,vsize,vdtype,vbytes), | |
877 | if vbytes < Mb: |
|
1011 | if vbytes < Mb: | |
878 | print '(%s kb)' % (vbytes/kb,) |
|
1012 | print '(%s kb)' % (vbytes/kb,) | |
879 | else: |
|
1013 | else: | |
880 | print '(%s Mb)' % (vbytes/Mb,) |
|
1014 | print '(%s Mb)' % (vbytes/Mb,) | |
881 | else: |
|
1015 | else: | |
882 | try: |
|
1016 | try: | |
883 | vstr = str(var) |
|
1017 | vstr = str(var) | |
884 | except UnicodeEncodeError: |
|
1018 | except UnicodeEncodeError: | |
885 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
1019 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
886 | 'backslashreplace') |
|
1020 | 'backslashreplace') | |
887 | vstr = vstr.replace('\n','\\n') |
|
1021 | vstr = vstr.replace('\n','\\n') | |
888 | if len(vstr) < 50: |
|
1022 | if len(vstr) < 50: | |
889 | print vstr |
|
1023 | print vstr | |
890 | else: |
|
1024 | else: | |
891 | printpl(vfmt_short) |
|
1025 | printpl(vfmt_short) | |
892 |
|
1026 | |||
893 | def magic_reset(self, parameter_s=''): |
|
1027 | def magic_reset(self, parameter_s=''): | |
894 | """Resets the namespace by removing all names defined by the user. |
|
1028 | """Resets the namespace by removing all names defined by the user. | |
895 |
|
1029 | |||
896 | Input/Output history are left around in case you need them.""" |
|
1030 | Input/Output history are left around in case you need them.""" | |
897 |
|
1031 | |||
898 | ans = self.shell.ask_yes_no( |
|
1032 | ans = self.shell.ask_yes_no( | |
899 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1033 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
900 | if not ans: |
|
1034 | if not ans: | |
901 | print 'Nothing done.' |
|
1035 | print 'Nothing done.' | |
902 | return |
|
1036 | return | |
903 | user_ns = self.shell.user_ns |
|
1037 | user_ns = self.shell.user_ns | |
904 | for i in self.magic_who_ls(): |
|
1038 | for i in self.magic_who_ls(): | |
905 | del(user_ns[i]) |
|
1039 | del(user_ns[i]) | |
906 |
|
1040 | |||
907 | def magic_logstart(self,parameter_s=''): |
|
1041 | def magic_logstart(self,parameter_s=''): | |
908 | """Start logging anywhere in a session. |
|
1042 | """Start logging anywhere in a session. | |
909 |
|
1043 | |||
910 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1044 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
911 |
|
1045 | |||
912 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1046 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
913 | current directory, in 'rotate' mode (see below). |
|
1047 | current directory, in 'rotate' mode (see below). | |
914 |
|
1048 | |||
915 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1049 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
916 | history up to that point and then continues logging. |
|
1050 | history up to that point and then continues logging. | |
917 |
|
1051 | |||
918 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1052 | %logstart takes a second optional parameter: logging mode. This can be one | |
919 | of (note that the modes are given unquoted):\\ |
|
1053 | of (note that the modes are given unquoted):\\ | |
920 | append: well, that says it.\\ |
|
1054 | append: well, that says it.\\ | |
921 | backup: rename (if exists) to name~ and start name.\\ |
|
1055 | backup: rename (if exists) to name~ and start name.\\ | |
922 | global: single logfile in your home dir, appended to.\\ |
|
1056 | global: single logfile in your home dir, appended to.\\ | |
923 | over : overwrite existing log.\\ |
|
1057 | over : overwrite existing log.\\ | |
924 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1058 | rotate: create rotating logs name.1~, name.2~, etc. | |
925 |
|
1059 | |||
926 | Options: |
|
1060 | Options: | |
927 |
|
1061 | |||
928 | -o: log also IPython's output. In this mode, all commands which |
|
1062 | -o: log also IPython's output. In this mode, all commands which | |
929 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1063 | generate an Out[NN] prompt are recorded to the logfile, right after | |
930 | their corresponding input line. The output lines are always |
|
1064 | their corresponding input line. The output lines are always | |
931 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1065 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
932 | Python code. |
|
1066 | Python code. | |
933 |
|
1067 | |||
934 | Since this marker is always the same, filtering only the output from |
|
1068 | Since this marker is always the same, filtering only the output from | |
935 | a log is very easy, using for example a simple awk call: |
|
1069 | a log is very easy, using for example a simple awk call: | |
936 |
|
1070 | |||
937 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1071 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
938 |
|
1072 | |||
939 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1073 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
940 | input, so that user lines are logged in their final form, converted |
|
1074 | input, so that user lines are logged in their final form, converted | |
941 | into valid Python. For example, %Exit is logged as |
|
1075 | into valid Python. For example, %Exit is logged as | |
942 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1076 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
943 | exactly as typed, with no transformations applied. |
|
1077 | exactly as typed, with no transformations applied. | |
944 |
|
1078 | |||
945 | -t: put timestamps before each input line logged (these are put in |
|
1079 | -t: put timestamps before each input line logged (these are put in | |
946 | comments).""" |
|
1080 | comments).""" | |
947 |
|
1081 | |||
948 | opts,par = self.parse_options(parameter_s,'ort') |
|
1082 | opts,par = self.parse_options(parameter_s,'ort') | |
949 | log_output = 'o' in opts |
|
1083 | log_output = 'o' in opts | |
950 | log_raw_input = 'r' in opts |
|
1084 | log_raw_input = 'r' in opts | |
951 | timestamp = 't' in opts |
|
1085 | timestamp = 't' in opts | |
952 |
|
1086 | |||
953 | rc = self.shell.rc |
|
1087 | rc = self.shell.rc | |
954 | logger = self.shell.logger |
|
1088 | logger = self.shell.logger | |
955 |
|
1089 | |||
956 | # if no args are given, the defaults set in the logger constructor by |
|
1090 | # if no args are given, the defaults set in the logger constructor by | |
957 | # ipytohn remain valid |
|
1091 | # ipytohn remain valid | |
958 | if par: |
|
1092 | if par: | |
959 | try: |
|
1093 | try: | |
960 | logfname,logmode = par.split() |
|
1094 | logfname,logmode = par.split() | |
961 | except: |
|
1095 | except: | |
962 | logfname = par |
|
1096 | logfname = par | |
963 | logmode = 'backup' |
|
1097 | logmode = 'backup' | |
964 | else: |
|
1098 | else: | |
965 | logfname = logger.logfname |
|
1099 | logfname = logger.logfname | |
966 | logmode = logger.logmode |
|
1100 | logmode = logger.logmode | |
967 | # put logfname into rc struct as if it had been called on the command |
|
1101 | # put logfname into rc struct as if it had been called on the command | |
968 | # line, so it ends up saved in the log header Save it in case we need |
|
1102 | # line, so it ends up saved in the log header Save it in case we need | |
969 | # to restore it... |
|
1103 | # to restore it... | |
970 | old_logfile = rc.opts.get('logfile','') |
|
1104 | old_logfile = rc.opts.get('logfile','') | |
971 | if logfname: |
|
1105 | if logfname: | |
972 | logfname = os.path.expanduser(logfname) |
|
1106 | logfname = os.path.expanduser(logfname) | |
973 | rc.opts.logfile = logfname |
|
1107 | rc.opts.logfile = logfname | |
974 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) |
|
1108 | loghead = self.shell.loghead_tpl % (rc.opts,rc.args) | |
975 | try: |
|
1109 | try: | |
976 | started = logger.logstart(logfname,loghead,logmode, |
|
1110 | started = logger.logstart(logfname,loghead,logmode, | |
977 | log_output,timestamp,log_raw_input) |
|
1111 | log_output,timestamp,log_raw_input) | |
978 | except: |
|
1112 | except: | |
979 | rc.opts.logfile = old_logfile |
|
1113 | rc.opts.logfile = old_logfile | |
980 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1114 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
981 | else: |
|
1115 | else: | |
982 | # log input history up to this point, optionally interleaving |
|
1116 | # log input history up to this point, optionally interleaving | |
983 | # output if requested |
|
1117 | # output if requested | |
984 |
|
1118 | |||
985 | if timestamp: |
|
1119 | if timestamp: | |
986 | # disable timestamping for the previous history, since we've |
|
1120 | # disable timestamping for the previous history, since we've | |
987 | # lost those already (no time machine here). |
|
1121 | # lost those already (no time machine here). | |
988 | logger.timestamp = False |
|
1122 | logger.timestamp = False | |
989 |
|
1123 | |||
990 | if log_raw_input: |
|
1124 | if log_raw_input: | |
991 | input_hist = self.shell.input_hist_raw |
|
1125 | input_hist = self.shell.input_hist_raw | |
992 | else: |
|
1126 | else: | |
993 | input_hist = self.shell.input_hist |
|
1127 | input_hist = self.shell.input_hist | |
994 |
|
1128 | |||
995 | if log_output: |
|
1129 | if log_output: | |
996 | log_write = logger.log_write |
|
1130 | log_write = logger.log_write | |
997 | output_hist = self.shell.output_hist |
|
1131 | output_hist = self.shell.output_hist | |
998 | for n in range(1,len(input_hist)-1): |
|
1132 | for n in range(1,len(input_hist)-1): | |
999 | log_write(input_hist[n].rstrip()) |
|
1133 | log_write(input_hist[n].rstrip()) | |
1000 | if n in output_hist: |
|
1134 | if n in output_hist: | |
1001 | log_write(repr(output_hist[n]),'output') |
|
1135 | log_write(repr(output_hist[n]),'output') | |
1002 | else: |
|
1136 | else: | |
1003 | logger.log_write(input_hist[1:]) |
|
1137 | logger.log_write(input_hist[1:]) | |
1004 | if timestamp: |
|
1138 | if timestamp: | |
1005 | # re-enable timestamping |
|
1139 | # re-enable timestamping | |
1006 | logger.timestamp = True |
|
1140 | logger.timestamp = True | |
1007 |
|
1141 | |||
1008 | print ('Activating auto-logging. ' |
|
1142 | print ('Activating auto-logging. ' | |
1009 | 'Current session state plus future input saved.') |
|
1143 | 'Current session state plus future input saved.') | |
1010 | logger.logstate() |
|
1144 | logger.logstate() | |
1011 |
|
1145 | |||
1012 | def magic_logoff(self,parameter_s=''): |
|
1146 | def magic_logoff(self,parameter_s=''): | |
1013 | """Temporarily stop logging. |
|
1147 | """Temporarily stop logging. | |
1014 |
|
1148 | |||
1015 | You must have previously started logging.""" |
|
1149 | You must have previously started logging.""" | |
1016 | self.shell.logger.switch_log(0) |
|
1150 | self.shell.logger.switch_log(0) | |
1017 |
|
1151 | |||
1018 | def magic_logon(self,parameter_s=''): |
|
1152 | def magic_logon(self,parameter_s=''): | |
1019 | """Restart logging. |
|
1153 | """Restart logging. | |
1020 |
|
1154 | |||
1021 | This function is for restarting logging which you've temporarily |
|
1155 | This function is for restarting logging which you've temporarily | |
1022 | stopped with %logoff. For starting logging for the first time, you |
|
1156 | stopped with %logoff. For starting logging for the first time, you | |
1023 | must use the %logstart function, which allows you to specify an |
|
1157 | must use the %logstart function, which allows you to specify an | |
1024 | optional log filename.""" |
|
1158 | optional log filename.""" | |
1025 |
|
1159 | |||
1026 | self.shell.logger.switch_log(1) |
|
1160 | self.shell.logger.switch_log(1) | |
1027 |
|
1161 | |||
1028 | def magic_logstate(self,parameter_s=''): |
|
1162 | def magic_logstate(self,parameter_s=''): | |
1029 | """Print the status of the logging system.""" |
|
1163 | """Print the status of the logging system.""" | |
1030 |
|
1164 | |||
1031 | self.shell.logger.logstate() |
|
1165 | self.shell.logger.logstate() | |
1032 |
|
1166 | |||
1033 | def magic_pdb(self, parameter_s=''): |
|
1167 | def magic_pdb(self, parameter_s=''): | |
1034 | """Control the automatic calling of the pdb interactive debugger. |
|
1168 | """Control the automatic calling of the pdb interactive debugger. | |
1035 |
|
1169 | |||
1036 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1170 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1037 | argument it works as a toggle. |
|
1171 | argument it works as a toggle. | |
1038 |
|
1172 | |||
1039 | When an exception is triggered, IPython can optionally call the |
|
1173 | When an exception is triggered, IPython can optionally call the | |
1040 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1174 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1041 | this feature on and off. |
|
1175 | this feature on and off. | |
1042 |
|
1176 | |||
1043 | The initial state of this feature is set in your ipythonrc |
|
1177 | The initial state of this feature is set in your ipythonrc | |
1044 | configuration file (the variable is called 'pdb'). |
|
1178 | configuration file (the variable is called 'pdb'). | |
1045 |
|
1179 | |||
1046 | If you want to just activate the debugger AFTER an exception has fired, |
|
1180 | If you want to just activate the debugger AFTER an exception has fired, | |
1047 | without having to type '%pdb on' and rerunning your code, you can use |
|
1181 | without having to type '%pdb on' and rerunning your code, you can use | |
1048 | the %debug magic.""" |
|
1182 | the %debug magic.""" | |
1049 |
|
1183 | |||
1050 | par = parameter_s.strip().lower() |
|
1184 | par = parameter_s.strip().lower() | |
1051 |
|
1185 | |||
1052 | if par: |
|
1186 | if par: | |
1053 | try: |
|
1187 | try: | |
1054 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1188 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1055 | except KeyError: |
|
1189 | except KeyError: | |
1056 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1190 | print ('Incorrect argument. Use on/1, off/0, ' | |
1057 | 'or nothing for a toggle.') |
|
1191 | 'or nothing for a toggle.') | |
1058 | return |
|
1192 | return | |
1059 | else: |
|
1193 | else: | |
1060 | # toggle |
|
1194 | # toggle | |
1061 | new_pdb = not self.shell.call_pdb |
|
1195 | new_pdb = not self.shell.call_pdb | |
1062 |
|
1196 | |||
1063 | # set on the shell |
|
1197 | # set on the shell | |
1064 | self.shell.call_pdb = new_pdb |
|
1198 | self.shell.call_pdb = new_pdb | |
1065 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1199 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1066 |
|
1200 | |||
1067 | def magic_debug(self, parameter_s=''): |
|
1201 | def magic_debug(self, parameter_s=''): | |
1068 | """Activate the interactive debugger in post-mortem mode. |
|
1202 | """Activate the interactive debugger in post-mortem mode. | |
1069 |
|
1203 | |||
1070 | If an exception has just occurred, this lets you inspect its stack |
|
1204 | If an exception has just occurred, this lets you inspect its stack | |
1071 | frames interactively. Note that this will always work only on the last |
|
1205 | frames interactively. Note that this will always work only on the last | |
1072 | traceback that occurred, so you must call this quickly after an |
|
1206 | traceback that occurred, so you must call this quickly after an | |
1073 | exception that you wish to inspect has fired, because if another one |
|
1207 | exception that you wish to inspect has fired, because if another one | |
1074 | occurs, it clobbers the previous one. |
|
1208 | occurs, it clobbers the previous one. | |
1075 |
|
1209 | |||
1076 | If you want IPython to automatically do this on every exception, see |
|
1210 | If you want IPython to automatically do this on every exception, see | |
1077 | the %pdb magic for more details. |
|
1211 | the %pdb magic for more details. | |
1078 | """ |
|
1212 | """ | |
1079 |
|
1213 | |||
1080 | self.shell.debugger(force=True) |
|
1214 | self.shell.debugger(force=True) | |
1081 |
|
1215 | |||
1082 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1216 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1083 | opts=None,arg_lst=None,prog_ns=None): |
|
1217 | opts=None,arg_lst=None,prog_ns=None): | |
1084 |
|
1218 | |||
1085 | """Run a statement through the python code profiler. |
|
1219 | """Run a statement through the python code profiler. | |
1086 |
|
1220 | |||
1087 | Usage:\\ |
|
1221 | Usage:\\ | |
1088 | %prun [options] statement |
|
1222 | %prun [options] statement | |
1089 |
|
1223 | |||
1090 | The given statement (which doesn't require quote marks) is run via the |
|
1224 | The given statement (which doesn't require quote marks) is run via the | |
1091 | python profiler in a manner similar to the profile.run() function. |
|
1225 | python profiler in a manner similar to the profile.run() function. | |
1092 | Namespaces are internally managed to work correctly; profile.run |
|
1226 | Namespaces are internally managed to work correctly; profile.run | |
1093 | cannot be used in IPython because it makes certain assumptions about |
|
1227 | cannot be used in IPython because it makes certain assumptions about | |
1094 | namespaces which do not hold under IPython. |
|
1228 | namespaces which do not hold under IPython. | |
1095 |
|
1229 | |||
1096 | Options: |
|
1230 | Options: | |
1097 |
|
1231 | |||
1098 | -l <limit>: you can place restrictions on what or how much of the |
|
1232 | -l <limit>: you can place restrictions on what or how much of the | |
1099 | profile gets printed. The limit value can be: |
|
1233 | profile gets printed. The limit value can be: | |
1100 |
|
1234 | |||
1101 | * A string: only information for function names containing this string |
|
1235 | * A string: only information for function names containing this string | |
1102 | is printed. |
|
1236 | is printed. | |
1103 |
|
1237 | |||
1104 | * An integer: only these many lines are printed. |
|
1238 | * An integer: only these many lines are printed. | |
1105 |
|
1239 | |||
1106 | * A float (between 0 and 1): this fraction of the report is printed |
|
1240 | * A float (between 0 and 1): this fraction of the report is printed | |
1107 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1241 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1108 |
|
1242 | |||
1109 | You can combine several limits with repeated use of the option. For |
|
1243 | You can combine several limits with repeated use of the option. For | |
1110 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1244 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1111 | information about class constructors. |
|
1245 | information about class constructors. | |
1112 |
|
1246 | |||
1113 | -r: return the pstats.Stats object generated by the profiling. This |
|
1247 | -r: return the pstats.Stats object generated by the profiling. This | |
1114 | object has all the information about the profile in it, and you can |
|
1248 | object has all the information about the profile in it, and you can | |
1115 | later use it for further analysis or in other functions. |
|
1249 | later use it for further analysis or in other functions. | |
1116 |
|
1250 | |||
1117 | -s <key>: sort profile by given key. You can provide more than one key |
|
1251 | -s <key>: sort profile by given key. You can provide more than one key | |
1118 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1252 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1119 | default sorting key is 'time'. |
|
1253 | default sorting key is 'time'. | |
1120 |
|
1254 | |||
1121 | The following is copied verbatim from the profile documentation |
|
1255 | The following is copied verbatim from the profile documentation | |
1122 | referenced below: |
|
1256 | referenced below: | |
1123 |
|
1257 | |||
1124 | When more than one key is provided, additional keys are used as |
|
1258 | When more than one key is provided, additional keys are used as | |
1125 | secondary criteria when the there is equality in all keys selected |
|
1259 | secondary criteria when the there is equality in all keys selected | |
1126 | before them. |
|
1260 | before them. | |
1127 |
|
1261 | |||
1128 | Abbreviations can be used for any key names, as long as the |
|
1262 | Abbreviations can be used for any key names, as long as the | |
1129 | abbreviation is unambiguous. The following are the keys currently |
|
1263 | abbreviation is unambiguous. The following are the keys currently | |
1130 | defined: |
|
1264 | defined: | |
1131 |
|
1265 | |||
1132 | Valid Arg Meaning\\ |
|
1266 | Valid Arg Meaning\\ | |
1133 | "calls" call count\\ |
|
1267 | "calls" call count\\ | |
1134 | "cumulative" cumulative time\\ |
|
1268 | "cumulative" cumulative time\\ | |
1135 | "file" file name\\ |
|
1269 | "file" file name\\ | |
1136 | "module" file name\\ |
|
1270 | "module" file name\\ | |
1137 | "pcalls" primitive call count\\ |
|
1271 | "pcalls" primitive call count\\ | |
1138 | "line" line number\\ |
|
1272 | "line" line number\\ | |
1139 | "name" function name\\ |
|
1273 | "name" function name\\ | |
1140 | "nfl" name/file/line\\ |
|
1274 | "nfl" name/file/line\\ | |
1141 | "stdname" standard name\\ |
|
1275 | "stdname" standard name\\ | |
1142 | "time" internal time |
|
1276 | "time" internal time | |
1143 |
|
1277 | |||
1144 | Note that all sorts on statistics are in descending order (placing |
|
1278 | Note that all sorts on statistics are in descending order (placing | |
1145 | most time consuming items first), where as name, file, and line number |
|
1279 | most time consuming items first), where as name, file, and line number | |
1146 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1280 | searches are in ascending order (i.e., alphabetical). The subtle | |
1147 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1281 | distinction between "nfl" and "stdname" is that the standard name is a | |
1148 | sort of the name as printed, which means that the embedded line |
|
1282 | sort of the name as printed, which means that the embedded line | |
1149 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1283 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1150 | would (if the file names were the same) appear in the string order |
|
1284 | would (if the file names were the same) appear in the string order | |
1151 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1285 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1152 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1286 | line numbers. In fact, sort_stats("nfl") is the same as | |
1153 | sort_stats("name", "file", "line"). |
|
1287 | sort_stats("name", "file", "line"). | |
1154 |
|
1288 | |||
1155 | -T <filename>: save profile results as shown on screen to a text |
|
1289 | -T <filename>: save profile results as shown on screen to a text | |
1156 | file. The profile is still shown on screen. |
|
1290 | file. The profile is still shown on screen. | |
1157 |
|
1291 | |||
1158 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1292 | -D <filename>: save (via dump_stats) profile statistics to given | |
1159 | filename. This data is in a format understod by the pstats module, and |
|
1293 | filename. This data is in a format understod by the pstats module, and | |
1160 | is generated by a call to the dump_stats() method of profile |
|
1294 | is generated by a call to the dump_stats() method of profile | |
1161 | objects. The profile is still shown on screen. |
|
1295 | objects. The profile is still shown on screen. | |
1162 |
|
1296 | |||
1163 | If you want to run complete programs under the profiler's control, use |
|
1297 | If you want to run complete programs under the profiler's control, use | |
1164 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1298 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1165 | contains profiler specific options as described here. |
|
1299 | contains profiler specific options as described here. | |
1166 |
|
1300 | |||
1167 | You can read the complete documentation for the profile module with:\\ |
|
1301 | You can read the complete documentation for the profile module with:\\ | |
1168 | In [1]: import profile; profile.help() """ |
|
1302 | In [1]: import profile; profile.help() """ | |
1169 |
|
1303 | |||
1170 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1304 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1171 | # protect user quote marks |
|
1305 | # protect user quote marks | |
1172 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1306 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1173 |
|
1307 | |||
1174 | if user_mode: # regular user call |
|
1308 | if user_mode: # regular user call | |
1175 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1309 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1176 | list_all=1) |
|
1310 | list_all=1) | |
1177 | namespace = self.shell.user_ns |
|
1311 | namespace = self.shell.user_ns | |
1178 | else: # called to run a program by %run -p |
|
1312 | else: # called to run a program by %run -p | |
1179 | try: |
|
1313 | try: | |
1180 | filename = get_py_filename(arg_lst[0]) |
|
1314 | filename = get_py_filename(arg_lst[0]) | |
1181 | except IOError,msg: |
|
1315 | except IOError,msg: | |
1182 | error(msg) |
|
1316 | error(msg) | |
1183 | return |
|
1317 | return | |
1184 |
|
1318 | |||
1185 | arg_str = 'execfile(filename,prog_ns)' |
|
1319 | arg_str = 'execfile(filename,prog_ns)' | |
1186 | namespace = locals() |
|
1320 | namespace = locals() | |
1187 |
|
1321 | |||
1188 | opts.merge(opts_def) |
|
1322 | opts.merge(opts_def) | |
1189 |
|
1323 | |||
1190 | prof = profile.Profile() |
|
1324 | prof = profile.Profile() | |
1191 | try: |
|
1325 | try: | |
1192 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1326 | prof = prof.runctx(arg_str,namespace,namespace) | |
1193 | sys_exit = '' |
|
1327 | sys_exit = '' | |
1194 | except SystemExit: |
|
1328 | except SystemExit: | |
1195 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1329 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1196 |
|
1330 | |||
1197 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1331 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1198 |
|
1332 | |||
1199 | lims = opts.l |
|
1333 | lims = opts.l | |
1200 | if lims: |
|
1334 | if lims: | |
1201 | lims = [] # rebuild lims with ints/floats/strings |
|
1335 | lims = [] # rebuild lims with ints/floats/strings | |
1202 | for lim in opts.l: |
|
1336 | for lim in opts.l: | |
1203 | try: |
|
1337 | try: | |
1204 | lims.append(int(lim)) |
|
1338 | lims.append(int(lim)) | |
1205 | except ValueError: |
|
1339 | except ValueError: | |
1206 | try: |
|
1340 | try: | |
1207 | lims.append(float(lim)) |
|
1341 | lims.append(float(lim)) | |
1208 | except ValueError: |
|
1342 | except ValueError: | |
1209 | lims.append(lim) |
|
1343 | lims.append(lim) | |
1210 |
|
1344 | |||
1211 | # Trap output. |
|
1345 | # Trap output. | |
1212 | stdout_trap = StringIO() |
|
1346 | stdout_trap = StringIO() | |
1213 |
|
1347 | |||
1214 | if hasattr(stats,'stream'): |
|
1348 | if hasattr(stats,'stream'): | |
1215 | # In newer versions of python, the stats object has a 'stream' |
|
1349 | # In newer versions of python, the stats object has a 'stream' | |
1216 | # attribute to write into. |
|
1350 | # attribute to write into. | |
1217 | stats.stream = stdout_trap |
|
1351 | stats.stream = stdout_trap | |
1218 | stats.print_stats(*lims) |
|
1352 | stats.print_stats(*lims) | |
1219 | else: |
|
1353 | else: | |
1220 | # For older versions, we manually redirect stdout during printing |
|
1354 | # For older versions, we manually redirect stdout during printing | |
1221 | sys_stdout = sys.stdout |
|
1355 | sys_stdout = sys.stdout | |
1222 | try: |
|
1356 | try: | |
1223 | sys.stdout = stdout_trap |
|
1357 | sys.stdout = stdout_trap | |
1224 | stats.print_stats(*lims) |
|
1358 | stats.print_stats(*lims) | |
1225 | finally: |
|
1359 | finally: | |
1226 | sys.stdout = sys_stdout |
|
1360 | sys.stdout = sys_stdout | |
1227 |
|
1361 | |||
1228 | output = stdout_trap.getvalue() |
|
1362 | output = stdout_trap.getvalue() | |
1229 | output = output.rstrip() |
|
1363 | output = output.rstrip() | |
1230 |
|
1364 | |||
1231 | page(output,screen_lines=self.shell.rc.screen_length) |
|
1365 | page(output,screen_lines=self.shell.rc.screen_length) | |
1232 | print sys_exit, |
|
1366 | print sys_exit, | |
1233 |
|
1367 | |||
1234 | dump_file = opts.D[0] |
|
1368 | dump_file = opts.D[0] | |
1235 | text_file = opts.T[0] |
|
1369 | text_file = opts.T[0] | |
1236 | if dump_file: |
|
1370 | if dump_file: | |
1237 | prof.dump_stats(dump_file) |
|
1371 | prof.dump_stats(dump_file) | |
1238 | print '\n*** Profile stats marshalled to file',\ |
|
1372 | print '\n*** Profile stats marshalled to file',\ | |
1239 | `dump_file`+'.',sys_exit |
|
1373 | `dump_file`+'.',sys_exit | |
1240 | if text_file: |
|
1374 | if text_file: | |
1241 | pfile = file(text_file,'w') |
|
1375 | pfile = file(text_file,'w') | |
1242 | pfile.write(output) |
|
1376 | pfile.write(output) | |
1243 | pfile.close() |
|
1377 | pfile.close() | |
1244 | print '\n*** Profile printout saved to text file',\ |
|
1378 | print '\n*** Profile printout saved to text file',\ | |
1245 | `text_file`+'.',sys_exit |
|
1379 | `text_file`+'.',sys_exit | |
1246 |
|
1380 | |||
1247 | if opts.has_key('r'): |
|
1381 | if opts.has_key('r'): | |
1248 | return stats |
|
1382 | return stats | |
1249 | else: |
|
1383 | else: | |
1250 | return None |
|
1384 | return None | |
1251 |
|
1385 | |||
1252 | def magic_run(self, parameter_s ='',runner=None): |
|
1386 | def magic_run(self, parameter_s ='',runner=None): | |
1253 | """Run the named file inside IPython as a program. |
|
1387 | """Run the named file inside IPython as a program. | |
1254 |
|
1388 | |||
1255 | Usage:\\ |
|
1389 | Usage:\\ | |
1256 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1390 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1257 |
|
1391 | |||
1258 | Parameters after the filename are passed as command-line arguments to |
|
1392 | Parameters after the filename are passed as command-line arguments to | |
1259 | the program (put in sys.argv). Then, control returns to IPython's |
|
1393 | the program (put in sys.argv). Then, control returns to IPython's | |
1260 | prompt. |
|
1394 | prompt. | |
1261 |
|
1395 | |||
1262 | This is similar to running at a system prompt:\\ |
|
1396 | This is similar to running at a system prompt:\\ | |
1263 | $ python file args\\ |
|
1397 | $ python file args\\ | |
1264 | but with the advantage of giving you IPython's tracebacks, and of |
|
1398 | but with the advantage of giving you IPython's tracebacks, and of | |
1265 | loading all variables into your interactive namespace for further use |
|
1399 | loading all variables into your interactive namespace for further use | |
1266 | (unless -p is used, see below). |
|
1400 | (unless -p is used, see below). | |
1267 |
|
1401 | |||
1268 | The file is executed in a namespace initially consisting only of |
|
1402 | The file is executed in a namespace initially consisting only of | |
1269 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1403 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1270 | sees its environment as if it were being run as a stand-alone |
|
1404 | sees its environment as if it were being run as a stand-alone | |
1271 | program. But after execution, the IPython interactive namespace gets |
|
1405 | program. But after execution, the IPython interactive namespace gets | |
1272 | updated with all variables defined in the program (except for __name__ |
|
1406 | updated with all variables defined in the program (except for __name__ | |
1273 | and sys.argv). This allows for very convenient loading of code for |
|
1407 | and sys.argv). This allows for very convenient loading of code for | |
1274 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1408 | interactive work, while giving each program a 'clean sheet' to run in. | |
1275 |
|
1409 | |||
1276 | Options: |
|
1410 | Options: | |
1277 |
|
1411 | |||
1278 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1412 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1279 | without extension (as python does under import). This allows running |
|
1413 | without extension (as python does under import). This allows running | |
1280 | scripts and reloading the definitions in them without calling code |
|
1414 | scripts and reloading the definitions in them without calling code | |
1281 | protected by an ' if __name__ == "__main__" ' clause. |
|
1415 | protected by an ' if __name__ == "__main__" ' clause. | |
1282 |
|
1416 | |||
1283 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1417 | -i: run the file in IPython's namespace instead of an empty one. This | |
1284 | is useful if you are experimenting with code written in a text editor |
|
1418 | is useful if you are experimenting with code written in a text editor | |
1285 | which depends on variables defined interactively. |
|
1419 | which depends on variables defined interactively. | |
1286 |
|
1420 | |||
1287 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1421 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1288 | being run. This is particularly useful if IPython is being used to |
|
1422 | being run. This is particularly useful if IPython is being used to | |
1289 | run unittests, which always exit with a sys.exit() call. In such |
|
1423 | run unittests, which always exit with a sys.exit() call. In such | |
1290 | cases you are interested in the output of the test results, not in |
|
1424 | cases you are interested in the output of the test results, not in | |
1291 | seeing a traceback of the unittest module. |
|
1425 | seeing a traceback of the unittest module. | |
1292 |
|
1426 | |||
1293 | -t: print timing information at the end of the run. IPython will give |
|
1427 | -t: print timing information at the end of the run. IPython will give | |
1294 | you an estimated CPU time consumption for your script, which under |
|
1428 | you an estimated CPU time consumption for your script, which under | |
1295 | Unix uses the resource module to avoid the wraparound problems of |
|
1429 | Unix uses the resource module to avoid the wraparound problems of | |
1296 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1430 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1297 | is also given (for Windows platforms this is reported as 0.0). |
|
1431 | is also given (for Windows platforms this is reported as 0.0). | |
1298 |
|
1432 | |||
1299 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1433 | If -t is given, an additional -N<N> option can be given, where <N> | |
1300 | must be an integer indicating how many times you want the script to |
|
1434 | must be an integer indicating how many times you want the script to | |
1301 | run. The final timing report will include total and per run results. |
|
1435 | run. The final timing report will include total and per run results. | |
1302 |
|
1436 | |||
1303 | For example (testing the script uniq_stable.py): |
|
1437 | For example (testing the script uniq_stable.py): | |
1304 |
|
1438 | |||
1305 | In [1]: run -t uniq_stable |
|
1439 | In [1]: run -t uniq_stable | |
1306 |
|
1440 | |||
1307 | IPython CPU timings (estimated):\\ |
|
1441 | IPython CPU timings (estimated):\\ | |
1308 | User : 0.19597 s.\\ |
|
1442 | User : 0.19597 s.\\ | |
1309 | System: 0.0 s.\\ |
|
1443 | System: 0.0 s.\\ | |
1310 |
|
1444 | |||
1311 | In [2]: run -t -N5 uniq_stable |
|
1445 | In [2]: run -t -N5 uniq_stable | |
1312 |
|
1446 | |||
1313 | IPython CPU timings (estimated):\\ |
|
1447 | IPython CPU timings (estimated):\\ | |
1314 | Total runs performed: 5\\ |
|
1448 | Total runs performed: 5\\ | |
1315 | Times : Total Per run\\ |
|
1449 | Times : Total Per run\\ | |
1316 | User : 0.910862 s, 0.1821724 s.\\ |
|
1450 | User : 0.910862 s, 0.1821724 s.\\ | |
1317 | System: 0.0 s, 0.0 s. |
|
1451 | System: 0.0 s, 0.0 s. | |
1318 |
|
1452 | |||
1319 | -d: run your program under the control of pdb, the Python debugger. |
|
1453 | -d: run your program under the control of pdb, the Python debugger. | |
1320 | This allows you to execute your program step by step, watch variables, |
|
1454 | This allows you to execute your program step by step, watch variables, | |
1321 | etc. Internally, what IPython does is similar to calling: |
|
1455 | etc. Internally, what IPython does is similar to calling: | |
1322 |
|
1456 | |||
1323 | pdb.run('execfile("YOURFILENAME")') |
|
1457 | pdb.run('execfile("YOURFILENAME")') | |
1324 |
|
1458 | |||
1325 | with a breakpoint set on line 1 of your file. You can change the line |
|
1459 | with a breakpoint set on line 1 of your file. You can change the line | |
1326 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1460 | number for this automatic breakpoint to be <N> by using the -bN option | |
1327 | (where N must be an integer). For example: |
|
1461 | (where N must be an integer). For example: | |
1328 |
|
1462 | |||
1329 | %run -d -b40 myscript |
|
1463 | %run -d -b40 myscript | |
1330 |
|
1464 | |||
1331 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1465 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1332 | the first breakpoint must be set on a line which actually does |
|
1466 | the first breakpoint must be set on a line which actually does | |
1333 | something (not a comment or docstring) for it to stop execution. |
|
1467 | something (not a comment or docstring) for it to stop execution. | |
1334 |
|
1468 | |||
1335 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1469 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1336 | first enter 'c' (without qoutes) to start execution up to the first |
|
1470 | first enter 'c' (without qoutes) to start execution up to the first | |
1337 | breakpoint. |
|
1471 | breakpoint. | |
1338 |
|
1472 | |||
1339 | Entering 'help' gives information about the use of the debugger. You |
|
1473 | Entering 'help' gives information about the use of the debugger. You | |
1340 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1474 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1341 | at a prompt. |
|
1475 | at a prompt. | |
1342 |
|
1476 | |||
1343 | -p: run program under the control of the Python profiler module (which |
|
1477 | -p: run program under the control of the Python profiler module (which | |
1344 | prints a detailed report of execution times, function calls, etc). |
|
1478 | prints a detailed report of execution times, function calls, etc). | |
1345 |
|
1479 | |||
1346 | You can pass other options after -p which affect the behavior of the |
|
1480 | You can pass other options after -p which affect the behavior of the | |
1347 | profiler itself. See the docs for %prun for details. |
|
1481 | profiler itself. See the docs for %prun for details. | |
1348 |
|
1482 | |||
1349 | In this mode, the program's variables do NOT propagate back to the |
|
1483 | In this mode, the program's variables do NOT propagate back to the | |
1350 | IPython interactive namespace (because they remain in the namespace |
|
1484 | IPython interactive namespace (because they remain in the namespace | |
1351 | where the profiler executes them). |
|
1485 | where the profiler executes them). | |
1352 |
|
1486 | |||
1353 | Internally this triggers a call to %prun, see its documentation for |
|
1487 | Internally this triggers a call to %prun, see its documentation for | |
1354 | details on the options available specifically for profiling. |
|
1488 | details on the options available specifically for profiling. | |
1355 |
|
1489 | |||
1356 | There is one special usage for which the text above doesn't apply: |
|
1490 | There is one special usage for which the text above doesn't apply: | |
1357 | if the filename ends with .ipy, the file is run as ipython script, |
|
1491 | if the filename ends with .ipy, the file is run as ipython script, | |
1358 | just as if the commands were written on IPython prompt. |
|
1492 | just as if the commands were written on IPython prompt. | |
1359 | """ |
|
1493 | """ | |
1360 |
|
1494 | |||
1361 | # get arguments and set sys.argv for program to be run. |
|
1495 | # get arguments and set sys.argv for program to be run. | |
1362 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1496 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1363 | mode='list',list_all=1) |
|
1497 | mode='list',list_all=1) | |
1364 |
|
1498 | |||
1365 | try: |
|
1499 | try: | |
1366 | filename = get_py_filename(arg_lst[0]) |
|
1500 | filename = get_py_filename(arg_lst[0]) | |
1367 | except IndexError: |
|
1501 | except IndexError: | |
1368 | warn('you must provide at least a filename.') |
|
1502 | warn('you must provide at least a filename.') | |
1369 | print '\n%run:\n',OInspect.getdoc(self.magic_run) |
|
1503 | print '\n%run:\n',OInspect.getdoc(self.magic_run) | |
1370 | return |
|
1504 | return | |
1371 | except IOError,msg: |
|
1505 | except IOError,msg: | |
1372 | error(msg) |
|
1506 | error(msg) | |
1373 | return |
|
1507 | return | |
1374 |
|
1508 | |||
1375 | if filename.lower().endswith('.ipy'): |
|
1509 | if filename.lower().endswith('.ipy'): | |
1376 | self.api.runlines(open(filename).read()) |
|
1510 | self.api.runlines(open(filename).read()) | |
1377 | return |
|
1511 | return | |
1378 |
|
1512 | |||
1379 | # Control the response to exit() calls made by the script being run |
|
1513 | # Control the response to exit() calls made by the script being run | |
1380 | exit_ignore = opts.has_key('e') |
|
1514 | exit_ignore = opts.has_key('e') | |
1381 |
|
1515 | |||
1382 | # Make sure that the running script gets a proper sys.argv as if it |
|
1516 | # Make sure that the running script gets a proper sys.argv as if it | |
1383 | # were run from a system shell. |
|
1517 | # were run from a system shell. | |
1384 | save_argv = sys.argv # save it for later restoring |
|
1518 | save_argv = sys.argv # save it for later restoring | |
1385 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1519 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1386 |
|
1520 | |||
1387 | if opts.has_key('i'): |
|
1521 | if opts.has_key('i'): | |
1388 | prog_ns = self.shell.user_ns |
|
1522 | prog_ns = self.shell.user_ns | |
1389 | __name__save = self.shell.user_ns['__name__'] |
|
1523 | __name__save = self.shell.user_ns['__name__'] | |
1390 | prog_ns['__name__'] = '__main__' |
|
1524 | prog_ns['__name__'] = '__main__' | |
1391 | else: |
|
1525 | else: | |
1392 | if opts.has_key('n'): |
|
1526 | if opts.has_key('n'): | |
1393 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1527 | name = os.path.splitext(os.path.basename(filename))[0] | |
1394 | else: |
|
1528 | else: | |
1395 | name = '__main__' |
|
1529 | name = '__main__' | |
1396 | prog_ns = {'__name__':name} |
|
1530 | prog_ns = {'__name__':name} | |
1397 |
|
1531 | |||
1398 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1532 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1399 | # set the __file__ global in the script's namespace |
|
1533 | # set the __file__ global in the script's namespace | |
1400 | prog_ns['__file__'] = filename |
|
1534 | prog_ns['__file__'] = filename | |
1401 |
|
1535 | |||
1402 | # pickle fix. See iplib for an explanation. But we need to make sure |
|
1536 | # pickle fix. See iplib for an explanation. But we need to make sure | |
1403 | # that, if we overwrite __main__, we replace it at the end |
|
1537 | # that, if we overwrite __main__, we replace it at the end | |
1404 | if prog_ns['__name__'] == '__main__': |
|
1538 | if prog_ns['__name__'] == '__main__': | |
1405 | restore_main = sys.modules['__main__'] |
|
1539 | restore_main = sys.modules['__main__'] | |
1406 | else: |
|
1540 | else: | |
1407 | restore_main = False |
|
1541 | restore_main = False | |
1408 |
|
1542 | |||
1409 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) |
|
1543 | sys.modules[prog_ns['__name__']] = FakeModule(prog_ns) | |
1410 |
|
1544 | |||
1411 | stats = None |
|
1545 | stats = None | |
1412 | try: |
|
1546 | try: | |
1413 | if self.shell.has_readline: |
|
1547 | if self.shell.has_readline: | |
1414 | self.shell.savehist() |
|
1548 | self.shell.savehist() | |
1415 |
|
1549 | |||
1416 | if opts.has_key('p'): |
|
1550 | if opts.has_key('p'): | |
1417 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1551 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1418 | else: |
|
1552 | else: | |
1419 | if opts.has_key('d'): |
|
1553 | if opts.has_key('d'): | |
1420 | deb = Debugger.Pdb(self.shell.rc.colors) |
|
1554 | deb = Debugger.Pdb(self.shell.rc.colors) | |
1421 | # reset Breakpoint state, which is moronically kept |
|
1555 | # reset Breakpoint state, which is moronically kept | |
1422 | # in a class |
|
1556 | # in a class | |
1423 | bdb.Breakpoint.next = 1 |
|
1557 | bdb.Breakpoint.next = 1 | |
1424 | bdb.Breakpoint.bplist = {} |
|
1558 | bdb.Breakpoint.bplist = {} | |
1425 | bdb.Breakpoint.bpbynumber = [None] |
|
1559 | bdb.Breakpoint.bpbynumber = [None] | |
1426 | # Set an initial breakpoint to stop execution |
|
1560 | # Set an initial breakpoint to stop execution | |
1427 | maxtries = 10 |
|
1561 | maxtries = 10 | |
1428 | bp = int(opts.get('b',[1])[0]) |
|
1562 | bp = int(opts.get('b',[1])[0]) | |
1429 | checkline = deb.checkline(filename,bp) |
|
1563 | checkline = deb.checkline(filename,bp) | |
1430 | if not checkline: |
|
1564 | if not checkline: | |
1431 | for bp in range(bp+1,bp+maxtries+1): |
|
1565 | for bp in range(bp+1,bp+maxtries+1): | |
1432 | if deb.checkline(filename,bp): |
|
1566 | if deb.checkline(filename,bp): | |
1433 | break |
|
1567 | break | |
1434 | else: |
|
1568 | else: | |
1435 | msg = ("\nI failed to find a valid line to set " |
|
1569 | msg = ("\nI failed to find a valid line to set " | |
1436 | "a breakpoint\n" |
|
1570 | "a breakpoint\n" | |
1437 | "after trying up to line: %s.\n" |
|
1571 | "after trying up to line: %s.\n" | |
1438 | "Please set a valid breakpoint manually " |
|
1572 | "Please set a valid breakpoint manually " | |
1439 | "with the -b option." % bp) |
|
1573 | "with the -b option." % bp) | |
1440 | error(msg) |
|
1574 | error(msg) | |
1441 | return |
|
1575 | return | |
1442 | # if we find a good linenumber, set the breakpoint |
|
1576 | # if we find a good linenumber, set the breakpoint | |
1443 | deb.do_break('%s:%s' % (filename,bp)) |
|
1577 | deb.do_break('%s:%s' % (filename,bp)) | |
1444 | # Start file run |
|
1578 | # Start file run | |
1445 | print "NOTE: Enter 'c' at the", |
|
1579 | print "NOTE: Enter 'c' at the", | |
1446 | print "%s prompt to start your script." % deb.prompt |
|
1580 | print "%s prompt to start your script." % deb.prompt | |
1447 | try: |
|
1581 | try: | |
1448 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1582 | deb.run('execfile("%s")' % filename,prog_ns) | |
1449 |
|
1583 | |||
1450 | except: |
|
1584 | except: | |
1451 | etype, value, tb = sys.exc_info() |
|
1585 | etype, value, tb = sys.exc_info() | |
1452 | # Skip three frames in the traceback: the %run one, |
|
1586 | # Skip three frames in the traceback: the %run one, | |
1453 | # one inside bdb.py, and the command-line typed by the |
|
1587 | # one inside bdb.py, and the command-line typed by the | |
1454 | # user (run by exec in pdb itself). |
|
1588 | # user (run by exec in pdb itself). | |
1455 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1589 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1456 | else: |
|
1590 | else: | |
1457 | if runner is None: |
|
1591 | if runner is None: | |
1458 | runner = self.shell.safe_execfile |
|
1592 | runner = self.shell.safe_execfile | |
1459 | if opts.has_key('t'): |
|
1593 | if opts.has_key('t'): | |
1460 | try: |
|
1594 | try: | |
1461 | nruns = int(opts['N'][0]) |
|
1595 | nruns = int(opts['N'][0]) | |
1462 | if nruns < 1: |
|
1596 | if nruns < 1: | |
1463 | error('Number of runs must be >=1') |
|
1597 | error('Number of runs must be >=1') | |
1464 | return |
|
1598 | return | |
1465 | except (KeyError): |
|
1599 | except (KeyError): | |
1466 | nruns = 1 |
|
1600 | nruns = 1 | |
1467 | if nruns == 1: |
|
1601 | if nruns == 1: | |
1468 | t0 = clock2() |
|
1602 | t0 = clock2() | |
1469 | runner(filename,prog_ns,prog_ns, |
|
1603 | runner(filename,prog_ns,prog_ns, | |
1470 | exit_ignore=exit_ignore) |
|
1604 | exit_ignore=exit_ignore) | |
1471 | t1 = clock2() |
|
1605 | t1 = clock2() | |
1472 | t_usr = t1[0]-t0[0] |
|
1606 | t_usr = t1[0]-t0[0] | |
1473 | t_sys = t1[1]-t1[1] |
|
1607 | t_sys = t1[1]-t1[1] | |
1474 | print "\nIPython CPU timings (estimated):" |
|
1608 | print "\nIPython CPU timings (estimated):" | |
1475 | print " User : %10s s." % t_usr |
|
1609 | print " User : %10s s." % t_usr | |
1476 | print " System: %10s s." % t_sys |
|
1610 | print " System: %10s s." % t_sys | |
1477 | else: |
|
1611 | else: | |
1478 | runs = range(nruns) |
|
1612 | runs = range(nruns) | |
1479 | t0 = clock2() |
|
1613 | t0 = clock2() | |
1480 | for nr in runs: |
|
1614 | for nr in runs: | |
1481 | runner(filename,prog_ns,prog_ns, |
|
1615 | runner(filename,prog_ns,prog_ns, | |
1482 | exit_ignore=exit_ignore) |
|
1616 | exit_ignore=exit_ignore) | |
1483 | t1 = clock2() |
|
1617 | t1 = clock2() | |
1484 | t_usr = t1[0]-t0[0] |
|
1618 | t_usr = t1[0]-t0[0] | |
1485 | t_sys = t1[1]-t1[1] |
|
1619 | t_sys = t1[1]-t1[1] | |
1486 | print "\nIPython CPU timings (estimated):" |
|
1620 | print "\nIPython CPU timings (estimated):" | |
1487 | print "Total runs performed:",nruns |
|
1621 | print "Total runs performed:",nruns | |
1488 | print " Times : %10s %10s" % ('Total','Per run') |
|
1622 | print " Times : %10s %10s" % ('Total','Per run') | |
1489 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1623 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1490 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1624 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1491 |
|
1625 | |||
1492 | else: |
|
1626 | else: | |
1493 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1627 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1494 | if opts.has_key('i'): |
|
1628 | if opts.has_key('i'): | |
1495 | self.shell.user_ns['__name__'] = __name__save |
|
1629 | self.shell.user_ns['__name__'] = __name__save | |
1496 | else: |
|
1630 | else: | |
1497 | # update IPython interactive namespace |
|
1631 | # update IPython interactive namespace | |
1498 | del prog_ns['__name__'] |
|
1632 | del prog_ns['__name__'] | |
1499 | self.shell.user_ns.update(prog_ns) |
|
1633 | self.shell.user_ns.update(prog_ns) | |
1500 | finally: |
|
1634 | finally: | |
1501 | sys.argv = save_argv |
|
1635 | sys.argv = save_argv | |
1502 | if restore_main: |
|
1636 | if restore_main: | |
1503 | sys.modules['__main__'] = restore_main |
|
1637 | sys.modules['__main__'] = restore_main | |
1504 | self.shell.reloadhist() |
|
1638 | self.shell.reloadhist() | |
1505 |
|
1639 | |||
1506 | return stats |
|
1640 | return stats | |
1507 |
|
1641 | |||
1508 | def magic_runlog(self, parameter_s =''): |
|
1642 | def magic_runlog(self, parameter_s =''): | |
1509 | """Run files as logs. |
|
1643 | """Run files as logs. | |
1510 |
|
1644 | |||
1511 | Usage:\\ |
|
1645 | Usage:\\ | |
1512 | %runlog file1 file2 ... |
|
1646 | %runlog file1 file2 ... | |
1513 |
|
1647 | |||
1514 | Run the named files (treating them as log files) in sequence inside |
|
1648 | Run the named files (treating them as log files) in sequence inside | |
1515 | the interpreter, and return to the prompt. This is much slower than |
|
1649 | the interpreter, and return to the prompt. This is much slower than | |
1516 | %run because each line is executed in a try/except block, but it |
|
1650 | %run because each line is executed in a try/except block, but it | |
1517 | allows running files with syntax errors in them. |
|
1651 | allows running files with syntax errors in them. | |
1518 |
|
1652 | |||
1519 | Normally IPython will guess when a file is one of its own logfiles, so |
|
1653 | Normally IPython will guess when a file is one of its own logfiles, so | |
1520 | you can typically use %run even for logs. This shorthand allows you to |
|
1654 | you can typically use %run even for logs. This shorthand allows you to | |
1521 | force any file to be treated as a log file.""" |
|
1655 | force any file to be treated as a log file.""" | |
1522 |
|
1656 | |||
1523 | for f in parameter_s.split(): |
|
1657 | for f in parameter_s.split(): | |
1524 | self.shell.safe_execfile(f,self.shell.user_ns, |
|
1658 | self.shell.safe_execfile(f,self.shell.user_ns, | |
1525 | self.shell.user_ns,islog=1) |
|
1659 | self.shell.user_ns,islog=1) | |
1526 |
|
1660 | |||
1527 | def magic_timeit(self, parameter_s =''): |
|
1661 | def magic_timeit(self, parameter_s =''): | |
1528 | """Time execution of a Python statement or expression |
|
1662 | """Time execution of a Python statement or expression | |
1529 |
|
1663 | |||
1530 | Usage:\\ |
|
1664 | Usage:\\ | |
1531 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1665 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1532 |
|
1666 | |||
1533 | Time execution of a Python statement or expression using the timeit |
|
1667 | Time execution of a Python statement or expression using the timeit | |
1534 | module. |
|
1668 | module. | |
1535 |
|
1669 | |||
1536 | Options: |
|
1670 | Options: | |
1537 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1671 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1538 | is not given, a fitting value is chosen. |
|
1672 | is not given, a fitting value is chosen. | |
1539 |
|
1673 | |||
1540 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1674 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1541 | Default: 3 |
|
1675 | Default: 3 | |
1542 |
|
1676 | |||
1543 | -t: use time.time to measure the time, which is the default on Unix. |
|
1677 | -t: use time.time to measure the time, which is the default on Unix. | |
1544 | This function measures wall time. |
|
1678 | This function measures wall time. | |
1545 |
|
1679 | |||
1546 | -c: use time.clock to measure the time, which is the default on |
|
1680 | -c: use time.clock to measure the time, which is the default on | |
1547 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1681 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1548 | instead and returns the CPU user time. |
|
1682 | instead and returns the CPU user time. | |
1549 |
|
1683 | |||
1550 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1684 | -p<P>: use a precision of <P> digits to display the timing result. | |
1551 | Default: 3 |
|
1685 | Default: 3 | |
1552 |
|
1686 | |||
1553 |
|
1687 | |||
1554 | Examples:\\ |
|
1688 | Examples:\\ | |
1555 | In [1]: %timeit pass |
|
1689 | In [1]: %timeit pass | |
1556 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1690 | 10000000 loops, best of 3: 53.3 ns per loop | |
1557 |
|
1691 | |||
1558 | In [2]: u = None |
|
1692 | In [2]: u = None | |
1559 |
|
1693 | |||
1560 | In [3]: %timeit u is None |
|
1694 | In [3]: %timeit u is None | |
1561 | 10000000 loops, best of 3: 184 ns per loop |
|
1695 | 10000000 loops, best of 3: 184 ns per loop | |
1562 |
|
1696 | |||
1563 | In [4]: %timeit -r 4 u == None |
|
1697 | In [4]: %timeit -r 4 u == None | |
1564 | 1000000 loops, best of 4: 242 ns per loop |
|
1698 | 1000000 loops, best of 4: 242 ns per loop | |
1565 |
|
1699 | |||
1566 | In [5]: import time |
|
1700 | In [5]: import time | |
1567 |
|
1701 | |||
1568 | In [6]: %timeit -n1 time.sleep(2) |
|
1702 | In [6]: %timeit -n1 time.sleep(2) | |
1569 | 1 loops, best of 3: 2 s per loop |
|
1703 | 1 loops, best of 3: 2 s per loop | |
1570 |
|
1704 | |||
1571 |
|
1705 | |||
1572 | The times reported by %timeit will be slightly higher than those |
|
1706 | The times reported by %timeit will be slightly higher than those | |
1573 | reported by the timeit.py script when variables are accessed. This is |
|
1707 | reported by the timeit.py script when variables are accessed. This is | |
1574 | due to the fact that %timeit executes the statement in the namespace |
|
1708 | due to the fact that %timeit executes the statement in the namespace | |
1575 | of the shell, compared with timeit.py, which uses a single setup |
|
1709 | of the shell, compared with timeit.py, which uses a single setup | |
1576 | statement to import function or create variables. Generally, the bias |
|
1710 | statement to import function or create variables. Generally, the bias | |
1577 | does not matter as long as results from timeit.py are not mixed with |
|
1711 | does not matter as long as results from timeit.py are not mixed with | |
1578 | those from %timeit.""" |
|
1712 | those from %timeit.""" | |
1579 |
|
1713 | |||
1580 | import timeit |
|
1714 | import timeit | |
1581 | import math |
|
1715 | import math | |
1582 |
|
1716 | |||
1583 | units = ["s", "ms", "\xc2\xb5s", "ns"] |
|
1717 | units = ["s", "ms", "\xc2\xb5s", "ns"] | |
1584 | scaling = [1, 1e3, 1e6, 1e9] |
|
1718 | scaling = [1, 1e3, 1e6, 1e9] | |
1585 |
|
1719 | |||
1586 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1720 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1587 | posix=False) |
|
1721 | posix=False) | |
1588 | if stmt == "": |
|
1722 | if stmt == "": | |
1589 | return |
|
1723 | return | |
1590 | timefunc = timeit.default_timer |
|
1724 | timefunc = timeit.default_timer | |
1591 | number = int(getattr(opts, "n", 0)) |
|
1725 | number = int(getattr(opts, "n", 0)) | |
1592 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1726 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1593 | precision = int(getattr(opts, "p", 3)) |
|
1727 | precision = int(getattr(opts, "p", 3)) | |
1594 | if hasattr(opts, "t"): |
|
1728 | if hasattr(opts, "t"): | |
1595 | timefunc = time.time |
|
1729 | timefunc = time.time | |
1596 | if hasattr(opts, "c"): |
|
1730 | if hasattr(opts, "c"): | |
1597 | timefunc = clock |
|
1731 | timefunc = clock | |
1598 |
|
1732 | |||
1599 | timer = timeit.Timer(timer=timefunc) |
|
1733 | timer = timeit.Timer(timer=timefunc) | |
1600 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1734 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1601 | # but is there a better way to achieve that the code stmt has access |
|
1735 | # but is there a better way to achieve that the code stmt has access | |
1602 | # to the shell namespace? |
|
1736 | # to the shell namespace? | |
1603 |
|
1737 | |||
1604 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1738 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1605 | 'setup': "pass"} |
|
1739 | 'setup': "pass"} | |
1606 | code = compile(src, "<magic-timeit>", "exec") |
|
1740 | code = compile(src, "<magic-timeit>", "exec") | |
1607 | ns = {} |
|
1741 | ns = {} | |
1608 | exec code in self.shell.user_ns, ns |
|
1742 | exec code in self.shell.user_ns, ns | |
1609 | timer.inner = ns["inner"] |
|
1743 | timer.inner = ns["inner"] | |
1610 |
|
1744 | |||
1611 | if number == 0: |
|
1745 | if number == 0: | |
1612 | # determine number so that 0.2 <= total time < 2.0 |
|
1746 | # determine number so that 0.2 <= total time < 2.0 | |
1613 | number = 1 |
|
1747 | number = 1 | |
1614 | for i in range(1, 10): |
|
1748 | for i in range(1, 10): | |
1615 | number *= 10 |
|
1749 | number *= 10 | |
1616 | if timer.timeit(number) >= 0.2: |
|
1750 | if timer.timeit(number) >= 0.2: | |
1617 | break |
|
1751 | break | |
1618 |
|
1752 | |||
1619 | best = min(timer.repeat(repeat, number)) / number |
|
1753 | best = min(timer.repeat(repeat, number)) / number | |
1620 |
|
1754 | |||
1621 | if best > 0.0: |
|
1755 | if best > 0.0: | |
1622 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1756 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1623 | else: |
|
1757 | else: | |
1624 | order = 3 |
|
1758 | order = 3 | |
1625 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1759 | print "%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1626 | precision, |
|
1760 | precision, | |
1627 | best * scaling[order], |
|
1761 | best * scaling[order], | |
1628 | units[order]) |
|
1762 | units[order]) | |
1629 |
|
1763 | |||
1630 | def magic_time(self,parameter_s = ''): |
|
1764 | def magic_time(self,parameter_s = ''): | |
1631 | """Time execution of a Python statement or expression. |
|
1765 | """Time execution of a Python statement or expression. | |
1632 |
|
1766 | |||
1633 | The CPU and wall clock times are printed, and the value of the |
|
1767 | The CPU and wall clock times are printed, and the value of the | |
1634 | expression (if any) is returned. Note that under Win32, system time |
|
1768 | expression (if any) is returned. Note that under Win32, system time | |
1635 | is always reported as 0, since it can not be measured. |
|
1769 | is always reported as 0, since it can not be measured. | |
1636 |
|
1770 | |||
1637 | This function provides very basic timing functionality. In Python |
|
1771 | This function provides very basic timing functionality. In Python | |
1638 | 2.3, the timeit module offers more control and sophistication, so this |
|
1772 | 2.3, the timeit module offers more control and sophistication, so this | |
1639 | could be rewritten to use it (patches welcome). |
|
1773 | could be rewritten to use it (patches welcome). | |
1640 |
|
1774 | |||
1641 | Some examples: |
|
1775 | Some examples: | |
1642 |
|
1776 | |||
1643 | In [1]: time 2**128 |
|
1777 | In [1]: time 2**128 | |
1644 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1778 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1645 | Wall time: 0.00 |
|
1779 | Wall time: 0.00 | |
1646 | Out[1]: 340282366920938463463374607431768211456L |
|
1780 | Out[1]: 340282366920938463463374607431768211456L | |
1647 |
|
1781 | |||
1648 | In [2]: n = 1000000 |
|
1782 | In [2]: n = 1000000 | |
1649 |
|
1783 | |||
1650 | In [3]: time sum(range(n)) |
|
1784 | In [3]: time sum(range(n)) | |
1651 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1785 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1652 | Wall time: 1.37 |
|
1786 | Wall time: 1.37 | |
1653 | Out[3]: 499999500000L |
|
1787 | Out[3]: 499999500000L | |
1654 |
|
1788 | |||
1655 | In [4]: time print 'hello world' |
|
1789 | In [4]: time print 'hello world' | |
1656 | hello world |
|
1790 | hello world | |
1657 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1791 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1658 | Wall time: 0.00 |
|
1792 | Wall time: 0.00 | |
1659 | """ |
|
1793 | """ | |
1660 |
|
1794 | |||
1661 | # fail immediately if the given expression can't be compiled |
|
1795 | # fail immediately if the given expression can't be compiled | |
1662 |
|
1796 | |||
1663 | expr = self.shell.prefilter(parameter_s,False) |
|
1797 | expr = self.shell.prefilter(parameter_s,False) | |
1664 |
|
1798 | |||
1665 | try: |
|
1799 | try: | |
1666 | mode = 'eval' |
|
1800 | mode = 'eval' | |
1667 | code = compile(expr,'<timed eval>',mode) |
|
1801 | code = compile(expr,'<timed eval>',mode) | |
1668 | except SyntaxError: |
|
1802 | except SyntaxError: | |
1669 | mode = 'exec' |
|
1803 | mode = 'exec' | |
1670 | code = compile(expr,'<timed exec>',mode) |
|
1804 | code = compile(expr,'<timed exec>',mode) | |
1671 | # skew measurement as little as possible |
|
1805 | # skew measurement as little as possible | |
1672 | glob = self.shell.user_ns |
|
1806 | glob = self.shell.user_ns | |
1673 | clk = clock2 |
|
1807 | clk = clock2 | |
1674 | wtime = time.time |
|
1808 | wtime = time.time | |
1675 | # time execution |
|
1809 | # time execution | |
1676 | wall_st = wtime() |
|
1810 | wall_st = wtime() | |
1677 | if mode=='eval': |
|
1811 | if mode=='eval': | |
1678 | st = clk() |
|
1812 | st = clk() | |
1679 | out = eval(code,glob) |
|
1813 | out = eval(code,glob) | |
1680 | end = clk() |
|
1814 | end = clk() | |
1681 | else: |
|
1815 | else: | |
1682 | st = clk() |
|
1816 | st = clk() | |
1683 | exec code in glob |
|
1817 | exec code in glob | |
1684 | end = clk() |
|
1818 | end = clk() | |
1685 | out = None |
|
1819 | out = None | |
1686 | wall_end = wtime() |
|
1820 | wall_end = wtime() | |
1687 | # Compute actual times and report |
|
1821 | # Compute actual times and report | |
1688 | wall_time = wall_end-wall_st |
|
1822 | wall_time = wall_end-wall_st | |
1689 | cpu_user = end[0]-st[0] |
|
1823 | cpu_user = end[0]-st[0] | |
1690 | cpu_sys = end[1]-st[1] |
|
1824 | cpu_sys = end[1]-st[1] | |
1691 | cpu_tot = cpu_user+cpu_sys |
|
1825 | cpu_tot = cpu_user+cpu_sys | |
1692 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1826 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1693 | (cpu_user,cpu_sys,cpu_tot) |
|
1827 | (cpu_user,cpu_sys,cpu_tot) | |
1694 | print "Wall time: %.2f" % wall_time |
|
1828 | print "Wall time: %.2f" % wall_time | |
1695 | return out |
|
1829 | return out | |
1696 |
|
1830 | |||
1697 | def magic_macro(self,parameter_s = ''): |
|
1831 | def magic_macro(self,parameter_s = ''): | |
1698 | """Define a set of input lines as a macro for future re-execution. |
|
1832 | """Define a set of input lines as a macro for future re-execution. | |
1699 |
|
1833 | |||
1700 | Usage:\\ |
|
1834 | Usage:\\ | |
1701 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1835 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1702 |
|
1836 | |||
1703 | Options: |
|
1837 | Options: | |
1704 |
|
1838 | |||
1705 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1839 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1706 | so that magics are loaded in their transformed version to valid |
|
1840 | so that magics are loaded in their transformed version to valid | |
1707 | Python. If this option is given, the raw input as typed as the |
|
1841 | Python. If this option is given, the raw input as typed as the | |
1708 | command line is used instead. |
|
1842 | command line is used instead. | |
1709 |
|
1843 | |||
1710 | This will define a global variable called `name` which is a string |
|
1844 | This will define a global variable called `name` which is a string | |
1711 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1845 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1712 | above) from your input history into a single string. This variable |
|
1846 | above) from your input history into a single string. This variable | |
1713 | acts like an automatic function which re-executes those lines as if |
|
1847 | acts like an automatic function which re-executes those lines as if | |
1714 | you had typed them. You just type 'name' at the prompt and the code |
|
1848 | you had typed them. You just type 'name' at the prompt and the code | |
1715 | executes. |
|
1849 | executes. | |
1716 |
|
1850 | |||
1717 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1851 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1718 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1852 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1719 | using the lines numbered 5,6 and 7. |
|
1853 | using the lines numbered 5,6 and 7. | |
1720 |
|
1854 | |||
1721 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1855 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1722 | notation, where N:M means numbers N through M-1. |
|
1856 | notation, where N:M means numbers N through M-1. | |
1723 |
|
1857 | |||
1724 | For example, if your history contains (%hist prints it): |
|
1858 | For example, if your history contains (%hist prints it): | |
1725 |
|
1859 | |||
1726 | 44: x=1\\ |
|
1860 | 44: x=1\\ | |
1727 | 45: y=3\\ |
|
1861 | 45: y=3\\ | |
1728 | 46: z=x+y\\ |
|
1862 | 46: z=x+y\\ | |
1729 | 47: print x\\ |
|
1863 | 47: print x\\ | |
1730 | 48: a=5\\ |
|
1864 | 48: a=5\\ | |
1731 | 49: print 'x',x,'y',y\\ |
|
1865 | 49: print 'x',x,'y',y\\ | |
1732 |
|
1866 | |||
1733 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1867 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1734 | called my_macro with: |
|
1868 | called my_macro with: | |
1735 |
|
1869 | |||
1736 | In [51]: %macro my_macro 44-47 49 |
|
1870 | In [51]: %macro my_macro 44-47 49 | |
1737 |
|
1871 | |||
1738 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1872 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1739 | in one pass. |
|
1873 | in one pass. | |
1740 |
|
1874 | |||
1741 | You don't need to give the line-numbers in order, and any given line |
|
1875 | You don't need to give the line-numbers in order, and any given line | |
1742 | number can appear multiple times. You can assemble macros with any |
|
1876 | number can appear multiple times. You can assemble macros with any | |
1743 | lines from your input history in any order. |
|
1877 | lines from your input history in any order. | |
1744 |
|
1878 | |||
1745 | The macro is a simple object which holds its value in an attribute, |
|
1879 | The macro is a simple object which holds its value in an attribute, | |
1746 | but IPython's display system checks for macros and executes them as |
|
1880 | but IPython's display system checks for macros and executes them as | |
1747 | code instead of printing them when you type their name. |
|
1881 | code instead of printing them when you type their name. | |
1748 |
|
1882 | |||
1749 | You can view a macro's contents by explicitly printing it with: |
|
1883 | You can view a macro's contents by explicitly printing it with: | |
1750 |
|
1884 | |||
1751 | 'print macro_name'. |
|
1885 | 'print macro_name'. | |
1752 |
|
1886 | |||
1753 | For one-off cases which DON'T contain magic function calls in them you |
|
1887 | For one-off cases which DON'T contain magic function calls in them you | |
1754 | can obtain similar results by explicitly executing slices from your |
|
1888 | can obtain similar results by explicitly executing slices from your | |
1755 | input history with: |
|
1889 | input history with: | |
1756 |
|
1890 | |||
1757 | In [60]: exec In[44:48]+In[49]""" |
|
1891 | In [60]: exec In[44:48]+In[49]""" | |
1758 |
|
1892 | |||
1759 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1893 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1760 | if not args: |
|
1894 | if not args: | |
1761 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
1895 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
1762 | macs.sort() |
|
1896 | macs.sort() | |
1763 | return macs |
|
1897 | return macs | |
1764 | name,ranges = args[0], args[1:] |
|
1898 | name,ranges = args[0], args[1:] | |
1765 | #print 'rng',ranges # dbg |
|
1899 | #print 'rng',ranges # dbg | |
1766 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1900 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
1767 | macro = Macro(lines) |
|
1901 | macro = Macro(lines) | |
1768 | self.shell.user_ns.update({name:macro}) |
|
1902 | self.shell.user_ns.update({name:macro}) | |
1769 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1903 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1770 | print 'Macro contents:' |
|
1904 | print 'Macro contents:' | |
1771 | print macro, |
|
1905 | print macro, | |
1772 |
|
1906 | |||
1773 | def magic_save(self,parameter_s = ''): |
|
1907 | def magic_save(self,parameter_s = ''): | |
1774 | """Save a set of lines to a given filename. |
|
1908 | """Save a set of lines to a given filename. | |
1775 |
|
1909 | |||
1776 | Usage:\\ |
|
1910 | Usage:\\ | |
1777 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1911 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
1778 |
|
1912 | |||
1779 | Options: |
|
1913 | Options: | |
1780 |
|
1914 | |||
1781 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1915 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1782 | so that magics are loaded in their transformed version to valid |
|
1916 | so that magics are loaded in their transformed version to valid | |
1783 | Python. If this option is given, the raw input as typed as the |
|
1917 | Python. If this option is given, the raw input as typed as the | |
1784 | command line is used instead. |
|
1918 | command line is used instead. | |
1785 |
|
1919 | |||
1786 | This function uses the same syntax as %macro for line extraction, but |
|
1920 | This function uses the same syntax as %macro for line extraction, but | |
1787 | instead of creating a macro it saves the resulting string to the |
|
1921 | instead of creating a macro it saves the resulting string to the | |
1788 | filename you specify. |
|
1922 | filename you specify. | |
1789 |
|
1923 | |||
1790 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
1924 | It adds a '.py' extension to the file if you don't do so yourself, and | |
1791 | it asks for confirmation before overwriting existing files.""" |
|
1925 | it asks for confirmation before overwriting existing files.""" | |
1792 |
|
1926 | |||
1793 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1927 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1794 | fname,ranges = args[0], args[1:] |
|
1928 | fname,ranges = args[0], args[1:] | |
1795 | if not fname.endswith('.py'): |
|
1929 | if not fname.endswith('.py'): | |
1796 | fname += '.py' |
|
1930 | fname += '.py' | |
1797 | if os.path.isfile(fname): |
|
1931 | if os.path.isfile(fname): | |
1798 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
1932 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
1799 | if ans.lower() not in ['y','yes']: |
|
1933 | if ans.lower() not in ['y','yes']: | |
1800 | print 'Operation cancelled.' |
|
1934 | print 'Operation cancelled.' | |
1801 | return |
|
1935 | return | |
1802 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
1936 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
1803 | f = file(fname,'w') |
|
1937 | f = file(fname,'w') | |
1804 | f.write(cmds) |
|
1938 | f.write(cmds) | |
1805 | f.close() |
|
1939 | f.close() | |
1806 | print 'The following commands were written to file `%s`:' % fname |
|
1940 | print 'The following commands were written to file `%s`:' % fname | |
1807 | print cmds |
|
1941 | print cmds | |
1808 |
|
1942 | |||
1809 | def _edit_macro(self,mname,macro): |
|
1943 | def _edit_macro(self,mname,macro): | |
1810 | """open an editor with the macro data in a file""" |
|
1944 | """open an editor with the macro data in a file""" | |
1811 | filename = self.shell.mktempfile(macro.value) |
|
1945 | filename = self.shell.mktempfile(macro.value) | |
1812 | self.shell.hooks.editor(filename) |
|
1946 | self.shell.hooks.editor(filename) | |
1813 |
|
1947 | |||
1814 | # and make a new macro object, to replace the old one |
|
1948 | # and make a new macro object, to replace the old one | |
1815 | mfile = open(filename) |
|
1949 | mfile = open(filename) | |
1816 | mvalue = mfile.read() |
|
1950 | mvalue = mfile.read() | |
1817 | mfile.close() |
|
1951 | mfile.close() | |
1818 | self.shell.user_ns[mname] = Macro(mvalue) |
|
1952 | self.shell.user_ns[mname] = Macro(mvalue) | |
1819 |
|
1953 | |||
1820 | def magic_ed(self,parameter_s=''): |
|
1954 | def magic_ed(self,parameter_s=''): | |
1821 | """Alias to %edit.""" |
|
1955 | """Alias to %edit.""" | |
1822 | return self.magic_edit(parameter_s) |
|
1956 | return self.magic_edit(parameter_s) | |
1823 |
|
1957 | |||
1824 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
1958 | def magic_edit(self,parameter_s='',last_call=['','']): | |
1825 | """Bring up an editor and execute the resulting code. |
|
1959 | """Bring up an editor and execute the resulting code. | |
1826 |
|
1960 | |||
1827 | Usage: |
|
1961 | Usage: | |
1828 | %edit [options] [args] |
|
1962 | %edit [options] [args] | |
1829 |
|
1963 | |||
1830 | %edit runs IPython's editor hook. The default version of this hook is |
|
1964 | %edit runs IPython's editor hook. The default version of this hook is | |
1831 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
1965 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
1832 | environment variable $EDITOR. If this isn't found, it will default to |
|
1966 | environment variable $EDITOR. If this isn't found, it will default to | |
1833 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
1967 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
1834 | docstring for how to change the editor hook. |
|
1968 | docstring for how to change the editor hook. | |
1835 |
|
1969 | |||
1836 | You can also set the value of this editor via the command line option |
|
1970 | You can also set the value of this editor via the command line option | |
1837 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
1971 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
1838 | specifically for IPython an editor different from your typical default |
|
1972 | specifically for IPython an editor different from your typical default | |
1839 | (and for Windows users who typically don't set environment variables). |
|
1973 | (and for Windows users who typically don't set environment variables). | |
1840 |
|
1974 | |||
1841 | This command allows you to conveniently edit multi-line code right in |
|
1975 | This command allows you to conveniently edit multi-line code right in | |
1842 | your IPython session. |
|
1976 | your IPython session. | |
1843 |
|
1977 | |||
1844 | If called without arguments, %edit opens up an empty editor with a |
|
1978 | If called without arguments, %edit opens up an empty editor with a | |
1845 | temporary file and will execute the contents of this file when you |
|
1979 | temporary file and will execute the contents of this file when you | |
1846 | close it (don't forget to save it!). |
|
1980 | close it (don't forget to save it!). | |
1847 |
|
1981 | |||
1848 |
|
1982 | |||
1849 | Options: |
|
1983 | Options: | |
1850 |
|
1984 | |||
1851 | -n <number>: open the editor at a specified line number. By default, |
|
1985 | -n <number>: open the editor at a specified line number. By default, | |
1852 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
1986 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
1853 | you can configure this by providing your own modified hook if your |
|
1987 | you can configure this by providing your own modified hook if your | |
1854 | favorite editor supports line-number specifications with a different |
|
1988 | favorite editor supports line-number specifications with a different | |
1855 | syntax. |
|
1989 | syntax. | |
1856 |
|
1990 | |||
1857 | -p: this will call the editor with the same data as the previous time |
|
1991 | -p: this will call the editor with the same data as the previous time | |
1858 | it was used, regardless of how long ago (in your current session) it |
|
1992 | it was used, regardless of how long ago (in your current session) it | |
1859 | was. |
|
1993 | was. | |
1860 |
|
1994 | |||
1861 | -r: use 'raw' input. This option only applies to input taken from the |
|
1995 | -r: use 'raw' input. This option only applies to input taken from the | |
1862 | user's history. By default, the 'processed' history is used, so that |
|
1996 | user's history. By default, the 'processed' history is used, so that | |
1863 | magics are loaded in their transformed version to valid Python. If |
|
1997 | magics are loaded in their transformed version to valid Python. If | |
1864 | this option is given, the raw input as typed as the command line is |
|
1998 | this option is given, the raw input as typed as the command line is | |
1865 | used instead. When you exit the editor, it will be executed by |
|
1999 | used instead. When you exit the editor, it will be executed by | |
1866 | IPython's own processor. |
|
2000 | IPython's own processor. | |
1867 |
|
2001 | |||
1868 | -x: do not execute the edited code immediately upon exit. This is |
|
2002 | -x: do not execute the edited code immediately upon exit. This is | |
1869 | mainly useful if you are editing programs which need to be called with |
|
2003 | mainly useful if you are editing programs which need to be called with | |
1870 | command line arguments, which you can then do using %run. |
|
2004 | command line arguments, which you can then do using %run. | |
1871 |
|
2005 | |||
1872 |
|
2006 | |||
1873 | Arguments: |
|
2007 | Arguments: | |
1874 |
|
2008 | |||
1875 | If arguments are given, the following possibilites exist: |
|
2009 | If arguments are given, the following possibilites exist: | |
1876 |
|
2010 | |||
1877 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2011 | - The arguments are numbers or pairs of colon-separated numbers (like | |
1878 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2012 | 1 4:8 9). These are interpreted as lines of previous input to be | |
1879 | loaded into the editor. The syntax is the same of the %macro command. |
|
2013 | loaded into the editor. The syntax is the same of the %macro command. | |
1880 |
|
2014 | |||
1881 | - If the argument doesn't start with a number, it is evaluated as a |
|
2015 | - If the argument doesn't start with a number, it is evaluated as a | |
1882 | variable and its contents loaded into the editor. You can thus edit |
|
2016 | variable and its contents loaded into the editor. You can thus edit | |
1883 | any string which contains python code (including the result of |
|
2017 | any string which contains python code (including the result of | |
1884 | previous edits). |
|
2018 | previous edits). | |
1885 |
|
2019 | |||
1886 | - If the argument is the name of an object (other than a string), |
|
2020 | - If the argument is the name of an object (other than a string), | |
1887 | IPython will try to locate the file where it was defined and open the |
|
2021 | IPython will try to locate the file where it was defined and open the | |
1888 | editor at the point where it is defined. You can use `%edit function` |
|
2022 | editor at the point where it is defined. You can use `%edit function` | |
1889 | to load an editor exactly at the point where 'function' is defined, |
|
2023 | to load an editor exactly at the point where 'function' is defined, | |
1890 | edit it and have the file be executed automatically. |
|
2024 | edit it and have the file be executed automatically. | |
1891 |
|
2025 | |||
1892 | If the object is a macro (see %macro for details), this opens up your |
|
2026 | If the object is a macro (see %macro for details), this opens up your | |
1893 | specified editor with a temporary file containing the macro's data. |
|
2027 | specified editor with a temporary file containing the macro's data. | |
1894 | Upon exit, the macro is reloaded with the contents of the file. |
|
2028 | Upon exit, the macro is reloaded with the contents of the file. | |
1895 |
|
2029 | |||
1896 | Note: opening at an exact line is only supported under Unix, and some |
|
2030 | Note: opening at an exact line is only supported under Unix, and some | |
1897 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2031 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
1898 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2032 | '+NUMBER' parameter necessary for this feature. Good editors like | |
1899 | (X)Emacs, vi, jed, pico and joe all do. |
|
2033 | (X)Emacs, vi, jed, pico and joe all do. | |
1900 |
|
2034 | |||
1901 | - If the argument is not found as a variable, IPython will look for a |
|
2035 | - If the argument is not found as a variable, IPython will look for a | |
1902 | file with that name (adding .py if necessary) and load it into the |
|
2036 | file with that name (adding .py if necessary) and load it into the | |
1903 | editor. It will execute its contents with execfile() when you exit, |
|
2037 | editor. It will execute its contents with execfile() when you exit, | |
1904 | loading any code in the file into your interactive namespace. |
|
2038 | loading any code in the file into your interactive namespace. | |
1905 |
|
2039 | |||
1906 | After executing your code, %edit will return as output the code you |
|
2040 | After executing your code, %edit will return as output the code you | |
1907 | typed in the editor (except when it was an existing file). This way |
|
2041 | typed in the editor (except when it was an existing file). This way | |
1908 | you can reload the code in further invocations of %edit as a variable, |
|
2042 | you can reload the code in further invocations of %edit as a variable, | |
1909 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2043 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
1910 | the output. |
|
2044 | the output. | |
1911 |
|
2045 | |||
1912 | Note that %edit is also available through the alias %ed. |
|
2046 | Note that %edit is also available through the alias %ed. | |
1913 |
|
2047 | |||
1914 | This is an example of creating a simple function inside the editor and |
|
2048 | This is an example of creating a simple function inside the editor and | |
1915 | then modifying it. First, start up the editor: |
|
2049 | then modifying it. First, start up the editor: | |
1916 |
|
2050 | |||
1917 | In [1]: ed\\ |
|
2051 | In [1]: ed\\ | |
1918 | Editing... done. Executing edited code...\\ |
|
2052 | Editing... done. Executing edited code...\\ | |
1919 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' |
|
2053 | Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n' | |
1920 |
|
2054 | |||
1921 | We can then call the function foo(): |
|
2055 | We can then call the function foo(): | |
1922 |
|
2056 | |||
1923 | In [2]: foo()\\ |
|
2057 | In [2]: foo()\\ | |
1924 | foo() was defined in an editing session |
|
2058 | foo() was defined in an editing session | |
1925 |
|
2059 | |||
1926 | Now we edit foo. IPython automatically loads the editor with the |
|
2060 | Now we edit foo. IPython automatically loads the editor with the | |
1927 | (temporary) file where foo() was previously defined: |
|
2061 | (temporary) file where foo() was previously defined: | |
1928 |
|
2062 | |||
1929 | In [3]: ed foo\\ |
|
2063 | In [3]: ed foo\\ | |
1930 | Editing... done. Executing edited code... |
|
2064 | Editing... done. Executing edited code... | |
1931 |
|
2065 | |||
1932 | And if we call foo() again we get the modified version: |
|
2066 | And if we call foo() again we get the modified version: | |
1933 |
|
2067 | |||
1934 | In [4]: foo()\\ |
|
2068 | In [4]: foo()\\ | |
1935 | foo() has now been changed! |
|
2069 | foo() has now been changed! | |
1936 |
|
2070 | |||
1937 | Here is an example of how to edit a code snippet successive |
|
2071 | Here is an example of how to edit a code snippet successive | |
1938 | times. First we call the editor: |
|
2072 | times. First we call the editor: | |
1939 |
|
2073 | |||
1940 | In [8]: ed\\ |
|
2074 | In [8]: ed\\ | |
1941 | Editing... done. Executing edited code...\\ |
|
2075 | Editing... done. Executing edited code...\\ | |
1942 | hello\\ |
|
2076 | hello\\ | |
1943 | Out[8]: "print 'hello'\\n" |
|
2077 | Out[8]: "print 'hello'\\n" | |
1944 |
|
2078 | |||
1945 | Now we call it again with the previous output (stored in _): |
|
2079 | Now we call it again with the previous output (stored in _): | |
1946 |
|
2080 | |||
1947 | In [9]: ed _\\ |
|
2081 | In [9]: ed _\\ | |
1948 | Editing... done. Executing edited code...\\ |
|
2082 | Editing... done. Executing edited code...\\ | |
1949 | hello world\\ |
|
2083 | hello world\\ | |
1950 | Out[9]: "print 'hello world'\\n" |
|
2084 | Out[9]: "print 'hello world'\\n" | |
1951 |
|
2085 | |||
1952 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2086 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
1953 |
|
2087 | |||
1954 | In [10]: ed _8\\ |
|
2088 | In [10]: ed _8\\ | |
1955 | Editing... done. Executing edited code...\\ |
|
2089 | Editing... done. Executing edited code...\\ | |
1956 | hello again\\ |
|
2090 | hello again\\ | |
1957 | Out[10]: "print 'hello again'\\n" |
|
2091 | Out[10]: "print 'hello again'\\n" | |
1958 |
|
2092 | |||
1959 |
|
2093 | |||
1960 | Changing the default editor hook: |
|
2094 | Changing the default editor hook: | |
1961 |
|
2095 | |||
1962 | If you wish to write your own editor hook, you can put it in a |
|
2096 | If you wish to write your own editor hook, you can put it in a | |
1963 | configuration file which you load at startup time. The default hook |
|
2097 | configuration file which you load at startup time. The default hook | |
1964 | is defined in the IPython.hooks module, and you can use that as a |
|
2098 | is defined in the IPython.hooks module, and you can use that as a | |
1965 | starting example for further modifications. That file also has |
|
2099 | starting example for further modifications. That file also has | |
1966 | general instructions on how to set a new hook for use once you've |
|
2100 | general instructions on how to set a new hook for use once you've | |
1967 | defined it.""" |
|
2101 | defined it.""" | |
1968 |
|
2102 | |||
1969 | # FIXME: This function has become a convoluted mess. It needs a |
|
2103 | # FIXME: This function has become a convoluted mess. It needs a | |
1970 | # ground-up rewrite with clean, simple logic. |
|
2104 | # ground-up rewrite with clean, simple logic. | |
1971 |
|
2105 | |||
1972 | def make_filename(arg): |
|
2106 | def make_filename(arg): | |
1973 | "Make a filename from the given args" |
|
2107 | "Make a filename from the given args" | |
1974 | try: |
|
2108 | try: | |
1975 | filename = get_py_filename(arg) |
|
2109 | filename = get_py_filename(arg) | |
1976 | except IOError: |
|
2110 | except IOError: | |
1977 | if args.endswith('.py'): |
|
2111 | if args.endswith('.py'): | |
1978 | filename = arg |
|
2112 | filename = arg | |
1979 | else: |
|
2113 | else: | |
1980 | filename = None |
|
2114 | filename = None | |
1981 | return filename |
|
2115 | return filename | |
1982 |
|
2116 | |||
1983 | # custom exceptions |
|
2117 | # custom exceptions | |
1984 | class DataIsObject(Exception): pass |
|
2118 | class DataIsObject(Exception): pass | |
1985 |
|
2119 | |||
1986 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2120 | opts,args = self.parse_options(parameter_s,'prxn:') | |
1987 | # Set a few locals from the options for convenience: |
|
2121 | # Set a few locals from the options for convenience: | |
1988 | opts_p = opts.has_key('p') |
|
2122 | opts_p = opts.has_key('p') | |
1989 | opts_r = opts.has_key('r') |
|
2123 | opts_r = opts.has_key('r') | |
1990 |
|
2124 | |||
1991 | # Default line number value |
|
2125 | # Default line number value | |
1992 | lineno = opts.get('n',None) |
|
2126 | lineno = opts.get('n',None) | |
1993 |
|
2127 | |||
1994 | if opts_p: |
|
2128 | if opts_p: | |
1995 | args = '_%s' % last_call[0] |
|
2129 | args = '_%s' % last_call[0] | |
1996 | if not self.shell.user_ns.has_key(args): |
|
2130 | if not self.shell.user_ns.has_key(args): | |
1997 | args = last_call[1] |
|
2131 | args = last_call[1] | |
1998 |
|
2132 | |||
1999 | # use last_call to remember the state of the previous call, but don't |
|
2133 | # use last_call to remember the state of the previous call, but don't | |
2000 | # let it be clobbered by successive '-p' calls. |
|
2134 | # let it be clobbered by successive '-p' calls. | |
2001 | try: |
|
2135 | try: | |
2002 | last_call[0] = self.shell.outputcache.prompt_count |
|
2136 | last_call[0] = self.shell.outputcache.prompt_count | |
2003 | if not opts_p: |
|
2137 | if not opts_p: | |
2004 | last_call[1] = parameter_s |
|
2138 | last_call[1] = parameter_s | |
2005 | except: |
|
2139 | except: | |
2006 | pass |
|
2140 | pass | |
2007 |
|
2141 | |||
2008 | # by default this is done with temp files, except when the given |
|
2142 | # by default this is done with temp files, except when the given | |
2009 | # arg is a filename |
|
2143 | # arg is a filename | |
2010 | use_temp = 1 |
|
2144 | use_temp = 1 | |
2011 |
|
2145 | |||
2012 | if re.match(r'\d',args): |
|
2146 | if re.match(r'\d',args): | |
2013 | # Mode where user specifies ranges of lines, like in %macro. |
|
2147 | # Mode where user specifies ranges of lines, like in %macro. | |
2014 | # This means that you can't edit files whose names begin with |
|
2148 | # This means that you can't edit files whose names begin with | |
2015 | # numbers this way. Tough. |
|
2149 | # numbers this way. Tough. | |
2016 | ranges = args.split() |
|
2150 | ranges = args.split() | |
2017 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2151 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2018 | elif args.endswith('.py'): |
|
2152 | elif args.endswith('.py'): | |
2019 | filename = make_filename(args) |
|
2153 | filename = make_filename(args) | |
2020 | data = '' |
|
2154 | data = '' | |
2021 | use_temp = 0 |
|
2155 | use_temp = 0 | |
2022 | elif args: |
|
2156 | elif args: | |
2023 | try: |
|
2157 | try: | |
2024 | # Load the parameter given as a variable. If not a string, |
|
2158 | # Load the parameter given as a variable. If not a string, | |
2025 | # process it as an object instead (below) |
|
2159 | # process it as an object instead (below) | |
2026 |
|
2160 | |||
2027 | #print '*** args',args,'type',type(args) # dbg |
|
2161 | #print '*** args',args,'type',type(args) # dbg | |
2028 | data = eval(args,self.shell.user_ns) |
|
2162 | data = eval(args,self.shell.user_ns) | |
2029 | if not type(data) in StringTypes: |
|
2163 | if not type(data) in StringTypes: | |
2030 | raise DataIsObject |
|
2164 | raise DataIsObject | |
2031 |
|
2165 | |||
2032 | except (NameError,SyntaxError): |
|
2166 | except (NameError,SyntaxError): | |
2033 | # given argument is not a variable, try as a filename |
|
2167 | # given argument is not a variable, try as a filename | |
2034 | filename = make_filename(args) |
|
2168 | filename = make_filename(args) | |
2035 | if filename is None: |
|
2169 | if filename is None: | |
2036 | warn("Argument given (%s) can't be found as a variable " |
|
2170 | warn("Argument given (%s) can't be found as a variable " | |
2037 | "or as a filename." % args) |
|
2171 | "or as a filename." % args) | |
2038 | return |
|
2172 | return | |
2039 |
|
2173 | |||
2040 | data = '' |
|
2174 | data = '' | |
2041 | use_temp = 0 |
|
2175 | use_temp = 0 | |
2042 | except DataIsObject: |
|
2176 | except DataIsObject: | |
2043 |
|
2177 | |||
2044 | # macros have a special edit function |
|
2178 | # macros have a special edit function | |
2045 | if isinstance(data,Macro): |
|
2179 | if isinstance(data,Macro): | |
2046 | self._edit_macro(args,data) |
|
2180 | self._edit_macro(args,data) | |
2047 | return |
|
2181 | return | |
2048 |
|
2182 | |||
2049 | # For objects, try to edit the file where they are defined |
|
2183 | # For objects, try to edit the file where they are defined | |
2050 | try: |
|
2184 | try: | |
2051 | filename = inspect.getabsfile(data) |
|
2185 | filename = inspect.getabsfile(data) | |
2052 | datafile = 1 |
|
2186 | datafile = 1 | |
2053 | except TypeError: |
|
2187 | except TypeError: | |
2054 | filename = make_filename(args) |
|
2188 | filename = make_filename(args) | |
2055 | datafile = 1 |
|
2189 | datafile = 1 | |
2056 | warn('Could not find file where `%s` is defined.\n' |
|
2190 | warn('Could not find file where `%s` is defined.\n' | |
2057 | 'Opening a file named `%s`' % (args,filename)) |
|
2191 | 'Opening a file named `%s`' % (args,filename)) | |
2058 | # Now, make sure we can actually read the source (if it was in |
|
2192 | # Now, make sure we can actually read the source (if it was in | |
2059 | # a temp file it's gone by now). |
|
2193 | # a temp file it's gone by now). | |
2060 | if datafile: |
|
2194 | if datafile: | |
2061 | try: |
|
2195 | try: | |
2062 | if lineno is None: |
|
2196 | if lineno is None: | |
2063 | lineno = inspect.getsourcelines(data)[1] |
|
2197 | lineno = inspect.getsourcelines(data)[1] | |
2064 | except IOError: |
|
2198 | except IOError: | |
2065 | filename = make_filename(args) |
|
2199 | filename = make_filename(args) | |
2066 | if filename is None: |
|
2200 | if filename is None: | |
2067 | warn('The file `%s` where `%s` was defined cannot ' |
|
2201 | warn('The file `%s` where `%s` was defined cannot ' | |
2068 | 'be read.' % (filename,data)) |
|
2202 | 'be read.' % (filename,data)) | |
2069 | return |
|
2203 | return | |
2070 | use_temp = 0 |
|
2204 | use_temp = 0 | |
2071 | else: |
|
2205 | else: | |
2072 | data = '' |
|
2206 | data = '' | |
2073 |
|
2207 | |||
2074 | if use_temp: |
|
2208 | if use_temp: | |
2075 | filename = self.shell.mktempfile(data) |
|
2209 | filename = self.shell.mktempfile(data) | |
2076 | print 'IPython will make a temporary file named:',filename |
|
2210 | print 'IPython will make a temporary file named:',filename | |
2077 |
|
2211 | |||
2078 | # do actual editing here |
|
2212 | # do actual editing here | |
2079 | print 'Editing...', |
|
2213 | print 'Editing...', | |
2080 | sys.stdout.flush() |
|
2214 | sys.stdout.flush() | |
2081 | self.shell.hooks.editor(filename,lineno) |
|
2215 | self.shell.hooks.editor(filename,lineno) | |
2082 | if opts.has_key('x'): # -x prevents actual execution |
|
2216 | if opts.has_key('x'): # -x prevents actual execution | |
2083 |
|
2217 | |||
2084 | else: |
|
2218 | else: | |
2085 | print 'done. Executing edited code...' |
|
2219 | print 'done. Executing edited code...' | |
2086 | if opts_r: |
|
2220 | if opts_r: | |
2087 | self.shell.runlines(file_read(filename)) |
|
2221 | self.shell.runlines(file_read(filename)) | |
2088 | else: |
|
2222 | else: | |
2089 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2223 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2090 | self.shell.user_ns) |
|
2224 | self.shell.user_ns) | |
2091 | if use_temp: |
|
2225 | if use_temp: | |
2092 | try: |
|
2226 | try: | |
2093 | return open(filename).read() |
|
2227 | return open(filename).read() | |
2094 | except IOError,msg: |
|
2228 | except IOError,msg: | |
2095 | if msg.filename == filename: |
|
2229 | if msg.filename == filename: | |
2096 | warn('File not found. Did you forget to save?') |
|
2230 | warn('File not found. Did you forget to save?') | |
2097 | return |
|
2231 | return | |
2098 | else: |
|
2232 | else: | |
2099 | self.shell.showtraceback() |
|
2233 | self.shell.showtraceback() | |
2100 |
|
2234 | |||
2101 | def magic_xmode(self,parameter_s = ''): |
|
2235 | def magic_xmode(self,parameter_s = ''): | |
2102 | """Switch modes for the exception handlers. |
|
2236 | """Switch modes for the exception handlers. | |
2103 |
|
2237 | |||
2104 | Valid modes: Plain, Context and Verbose. |
|
2238 | Valid modes: Plain, Context and Verbose. | |
2105 |
|
2239 | |||
2106 | If called without arguments, acts as a toggle.""" |
|
2240 | If called without arguments, acts as a toggle.""" | |
2107 |
|
2241 | |||
2108 | def xmode_switch_err(name): |
|
2242 | def xmode_switch_err(name): | |
2109 | warn('Error changing %s exception modes.\n%s' % |
|
2243 | warn('Error changing %s exception modes.\n%s' % | |
2110 | (name,sys.exc_info()[1])) |
|
2244 | (name,sys.exc_info()[1])) | |
2111 |
|
2245 | |||
2112 | shell = self.shell |
|
2246 | shell = self.shell | |
2113 | new_mode = parameter_s.strip().capitalize() |
|
2247 | new_mode = parameter_s.strip().capitalize() | |
2114 | try: |
|
2248 | try: | |
2115 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2249 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2116 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2250 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2117 | except: |
|
2251 | except: | |
2118 | xmode_switch_err('user') |
|
2252 | xmode_switch_err('user') | |
2119 |
|
2253 | |||
2120 | # threaded shells use a special handler in sys.excepthook |
|
2254 | # threaded shells use a special handler in sys.excepthook | |
2121 | if shell.isthreaded: |
|
2255 | if shell.isthreaded: | |
2122 | try: |
|
2256 | try: | |
2123 | shell.sys_excepthook.set_mode(mode=new_mode) |
|
2257 | shell.sys_excepthook.set_mode(mode=new_mode) | |
2124 | except: |
|
2258 | except: | |
2125 | xmode_switch_err('threaded') |
|
2259 | xmode_switch_err('threaded') | |
2126 |
|
2260 | |||
2127 | def magic_colors(self,parameter_s = ''): |
|
2261 | def magic_colors(self,parameter_s = ''): | |
2128 | """Switch color scheme for prompts, info system and exception handlers. |
|
2262 | """Switch color scheme for prompts, info system and exception handlers. | |
2129 |
|
2263 | |||
2130 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2264 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2131 |
|
2265 | |||
2132 | Color scheme names are not case-sensitive.""" |
|
2266 | Color scheme names are not case-sensitive.""" | |
2133 |
|
2267 | |||
2134 | def color_switch_err(name): |
|
2268 | def color_switch_err(name): | |
2135 | warn('Error changing %s color schemes.\n%s' % |
|
2269 | warn('Error changing %s color schemes.\n%s' % | |
2136 | (name,sys.exc_info()[1])) |
|
2270 | (name,sys.exc_info()[1])) | |
2137 |
|
2271 | |||
2138 |
|
2272 | |||
2139 | new_scheme = parameter_s.strip() |
|
2273 | new_scheme = parameter_s.strip() | |
2140 | if not new_scheme: |
|
2274 | if not new_scheme: | |
2141 | print 'You must specify a color scheme.' |
|
2275 | print 'You must specify a color scheme.' | |
2142 | return |
|
2276 | return | |
2143 | # local shortcut |
|
2277 | # local shortcut | |
2144 | shell = self.shell |
|
2278 | shell = self.shell | |
2145 |
|
2279 | |||
2146 | import IPython.rlineimpl as readline |
|
2280 | import IPython.rlineimpl as readline | |
2147 |
|
2281 | |||
2148 | if not readline.have_readline and sys.platform == "win32": |
|
2282 | if not readline.have_readline and sys.platform == "win32": | |
2149 | msg = """\ |
|
2283 | msg = """\ | |
2150 | Proper color support under MS Windows requires the pyreadline library. |
|
2284 | Proper color support under MS Windows requires the pyreadline library. | |
2151 | You can find it at: |
|
2285 | You can find it at: | |
2152 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2286 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2153 | Gary's readline needs the ctypes module, from: |
|
2287 | Gary's readline needs the ctypes module, from: | |
2154 | http://starship.python.net/crew/theller/ctypes |
|
2288 | http://starship.python.net/crew/theller/ctypes | |
2155 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2289 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2156 |
|
2290 | |||
2157 | Defaulting color scheme to 'NoColor'""" |
|
2291 | Defaulting color scheme to 'NoColor'""" | |
2158 | new_scheme = 'NoColor' |
|
2292 | new_scheme = 'NoColor' | |
2159 | warn(msg) |
|
2293 | warn(msg) | |
2160 |
|
2294 | |||
2161 | # readline option is 0 |
|
2295 | # readline option is 0 | |
2162 | if not shell.has_readline: |
|
2296 | if not shell.has_readline: | |
2163 | new_scheme = 'NoColor' |
|
2297 | new_scheme = 'NoColor' | |
2164 |
|
2298 | |||
2165 | # Set prompt colors |
|
2299 | # Set prompt colors | |
2166 | try: |
|
2300 | try: | |
2167 | shell.outputcache.set_colors(new_scheme) |
|
2301 | shell.outputcache.set_colors(new_scheme) | |
2168 | except: |
|
2302 | except: | |
2169 | color_switch_err('prompt') |
|
2303 | color_switch_err('prompt') | |
2170 | else: |
|
2304 | else: | |
2171 | shell.rc.colors = \ |
|
2305 | shell.rc.colors = \ | |
2172 | shell.outputcache.color_table.active_scheme_name |
|
2306 | shell.outputcache.color_table.active_scheme_name | |
2173 | # Set exception colors |
|
2307 | # Set exception colors | |
2174 | try: |
|
2308 | try: | |
2175 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2309 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2176 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2310 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2177 | except: |
|
2311 | except: | |
2178 | color_switch_err('exception') |
|
2312 | color_switch_err('exception') | |
2179 |
|
2313 | |||
2180 | # threaded shells use a verbose traceback in sys.excepthook |
|
2314 | # threaded shells use a verbose traceback in sys.excepthook | |
2181 | if shell.isthreaded: |
|
2315 | if shell.isthreaded: | |
2182 | try: |
|
2316 | try: | |
2183 | shell.sys_excepthook.set_colors(scheme=new_scheme) |
|
2317 | shell.sys_excepthook.set_colors(scheme=new_scheme) | |
2184 | except: |
|
2318 | except: | |
2185 | color_switch_err('system exception handler') |
|
2319 | color_switch_err('system exception handler') | |
2186 |
|
2320 | |||
2187 | # Set info (for 'object?') colors |
|
2321 | # Set info (for 'object?') colors | |
2188 | if shell.rc.color_info: |
|
2322 | if shell.rc.color_info: | |
2189 | try: |
|
2323 | try: | |
2190 | shell.inspector.set_active_scheme(new_scheme) |
|
2324 | shell.inspector.set_active_scheme(new_scheme) | |
2191 | except: |
|
2325 | except: | |
2192 | color_switch_err('object inspector') |
|
2326 | color_switch_err('object inspector') | |
2193 | else: |
|
2327 | else: | |
2194 | shell.inspector.set_active_scheme('NoColor') |
|
2328 | shell.inspector.set_active_scheme('NoColor') | |
2195 |
|
2329 | |||
2196 | def magic_color_info(self,parameter_s = ''): |
|
2330 | def magic_color_info(self,parameter_s = ''): | |
2197 | """Toggle color_info. |
|
2331 | """Toggle color_info. | |
2198 |
|
2332 | |||
2199 | The color_info configuration parameter controls whether colors are |
|
2333 | The color_info configuration parameter controls whether colors are | |
2200 | used for displaying object details (by things like %psource, %pfile or |
|
2334 | used for displaying object details (by things like %psource, %pfile or | |
2201 | the '?' system). This function toggles this value with each call. |
|
2335 | the '?' system). This function toggles this value with each call. | |
2202 |
|
2336 | |||
2203 | Note that unless you have a fairly recent pager (less works better |
|
2337 | Note that unless you have a fairly recent pager (less works better | |
2204 | than more) in your system, using colored object information displays |
|
2338 | than more) in your system, using colored object information displays | |
2205 | will not work properly. Test it and see.""" |
|
2339 | will not work properly. Test it and see.""" | |
2206 |
|
2340 | |||
2207 | self.shell.rc.color_info = 1 - self.shell.rc.color_info |
|
2341 | self.shell.rc.color_info = 1 - self.shell.rc.color_info | |
2208 | self.magic_colors(self.shell.rc.colors) |
|
2342 | self.magic_colors(self.shell.rc.colors) | |
2209 | print 'Object introspection functions have now coloring:', |
|
2343 | print 'Object introspection functions have now coloring:', | |
2210 | print ['OFF','ON'][self.shell.rc.color_info] |
|
2344 | print ['OFF','ON'][self.shell.rc.color_info] | |
2211 |
|
2345 | |||
2212 | def magic_Pprint(self, parameter_s=''): |
|
2346 | def magic_Pprint(self, parameter_s=''): | |
2213 | """Toggle pretty printing on/off.""" |
|
2347 | """Toggle pretty printing on/off.""" | |
2214 |
|
2348 | |||
2215 | self.shell.rc.pprint = 1 - self.shell.rc.pprint |
|
2349 | self.shell.rc.pprint = 1 - self.shell.rc.pprint | |
2216 | print 'Pretty printing has been turned', \ |
|
2350 | print 'Pretty printing has been turned', \ | |
2217 | ['OFF','ON'][self.shell.rc.pprint] |
|
2351 | ['OFF','ON'][self.shell.rc.pprint] | |
2218 |
|
2352 | |||
2219 | def magic_exit(self, parameter_s=''): |
|
2353 | def magic_exit(self, parameter_s=''): | |
2220 | """Exit IPython, confirming if configured to do so. |
|
2354 | """Exit IPython, confirming if configured to do so. | |
2221 |
|
2355 | |||
2222 | You can configure whether IPython asks for confirmation upon exit by |
|
2356 | You can configure whether IPython asks for confirmation upon exit by | |
2223 | setting the confirm_exit flag in the ipythonrc file.""" |
|
2357 | setting the confirm_exit flag in the ipythonrc file.""" | |
2224 |
|
2358 | |||
2225 | self.shell.exit() |
|
2359 | self.shell.exit() | |
2226 |
|
2360 | |||
2227 | def magic_quit(self, parameter_s=''): |
|
2361 | def magic_quit(self, parameter_s=''): | |
2228 | """Exit IPython, confirming if configured to do so (like %exit)""" |
|
2362 | """Exit IPython, confirming if configured to do so (like %exit)""" | |
2229 |
|
2363 | |||
2230 | self.shell.exit() |
|
2364 | self.shell.exit() | |
2231 |
|
2365 | |||
2232 | def magic_Exit(self, parameter_s=''): |
|
2366 | def magic_Exit(self, parameter_s=''): | |
2233 | """Exit IPython without confirmation.""" |
|
2367 | """Exit IPython without confirmation.""" | |
2234 |
|
2368 | |||
2235 | self.shell.exit_now = True |
|
2369 | self.shell.exit_now = True | |
2236 |
|
2370 | |||
2237 | #...................................................................... |
|
2371 | #...................................................................... | |
2238 | # Functions to implement unix shell-type things |
|
2372 | # Functions to implement unix shell-type things | |
2239 |
|
2373 | |||
2240 | def magic_alias(self, parameter_s = ''): |
|
2374 | def magic_alias(self, parameter_s = ''): | |
2241 | """Define an alias for a system command. |
|
2375 | """Define an alias for a system command. | |
2242 |
|
2376 | |||
2243 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2377 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2244 |
|
2378 | |||
2245 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2379 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2246 | params' (from your underlying operating system). |
|
2380 | params' (from your underlying operating system). | |
2247 |
|
2381 | |||
2248 | Aliases have lower precedence than magic functions and Python normal |
|
2382 | Aliases have lower precedence than magic functions and Python normal | |
2249 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2383 | variables, so if 'foo' is both a Python variable and an alias, the | |
2250 | alias can not be executed until 'del foo' removes the Python variable. |
|
2384 | alias can not be executed until 'del foo' removes the Python variable. | |
2251 |
|
2385 | |||
2252 | You can use the %l specifier in an alias definition to represent the |
|
2386 | You can use the %l specifier in an alias definition to represent the | |
2253 | whole line when the alias is called. For example: |
|
2387 | whole line when the alias is called. For example: | |
2254 |
|
2388 | |||
2255 | In [2]: alias all echo "Input in brackets: <%l>"\\ |
|
2389 | In [2]: alias all echo "Input in brackets: <%l>"\\ | |
2256 | In [3]: all hello world\\ |
|
2390 | In [3]: all hello world\\ | |
2257 | Input in brackets: <hello world> |
|
2391 | Input in brackets: <hello world> | |
2258 |
|
2392 | |||
2259 | You can also define aliases with parameters using %s specifiers (one |
|
2393 | You can also define aliases with parameters using %s specifiers (one | |
2260 | per parameter): |
|
2394 | per parameter): | |
2261 |
|
2395 | |||
2262 | In [1]: alias parts echo first %s second %s\\ |
|
2396 | In [1]: alias parts echo first %s second %s\\ | |
2263 | In [2]: %parts A B\\ |
|
2397 | In [2]: %parts A B\\ | |
2264 | first A second B\\ |
|
2398 | first A second B\\ | |
2265 | In [3]: %parts A\\ |
|
2399 | In [3]: %parts A\\ | |
2266 | Incorrect number of arguments: 2 expected.\\ |
|
2400 | Incorrect number of arguments: 2 expected.\\ | |
2267 | parts is an alias to: 'echo first %s second %s' |
|
2401 | parts is an alias to: 'echo first %s second %s' | |
2268 |
|
2402 | |||
2269 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2403 | Note that %l and %s are mutually exclusive. You can only use one or | |
2270 | the other in your aliases. |
|
2404 | the other in your aliases. | |
2271 |
|
2405 | |||
2272 | Aliases expand Python variables just like system calls using ! or !! |
|
2406 | Aliases expand Python variables just like system calls using ! or !! | |
2273 | do: all expressions prefixed with '$' get expanded. For details of |
|
2407 | do: all expressions prefixed with '$' get expanded. For details of | |
2274 | the semantic rules, see PEP-215: |
|
2408 | the semantic rules, see PEP-215: | |
2275 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2409 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2276 | IPython for variable expansion. If you want to access a true shell |
|
2410 | IPython for variable expansion. If you want to access a true shell | |
2277 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2411 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2278 |
|
2412 | |||
2279 | In [6]: alias show echo\\ |
|
2413 | In [6]: alias show echo\\ | |
2280 | In [7]: PATH='A Python string'\\ |
|
2414 | In [7]: PATH='A Python string'\\ | |
2281 | In [8]: show $PATH\\ |
|
2415 | In [8]: show $PATH\\ | |
2282 | A Python string\\ |
|
2416 | A Python string\\ | |
2283 | In [9]: show $$PATH\\ |
|
2417 | In [9]: show $$PATH\\ | |
2284 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2418 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2285 |
|
2419 | |||
2286 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2420 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2287 | and %rehashx functions, which automatically create aliases for the |
|
2421 | and %rehashx functions, which automatically create aliases for the | |
2288 | contents of your $PATH. |
|
2422 | contents of your $PATH. | |
2289 |
|
2423 | |||
2290 | If called with no parameters, %alias prints the current alias table.""" |
|
2424 | If called with no parameters, %alias prints the current alias table.""" | |
2291 |
|
2425 | |||
2292 | par = parameter_s.strip() |
|
2426 | par = parameter_s.strip() | |
2293 | if not par: |
|
2427 | if not par: | |
2294 | stored = self.db.get('stored_aliases', {} ) |
|
2428 | stored = self.db.get('stored_aliases', {} ) | |
2295 | atab = self.shell.alias_table |
|
2429 | atab = self.shell.alias_table | |
2296 | aliases = atab.keys() |
|
2430 | aliases = atab.keys() | |
2297 | aliases.sort() |
|
2431 | aliases.sort() | |
2298 | res = [] |
|
2432 | res = [] | |
2299 | showlast = [] |
|
2433 | showlast = [] | |
2300 | for alias in aliases: |
|
2434 | for alias in aliases: | |
2301 | special = False |
|
2435 | special = False | |
2302 | try: |
|
2436 | try: | |
2303 | tgt = atab[alias][1] |
|
2437 | tgt = atab[alias][1] | |
2304 | except (TypeError, AttributeError): |
|
2438 | except (TypeError, AttributeError): | |
2305 | # unsubscriptable? probably a callable |
|
2439 | # unsubscriptable? probably a callable | |
2306 | tgt = atab[alias] |
|
2440 | tgt = atab[alias] | |
2307 | special = True |
|
2441 | special = True | |
2308 | # 'interesting' aliases |
|
2442 | # 'interesting' aliases | |
2309 | if (alias in stored or |
|
2443 | if (alias in stored or | |
2310 | special or |
|
2444 | special or | |
2311 | alias.lower() != os.path.splitext(tgt)[0].lower() or |
|
2445 | alias.lower() != os.path.splitext(tgt)[0].lower() or | |
2312 | ' ' in tgt): |
|
2446 | ' ' in tgt): | |
2313 | showlast.append((alias, tgt)) |
|
2447 | showlast.append((alias, tgt)) | |
2314 | else: |
|
2448 | else: | |
2315 | res.append((alias, tgt )) |
|
2449 | res.append((alias, tgt )) | |
2316 |
|
2450 | |||
2317 | # show most interesting aliases last |
|
2451 | # show most interesting aliases last | |
2318 | res.extend(showlast) |
|
2452 | res.extend(showlast) | |
2319 | print "Total number of aliases:",len(aliases) |
|
2453 | print "Total number of aliases:",len(aliases) | |
2320 | return res |
|
2454 | return res | |
2321 | try: |
|
2455 | try: | |
2322 | alias,cmd = par.split(None,1) |
|
2456 | alias,cmd = par.split(None,1) | |
2323 | except: |
|
2457 | except: | |
2324 | print OInspect.getdoc(self.magic_alias) |
|
2458 | print OInspect.getdoc(self.magic_alias) | |
2325 | else: |
|
2459 | else: | |
2326 | nargs = cmd.count('%s') |
|
2460 | nargs = cmd.count('%s') | |
2327 | if nargs>0 and cmd.find('%l')>=0: |
|
2461 | if nargs>0 and cmd.find('%l')>=0: | |
2328 | error('The %s and %l specifiers are mutually exclusive ' |
|
2462 | error('The %s and %l specifiers are mutually exclusive ' | |
2329 | 'in alias definitions.') |
|
2463 | 'in alias definitions.') | |
2330 | else: # all looks OK |
|
2464 | else: # all looks OK | |
2331 | self.shell.alias_table[alias] = (nargs,cmd) |
|
2465 | self.shell.alias_table[alias] = (nargs,cmd) | |
2332 | self.shell.alias_table_validate(verbose=0) |
|
2466 | self.shell.alias_table_validate(verbose=0) | |
2333 | # end magic_alias |
|
2467 | # end magic_alias | |
2334 |
|
2468 | |||
2335 | def magic_unalias(self, parameter_s = ''): |
|
2469 | def magic_unalias(self, parameter_s = ''): | |
2336 | """Remove an alias""" |
|
2470 | """Remove an alias""" | |
2337 |
|
2471 | |||
2338 | aname = parameter_s.strip() |
|
2472 | aname = parameter_s.strip() | |
2339 | if aname in self.shell.alias_table: |
|
2473 | if aname in self.shell.alias_table: | |
2340 | del self.shell.alias_table[aname] |
|
2474 | del self.shell.alias_table[aname] | |
2341 | stored = self.db.get('stored_aliases', {} ) |
|
2475 | stored = self.db.get('stored_aliases', {} ) | |
2342 | if aname in stored: |
|
2476 | if aname in stored: | |
2343 | print "Removing %stored alias",aname |
|
2477 | print "Removing %stored alias",aname | |
2344 | del stored[aname] |
|
2478 | del stored[aname] | |
2345 | self.db['stored_aliases'] = stored |
|
2479 | self.db['stored_aliases'] = stored | |
2346 |
|
2480 | |||
2347 |
|
2481 | |||
2348 | def magic_rehashx(self, parameter_s = ''): |
|
2482 | def magic_rehashx(self, parameter_s = ''): | |
2349 | """Update the alias table with all executable files in $PATH. |
|
2483 | """Update the alias table with all executable files in $PATH. | |
2350 |
|
2484 | |||
2351 | This version explicitly checks that every entry in $PATH is a file |
|
2485 | This version explicitly checks that every entry in $PATH is a file | |
2352 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2486 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2353 |
|
2487 | |||
2354 | Under Windows, it checks executability as a match agains a |
|
2488 | Under Windows, it checks executability as a match agains a | |
2355 | '|'-separated string of extensions, stored in the IPython config |
|
2489 | '|'-separated string of extensions, stored in the IPython config | |
2356 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2490 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2357 |
|
2491 | |||
2358 | This function also resets the root module cache of module completer, |
|
2492 | This function also resets the root module cache of module completer, | |
2359 | used on slow filesystems. |
|
2493 | used on slow filesystems. | |
2360 | """ |
|
2494 | """ | |
2361 |
|
2495 | |||
2362 |
|
2496 | |||
2363 | ip = self.api |
|
2497 | ip = self.api | |
2364 |
|
2498 | |||
2365 | # for the benefit of module completer in ipy_completers.py |
|
2499 | # for the benefit of module completer in ipy_completers.py | |
2366 | del ip.db['rootmodules'] |
|
2500 | del ip.db['rootmodules'] | |
2367 |
|
2501 | |||
2368 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2502 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2369 | os.environ.get('PATH','').split(os.pathsep)] |
|
2503 | os.environ.get('PATH','').split(os.pathsep)] | |
2370 | path = filter(os.path.isdir,path) |
|
2504 | path = filter(os.path.isdir,path) | |
2371 |
|
2505 | |||
2372 | alias_table = self.shell.alias_table |
|
2506 | alias_table = self.shell.alias_table | |
2373 | syscmdlist = [] |
|
2507 | syscmdlist = [] | |
2374 | if os.name == 'posix': |
|
2508 | if os.name == 'posix': | |
2375 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2509 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2376 | os.access(fname,os.X_OK) |
|
2510 | os.access(fname,os.X_OK) | |
2377 | else: |
|
2511 | else: | |
2378 |
|
2512 | |||
2379 | try: |
|
2513 | try: | |
2380 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2514 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2381 | except KeyError: |
|
2515 | except KeyError: | |
2382 | winext = 'exe|com|bat|py' |
|
2516 | winext = 'exe|com|bat|py' | |
2383 | if 'py' not in winext: |
|
2517 | if 'py' not in winext: | |
2384 | winext += '|py' |
|
2518 | winext += '|py' | |
2385 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2519 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2386 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2520 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2387 | savedir = os.getcwd() |
|
2521 | savedir = os.getcwd() | |
2388 | try: |
|
2522 | try: | |
2389 | # write the whole loop for posix/Windows so we don't have an if in |
|
2523 | # write the whole loop for posix/Windows so we don't have an if in | |
2390 | # the innermost part |
|
2524 | # the innermost part | |
2391 | if os.name == 'posix': |
|
2525 | if os.name == 'posix': | |
2392 | for pdir in path: |
|
2526 | for pdir in path: | |
2393 | os.chdir(pdir) |
|
2527 | os.chdir(pdir) | |
2394 | for ff in os.listdir(pdir): |
|
2528 | for ff in os.listdir(pdir): | |
2395 | if isexec(ff) and ff not in self.shell.no_alias: |
|
2529 | if isexec(ff) and ff not in self.shell.no_alias: | |
2396 | # each entry in the alias table must be (N,name), |
|
2530 | # each entry in the alias table must be (N,name), | |
2397 | # where N is the number of positional arguments of the |
|
2531 | # where N is the number of positional arguments of the | |
2398 | # alias. |
|
2532 | # alias. | |
2399 | alias_table[ff] = (0,ff) |
|
2533 | alias_table[ff] = (0,ff) | |
2400 | syscmdlist.append(ff) |
|
2534 | syscmdlist.append(ff) | |
2401 | else: |
|
2535 | else: | |
2402 | for pdir in path: |
|
2536 | for pdir in path: | |
2403 | os.chdir(pdir) |
|
2537 | os.chdir(pdir) | |
2404 | for ff in os.listdir(pdir): |
|
2538 | for ff in os.listdir(pdir): | |
2405 | base, ext = os.path.splitext(ff) |
|
2539 | base, ext = os.path.splitext(ff) | |
2406 | if isexec(ff) and base not in self.shell.no_alias: |
|
2540 | if isexec(ff) and base not in self.shell.no_alias: | |
2407 | if ext.lower() == '.exe': |
|
2541 | if ext.lower() == '.exe': | |
2408 | ff = base |
|
2542 | ff = base | |
2409 | alias_table[base.lower()] = (0,ff) |
|
2543 | alias_table[base.lower()] = (0,ff) | |
2410 | syscmdlist.append(ff) |
|
2544 | syscmdlist.append(ff) | |
2411 | # Make sure the alias table doesn't contain keywords or builtins |
|
2545 | # Make sure the alias table doesn't contain keywords or builtins | |
2412 | self.shell.alias_table_validate() |
|
2546 | self.shell.alias_table_validate() | |
2413 | # Call again init_auto_alias() so we get 'rm -i' and other |
|
2547 | # Call again init_auto_alias() so we get 'rm -i' and other | |
2414 | # modified aliases since %rehashx will probably clobber them |
|
2548 | # modified aliases since %rehashx will probably clobber them | |
2415 |
|
2549 | |||
2416 | # no, we don't want them. if %rehashx clobbers them, good, |
|
2550 | # no, we don't want them. if %rehashx clobbers them, good, | |
2417 | # we'll probably get better versions |
|
2551 | # we'll probably get better versions | |
2418 | # self.shell.init_auto_alias() |
|
2552 | # self.shell.init_auto_alias() | |
2419 | db = ip.db |
|
2553 | db = ip.db | |
2420 | db['syscmdlist'] = syscmdlist |
|
2554 | db['syscmdlist'] = syscmdlist | |
2421 | finally: |
|
2555 | finally: | |
2422 | os.chdir(savedir) |
|
2556 | os.chdir(savedir) | |
2423 |
|
2557 | |||
2424 | def magic_pwd(self, parameter_s = ''): |
|
2558 | def magic_pwd(self, parameter_s = ''): | |
2425 | """Return the current working directory path.""" |
|
2559 | """Return the current working directory path.""" | |
2426 | return os.getcwd() |
|
2560 | return os.getcwd() | |
2427 |
|
2561 | |||
2428 | def magic_cd(self, parameter_s=''): |
|
2562 | def magic_cd(self, parameter_s=''): | |
2429 | """Change the current working directory. |
|
2563 | """Change the current working directory. | |
2430 |
|
2564 | |||
2431 | This command automatically maintains an internal list of directories |
|
2565 | This command automatically maintains an internal list of directories | |
2432 | you visit during your IPython session, in the variable _dh. The |
|
2566 | you visit during your IPython session, in the variable _dh. The | |
2433 | command %dhist shows this history nicely formatted. You can also |
|
2567 | command %dhist shows this history nicely formatted. You can also | |
2434 | do 'cd -<tab>' to see directory history conveniently. |
|
2568 | do 'cd -<tab>' to see directory history conveniently. | |
2435 |
|
2569 | |||
2436 | Usage: |
|
2570 | Usage: | |
2437 |
|
2571 | |||
2438 | cd 'dir': changes to directory 'dir'. |
|
2572 | cd 'dir': changes to directory 'dir'. | |
2439 |
|
2573 | |||
2440 | cd -: changes to the last visited directory. |
|
2574 | cd -: changes to the last visited directory. | |
2441 |
|
2575 | |||
2442 | cd -<n>: changes to the n-th directory in the directory history. |
|
2576 | cd -<n>: changes to the n-th directory in the directory history. | |
2443 |
|
2577 | |||
2444 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2578 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2445 | (note: cd <bookmark_name> is enough if there is no |
|
2579 | (note: cd <bookmark_name> is enough if there is no | |
2446 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2580 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2447 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2581 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2448 |
|
2582 | |||
2449 | Options: |
|
2583 | Options: | |
2450 |
|
2584 | |||
2451 | -q: quiet. Do not print the working directory after the cd command is |
|
2585 | -q: quiet. Do not print the working directory after the cd command is | |
2452 | executed. By default IPython's cd command does print this directory, |
|
2586 | executed. By default IPython's cd command does print this directory, | |
2453 | since the default prompts do not display path information. |
|
2587 | since the default prompts do not display path information. | |
2454 |
|
2588 | |||
2455 | Note that !cd doesn't work for this purpose because the shell where |
|
2589 | Note that !cd doesn't work for this purpose because the shell where | |
2456 | !command runs is immediately discarded after executing 'command'.""" |
|
2590 | !command runs is immediately discarded after executing 'command'.""" | |
2457 |
|
2591 | |||
2458 | parameter_s = parameter_s.strip() |
|
2592 | parameter_s = parameter_s.strip() | |
2459 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2593 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2460 |
|
2594 | |||
2461 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2595 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2462 | # jump in directory history by number |
|
2596 | # jump in directory history by number | |
2463 | if numcd: |
|
2597 | if numcd: | |
2464 | nn = int(numcd.group(2)) |
|
2598 | nn = int(numcd.group(2)) | |
2465 | try: |
|
2599 | try: | |
2466 | ps = self.shell.user_ns['_dh'][nn] |
|
2600 | ps = self.shell.user_ns['_dh'][nn] | |
2467 | except IndexError: |
|
2601 | except IndexError: | |
2468 | print 'The requested directory does not exist in history.' |
|
2602 | print 'The requested directory does not exist in history.' | |
2469 | return |
|
2603 | return | |
2470 | else: |
|
2604 | else: | |
2471 | opts = {} |
|
2605 | opts = {} | |
2472 | else: |
|
2606 | else: | |
2473 | #turn all non-space-escaping backslashes to slashes, |
|
2607 | #turn all non-space-escaping backslashes to slashes, | |
2474 | # for c:\windows\directory\names\ |
|
2608 | # for c:\windows\directory\names\ | |
2475 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2609 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2476 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2610 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2477 | # jump to previous |
|
2611 | # jump to previous | |
2478 | if ps == '-': |
|
2612 | if ps == '-': | |
2479 | try: |
|
2613 | try: | |
2480 | ps = self.shell.user_ns['_dh'][-2] |
|
2614 | ps = self.shell.user_ns['_dh'][-2] | |
2481 | except IndexError: |
|
2615 | except IndexError: | |
2482 | print 'No previous directory to change to.' |
|
2616 | print 'No previous directory to change to.' | |
2483 | return |
|
2617 | return | |
2484 | # jump to bookmark if needed |
|
2618 | # jump to bookmark if needed | |
2485 | else: |
|
2619 | else: | |
2486 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2620 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2487 | bkms = self.db.get('bookmarks', {}) |
|
2621 | bkms = self.db.get('bookmarks', {}) | |
2488 |
|
2622 | |||
2489 | if bkms.has_key(ps): |
|
2623 | if bkms.has_key(ps): | |
2490 | target = bkms[ps] |
|
2624 | target = bkms[ps] | |
2491 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2625 | print '(bookmark:%s) -> %s' % (ps,target) | |
2492 | ps = target |
|
2626 | ps = target | |
2493 | else: |
|
2627 | else: | |
2494 | if opts.has_key('b'): |
|
2628 | if opts.has_key('b'): | |
2495 | error("Bookmark '%s' not found. " |
|
2629 | error("Bookmark '%s' not found. " | |
2496 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2630 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2497 | return |
|
2631 | return | |
2498 |
|
2632 | |||
2499 | # at this point ps should point to the target dir |
|
2633 | # at this point ps should point to the target dir | |
2500 | if ps: |
|
2634 | if ps: | |
2501 | try: |
|
2635 | try: | |
2502 | os.chdir(os.path.expanduser(ps)) |
|
2636 | os.chdir(os.path.expanduser(ps)) | |
2503 | if self.shell.rc.term_title: |
|
2637 | if self.shell.rc.term_title: | |
2504 | #print 'set term title:',self.shell.rc.term_title # dbg |
|
2638 | #print 'set term title:',self.shell.rc.term_title # dbg | |
2505 | ttitle = 'IPy ' + abbrev_cwd() |
|
2639 | ttitle = 'IPy ' + abbrev_cwd() | |
2506 | platutils.set_term_title(ttitle) |
|
2640 | platutils.set_term_title(ttitle) | |
2507 | except OSError: |
|
2641 | except OSError: | |
2508 | print sys.exc_info()[1] |
|
2642 | print sys.exc_info()[1] | |
2509 | else: |
|
2643 | else: | |
2510 | cwd = os.getcwd() |
|
2644 | cwd = os.getcwd() | |
2511 | dhist = self.shell.user_ns['_dh'] |
|
2645 | dhist = self.shell.user_ns['_dh'] | |
2512 | dhist.append(cwd) |
|
2646 | dhist.append(cwd) | |
2513 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2647 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2514 |
|
2648 | |||
2515 | else: |
|
2649 | else: | |
2516 | os.chdir(self.shell.home_dir) |
|
2650 | os.chdir(self.shell.home_dir) | |
2517 | if self.shell.rc.term_title: |
|
2651 | if self.shell.rc.term_title: | |
2518 | platutils.set_term_title("IPy ~") |
|
2652 | platutils.set_term_title("IPy ~") | |
2519 | cwd = os.getcwd() |
|
2653 | cwd = os.getcwd() | |
2520 | dhist = self.shell.user_ns['_dh'] |
|
2654 | dhist = self.shell.user_ns['_dh'] | |
2521 | dhist.append(cwd) |
|
2655 | dhist.append(cwd) | |
2522 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2656 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2523 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2657 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2524 | print self.shell.user_ns['_dh'][-1] |
|
2658 | print self.shell.user_ns['_dh'][-1] | |
2525 |
|
2659 | |||
2526 |
|
2660 | |||
2527 | def magic_env(self, parameter_s=''): |
|
2661 | def magic_env(self, parameter_s=''): | |
2528 | """List environment variables.""" |
|
2662 | """List environment variables.""" | |
2529 |
|
2663 | |||
2530 | return os.environ.data |
|
2664 | return os.environ.data | |
2531 |
|
2665 | |||
2532 | def magic_pushd(self, parameter_s=''): |
|
2666 | def magic_pushd(self, parameter_s=''): | |
2533 | """Place the current dir on stack and change directory. |
|
2667 | """Place the current dir on stack and change directory. | |
2534 |
|
2668 | |||
2535 | Usage:\\ |
|
2669 | Usage:\\ | |
2536 | %pushd ['dirname'] |
|
2670 | %pushd ['dirname'] | |
2537 |
|
2671 | |||
2538 | %pushd with no arguments does a %pushd to your home directory. |
|
2672 | %pushd with no arguments does a %pushd to your home directory. | |
2539 | """ |
|
2673 | """ | |
2540 | if parameter_s == '': parameter_s = '~' |
|
2674 | if parameter_s == '': parameter_s = '~' | |
2541 | dir_s = self.shell.dir_stack |
|
2675 | dir_s = self.shell.dir_stack | |
2542 | if len(dir_s)>0 and os.path.expanduser(parameter_s) != \ |
|
2676 | if len(dir_s)>0 and os.path.expanduser(parameter_s) != \ | |
2543 | os.path.expanduser(self.shell.dir_stack[0]): |
|
2677 | os.path.expanduser(self.shell.dir_stack[0]): | |
2544 | try: |
|
2678 | try: | |
2545 | self.magic_cd(parameter_s) |
|
2679 | self.magic_cd(parameter_s) | |
2546 | dir_s.insert(0,os.getcwd().replace(self.home_dir,'~')) |
|
2680 | dir_s.insert(0,os.getcwd().replace(self.home_dir,'~')) | |
2547 | self.magic_dirs() |
|
2681 | self.magic_dirs() | |
2548 | except: |
|
2682 | except: | |
2549 | print 'Invalid directory' |
|
2683 | print 'Invalid directory' | |
2550 | else: |
|
2684 | else: | |
2551 | print 'You are already there!' |
|
2685 | print 'You are already there!' | |
2552 |
|
2686 | |||
2553 | def magic_popd(self, parameter_s=''): |
|
2687 | def magic_popd(self, parameter_s=''): | |
2554 | """Change to directory popped off the top of the stack. |
|
2688 | """Change to directory popped off the top of the stack. | |
2555 | """ |
|
2689 | """ | |
2556 | if len (self.shell.dir_stack) > 1: |
|
2690 | if len (self.shell.dir_stack) > 1: | |
2557 | self.shell.dir_stack.pop(0) |
|
2691 | self.shell.dir_stack.pop(0) | |
2558 | self.magic_cd(self.shell.dir_stack[0]) |
|
2692 | self.magic_cd(self.shell.dir_stack[0]) | |
2559 | print self.shell.dir_stack[0] |
|
2693 | print self.shell.dir_stack[0] | |
2560 | else: |
|
2694 | else: | |
2561 | print "You can't remove the starting directory from the stack:",\ |
|
2695 | print "You can't remove the starting directory from the stack:",\ | |
2562 | self.shell.dir_stack |
|
2696 | self.shell.dir_stack | |
2563 |
|
2697 | |||
2564 | def magic_dirs(self, parameter_s=''): |
|
2698 | def magic_dirs(self, parameter_s=''): | |
2565 | """Return the current directory stack.""" |
|
2699 | """Return the current directory stack.""" | |
2566 |
|
2700 | |||
2567 | return self.shell.dir_stack[:] |
|
2701 | return self.shell.dir_stack[:] | |
2568 |
|
2702 | |||
|
2703 | def magic_dhist(self, parameter_s=''): | |||
|
2704 | """Print your history of visited directories. | |||
|
2705 | ||||
|
2706 | %dhist -> print full history\\ | |||
|
2707 | %dhist n -> print last n entries only\\ | |||
|
2708 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |||
|
2709 | ||||
|
2710 | This history is automatically maintained by the %cd command, and | |||
|
2711 | always available as the global list variable _dh. You can use %cd -<n> | |||
|
2712 | to go to directory number <n>.""" | |||
|
2713 | ||||
|
2714 | dh = self.shell.user_ns['_dh'] | |||
|
2715 | if parameter_s: | |||
|
2716 | try: | |||
|
2717 | args = map(int,parameter_s.split()) | |||
|
2718 | except: | |||
|
2719 | self.arg_err(Magic.magic_dhist) | |||
|
2720 | return | |||
|
2721 | if len(args) == 1: | |||
|
2722 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |||
|
2723 | elif len(args) == 2: | |||
|
2724 | ini,fin = args | |||
|
2725 | else: | |||
|
2726 | self.arg_err(Magic.magic_dhist) | |||
|
2727 | return | |||
|
2728 | else: | |||
|
2729 | ini,fin = 0,len(dh) | |||
|
2730 | nlprint(dh, | |||
|
2731 | header = 'Directory history (kept in _dh)', | |||
|
2732 | start=ini,stop=fin) | |||
|
2733 | ||||
|
2734 | ||||
2569 | def magic_sc(self, parameter_s=''): |
|
2735 | def magic_sc(self, parameter_s=''): | |
2570 | """Shell capture - execute a shell command and capture its output. |
|
2736 | """Shell capture - execute a shell command and capture its output. | |
2571 |
|
2737 | |||
2572 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2738 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2573 |
|
2739 | |||
2574 | You should use the form 'var = !command' instead. Example: |
|
2740 | You should use the form 'var = !command' instead. Example: | |
2575 |
|
2741 | |||
2576 | "%sc -l myfiles = ls ~" should now be written as |
|
2742 | "%sc -l myfiles = ls ~" should now be written as | |
2577 |
|
2743 | |||
2578 | "myfiles = !ls ~" |
|
2744 | "myfiles = !ls ~" | |
2579 |
|
2745 | |||
2580 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2746 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2581 | below. |
|
2747 | below. | |
2582 |
|
2748 | |||
2583 | -- |
|
2749 | -- | |
2584 | %sc [options] varname=command |
|
2750 | %sc [options] varname=command | |
2585 |
|
2751 | |||
2586 | IPython will run the given command using commands.getoutput(), and |
|
2752 | IPython will run the given command using commands.getoutput(), and | |
2587 | will then update the user's interactive namespace with a variable |
|
2753 | will then update the user's interactive namespace with a variable | |
2588 | called varname, containing the value of the call. Your command can |
|
2754 | called varname, containing the value of the call. Your command can | |
2589 | contain shell wildcards, pipes, etc. |
|
2755 | contain shell wildcards, pipes, etc. | |
2590 |
|
2756 | |||
2591 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2757 | The '=' sign in the syntax is mandatory, and the variable name you | |
2592 | supply must follow Python's standard conventions for valid names. |
|
2758 | supply must follow Python's standard conventions for valid names. | |
2593 |
|
2759 | |||
2594 | (A special format without variable name exists for internal use) |
|
2760 | (A special format without variable name exists for internal use) | |
2595 |
|
2761 | |||
2596 | Options: |
|
2762 | Options: | |
2597 |
|
2763 | |||
2598 | -l: list output. Split the output on newlines into a list before |
|
2764 | -l: list output. Split the output on newlines into a list before | |
2599 | assigning it to the given variable. By default the output is stored |
|
2765 | assigning it to the given variable. By default the output is stored | |
2600 | as a single string. |
|
2766 | as a single string. | |
2601 |
|
2767 | |||
2602 | -v: verbose. Print the contents of the variable. |
|
2768 | -v: verbose. Print the contents of the variable. | |
2603 |
|
2769 | |||
2604 | In most cases you should not need to split as a list, because the |
|
2770 | In most cases you should not need to split as a list, because the | |
2605 | returned value is a special type of string which can automatically |
|
2771 | returned value is a special type of string which can automatically | |
2606 | provide its contents either as a list (split on newlines) or as a |
|
2772 | provide its contents either as a list (split on newlines) or as a | |
2607 | space-separated string. These are convenient, respectively, either |
|
2773 | space-separated string. These are convenient, respectively, either | |
2608 | for sequential processing or to be passed to a shell command. |
|
2774 | for sequential processing or to be passed to a shell command. | |
2609 |
|
2775 | |||
2610 | For example: |
|
2776 | For example: | |
2611 |
|
2777 | |||
2612 | # Capture into variable a |
|
2778 | # Capture into variable a | |
2613 | In [9]: sc a=ls *py |
|
2779 | In [9]: sc a=ls *py | |
2614 |
|
2780 | |||
2615 | # a is a string with embedded newlines |
|
2781 | # a is a string with embedded newlines | |
2616 | In [10]: a |
|
2782 | In [10]: a | |
2617 | Out[10]: 'setup.py\nwin32_manual_post_install.py' |
|
2783 | Out[10]: 'setup.py\nwin32_manual_post_install.py' | |
2618 |
|
2784 | |||
2619 | # which can be seen as a list: |
|
2785 | # which can be seen as a list: | |
2620 | In [11]: a.l |
|
2786 | In [11]: a.l | |
2621 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] |
|
2787 | Out[11]: ['setup.py', 'win32_manual_post_install.py'] | |
2622 |
|
2788 | |||
2623 | # or as a whitespace-separated string: |
|
2789 | # or as a whitespace-separated string: | |
2624 | In [12]: a.s |
|
2790 | In [12]: a.s | |
2625 | Out[12]: 'setup.py win32_manual_post_install.py' |
|
2791 | Out[12]: 'setup.py win32_manual_post_install.py' | |
2626 |
|
2792 | |||
2627 | # a.s is useful to pass as a single command line: |
|
2793 | # a.s is useful to pass as a single command line: | |
2628 | In [13]: !wc -l $a.s |
|
2794 | In [13]: !wc -l $a.s | |
2629 | 146 setup.py |
|
2795 | 146 setup.py | |
2630 | 130 win32_manual_post_install.py |
|
2796 | 130 win32_manual_post_install.py | |
2631 | 276 total |
|
2797 | 276 total | |
2632 |
|
2798 | |||
2633 | # while the list form is useful to loop over: |
|
2799 | # while the list form is useful to loop over: | |
2634 | In [14]: for f in a.l: |
|
2800 | In [14]: for f in a.l: | |
2635 | ....: !wc -l $f |
|
2801 | ....: !wc -l $f | |
2636 | ....: |
|
2802 | ....: | |
2637 | 146 setup.py |
|
2803 | 146 setup.py | |
2638 | 130 win32_manual_post_install.py |
|
2804 | 130 win32_manual_post_install.py | |
2639 |
|
2805 | |||
2640 | Similiarly, the lists returned by the -l option are also special, in |
|
2806 | Similiarly, the lists returned by the -l option are also special, in | |
2641 | the sense that you can equally invoke the .s attribute on them to |
|
2807 | the sense that you can equally invoke the .s attribute on them to | |
2642 | automatically get a whitespace-separated string from their contents: |
|
2808 | automatically get a whitespace-separated string from their contents: | |
2643 |
|
2809 | |||
2644 | In [1]: sc -l b=ls *py |
|
2810 | In [1]: sc -l b=ls *py | |
2645 |
|
2811 | |||
2646 | In [2]: b |
|
2812 | In [2]: b | |
2647 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] |
|
2813 | Out[2]: ['setup.py', 'win32_manual_post_install.py'] | |
2648 |
|
2814 | |||
2649 | In [3]: b.s |
|
2815 | In [3]: b.s | |
2650 | Out[3]: 'setup.py win32_manual_post_install.py' |
|
2816 | Out[3]: 'setup.py win32_manual_post_install.py' | |
2651 |
|
2817 | |||
2652 | In summary, both the lists and strings used for ouptut capture have |
|
2818 | In summary, both the lists and strings used for ouptut capture have | |
2653 | the following special attributes: |
|
2819 | the following special attributes: | |
2654 |
|
2820 | |||
2655 | .l (or .list) : value as list. |
|
2821 | .l (or .list) : value as list. | |
2656 | .n (or .nlstr): value as newline-separated string. |
|
2822 | .n (or .nlstr): value as newline-separated string. | |
2657 | .s (or .spstr): value as space-separated string. |
|
2823 | .s (or .spstr): value as space-separated string. | |
2658 | """ |
|
2824 | """ | |
2659 |
|
2825 | |||
2660 | opts,args = self.parse_options(parameter_s,'lv') |
|
2826 | opts,args = self.parse_options(parameter_s,'lv') | |
2661 | # Try to get a variable name and command to run |
|
2827 | # Try to get a variable name and command to run | |
2662 | try: |
|
2828 | try: | |
2663 | # the variable name must be obtained from the parse_options |
|
2829 | # the variable name must be obtained from the parse_options | |
2664 | # output, which uses shlex.split to strip options out. |
|
2830 | # output, which uses shlex.split to strip options out. | |
2665 | var,_ = args.split('=',1) |
|
2831 | var,_ = args.split('=',1) | |
2666 | var = var.strip() |
|
2832 | var = var.strip() | |
2667 | # But the the command has to be extracted from the original input |
|
2833 | # But the the command has to be extracted from the original input | |
2668 | # parameter_s, not on what parse_options returns, to avoid the |
|
2834 | # parameter_s, not on what parse_options returns, to avoid the | |
2669 | # quote stripping which shlex.split performs on it. |
|
2835 | # quote stripping which shlex.split performs on it. | |
2670 | _,cmd = parameter_s.split('=',1) |
|
2836 | _,cmd = parameter_s.split('=',1) | |
2671 | except ValueError: |
|
2837 | except ValueError: | |
2672 | var,cmd = '','' |
|
2838 | var,cmd = '','' | |
2673 | # If all looks ok, proceed |
|
2839 | # If all looks ok, proceed | |
2674 | out,err = self.shell.getoutputerror(cmd) |
|
2840 | out,err = self.shell.getoutputerror(cmd) | |
2675 | if err: |
|
2841 | if err: | |
2676 | print >> Term.cerr,err |
|
2842 | print >> Term.cerr,err | |
2677 | if opts.has_key('l'): |
|
2843 | if opts.has_key('l'): | |
2678 | out = SList(out.split('\n')) |
|
2844 | out = SList(out.split('\n')) | |
2679 | else: |
|
2845 | else: | |
2680 | out = LSString(out) |
|
2846 | out = LSString(out) | |
2681 | if opts.has_key('v'): |
|
2847 | if opts.has_key('v'): | |
2682 | print '%s ==\n%s' % (var,pformat(out)) |
|
2848 | print '%s ==\n%s' % (var,pformat(out)) | |
2683 | if var: |
|
2849 | if var: | |
2684 | self.shell.user_ns.update({var:out}) |
|
2850 | self.shell.user_ns.update({var:out}) | |
2685 | else: |
|
2851 | else: | |
2686 | return out |
|
2852 | return out | |
2687 |
|
2853 | |||
2688 | def magic_sx(self, parameter_s=''): |
|
2854 | def magic_sx(self, parameter_s=''): | |
2689 | """Shell execute - run a shell command and capture its output. |
|
2855 | """Shell execute - run a shell command and capture its output. | |
2690 |
|
2856 | |||
2691 | %sx command |
|
2857 | %sx command | |
2692 |
|
2858 | |||
2693 | IPython will run the given command using commands.getoutput(), and |
|
2859 | IPython will run the given command using commands.getoutput(), and | |
2694 | return the result formatted as a list (split on '\\n'). Since the |
|
2860 | return the result formatted as a list (split on '\\n'). Since the | |
2695 | output is _returned_, it will be stored in ipython's regular output |
|
2861 | output is _returned_, it will be stored in ipython's regular output | |
2696 | cache Out[N] and in the '_N' automatic variables. |
|
2862 | cache Out[N] and in the '_N' automatic variables. | |
2697 |
|
2863 | |||
2698 | Notes: |
|
2864 | Notes: | |
2699 |
|
2865 | |||
2700 | 1) If an input line begins with '!!', then %sx is automatically |
|
2866 | 1) If an input line begins with '!!', then %sx is automatically | |
2701 | invoked. That is, while: |
|
2867 | invoked. That is, while: | |
2702 | !ls |
|
2868 | !ls | |
2703 | causes ipython to simply issue system('ls'), typing |
|
2869 | causes ipython to simply issue system('ls'), typing | |
2704 | !!ls |
|
2870 | !!ls | |
2705 | is a shorthand equivalent to: |
|
2871 | is a shorthand equivalent to: | |
2706 | %sx ls |
|
2872 | %sx ls | |
2707 |
|
2873 | |||
2708 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2874 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2709 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2875 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2710 | to process line-oriented shell output via further python commands. |
|
2876 | to process line-oriented shell output via further python commands. | |
2711 | %sc is meant to provide much finer control, but requires more |
|
2877 | %sc is meant to provide much finer control, but requires more | |
2712 | typing. |
|
2878 | typing. | |
2713 |
|
2879 | |||
2714 | 3) Just like %sc -l, this is a list with special attributes: |
|
2880 | 3) Just like %sc -l, this is a list with special attributes: | |
2715 |
|
2881 | |||
2716 | .l (or .list) : value as list. |
|
2882 | .l (or .list) : value as list. | |
2717 | .n (or .nlstr): value as newline-separated string. |
|
2883 | .n (or .nlstr): value as newline-separated string. | |
2718 | .s (or .spstr): value as whitespace-separated string. |
|
2884 | .s (or .spstr): value as whitespace-separated string. | |
2719 |
|
2885 | |||
2720 | This is very useful when trying to use such lists as arguments to |
|
2886 | This is very useful when trying to use such lists as arguments to | |
2721 | system commands.""" |
|
2887 | system commands.""" | |
2722 |
|
2888 | |||
2723 | if parameter_s: |
|
2889 | if parameter_s: | |
2724 | out,err = self.shell.getoutputerror(parameter_s) |
|
2890 | out,err = self.shell.getoutputerror(parameter_s) | |
2725 | if err: |
|
2891 | if err: | |
2726 | print >> Term.cerr,err |
|
2892 | print >> Term.cerr,err | |
2727 | return SList(out.split('\n')) |
|
2893 | return SList(out.split('\n')) | |
2728 |
|
2894 | |||
2729 | def magic_bg(self, parameter_s=''): |
|
2895 | def magic_bg(self, parameter_s=''): | |
2730 | """Run a job in the background, in a separate thread. |
|
2896 | """Run a job in the background, in a separate thread. | |
2731 |
|
2897 | |||
2732 | For example, |
|
2898 | For example, | |
2733 |
|
2899 | |||
2734 | %bg myfunc(x,y,z=1) |
|
2900 | %bg myfunc(x,y,z=1) | |
2735 |
|
2901 | |||
2736 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the |
|
2902 | will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the | |
2737 | execution starts, a message will be printed indicating the job |
|
2903 | execution starts, a message will be printed indicating the job | |
2738 | number. If your job number is 5, you can use |
|
2904 | number. If your job number is 5, you can use | |
2739 |
|
2905 | |||
2740 | myvar = jobs.result(5) or myvar = jobs[5].result |
|
2906 | myvar = jobs.result(5) or myvar = jobs[5].result | |
2741 |
|
2907 | |||
2742 | to assign this result to variable 'myvar'. |
|
2908 | to assign this result to variable 'myvar'. | |
2743 |
|
2909 | |||
2744 | IPython has a job manager, accessible via the 'jobs' object. You can |
|
2910 | IPython has a job manager, accessible via the 'jobs' object. You can | |
2745 | type jobs? to get more information about it, and use jobs.<TAB> to see |
|
2911 | type jobs? to get more information about it, and use jobs.<TAB> to see | |
2746 | its attributes. All attributes not starting with an underscore are |
|
2912 | its attributes. All attributes not starting with an underscore are | |
2747 | meant for public use. |
|
2913 | meant for public use. | |
2748 |
|
2914 | |||
2749 | In particular, look at the jobs.new() method, which is used to create |
|
2915 | In particular, look at the jobs.new() method, which is used to create | |
2750 | new jobs. This magic %bg function is just a convenience wrapper |
|
2916 | new jobs. This magic %bg function is just a convenience wrapper | |
2751 | around jobs.new(), for expression-based jobs. If you want to create a |
|
2917 | around jobs.new(), for expression-based jobs. If you want to create a | |
2752 | new job with an explicit function object and arguments, you must call |
|
2918 | new job with an explicit function object and arguments, you must call | |
2753 | jobs.new() directly. |
|
2919 | jobs.new() directly. | |
2754 |
|
2920 | |||
2755 | The jobs.new docstring also describes in detail several important |
|
2921 | The jobs.new docstring also describes in detail several important | |
2756 | caveats associated with a thread-based model for background job |
|
2922 | caveats associated with a thread-based model for background job | |
2757 | execution. Type jobs.new? for details. |
|
2923 | execution. Type jobs.new? for details. | |
2758 |
|
2924 | |||
2759 | You can check the status of all jobs with jobs.status(). |
|
2925 | You can check the status of all jobs with jobs.status(). | |
2760 |
|
2926 | |||
2761 | The jobs variable is set by IPython into the Python builtin namespace. |
|
2927 | The jobs variable is set by IPython into the Python builtin namespace. | |
2762 | If you ever declare a variable named 'jobs', you will shadow this |
|
2928 | If you ever declare a variable named 'jobs', you will shadow this | |
2763 | name. You can either delete your global jobs variable to regain |
|
2929 | name. You can either delete your global jobs variable to regain | |
2764 | access to the job manager, or make a new name and assign it manually |
|
2930 | access to the job manager, or make a new name and assign it manually | |
2765 | to the manager (stored in IPython's namespace). For example, to |
|
2931 | to the manager (stored in IPython's namespace). For example, to | |
2766 | assign the job manager to the Jobs name, use: |
|
2932 | assign the job manager to the Jobs name, use: | |
2767 |
|
2933 | |||
2768 | Jobs = __builtins__.jobs""" |
|
2934 | Jobs = __builtins__.jobs""" | |
2769 |
|
2935 | |||
2770 | self.shell.jobs.new(parameter_s,self.shell.user_ns) |
|
2936 | self.shell.jobs.new(parameter_s,self.shell.user_ns) | |
2771 |
|
2937 | |||
|
2938 | def magic_r(self, parameter_s=''): | |||
|
2939 | """Repeat previous input. | |||
|
2940 | ||||
|
2941 | If given an argument, repeats the previous command which starts with | |||
|
2942 | the same string, otherwise it just repeats the previous input. | |||
|
2943 | ||||
|
2944 | Shell escaped commands (with ! as first character) are not recognized | |||
|
2945 | by this system, only pure python code and magic commands. | |||
|
2946 | """ | |||
|
2947 | ||||
|
2948 | start = parameter_s.strip() | |||
|
2949 | esc_magic = self.shell.ESC_MAGIC | |||
|
2950 | # Identify magic commands even if automagic is on (which means | |||
|
2951 | # the in-memory version is different from that typed by the user). | |||
|
2952 | if self.shell.rc.automagic: | |||
|
2953 | start_magic = esc_magic+start | |||
|
2954 | else: | |||
|
2955 | start_magic = start | |||
|
2956 | # Look through the input history in reverse | |||
|
2957 | for n in range(len(self.shell.input_hist)-2,0,-1): | |||
|
2958 | input = self.shell.input_hist[n] | |||
|
2959 | # skip plain 'r' lines so we don't recurse to infinity | |||
|
2960 | if input != '_ip.magic("r")\n' and \ | |||
|
2961 | (input.startswith(start) or input.startswith(start_magic)): | |||
|
2962 | #print 'match',`input` # dbg | |||
|
2963 | print 'Executing:',input, | |||
|
2964 | self.shell.runlines(input) | |||
|
2965 | return | |||
|
2966 | print 'No previous input matching `%s` found.' % start | |||
|
2967 | ||||
2772 |
|
2968 | |||
2773 | def magic_bookmark(self, parameter_s=''): |
|
2969 | def magic_bookmark(self, parameter_s=''): | |
2774 | """Manage IPython's bookmark system. |
|
2970 | """Manage IPython's bookmark system. | |
2775 |
|
2971 | |||
2776 | %bookmark <name> - set bookmark to current dir |
|
2972 | %bookmark <name> - set bookmark to current dir | |
2777 | %bookmark <name> <dir> - set bookmark to <dir> |
|
2973 | %bookmark <name> <dir> - set bookmark to <dir> | |
2778 | %bookmark -l - list all bookmarks |
|
2974 | %bookmark -l - list all bookmarks | |
2779 | %bookmark -d <name> - remove bookmark |
|
2975 | %bookmark -d <name> - remove bookmark | |
2780 | %bookmark -r - remove all bookmarks |
|
2976 | %bookmark -r - remove all bookmarks | |
2781 |
|
2977 | |||
2782 | You can later on access a bookmarked folder with: |
|
2978 | You can later on access a bookmarked folder with: | |
2783 | %cd -b <name> |
|
2979 | %cd -b <name> | |
2784 | or simply '%cd <name>' if there is no directory called <name> AND |
|
2980 | or simply '%cd <name>' if there is no directory called <name> AND | |
2785 | there is such a bookmark defined. |
|
2981 | there is such a bookmark defined. | |
2786 |
|
2982 | |||
2787 | Your bookmarks persist through IPython sessions, but they are |
|
2983 | Your bookmarks persist through IPython sessions, but they are | |
2788 | associated with each profile.""" |
|
2984 | associated with each profile.""" | |
2789 |
|
2985 | |||
2790 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
2986 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
2791 | if len(args) > 2: |
|
2987 | if len(args) > 2: | |
2792 | error('You can only give at most two arguments') |
|
2988 | error('You can only give at most two arguments') | |
2793 | return |
|
2989 | return | |
2794 |
|
2990 | |||
2795 | bkms = self.db.get('bookmarks',{}) |
|
2991 | bkms = self.db.get('bookmarks',{}) | |
2796 |
|
2992 | |||
2797 | if opts.has_key('d'): |
|
2993 | if opts.has_key('d'): | |
2798 | try: |
|
2994 | try: | |
2799 | todel = args[0] |
|
2995 | todel = args[0] | |
2800 | except IndexError: |
|
2996 | except IndexError: | |
2801 | error('You must provide a bookmark to delete') |
|
2997 | error('You must provide a bookmark to delete') | |
2802 | else: |
|
2998 | else: | |
2803 | try: |
|
2999 | try: | |
2804 | del bkms[todel] |
|
3000 | del bkms[todel] | |
2805 | except: |
|
3001 | except: | |
2806 | error("Can't delete bookmark '%s'" % todel) |
|
3002 | error("Can't delete bookmark '%s'" % todel) | |
2807 | elif opts.has_key('r'): |
|
3003 | elif opts.has_key('r'): | |
2808 | bkms = {} |
|
3004 | bkms = {} | |
2809 | elif opts.has_key('l'): |
|
3005 | elif opts.has_key('l'): | |
2810 | bks = bkms.keys() |
|
3006 | bks = bkms.keys() | |
2811 | bks.sort() |
|
3007 | bks.sort() | |
2812 | if bks: |
|
3008 | if bks: | |
2813 | size = max(map(len,bks)) |
|
3009 | size = max(map(len,bks)) | |
2814 | else: |
|
3010 | else: | |
2815 | size = 0 |
|
3011 | size = 0 | |
2816 | fmt = '%-'+str(size)+'s -> %s' |
|
3012 | fmt = '%-'+str(size)+'s -> %s' | |
2817 | print 'Current bookmarks:' |
|
3013 | print 'Current bookmarks:' | |
2818 | for bk in bks: |
|
3014 | for bk in bks: | |
2819 | print fmt % (bk,bkms[bk]) |
|
3015 | print fmt % (bk,bkms[bk]) | |
2820 | else: |
|
3016 | else: | |
2821 | if not args: |
|
3017 | if not args: | |
2822 | error("You must specify the bookmark name") |
|
3018 | error("You must specify the bookmark name") | |
2823 | elif len(args)==1: |
|
3019 | elif len(args)==1: | |
2824 | bkms[args[0]] = os.getcwd() |
|
3020 | bkms[args[0]] = os.getcwd() | |
2825 | elif len(args)==2: |
|
3021 | elif len(args)==2: | |
2826 | bkms[args[0]] = args[1] |
|
3022 | bkms[args[0]] = args[1] | |
2827 | self.db['bookmarks'] = bkms |
|
3023 | self.db['bookmarks'] = bkms | |
2828 |
|
3024 | |||
2829 | def magic_pycat(self, parameter_s=''): |
|
3025 | def magic_pycat(self, parameter_s=''): | |
2830 | """Show a syntax-highlighted file through a pager. |
|
3026 | """Show a syntax-highlighted file through a pager. | |
2831 |
|
3027 | |||
2832 | This magic is similar to the cat utility, but it will assume the file |
|
3028 | This magic is similar to the cat utility, but it will assume the file | |
2833 | to be Python source and will show it with syntax highlighting. """ |
|
3029 | to be Python source and will show it with syntax highlighting. """ | |
2834 |
|
3030 | |||
2835 | try: |
|
3031 | try: | |
2836 | filename = get_py_filename(parameter_s) |
|
3032 | filename = get_py_filename(parameter_s) | |
2837 | cont = file_read(filename) |
|
3033 | cont = file_read(filename) | |
2838 | except IOError: |
|
3034 | except IOError: | |
2839 | try: |
|
3035 | try: | |
2840 | cont = eval(parameter_s,self.user_ns) |
|
3036 | cont = eval(parameter_s,self.user_ns) | |
2841 | except NameError: |
|
3037 | except NameError: | |
2842 | cont = None |
|
3038 | cont = None | |
2843 | if cont is None: |
|
3039 | if cont is None: | |
2844 | print "Error: no such file or variable" |
|
3040 | print "Error: no such file or variable" | |
2845 | return |
|
3041 | return | |
2846 |
|
3042 | |||
2847 | page(self.shell.pycolorize(cont), |
|
3043 | page(self.shell.pycolorize(cont), | |
2848 | screen_lines=self.shell.rc.screen_length) |
|
3044 | screen_lines=self.shell.rc.screen_length) | |
2849 |
|
3045 | |||
2850 | def magic_cpaste(self, parameter_s=''): |
|
3046 | def magic_cpaste(self, parameter_s=''): | |
2851 | """Allows you to paste & execute a pre-formatted code block from clipboard |
|
3047 | """Allows you to paste & execute a pre-formatted code block from clipboard | |
2852 |
|
3048 | |||
2853 | You must terminate the block with '--' (two minus-signs) alone on the |
|
3049 | You must terminate the block with '--' (two minus-signs) alone on the | |
2854 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' |
|
3050 | line. You can also provide your own sentinel with '%paste -s %%' ('%%' | |
2855 | is the new sentinel for this operation) |
|
3051 | is the new sentinel for this operation) | |
2856 |
|
3052 | |||
2857 | The block is dedented prior to execution to enable execution of method |
|
3053 | The block is dedented prior to execution to enable execution of method | |
2858 | definitions. '>' and '+' characters at the beginning of a line are |
|
3054 | definitions. '>' and '+' characters at the beginning of a line are | |
2859 | ignored, to allow pasting directly from e-mails or diff files. The |
|
3055 | ignored, to allow pasting directly from e-mails or diff files. The | |
2860 | executed block is also assigned to variable named 'pasted_block' for |
|
3056 | executed block is also assigned to variable named 'pasted_block' for | |
2861 | later editing with '%edit pasted_block'. |
|
3057 | later editing with '%edit pasted_block'. | |
2862 |
|
3058 | |||
2863 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
3059 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
2864 | This assigns the pasted block to variable 'foo' as string, without |
|
3060 | This assigns the pasted block to variable 'foo' as string, without | |
2865 | dedenting or executing it. |
|
3061 | dedenting or executing it. | |
2866 |
|
3062 | |||
2867 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
3063 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
2868 | Just press enter and type -- (and press enter again) and the block |
|
3064 | Just press enter and type -- (and press enter again) and the block | |
2869 | will be what was just pasted. |
|
3065 | will be what was just pasted. | |
2870 |
|
3066 | |||
2871 | IPython statements (magics, shell escapes) are not supported (yet). |
|
3067 | IPython statements (magics, shell escapes) are not supported (yet). | |
2872 | """ |
|
3068 | """ | |
2873 | opts,args = self.parse_options(parameter_s,'s:',mode='string') |
|
3069 | opts,args = self.parse_options(parameter_s,'s:',mode='string') | |
2874 | par = args.strip() |
|
3070 | par = args.strip() | |
2875 | sentinel = opts.get('s','--') |
|
3071 | sentinel = opts.get('s','--') | |
2876 |
|
3072 | |||
2877 | from IPython import iplib |
|
3073 | from IPython import iplib | |
2878 | lines = [] |
|
3074 | lines = [] | |
2879 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3075 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
2880 | while 1: |
|
3076 | while 1: | |
2881 | l = iplib.raw_input_original(':') |
|
3077 | l = iplib.raw_input_original(':') | |
2882 | if l ==sentinel: |
|
3078 | if l ==sentinel: | |
2883 | break |
|
3079 | break | |
2884 | lines.append(l.lstrip('>').lstrip('+')) |
|
3080 | lines.append(l.lstrip('>').lstrip('+')) | |
2885 | block = "\n".join(lines) + '\n' |
|
3081 | block = "\n".join(lines) + '\n' | |
2886 | #print "block:\n",block |
|
3082 | #print "block:\n",block | |
2887 | if not par: |
|
3083 | if not par: | |
2888 | b = textwrap.dedent(block) |
|
3084 | b = textwrap.dedent(block) | |
2889 | exec b in self.user_ns |
|
3085 | exec b in self.user_ns | |
2890 | self.user_ns['pasted_block'] = b |
|
3086 | self.user_ns['pasted_block'] = b | |
2891 | else: |
|
3087 | else: | |
2892 | self.user_ns[par] = block |
|
3088 | self.user_ns[par] = block | |
2893 | print "Block assigned to '%s'" % par |
|
3089 | print "Block assigned to '%s'" % par | |
2894 |
|
3090 | |||
2895 | def magic_quickref(self,arg): |
|
3091 | def magic_quickref(self,arg): | |
2896 | """ Show a quick reference sheet """ |
|
3092 | """ Show a quick reference sheet """ | |
2897 | import IPython.usage |
|
3093 | import IPython.usage | |
2898 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') |
|
3094 | qr = IPython.usage.quick_reference + self.magic_magic('-brief') | |
2899 |
|
3095 | |||
2900 | page(qr) |
|
3096 | page(qr) | |
2901 |
|
3097 | |||
2902 | def magic_upgrade(self,arg): |
|
3098 | def magic_upgrade(self,arg): | |
2903 | """ Upgrade your IPython installation |
|
3099 | """ Upgrade your IPython installation | |
2904 |
|
3100 | |||
2905 | This will copy the config files that don't yet exist in your |
|
3101 | This will copy the config files that don't yet exist in your | |
2906 | ipython dir from the system config dir. Use this after upgrading |
|
3102 | ipython dir from the system config dir. Use this after upgrading | |
2907 | IPython if you don't wish to delete your .ipython dir. |
|
3103 | IPython if you don't wish to delete your .ipython dir. | |
2908 |
|
3104 | |||
2909 | Call with -nolegacy to get rid of ipythonrc* files (recommended for |
|
3105 | Call with -nolegacy to get rid of ipythonrc* files (recommended for | |
2910 | new users) |
|
3106 | new users) | |
2911 |
|
3107 | |||
2912 | """ |
|
3108 | """ | |
2913 | ip = self.getapi() |
|
3109 | ip = self.getapi() | |
2914 | ipinstallation = path(IPython.__file__).dirname() |
|
3110 | ipinstallation = path(IPython.__file__).dirname() | |
2915 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') |
|
3111 | upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py') | |
2916 | src_config = ipinstallation / 'UserConfig' |
|
3112 | src_config = ipinstallation / 'UserConfig' | |
2917 | userdir = path(ip.options.ipythondir) |
|
3113 | userdir = path(ip.options.ipythondir) | |
2918 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) |
|
3114 | cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir) | |
2919 | print ">",cmd |
|
3115 | print ">",cmd | |
2920 | shell(cmd) |
|
3116 | shell(cmd) | |
2921 | if arg == '-nolegacy': |
|
3117 | if arg == '-nolegacy': | |
2922 | legacy = userdir.files('ipythonrc*') |
|
3118 | legacy = userdir.files('ipythonrc*') | |
2923 | print "Nuking legacy files:",legacy |
|
3119 | print "Nuking legacy files:",legacy | |
2924 |
|
3120 | |||
2925 | [p.remove() for p in legacy] |
|
3121 | [p.remove() for p in legacy] | |
2926 | suffix = (sys.platform == 'win32' and '.ini' or '') |
|
3122 | suffix = (sys.platform == 'win32' and '.ini' or '') | |
2927 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') |
|
3123 | (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n') | |
2928 |
|
3124 | |||
2929 |
|
3125 | |||
2930 | def magic_doctest_mode(self,parameter_s=''): |
|
3126 | def magic_doctest_mode(self,parameter_s=''): | |
2931 | """Toggle doctest mode on and off. |
|
3127 | """Toggle doctest mode on and off. | |
2932 |
|
3128 | |||
2933 | This mode allows you to toggle the prompt behavior between normal |
|
3129 | This mode allows you to toggle the prompt behavior between normal | |
2934 | IPython prompts and ones that are as similar to the default IPython |
|
3130 | IPython prompts and ones that are as similar to the default IPython | |
2935 | interpreter as possible. |
|
3131 | interpreter as possible. | |
2936 |
|
3132 | |||
2937 | It also supports the pasting of code snippets that have leading '>>>' |
|
3133 | It also supports the pasting of code snippets that have leading '>>>' | |
2938 | and '...' prompts in them. This means that you can paste doctests from |
|
3134 | and '...' prompts in them. This means that you can paste doctests from | |
2939 | files or docstrings (even if they have leading whitespace), and the |
|
3135 | files or docstrings (even if they have leading whitespace), and the | |
2940 | code will execute correctly. You can then use '%history -tn' to see |
|
3136 | code will execute correctly. You can then use '%history -tn' to see | |
2941 | the translated history without line numbers; this will give you the |
|
3137 | the translated history without line numbers; this will give you the | |
2942 | input after removal of all the leading prompts and whitespace, which |
|
3138 | input after removal of all the leading prompts and whitespace, which | |
2943 | can be pasted back into an editor. |
|
3139 | can be pasted back into an editor. | |
2944 |
|
3140 | |||
2945 | With these features, you can switch into this mode easily whenever you |
|
3141 | With these features, you can switch into this mode easily whenever you | |
2946 | need to do testing and changes to doctests, without having to leave |
|
3142 | need to do testing and changes to doctests, without having to leave | |
2947 | your existing IPython session. |
|
3143 | your existing IPython session. | |
2948 | """ |
|
3144 | """ | |
2949 |
|
3145 | |||
2950 | # XXX - Fix this to have cleaner activate/deactivate calls. |
|
3146 | # XXX - Fix this to have cleaner activate/deactivate calls. | |
2951 | from IPython.Extensions import InterpreterPasteInput as ipaste |
|
3147 | from IPython.Extensions import InterpreterPasteInput as ipaste | |
2952 | from IPython.ipstruct import Struct |
|
3148 | from IPython.ipstruct import Struct | |
2953 |
|
3149 | |||
2954 | # Shorthands |
|
3150 | # Shorthands | |
2955 | shell = self.shell |
|
3151 | shell = self.shell | |
2956 | oc = shell.outputcache |
|
3152 | oc = shell.outputcache | |
2957 | rc = shell.rc |
|
3153 | rc = shell.rc | |
2958 | meta = shell.meta |
|
3154 | meta = shell.meta | |
2959 | # dstore is a data store kept in the instance metadata bag to track any |
|
3155 | # dstore is a data store kept in the instance metadata bag to track any | |
2960 | # changes we make, so we can undo them later. |
|
3156 | # changes we make, so we can undo them later. | |
2961 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3157 | dstore = meta.setdefault('doctest_mode',Struct()) | |
2962 | save_dstore = dstore.setdefault |
|
3158 | save_dstore = dstore.setdefault | |
2963 |
|
3159 | |||
2964 | # save a few values we'll need to recover later |
|
3160 | # save a few values we'll need to recover later | |
2965 | mode = save_dstore('mode',False) |
|
3161 | mode = save_dstore('mode',False) | |
2966 | save_dstore('rc_pprint',rc.pprint) |
|
3162 | save_dstore('rc_pprint',rc.pprint) | |
2967 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3163 | save_dstore('xmode',shell.InteractiveTB.mode) | |
2968 | save_dstore('rc_separate_in',rc.separate_in) |
|
3164 | save_dstore('rc_separate_in',rc.separate_in) | |
2969 | save_dstore('rc_separate_out',rc.separate_out) |
|
3165 | save_dstore('rc_separate_out',rc.separate_out) | |
2970 | save_dstore('rc_separate_out2',rc.separate_out2) |
|
3166 | save_dstore('rc_separate_out2',rc.separate_out2) | |
2971 | save_dstore('rc_prompts_pad_left',rc.prompts_pad_left) |
|
3167 | save_dstore('rc_prompts_pad_left',rc.prompts_pad_left) | |
2972 |
|
3168 | |||
2973 | if mode == False: |
|
3169 | if mode == False: | |
2974 | # turn on |
|
3170 | # turn on | |
2975 | ipaste.activate_prefilter() |
|
3171 | ipaste.activate_prefilter() | |
2976 |
|
3172 | |||
2977 | oc.prompt1.p_template = '>>> ' |
|
3173 | oc.prompt1.p_template = '>>> ' | |
2978 | oc.prompt2.p_template = '... ' |
|
3174 | oc.prompt2.p_template = '... ' | |
2979 | oc.prompt_out.p_template = '' |
|
3175 | oc.prompt_out.p_template = '' | |
2980 |
|
3176 | |||
2981 | oc.prompt1.sep = '\n' |
|
3177 | oc.prompt1.sep = '\n' | |
2982 | oc.output_sep = '' |
|
3178 | oc.output_sep = '' | |
2983 | oc.output_sep2 = '' |
|
3179 | oc.output_sep2 = '' | |
2984 |
|
3180 | |||
2985 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3181 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
2986 | oc.prompt_out.pad_left = False |
|
3182 | oc.prompt_out.pad_left = False | |
2987 |
|
3183 | |||
2988 | rc.pprint = False |
|
3184 | rc.pprint = False | |
2989 |
|
3185 | |||
2990 | shell.magic_xmode('Plain') |
|
3186 | shell.magic_xmode('Plain') | |
2991 |
|
3187 | |||
2992 | else: |
|
3188 | else: | |
2993 | # turn off |
|
3189 | # turn off | |
2994 | ipaste.deactivate_prefilter() |
|
3190 | ipaste.deactivate_prefilter() | |
2995 |
|
3191 | |||
2996 | oc.prompt1.p_template = rc.prompt_in1 |
|
3192 | oc.prompt1.p_template = rc.prompt_in1 | |
2997 | oc.prompt2.p_template = rc.prompt_in2 |
|
3193 | oc.prompt2.p_template = rc.prompt_in2 | |
2998 | oc.prompt_out.p_template = rc.prompt_out |
|
3194 | oc.prompt_out.p_template = rc.prompt_out | |
2999 |
|
3195 | |||
3000 | oc.prompt1.sep = dstore.rc_separate_in |
|
3196 | oc.prompt1.sep = dstore.rc_separate_in | |
3001 | oc.output_sep = dstore.rc_separate_out |
|
3197 | oc.output_sep = dstore.rc_separate_out | |
3002 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3198 | oc.output_sep2 = dstore.rc_separate_out2 | |
3003 |
|
3199 | |||
3004 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3200 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3005 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3201 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3006 |
|
3202 | |||
3007 | rc.pprint = dstore.rc_pprint |
|
3203 | rc.pprint = dstore.rc_pprint | |
3008 |
|
3204 | |||
3009 | shell.magic_xmode(dstore.xmode) |
|
3205 | shell.magic_xmode(dstore.xmode) | |
3010 |
|
3206 | |||
3011 | # Store new mode and inform |
|
3207 | # Store new mode and inform | |
3012 | dstore.mode = bool(1-int(mode)) |
|
3208 | dstore.mode = bool(1-int(mode)) | |
3013 | print 'Doctest mode is:', |
|
3209 | print 'Doctest mode is:', | |
3014 | print ['OFF','ON'][dstore.mode] |
|
3210 | print ['OFF','ON'][dstore.mode] | |
3015 |
|
3211 | |||
3016 | # end Magic |
|
3212 | # end Magic |
@@ -1,579 +1,577 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Tools for inspecting Python objects. |
|
2 | """Tools for inspecting Python objects. | |
3 |
|
3 | |||
4 | Uses syntax highlighting for presenting the various information elements. |
|
4 | Uses syntax highlighting for presenting the various information elements. | |
5 |
|
5 | |||
6 | Similar in spirit to the inspect module, but all calls take a name argument to |
|
6 | Similar in spirit to the inspect module, but all calls take a name argument to | |
7 | reference the name under which an object is being read. |
|
7 | reference the name under which an object is being read. | |
8 |
|
8 | |||
9 |
$Id: OInspect.py 27 |
|
9 | $Id: OInspect.py 2723 2007-09-07 07:44:16Z fperez $ | |
10 | """ |
|
10 | """ | |
11 |
|
11 | |||
12 | #***************************************************************************** |
|
12 | #***************************************************************************** | |
13 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
13 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the BSD License. The full license is in |
|
15 | # Distributed under the terms of the BSD License. The full license is in | |
16 | # the file COPYING, distributed as part of this software. |
|
16 | # the file COPYING, distributed as part of this software. | |
17 | #***************************************************************************** |
|
17 | #***************************************************************************** | |
18 |
|
18 | |||
19 | from IPython import Release |
|
19 | from IPython import Release | |
20 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
20 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
21 | __license__ = Release.license |
|
21 | __license__ = Release.license | |
22 |
|
22 | |||
23 | __all__ = ['Inspector','InspectColors'] |
|
23 | __all__ = ['Inspector','InspectColors'] | |
24 |
|
24 | |||
25 | # stdlib modules |
|
25 | # stdlib modules | |
26 | import __builtin__ |
|
26 | import __builtin__ | |
27 | import inspect |
|
27 | import inspect | |
28 | import linecache |
|
28 | import linecache | |
29 | import string |
|
29 | import string | |
30 | import StringIO |
|
30 | import StringIO | |
31 | import types |
|
31 | import types | |
32 | import os |
|
32 | import os | |
33 | import sys |
|
33 | import sys | |
34 | # IPython's own |
|
34 | # IPython's own | |
35 | from IPython import PyColorize |
|
35 | from IPython import PyColorize | |
36 | from IPython.genutils import page,indent,Term,mkdict |
|
36 | from IPython.genutils import page,indent,Term,mkdict | |
37 | from IPython.Itpl import itpl |
|
37 | from IPython.Itpl import itpl | |
38 | from IPython.wildcard import list_namespace |
|
38 | from IPython.wildcard import list_namespace | |
39 | from IPython.ColorANSI import * |
|
39 | from IPython.ColorANSI import * | |
40 |
|
40 | |||
41 | #**************************************************************************** |
|
41 | #**************************************************************************** | |
42 | # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We |
|
42 | # HACK!!! This is a crude fix for bugs in python 2.3's inspect module. We | |
43 | # simply monkeypatch inspect with code copied from python 2.4. |
|
43 | # simply monkeypatch inspect with code copied from python 2.4. | |
44 | if sys.version_info[:2] == (2,3): |
|
44 | if sys.version_info[:2] == (2,3): | |
45 | from inspect import ismodule, getabsfile, modulesbyfile |
|
45 | from inspect import ismodule, getabsfile, modulesbyfile | |
46 | def getmodule(object): |
|
46 | def getmodule(object): | |
47 | """Return the module an object was defined in, or None if not found.""" |
|
47 | """Return the module an object was defined in, or None if not found.""" | |
48 | if ismodule(object): |
|
48 | if ismodule(object): | |
49 | return object |
|
49 | return object | |
50 | if hasattr(object, '__module__'): |
|
50 | if hasattr(object, '__module__'): | |
51 | return sys.modules.get(object.__module__) |
|
51 | return sys.modules.get(object.__module__) | |
52 | try: |
|
52 | try: | |
53 | file = getabsfile(object) |
|
53 | file = getabsfile(object) | |
54 | except TypeError: |
|
54 | except TypeError: | |
55 | return None |
|
55 | return None | |
56 | if file in modulesbyfile: |
|
56 | if file in modulesbyfile: | |
57 | return sys.modules.get(modulesbyfile[file]) |
|
57 | return sys.modules.get(modulesbyfile[file]) | |
58 | for module in sys.modules.values(): |
|
58 | for module in sys.modules.values(): | |
59 | if hasattr(module, '__file__'): |
|
59 | if hasattr(module, '__file__'): | |
60 | modulesbyfile[ |
|
60 | modulesbyfile[ | |
61 | os.path.realpath( |
|
61 | os.path.realpath( | |
62 | getabsfile(module))] = module.__name__ |
|
62 | getabsfile(module))] = module.__name__ | |
63 | if file in modulesbyfile: |
|
63 | if file in modulesbyfile: | |
64 | return sys.modules.get(modulesbyfile[file]) |
|
64 | return sys.modules.get(modulesbyfile[file]) | |
65 | main = sys.modules['__main__'] |
|
65 | main = sys.modules['__main__'] | |
66 | if not hasattr(object, '__name__'): |
|
66 | if not hasattr(object, '__name__'): | |
67 | return None |
|
67 | return None | |
68 | if hasattr(main, object.__name__): |
|
68 | if hasattr(main, object.__name__): | |
69 | mainobject = getattr(main, object.__name__) |
|
69 | mainobject = getattr(main, object.__name__) | |
70 | if mainobject is object: |
|
70 | if mainobject is object: | |
71 | return main |
|
71 | return main | |
72 | builtin = sys.modules['__builtin__'] |
|
72 | builtin = sys.modules['__builtin__'] | |
73 | if hasattr(builtin, object.__name__): |
|
73 | if hasattr(builtin, object.__name__): | |
74 | builtinobject = getattr(builtin, object.__name__) |
|
74 | builtinobject = getattr(builtin, object.__name__) | |
75 | if builtinobject is object: |
|
75 | if builtinobject is object: | |
76 | return builtin |
|
76 | return builtin | |
77 |
|
77 | |||
78 | inspect.getmodule = getmodule |
|
78 | inspect.getmodule = getmodule | |
79 |
|
79 | |||
80 | #**************************************************************************** |
|
80 | #**************************************************************************** | |
81 | # Builtin color schemes |
|
81 | # Builtin color schemes | |
82 |
|
82 | |||
83 | Colors = TermColors # just a shorthand |
|
83 | Colors = TermColors # just a shorthand | |
84 |
|
84 | |||
85 | # Build a few color schemes |
|
85 | # Build a few color schemes | |
86 | NoColor = ColorScheme( |
|
86 | NoColor = ColorScheme( | |
87 | 'NoColor',{ |
|
87 | 'NoColor',{ | |
88 | 'header' : Colors.NoColor, |
|
88 | 'header' : Colors.NoColor, | |
89 | 'normal' : Colors.NoColor # color off (usu. Colors.Normal) |
|
89 | 'normal' : Colors.NoColor # color off (usu. Colors.Normal) | |
90 | } ) |
|
90 | } ) | |
91 |
|
91 | |||
92 | LinuxColors = ColorScheme( |
|
92 | LinuxColors = ColorScheme( | |
93 | 'Linux',{ |
|
93 | 'Linux',{ | |
94 | 'header' : Colors.LightRed, |
|
94 | 'header' : Colors.LightRed, | |
95 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
95 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) | |
96 | } ) |
|
96 | } ) | |
97 |
|
97 | |||
98 | LightBGColors = ColorScheme( |
|
98 | LightBGColors = ColorScheme( | |
99 | 'LightBG',{ |
|
99 | 'LightBG',{ | |
100 | 'header' : Colors.Red, |
|
100 | 'header' : Colors.Red, | |
101 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
101 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) | |
102 | } ) |
|
102 | } ) | |
103 |
|
103 | |||
104 | # Build table of color schemes (needed by the parser) |
|
104 | # Build table of color schemes (needed by the parser) | |
105 | InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors], |
|
105 | InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors], | |
106 | 'Linux') |
|
106 | 'Linux') | |
107 |
|
107 | |||
108 | #**************************************************************************** |
|
108 | #**************************************************************************** | |
109 | # Auxiliary functions |
|
109 | # Auxiliary functions | |
110 | def getdoc(obj): |
|
110 | def getdoc(obj): | |
111 | """Stable wrapper around inspect.getdoc. |
|
111 | """Stable wrapper around inspect.getdoc. | |
112 |
|
112 | |||
113 | This can't crash because of attribute problems. |
|
113 | This can't crash because of attribute problems. | |
114 |
|
114 | |||
115 | It also attempts to call a getdoc() method on the given object. This |
|
115 | It also attempts to call a getdoc() method on the given object. This | |
116 | allows objects which provide their docstrings via non-standard mechanisms |
|
116 | allows objects which provide their docstrings via non-standard mechanisms | |
117 | (like Pyro proxies) to still be inspected by ipython's ? system.""" |
|
117 | (like Pyro proxies) to still be inspected by ipython's ? system.""" | |
118 |
|
118 | |||
119 | ds = None # default return value |
|
119 | ds = None # default return value | |
120 | try: |
|
120 | try: | |
121 | ds = inspect.getdoc(obj) |
|
121 | ds = inspect.getdoc(obj) | |
122 | except: |
|
122 | except: | |
123 | # Harden against an inspect failure, which can occur with |
|
123 | # Harden against an inspect failure, which can occur with | |
124 | # SWIG-wrapped extensions. |
|
124 | # SWIG-wrapped extensions. | |
125 | pass |
|
125 | pass | |
126 | # Allow objects to offer customized documentation via a getdoc method: |
|
126 | # Allow objects to offer customized documentation via a getdoc method: | |
127 | try: |
|
127 | try: | |
128 | ds2 = obj.getdoc() |
|
128 | ds2 = obj.getdoc() | |
129 | except: |
|
129 | except: | |
130 | pass |
|
130 | pass | |
131 | else: |
|
131 | else: | |
132 | # if we get extra info, we add it to the normal docstring. |
|
132 | # if we get extra info, we add it to the normal docstring. | |
133 | if ds is None: |
|
133 | if ds is None: | |
134 | ds = ds2 |
|
134 | ds = ds2 | |
135 | else: |
|
135 | else: | |
136 | ds = '%s\n%s' % (ds,ds2) |
|
136 | ds = '%s\n%s' % (ds,ds2) | |
137 | return ds |
|
137 | return ds | |
138 |
|
138 | |||
139 | def getsource(obj,is_binary=False): |
|
139 | def getsource(obj,is_binary=False): | |
140 | """Wrapper around inspect.getsource. |
|
140 | """Wrapper around inspect.getsource. | |
141 |
|
141 | |||
142 | This can be modified by other projects to provide customized source |
|
142 | This can be modified by other projects to provide customized source | |
143 | extraction. |
|
143 | extraction. | |
144 |
|
144 | |||
145 | Inputs: |
|
145 | Inputs: | |
146 |
|
146 | |||
147 | - obj: an object whose source code we will attempt to extract. |
|
147 | - obj: an object whose source code we will attempt to extract. | |
148 |
|
148 | |||
149 | Optional inputs: |
|
149 | Optional inputs: | |
150 |
|
150 | |||
151 | - is_binary: whether the object is known to come from a binary source. |
|
151 | - is_binary: whether the object is known to come from a binary source. | |
152 | This implementation will skip returning any output for binary objects, but |
|
152 | This implementation will skip returning any output for binary objects, but | |
153 | custom extractors may know how to meaningfully process them.""" |
|
153 | custom extractors may know how to meaningfully process them.""" | |
154 |
|
154 | |||
155 | if is_binary: |
|
155 | if is_binary: | |
156 | return None |
|
156 | return None | |
157 | else: |
|
157 | else: | |
158 | return inspect.getsource(obj) |
|
158 | return inspect.getsource(obj) | |
159 |
|
159 | |||
160 | #**************************************************************************** |
|
160 | #**************************************************************************** | |
161 | # Class definitions |
|
161 | # Class definitions | |
162 |
|
162 | |||
163 | class myStringIO(StringIO.StringIO): |
|
163 | class myStringIO(StringIO.StringIO): | |
164 | """Adds a writeln method to normal StringIO.""" |
|
164 | """Adds a writeln method to normal StringIO.""" | |
165 | def writeln(self,*arg,**kw): |
|
165 | def writeln(self,*arg,**kw): | |
166 | """Does a write() and then a write('\n')""" |
|
166 | """Does a write() and then a write('\n')""" | |
167 | self.write(*arg,**kw) |
|
167 | self.write(*arg,**kw) | |
168 | self.write('\n') |
|
168 | self.write('\n') | |
169 |
|
169 | |||
170 | class Inspector: |
|
170 | class Inspector: | |
171 | def __init__(self,color_table,code_color_table,scheme, |
|
171 | def __init__(self,color_table,code_color_table,scheme, | |
172 | str_detail_level=0): |
|
172 | str_detail_level=0): | |
173 | self.color_table = color_table |
|
173 | self.color_table = color_table | |
174 | self.parser = PyColorize.Parser(code_color_table,out='str') |
|
174 | self.parser = PyColorize.Parser(code_color_table,out='str') | |
175 | self.format = self.parser.format |
|
175 | self.format = self.parser.format | |
176 | self.str_detail_level = str_detail_level |
|
176 | self.str_detail_level = str_detail_level | |
177 | self.set_active_scheme(scheme) |
|
177 | self.set_active_scheme(scheme) | |
178 |
|
178 | |||
179 | def __getargspec(self,obj): |
|
179 | def __getargspec(self,obj): | |
180 | """Get the names and default values of a function's arguments. |
|
180 | """Get the names and default values of a function's arguments. | |
181 |
|
181 | |||
182 | A tuple of four things is returned: (args, varargs, varkw, defaults). |
|
182 | A tuple of four things is returned: (args, varargs, varkw, defaults). | |
183 | 'args' is a list of the argument names (it may contain nested lists). |
|
183 | 'args' is a list of the argument names (it may contain nested lists). | |
184 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
|
184 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. | |
185 | 'defaults' is an n-tuple of the default values of the last n arguments. |
|
185 | 'defaults' is an n-tuple of the default values of the last n arguments. | |
186 |
|
186 | |||
187 | Modified version of inspect.getargspec from the Python Standard |
|
187 | Modified version of inspect.getargspec from the Python Standard | |
188 | Library.""" |
|
188 | Library.""" | |
189 |
|
189 | |||
190 | if inspect.isfunction(obj): |
|
190 | if inspect.isfunction(obj): | |
191 | func_obj = obj |
|
191 | func_obj = obj | |
192 | elif inspect.ismethod(obj): |
|
192 | elif inspect.ismethod(obj): | |
193 | func_obj = obj.im_func |
|
193 | func_obj = obj.im_func | |
194 | else: |
|
194 | else: | |
195 | raise TypeError, 'arg is not a Python function' |
|
195 | raise TypeError, 'arg is not a Python function' | |
196 | args, varargs, varkw = inspect.getargs(func_obj.func_code) |
|
196 | args, varargs, varkw = inspect.getargs(func_obj.func_code) | |
197 | return args, varargs, varkw, func_obj.func_defaults |
|
197 | return args, varargs, varkw, func_obj.func_defaults | |
198 |
|
198 | |||
199 | def __getdef(self,obj,oname=''): |
|
199 | def __getdef(self,obj,oname=''): | |
200 | """Return the definition header for any callable object. |
|
200 | """Return the definition header for any callable object. | |
201 |
|
201 | |||
202 | If any exception is generated, None is returned instead and the |
|
202 | If any exception is generated, None is returned instead and the | |
203 | exception is suppressed.""" |
|
203 | exception is suppressed.""" | |
204 |
|
204 | |||
205 | try: |
|
205 | try: | |
206 | return oname + inspect.formatargspec(*self.__getargspec(obj)) |
|
206 | return oname + inspect.formatargspec(*self.__getargspec(obj)) | |
207 | except: |
|
207 | except: | |
208 | return None |
|
208 | return None | |
209 |
|
209 | |||
210 | def __head(self,h): |
|
210 | def __head(self,h): | |
211 | """Return a header string with proper colors.""" |
|
211 | """Return a header string with proper colors.""" | |
212 | return '%s%s%s' % (self.color_table.active_colors.header,h, |
|
212 | return '%s%s%s' % (self.color_table.active_colors.header,h, | |
213 | self.color_table.active_colors.normal) |
|
213 | self.color_table.active_colors.normal) | |
214 |
|
214 | |||
215 | def set_active_scheme(self,scheme): |
|
215 | def set_active_scheme(self,scheme): | |
216 | self.color_table.set_active_scheme(scheme) |
|
216 | self.color_table.set_active_scheme(scheme) | |
217 | self.parser.color_table.set_active_scheme(scheme) |
|
217 | self.parser.color_table.set_active_scheme(scheme) | |
218 |
|
218 | |||
219 | def noinfo(self,msg,oname): |
|
219 | def noinfo(self,msg,oname): | |
220 | """Generic message when no information is found.""" |
|
220 | """Generic message when no information is found.""" | |
221 | print 'No %s found' % msg, |
|
221 | print 'No %s found' % msg, | |
222 | if oname: |
|
222 | if oname: | |
223 | print 'for %s' % oname |
|
223 | print 'for %s' % oname | |
224 | else: |
|
224 | else: | |
225 |
|
225 | |||
226 |
|
226 | |||
227 | def pdef(self,obj,oname=''): |
|
227 | def pdef(self,obj,oname=''): | |
228 | """Print the definition header for any callable object. |
|
228 | """Print the definition header for any callable object. | |
229 |
|
229 | |||
230 | If the object is a class, print the constructor information.""" |
|
230 | If the object is a class, print the constructor information.""" | |
231 |
|
231 | |||
232 | if not callable(obj): |
|
232 | if not callable(obj): | |
233 | print 'Object is not callable.' |
|
233 | print 'Object is not callable.' | |
234 | return |
|
234 | return | |
235 |
|
235 | |||
236 | header = '' |
|
236 | header = '' | |
237 |
|
237 | |||
238 | if inspect.isclass(obj): |
|
238 | if inspect.isclass(obj): | |
239 | header = self.__head('Class constructor information:\n') |
|
239 | header = self.__head('Class constructor information:\n') | |
240 | obj = obj.__init__ |
|
240 | obj = obj.__init__ | |
241 |
elif type(obj) is types.InstanceType |
|
241 | elif type(obj) is types.InstanceType: | |
242 | isinstance(obj,object): |
|
|||
243 | obj = obj.__call__ |
|
242 | obj = obj.__call__ | |
244 |
|
243 | |||
245 | output = self.__getdef(obj,oname) |
|
244 | output = self.__getdef(obj,oname) | |
246 | if output is None: |
|
245 | if output is None: | |
247 | self.noinfo('definition header',oname) |
|
246 | self.noinfo('definition header',oname) | |
248 | else: |
|
247 | else: | |
249 | print >>Term.cout, header,self.format(output), |
|
248 | print >>Term.cout, header,self.format(output), | |
250 |
|
249 | |||
251 | def pdoc(self,obj,oname='',formatter = None): |
|
250 | def pdoc(self,obj,oname='',formatter = None): | |
252 | """Print the docstring for any object. |
|
251 | """Print the docstring for any object. | |
253 |
|
252 | |||
254 | Optional: |
|
253 | Optional: | |
255 | -formatter: a function to run the docstring through for specially |
|
254 | -formatter: a function to run the docstring through for specially | |
256 | formatted docstrings.""" |
|
255 | formatted docstrings.""" | |
257 |
|
256 | |||
258 | head = self.__head # so that itpl can find it even if private |
|
257 | head = self.__head # so that itpl can find it even if private | |
259 | ds = getdoc(obj) |
|
258 | ds = getdoc(obj) | |
260 | if formatter: |
|
259 | if formatter: | |
261 | ds = formatter(ds) |
|
260 | ds = formatter(ds) | |
262 | if inspect.isclass(obj): |
|
261 | if inspect.isclass(obj): | |
263 | init_ds = getdoc(obj.__init__) |
|
262 | init_ds = getdoc(obj.__init__) | |
264 | output = itpl('$head("Class Docstring:")\n' |
|
263 | output = itpl('$head("Class Docstring:")\n' | |
265 | '$indent(ds)\n' |
|
264 | '$indent(ds)\n' | |
266 | '$head("Constructor Docstring"):\n' |
|
265 | '$head("Constructor Docstring"):\n' | |
267 | '$indent(init_ds)') |
|
266 | '$indent(init_ds)') | |
268 | elif (type(obj) is types.InstanceType or isinstance(obj,object)) \ |
|
267 | elif (type(obj) is types.InstanceType or isinstance(obj,object)) \ | |
269 | and hasattr(obj,'__call__'): |
|
268 | and hasattr(obj,'__call__'): | |
270 | call_ds = getdoc(obj.__call__) |
|
269 | call_ds = getdoc(obj.__call__) | |
271 | if call_ds: |
|
270 | if call_ds: | |
272 | output = itpl('$head("Class Docstring:")\n$indent(ds)\n' |
|
271 | output = itpl('$head("Class Docstring:")\n$indent(ds)\n' | |
273 | '$head("Calling Docstring:")\n$indent(call_ds)') |
|
272 | '$head("Calling Docstring:")\n$indent(call_ds)') | |
274 | else: |
|
273 | else: | |
275 | output = ds |
|
274 | output = ds | |
276 | else: |
|
275 | else: | |
277 | output = ds |
|
276 | output = ds | |
278 | if output is None: |
|
277 | if output is None: | |
279 | self.noinfo('documentation',oname) |
|
278 | self.noinfo('documentation',oname) | |
280 | return |
|
279 | return | |
281 | page(output) |
|
280 | page(output) | |
282 |
|
281 | |||
283 | def psource(self,obj,oname=''): |
|
282 | def psource(self,obj,oname=''): | |
284 | """Print the source code for an object.""" |
|
283 | """Print the source code for an object.""" | |
285 |
|
284 | |||
286 | # Flush the source cache because inspect can return out-of-date source |
|
285 | # Flush the source cache because inspect can return out-of-date source | |
287 | linecache.checkcache() |
|
286 | linecache.checkcache() | |
288 | try: |
|
287 | try: | |
289 | src = getsource(obj) |
|
288 | src = getsource(obj) | |
290 | except: |
|
289 | except: | |
291 | self.noinfo('source',oname) |
|
290 | self.noinfo('source',oname) | |
292 | else: |
|
291 | else: | |
293 | page(self.format(src)) |
|
292 | page(self.format(src)) | |
294 |
|
293 | |||
295 | def pfile(self,obj,oname=''): |
|
294 | def pfile(self,obj,oname=''): | |
296 | """Show the whole file where an object was defined.""" |
|
295 | """Show the whole file where an object was defined.""" | |
297 | try: |
|
296 | try: | |
298 | sourcelines,lineno = inspect.getsourcelines(obj) |
|
297 | sourcelines,lineno = inspect.getsourcelines(obj) | |
299 | except: |
|
298 | except: | |
300 | self.noinfo('file',oname) |
|
299 | self.noinfo('file',oname) | |
301 | else: |
|
300 | else: | |
302 | # run contents of file through pager starting at line |
|
301 | # run contents of file through pager starting at line | |
303 | # where the object is defined |
|
302 | # where the object is defined | |
304 | ofile = inspect.getabsfile(obj) |
|
303 | ofile = inspect.getabsfile(obj) | |
305 |
|
304 | |||
306 | if (ofile.endswith('.so') or ofile.endswith('.dll')): |
|
305 | if (ofile.endswith('.so') or ofile.endswith('.dll')): | |
307 | print 'File %r is binary, not printing.' % ofile |
|
306 | print 'File %r is binary, not printing.' % ofile | |
308 | elif not os.path.isfile(ofile): |
|
307 | elif not os.path.isfile(ofile): | |
309 | print 'File %r does not exist, not printing.' % ofile |
|
308 | print 'File %r does not exist, not printing.' % ofile | |
310 | else: |
|
309 | else: | |
311 | # Print only text files, not extension binaries. |
|
310 | # Print only text files, not extension binaries. | |
312 | page(self.format(open(ofile).read()),lineno) |
|
311 | page(self.format(open(ofile).read()),lineno) | |
313 | #page(self.format(open(inspect.getabsfile(obj)).read()),lineno) |
|
312 | #page(self.format(open(inspect.getabsfile(obj)).read()),lineno) | |
314 |
|
313 | |||
315 | def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): |
|
314 | def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): | |
316 | """Show detailed information about an object. |
|
315 | """Show detailed information about an object. | |
317 |
|
316 | |||
318 | Optional arguments: |
|
317 | Optional arguments: | |
319 |
|
318 | |||
320 | - oname: name of the variable pointing to the object. |
|
319 | - oname: name of the variable pointing to the object. | |
321 |
|
320 | |||
322 | - formatter: special formatter for docstrings (see pdoc) |
|
321 | - formatter: special formatter for docstrings (see pdoc) | |
323 |
|
322 | |||
324 | - info: a structure with some information fields which may have been |
|
323 | - info: a structure with some information fields which may have been | |
325 | precomputed already. |
|
324 | precomputed already. | |
326 |
|
325 | |||
327 | - detail_level: if set to 1, more information is given. |
|
326 | - detail_level: if set to 1, more information is given. | |
328 | """ |
|
327 | """ | |
329 |
|
328 | |||
330 | obj_type = type(obj) |
|
329 | obj_type = type(obj) | |
331 |
|
330 | |||
332 | header = self.__head |
|
331 | header = self.__head | |
333 | if info is None: |
|
332 | if info is None: | |
334 | ismagic = 0 |
|
333 | ismagic = 0 | |
335 | isalias = 0 |
|
334 | isalias = 0 | |
336 | ospace = '' |
|
335 | ospace = '' | |
337 | else: |
|
336 | else: | |
338 | ismagic = info.ismagic |
|
337 | ismagic = info.ismagic | |
339 | isalias = info.isalias |
|
338 | isalias = info.isalias | |
340 | ospace = info.namespace |
|
339 | ospace = info.namespace | |
341 | # Get docstring, special-casing aliases: |
|
340 | # Get docstring, special-casing aliases: | |
342 | if isalias: |
|
341 | if isalias: | |
343 | if not callable(obj): |
|
342 | if not callable(obj): | |
344 | try: |
|
343 | try: | |
345 | ds = "Alias to the system command:\n %s" % obj[1] |
|
344 | ds = "Alias to the system command:\n %s" % obj[1] | |
346 | except: |
|
345 | except: | |
347 | ds = "Alias: " + str(obj) |
|
346 | ds = "Alias: " + str(obj) | |
348 | else: |
|
347 | else: | |
349 | ds = "Alias to " + str(obj) |
|
348 | ds = "Alias to " + str(obj) | |
350 | if obj.__doc__: |
|
349 | if obj.__doc__: | |
351 | ds += "\nDocstring:\n" + obj.__doc__ |
|
350 | ds += "\nDocstring:\n" + obj.__doc__ | |
352 | else: |
|
351 | else: | |
353 | ds = getdoc(obj) |
|
352 | ds = getdoc(obj) | |
354 | if ds is None: |
|
353 | if ds is None: | |
355 | ds = '<no docstring>' |
|
354 | ds = '<no docstring>' | |
356 | if formatter is not None: |
|
355 | if formatter is not None: | |
357 | ds = formatter(ds) |
|
356 | ds = formatter(ds) | |
358 |
|
357 | |||
359 | # store output in a list which gets joined with \n at the end. |
|
358 | # store output in a list which gets joined with \n at the end. | |
360 | out = myStringIO() |
|
359 | out = myStringIO() | |
361 |
|
360 | |||
362 | string_max = 200 # max size of strings to show (snipped if longer) |
|
361 | string_max = 200 # max size of strings to show (snipped if longer) | |
363 | shalf = int((string_max -5)/2) |
|
362 | shalf = int((string_max -5)/2) | |
364 |
|
363 | |||
365 | if ismagic: |
|
364 | if ismagic: | |
366 | obj_type_name = 'Magic function' |
|
365 | obj_type_name = 'Magic function' | |
367 | elif isalias: |
|
366 | elif isalias: | |
368 | obj_type_name = 'System alias' |
|
367 | obj_type_name = 'System alias' | |
369 | else: |
|
368 | else: | |
370 | obj_type_name = obj_type.__name__ |
|
369 | obj_type_name = obj_type.__name__ | |
371 | out.writeln(header('Type:\t\t')+obj_type_name) |
|
370 | out.writeln(header('Type:\t\t')+obj_type_name) | |
372 |
|
371 | |||
373 | try: |
|
372 | try: | |
374 | bclass = obj.__class__ |
|
373 | bclass = obj.__class__ | |
375 | out.writeln(header('Base Class:\t')+str(bclass)) |
|
374 | out.writeln(header('Base Class:\t')+str(bclass)) | |
376 | except: pass |
|
375 | except: pass | |
377 |
|
376 | |||
378 | # String form, but snip if too long in ? form (full in ??) |
|
377 | # String form, but snip if too long in ? form (full in ??) | |
379 | if detail_level >= self.str_detail_level: |
|
378 | if detail_level >= self.str_detail_level: | |
380 | try: |
|
379 | try: | |
381 | ostr = str(obj) |
|
380 | ostr = str(obj) | |
382 | str_head = 'String Form:' |
|
381 | str_head = 'String Form:' | |
383 | if not detail_level and len(ostr)>string_max: |
|
382 | if not detail_level and len(ostr)>string_max: | |
384 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] |
|
383 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] | |
385 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ |
|
384 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ | |
386 | join(map(string.strip,ostr.split("\n"))) |
|
385 | join(map(string.strip,ostr.split("\n"))) | |
387 | if ostr.find('\n') > -1: |
|
386 | if ostr.find('\n') > -1: | |
388 | # Print multi-line strings starting at the next line. |
|
387 | # Print multi-line strings starting at the next line. | |
389 | str_sep = '\n' |
|
388 | str_sep = '\n' | |
390 | else: |
|
389 | else: | |
391 | str_sep = '\t' |
|
390 | str_sep = '\t' | |
392 | out.writeln("%s%s%s" % (header(str_head),str_sep,ostr)) |
|
391 | out.writeln("%s%s%s" % (header(str_head),str_sep,ostr)) | |
393 | except: |
|
392 | except: | |
394 | pass |
|
393 | pass | |
395 |
|
394 | |||
396 | if ospace: |
|
395 | if ospace: | |
397 | out.writeln(header('Namespace:\t')+ospace) |
|
396 | out.writeln(header('Namespace:\t')+ospace) | |
398 |
|
397 | |||
399 | # Length (for strings and lists) |
|
398 | # Length (for strings and lists) | |
400 | try: |
|
399 | try: | |
401 | length = str(len(obj)) |
|
400 | length = str(len(obj)) | |
402 | out.writeln(header('Length:\t\t')+length) |
|
401 | out.writeln(header('Length:\t\t')+length) | |
403 | except: pass |
|
402 | except: pass | |
404 |
|
403 | |||
405 | # Filename where object was defined |
|
404 | # Filename where object was defined | |
406 | binary_file = False |
|
405 | binary_file = False | |
407 | try: |
|
406 | try: | |
408 | fname = inspect.getabsfile(obj) |
|
407 | fname = inspect.getabsfile(obj) | |
409 | if fname.endswith('<string>'): |
|
408 | if fname.endswith('<string>'): | |
410 | fname = 'Dynamically generated function. No source code available.' |
|
409 | fname = 'Dynamically generated function. No source code available.' | |
411 |
if (fname.endswith('.so') or fname.endswith('.dll') |
|
410 | if (fname.endswith('.so') or fname.endswith('.dll')): | |
412 | not os.path.isfile(fname)): |
|
|||
413 | binary_file = True |
|
411 | binary_file = True | |
414 | out.writeln(header('File:\t\t')+fname) |
|
412 | out.writeln(header('File:\t\t')+fname) | |
415 | except: |
|
413 | except: | |
416 | # if anything goes wrong, we don't want to show source, so it's as |
|
414 | # if anything goes wrong, we don't want to show source, so it's as | |
417 | # if the file was binary |
|
415 | # if the file was binary | |
418 | binary_file = True |
|
416 | binary_file = True | |
419 |
|
417 | |||
420 | # reconstruct the function definition and print it: |
|
418 | # reconstruct the function definition and print it: | |
421 | defln = self.__getdef(obj,oname) |
|
419 | defln = self.__getdef(obj,oname) | |
422 | if defln: |
|
420 | if defln: | |
423 | out.write(header('Definition:\t')+self.format(defln)) |
|
421 | out.write(header('Definition:\t')+self.format(defln)) | |
424 |
|
422 | |||
425 | # Docstrings only in detail 0 mode, since source contains them (we |
|
423 | # Docstrings only in detail 0 mode, since source contains them (we | |
426 | # avoid repetitions). If source fails, we add them back, see below. |
|
424 | # avoid repetitions). If source fails, we add them back, see below. | |
427 | if ds and detail_level == 0: |
|
425 | if ds and detail_level == 0: | |
428 | out.writeln(header('Docstring:\n') + indent(ds)) |
|
426 | out.writeln(header('Docstring:\n') + indent(ds)) | |
429 |
|
||||
430 |
|
427 | |||
431 | # Original source code for any callable |
|
428 | # Original source code for any callable | |
432 | if detail_level: |
|
429 | if detail_level: | |
433 |
# Flush the source cache because inspect can return out-of-date |
|
430 | # Flush the source cache because inspect can return out-of-date | |
|
431 | # source | |||
434 | linecache.checkcache() |
|
432 | linecache.checkcache() | |
435 | source_success = False |
|
433 | source_success = False | |
436 | try: |
|
434 | try: | |
437 | source = self.format(getsource(obj,binary_file)) |
|
435 | source = self.format(getsource(obj,binary_file)) | |
438 | if source: |
|
436 | if source: | |
439 | out.write(header('Source:\n')+source.rstrip()) |
|
437 | out.write(header('Source:\n')+source.rstrip()) | |
440 | source_success = True |
|
438 | source_success = True | |
441 | except Exception, msg: |
|
439 | except Exception, msg: | |
442 | pass |
|
440 | pass | |
443 |
|
441 | |||
444 | if ds and not source_success: |
|
442 | if ds and not source_success: | |
445 | out.writeln(header('Docstring [source file open failed]:\n') |
|
443 | out.writeln(header('Docstring [source file open failed]:\n') | |
446 | + indent(ds)) |
|
444 | + indent(ds)) | |
447 |
|
445 | |||
448 | # Constructor docstring for classes |
|
446 | # Constructor docstring for classes | |
449 | if inspect.isclass(obj): |
|
447 | if inspect.isclass(obj): | |
450 | # reconstruct the function definition and print it: |
|
448 | # reconstruct the function definition and print it: | |
451 | try: |
|
449 | try: | |
452 | obj_init = obj.__init__ |
|
450 | obj_init = obj.__init__ | |
453 | except AttributeError: |
|
451 | except AttributeError: | |
454 | init_def = init_ds = None |
|
452 | init_def = init_ds = None | |
455 | else: |
|
453 | else: | |
456 | init_def = self.__getdef(obj_init,oname) |
|
454 | init_def = self.__getdef(obj_init,oname) | |
457 | init_ds = getdoc(obj_init) |
|
455 | init_ds = getdoc(obj_init) | |
458 | # Skip Python's auto-generated docstrings |
|
456 | # Skip Python's auto-generated docstrings | |
459 | if init_ds and \ |
|
457 | if init_ds and \ | |
460 | init_ds.startswith('x.__init__(...) initializes'): |
|
458 | init_ds.startswith('x.__init__(...) initializes'): | |
461 | init_ds = None |
|
459 | init_ds = None | |
462 |
|
460 | |||
463 | if init_def or init_ds: |
|
461 | if init_def or init_ds: | |
464 | out.writeln(header('\nConstructor information:')) |
|
462 | out.writeln(header('\nConstructor information:')) | |
465 | if init_def: |
|
463 | if init_def: | |
466 | out.write(header('Definition:\t')+ self.format(init_def)) |
|
464 | out.write(header('Definition:\t')+ self.format(init_def)) | |
467 | if init_ds: |
|
465 | if init_ds: | |
468 | out.writeln(header('Docstring:\n') + indent(init_ds)) |
|
466 | out.writeln(header('Docstring:\n') + indent(init_ds)) | |
469 | # and class docstring for instances: |
|
467 | # and class docstring for instances: | |
470 | elif obj_type is types.InstanceType or \ |
|
468 | elif obj_type is types.InstanceType or \ | |
471 | isinstance(obj,object): |
|
469 | isinstance(obj,object): | |
472 |
|
470 | |||
473 | # First, check whether the instance docstring is identical to the |
|
471 | # First, check whether the instance docstring is identical to the | |
474 | # class one, and print it separately if they don't coincide. In |
|
472 | # class one, and print it separately if they don't coincide. In | |
475 | # most cases they will, but it's nice to print all the info for |
|
473 | # most cases they will, but it's nice to print all the info for | |
476 | # objects which use instance-customized docstrings. |
|
474 | # objects which use instance-customized docstrings. | |
477 | if ds: |
|
475 | if ds: | |
478 | class_ds = getdoc(obj.__class__) |
|
476 | class_ds = getdoc(obj.__class__) | |
479 | # Skip Python's auto-generated docstrings |
|
477 | # Skip Python's auto-generated docstrings | |
480 | if class_ds and \ |
|
478 | if class_ds and \ | |
481 | (class_ds.startswith('function(code, globals[,') or \ |
|
479 | (class_ds.startswith('function(code, globals[,') or \ | |
482 | class_ds.startswith('instancemethod(function, instance,') or \ |
|
480 | class_ds.startswith('instancemethod(function, instance,') or \ | |
483 | class_ds.startswith('module(name[,') ): |
|
481 | class_ds.startswith('module(name[,') ): | |
484 | class_ds = None |
|
482 | class_ds = None | |
485 | if class_ds and ds != class_ds: |
|
483 | if class_ds and ds != class_ds: | |
486 | out.writeln(header('Class Docstring:\n') + |
|
484 | out.writeln(header('Class Docstring:\n') + | |
487 | indent(class_ds)) |
|
485 | indent(class_ds)) | |
488 |
|
486 | |||
489 | # Next, try to show constructor docstrings |
|
487 | # Next, try to show constructor docstrings | |
490 | try: |
|
488 | try: | |
491 | init_ds = getdoc(obj.__init__) |
|
489 | init_ds = getdoc(obj.__init__) | |
492 | # Skip Python's auto-generated docstrings |
|
490 | # Skip Python's auto-generated docstrings | |
493 | if init_ds and \ |
|
491 | if init_ds and \ | |
494 | init_ds.startswith('x.__init__(...) initializes'): |
|
492 | init_ds.startswith('x.__init__(...) initializes'): | |
495 | init_ds = None |
|
493 | init_ds = None | |
496 | except AttributeError: |
|
494 | except AttributeError: | |
497 | init_ds = None |
|
495 | init_ds = None | |
498 | if init_ds: |
|
496 | if init_ds: | |
499 | out.writeln(header('Constructor Docstring:\n') + |
|
497 | out.writeln(header('Constructor Docstring:\n') + | |
500 | indent(init_ds)) |
|
498 | indent(init_ds)) | |
501 |
|
499 | |||
502 | # Call form docstring for callable instances |
|
500 | # Call form docstring for callable instances | |
503 | if hasattr(obj,'__call__'): |
|
501 | if hasattr(obj,'__call__'): | |
504 | #out.writeln(header('Callable:\t')+'Yes') |
|
502 | #out.writeln(header('Callable:\t')+'Yes') | |
505 | call_def = self.__getdef(obj.__call__,oname) |
|
503 | call_def = self.__getdef(obj.__call__,oname) | |
506 | #if call_def is None: |
|
504 | #if call_def is None: | |
507 | # out.writeln(header('Call def:\t')+ |
|
505 | # out.writeln(header('Call def:\t')+ | |
508 | # 'Calling definition not available.') |
|
506 | # 'Calling definition not available.') | |
509 | if call_def is not None: |
|
507 | if call_def is not None: | |
510 | out.writeln(header('Call def:\t')+self.format(call_def)) |
|
508 | out.writeln(header('Call def:\t')+self.format(call_def)) | |
511 | call_ds = getdoc(obj.__call__) |
|
509 | call_ds = getdoc(obj.__call__) | |
512 | # Skip Python's auto-generated docstrings |
|
510 | # Skip Python's auto-generated docstrings | |
513 | if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): |
|
511 | if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): | |
514 | call_ds = None |
|
512 | call_ds = None | |
515 | if call_ds: |
|
513 | if call_ds: | |
516 | out.writeln(header('Call docstring:\n') + indent(call_ds)) |
|
514 | out.writeln(header('Call docstring:\n') + indent(call_ds)) | |
517 |
|
515 | |||
518 | # Finally send to printer/pager |
|
516 | # Finally send to printer/pager | |
519 | output = out.getvalue() |
|
517 | output = out.getvalue() | |
520 | if output: |
|
518 | if output: | |
521 | page(output) |
|
519 | page(output) | |
522 | # end pinfo |
|
520 | # end pinfo | |
523 |
|
521 | |||
524 | def psearch(self,pattern,ns_table,ns_search=[], |
|
522 | def psearch(self,pattern,ns_table,ns_search=[], | |
525 | ignore_case=False,show_all=False): |
|
523 | ignore_case=False,show_all=False): | |
526 | """Search namespaces with wildcards for objects. |
|
524 | """Search namespaces with wildcards for objects. | |
527 |
|
525 | |||
528 | Arguments: |
|
526 | Arguments: | |
529 |
|
527 | |||
530 | - pattern: string containing shell-like wildcards to use in namespace |
|
528 | - pattern: string containing shell-like wildcards to use in namespace | |
531 | searches and optionally a type specification to narrow the search to |
|
529 | searches and optionally a type specification to narrow the search to | |
532 | objects of that type. |
|
530 | objects of that type. | |
533 |
|
531 | |||
534 | - ns_table: dict of name->namespaces for search. |
|
532 | - ns_table: dict of name->namespaces for search. | |
535 |
|
533 | |||
536 | Optional arguments: |
|
534 | Optional arguments: | |
537 |
|
535 | |||
538 | - ns_search: list of namespace names to include in search. |
|
536 | - ns_search: list of namespace names to include in search. | |
539 |
|
537 | |||
540 | - ignore_case(False): make the search case-insensitive. |
|
538 | - ignore_case(False): make the search case-insensitive. | |
541 |
|
539 | |||
542 | - show_all(False): show all names, including those starting with |
|
540 | - show_all(False): show all names, including those starting with | |
543 | underscores. |
|
541 | underscores. | |
544 | """ |
|
542 | """ | |
545 | #print 'ps pattern:<%r>' % pattern # dbg |
|
543 | #print 'ps pattern:<%r>' % pattern # dbg | |
546 |
|
544 | |||
547 | # defaults |
|
545 | # defaults | |
548 | type_pattern = 'all' |
|
546 | type_pattern = 'all' | |
549 | filter = '' |
|
547 | filter = '' | |
550 |
|
548 | |||
551 | cmds = pattern.split() |
|
549 | cmds = pattern.split() | |
552 | len_cmds = len(cmds) |
|
550 | len_cmds = len(cmds) | |
553 | if len_cmds == 1: |
|
551 | if len_cmds == 1: | |
554 | # Only filter pattern given |
|
552 | # Only filter pattern given | |
555 | filter = cmds[0] |
|
553 | filter = cmds[0] | |
556 | elif len_cmds == 2: |
|
554 | elif len_cmds == 2: | |
557 | # Both filter and type specified |
|
555 | # Both filter and type specified | |
558 | filter,type_pattern = cmds |
|
556 | filter,type_pattern = cmds | |
559 | else: |
|
557 | else: | |
560 | raise ValueError('invalid argument string for psearch: <%s>' % |
|
558 | raise ValueError('invalid argument string for psearch: <%s>' % | |
561 | pattern) |
|
559 | pattern) | |
562 |
|
560 | |||
563 | # filter search namespaces |
|
561 | # filter search namespaces | |
564 | for name in ns_search: |
|
562 | for name in ns_search: | |
565 | if name not in ns_table: |
|
563 | if name not in ns_table: | |
566 | raise ValueError('invalid namespace <%s>. Valid names: %s' % |
|
564 | raise ValueError('invalid namespace <%s>. Valid names: %s' % | |
567 | (name,ns_table.keys())) |
|
565 | (name,ns_table.keys())) | |
568 |
|
566 | |||
569 | #print 'type_pattern:',type_pattern # dbg |
|
567 | #print 'type_pattern:',type_pattern # dbg | |
570 | search_result = [] |
|
568 | search_result = [] | |
571 | for ns_name in ns_search: |
|
569 | for ns_name in ns_search: | |
572 | ns = ns_table[ns_name] |
|
570 | ns = ns_table[ns_name] | |
573 | tmp_res = list(list_namespace(ns,type_pattern,filter, |
|
571 | tmp_res = list(list_namespace(ns,type_pattern,filter, | |
574 | ignore_case=ignore_case, |
|
572 | ignore_case=ignore_case, | |
575 | show_all=show_all)) |
|
573 | show_all=show_all)) | |
576 | search_result.extend(tmp_res) |
|
574 | search_result.extend(tmp_res) | |
577 | search_result.sort() |
|
575 | search_result.sort() | |
578 |
|
576 | |||
579 | page('\n'.join(search_result)) |
|
577 | page('\n'.join(search_result)) |
@@ -1,763 +1,763 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | IPython -- An enhanced Interactive Python |
|
3 | IPython -- An enhanced Interactive Python | |
4 |
|
4 | |||
5 | Requires Python 2.1 or better. |
|
5 | Requires Python 2.1 or better. | |
6 |
|
6 | |||
7 | This file contains the main make_IPython() starter function. |
|
7 | This file contains the main make_IPython() starter function. | |
8 |
|
8 | |||
9 |
$Id: ipmaker.py 27 |
|
9 | $Id: ipmaker.py 2723 2007-09-07 07:44:16Z fperez $""" | |
10 |
|
10 | |||
11 | #***************************************************************************** |
|
11 | #***************************************************************************** | |
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> |
|
12 | # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu> | |
13 | # |
|
13 | # | |
14 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | # Distributed under the terms of the BSD License. The full license is in | |
15 | # the file COPYING, distributed as part of this software. |
|
15 | # the file COPYING, distributed as part of this software. | |
16 | #***************************************************************************** |
|
16 | #***************************************************************************** | |
17 |
|
17 | |||
18 | from IPython import Release |
|
18 | from IPython import Release | |
19 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
19 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
20 | __license__ = Release.license |
|
20 | __license__ = Release.license | |
21 | __version__ = Release.version |
|
21 | __version__ = Release.version | |
22 |
|
22 | |||
23 | try: |
|
23 | try: | |
24 | credits._Printer__data = """ |
|
24 | credits._Printer__data = """ | |
25 | Python: %s |
|
25 | Python: %s | |
26 |
|
26 | |||
27 | IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users. |
|
27 | IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users. | |
28 | See http://ipython.scipy.org for more information.""" \ |
|
28 | See http://ipython.scipy.org for more information.""" \ | |
29 | % credits._Printer__data |
|
29 | % credits._Printer__data | |
30 |
|
30 | |||
31 | copyright._Printer__data += """ |
|
31 | copyright._Printer__data += """ | |
32 |
|
32 | |||
33 | Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray. |
|
33 | Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray. | |
34 | All Rights Reserved.""" |
|
34 | All Rights Reserved.""" | |
35 | except NameError: |
|
35 | except NameError: | |
36 | # Can happen if ipython was started with 'python -S', so that site.py is |
|
36 | # Can happen if ipython was started with 'python -S', so that site.py is | |
37 | # not loaded |
|
37 | # not loaded | |
38 | pass |
|
38 | pass | |
39 |
|
39 | |||
40 | #**************************************************************************** |
|
40 | #**************************************************************************** | |
41 | # Required modules |
|
41 | # Required modules | |
42 |
|
42 | |||
43 | # From the standard library |
|
43 | # From the standard library | |
44 | import __main__ |
|
44 | import __main__ | |
45 | import __builtin__ |
|
45 | import __builtin__ | |
46 | import os |
|
46 | import os | |
47 | import re |
|
47 | import re | |
48 | import sys |
|
48 | import sys | |
49 | import types |
|
49 | import types | |
50 | from pprint import pprint,pformat |
|
50 | from pprint import pprint,pformat | |
51 |
|
51 | |||
52 | # Our own |
|
52 | # Our own | |
53 | from IPython import DPyGetOpt |
|
53 | from IPython import DPyGetOpt | |
54 | from IPython.ipstruct import Struct |
|
54 | from IPython.ipstruct import Struct | |
55 | from IPython.OutputTrap import OutputTrap |
|
55 | from IPython.OutputTrap import OutputTrap | |
56 | from IPython.ConfigLoader import ConfigLoader |
|
56 | from IPython.ConfigLoader import ConfigLoader | |
57 | from IPython.iplib import InteractiveShell |
|
57 | from IPython.iplib import InteractiveShell | |
58 | from IPython.usage import cmd_line_usage,interactive_usage |
|
58 | from IPython.usage import cmd_line_usage,interactive_usage | |
59 | from IPython.genutils import * |
|
59 | from IPython.genutils import * | |
60 |
|
60 | |||
61 | #----------------------------------------------------------------------------- |
|
61 | #----------------------------------------------------------------------------- | |
62 | def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1, |
|
62 | def make_IPython(argv=None,user_ns=None,user_global_ns=None,debug=1, | |
63 | rc_override=None,shell_class=InteractiveShell, |
|
63 | rc_override=None,shell_class=InteractiveShell, | |
64 | embedded=False,**kw): |
|
64 | embedded=False,**kw): | |
65 | """This is a dump of IPython into a single function. |
|
65 | """This is a dump of IPython into a single function. | |
66 |
|
66 | |||
67 | Later it will have to be broken up in a sensible manner. |
|
67 | Later it will have to be broken up in a sensible manner. | |
68 |
|
68 | |||
69 | Arguments: |
|
69 | Arguments: | |
70 |
|
70 | |||
71 | - argv: a list similar to sys.argv[1:]. It should NOT contain the desired |
|
71 | - argv: a list similar to sys.argv[1:]. It should NOT contain the desired | |
72 | script name, b/c DPyGetOpt strips the first argument only for the real |
|
72 | script name, b/c DPyGetOpt strips the first argument only for the real | |
73 | sys.argv. |
|
73 | sys.argv. | |
74 |
|
74 | |||
75 | - user_ns: a dict to be used as the user's namespace.""" |
|
75 | - user_ns: a dict to be used as the user's namespace.""" | |
76 |
|
76 | |||
77 | #---------------------------------------------------------------------- |
|
77 | #---------------------------------------------------------------------- | |
78 | # Defaults and initialization |
|
78 | # Defaults and initialization | |
79 |
|
79 | |||
80 | # For developer debugging, deactivates crash handler and uses pdb. |
|
80 | # For developer debugging, deactivates crash handler and uses pdb. | |
81 | DEVDEBUG = False |
|
81 | DEVDEBUG = False | |
82 |
|
82 | |||
83 | if argv is None: |
|
83 | if argv is None: | |
84 | argv = sys.argv |
|
84 | argv = sys.argv | |
85 |
|
85 | |||
86 | # __IP is the main global that lives throughout and represents the whole |
|
86 | # __IP is the main global that lives throughout and represents the whole | |
87 | # application. If the user redefines it, all bets are off as to what |
|
87 | # application. If the user redefines it, all bets are off as to what | |
88 | # happens. |
|
88 | # happens. | |
89 |
|
89 | |||
90 | # __IP is the name of he global which the caller will have accessible as |
|
90 | # __IP is the name of he global which the caller will have accessible as | |
91 | # __IP.name. We set its name via the first parameter passed to |
|
91 | # __IP.name. We set its name via the first parameter passed to | |
92 | # InteractiveShell: |
|
92 | # InteractiveShell: | |
93 |
|
93 | |||
94 | IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns, |
|
94 | IP = shell_class('__IP',user_ns=user_ns,user_global_ns=user_global_ns, | |
95 | embedded=embedded,**kw) |
|
95 | embedded=embedded,**kw) | |
96 |
|
96 | |||
97 | # Put 'help' in the user namespace |
|
97 | # Put 'help' in the user namespace | |
98 | from site import _Helper |
|
98 | from site import _Helper | |
99 | IP.user_config_ns = {} |
|
99 | IP.user_config_ns = {} | |
100 | IP.user_ns['help'] = _Helper() |
|
100 | IP.user_ns['help'] = _Helper() | |
101 |
|
101 | |||
102 |
|
102 | |||
103 | if DEVDEBUG: |
|
103 | if DEVDEBUG: | |
104 | # For developer debugging only (global flag) |
|
104 | # For developer debugging only (global flag) | |
105 | from IPython import ultraTB |
|
105 | from IPython import ultraTB | |
106 | sys.excepthook = ultraTB.VerboseTB(call_pdb=1) |
|
106 | sys.excepthook = ultraTB.VerboseTB(call_pdb=1) | |
107 |
|
107 | |||
108 | IP.BANNER_PARTS = ['Python %s\n' |
|
108 | IP.BANNER_PARTS = ['Python %s\n' | |
109 | 'Type "copyright", "credits" or "license" ' |
|
109 | 'Type "copyright", "credits" or "license" ' | |
110 | 'for more information.\n' |
|
110 | 'for more information.\n' | |
111 | % (sys.version.split('\n')[0],), |
|
111 | % (sys.version.split('\n')[0],), | |
112 | "IPython %s -- An enhanced Interactive Python." |
|
112 | "IPython %s -- An enhanced Interactive Python." | |
113 | % (__version__,), |
|
113 | % (__version__,), | |
114 | """\ |
|
114 | """\ | |
115 |
? -> Introduction |
|
115 | ? -> Introduction and overview of IPython's features. | |
116 | %quickref -> Quick reference. |
|
116 | %quickref -> Quick reference. | |
117 | help -> Python's own help system. |
|
117 | help -> Python's own help system. | |
118 | object? -> Details about 'object'. ?object also works, ?? prints more. |
|
118 | object? -> Details about 'object'. ?object also works, ?? prints more. | |
119 | """ ] |
|
119 | """ ] | |
120 |
|
120 | |||
121 | IP.usage = interactive_usage |
|
121 | IP.usage = interactive_usage | |
122 |
|
122 | |||
123 | # Platform-dependent suffix and directory names. We use _ipython instead |
|
123 | # Platform-dependent suffix and directory names. We use _ipython instead | |
124 | # of .ipython under win32 b/c there's software that breaks with .named |
|
124 | # of .ipython under win32 b/c there's software that breaks with .named | |
125 | # directories on that platform. |
|
125 | # directories on that platform. | |
126 | if os.name == 'posix': |
|
126 | if os.name == 'posix': | |
127 | rc_suffix = '' |
|
127 | rc_suffix = '' | |
128 | ipdir_def = '.ipython' |
|
128 | ipdir_def = '.ipython' | |
129 | else: |
|
129 | else: | |
130 | rc_suffix = '.ini' |
|
130 | rc_suffix = '.ini' | |
131 | ipdir_def = '_ipython' |
|
131 | ipdir_def = '_ipython' | |
132 |
|
132 | |||
133 | # default directory for configuration |
|
133 | # default directory for configuration | |
134 | ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR', |
|
134 | ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR', | |
135 | os.path.join(IP.home_dir,ipdir_def))) |
|
135 | os.path.join(IP.home_dir,ipdir_def))) | |
136 |
|
136 | |||
137 | sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran |
|
137 | sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran | |
138 |
|
138 | |||
139 | # we need the directory where IPython itself is installed |
|
139 | # we need the directory where IPython itself is installed | |
140 | import IPython |
|
140 | import IPython | |
141 | IPython_dir = os.path.dirname(IPython.__file__) |
|
141 | IPython_dir = os.path.dirname(IPython.__file__) | |
142 | del IPython |
|
142 | del IPython | |
143 |
|
143 | |||
144 | #------------------------------------------------------------------------- |
|
144 | #------------------------------------------------------------------------- | |
145 | # Command line handling |
|
145 | # Command line handling | |
146 |
|
146 | |||
147 | # Valid command line options (uses DPyGetOpt syntax, like Perl's |
|
147 | # Valid command line options (uses DPyGetOpt syntax, like Perl's | |
148 | # GetOpt::Long) |
|
148 | # GetOpt::Long) | |
149 |
|
149 | |||
150 | # Any key not listed here gets deleted even if in the file (like session |
|
150 | # Any key not listed here gets deleted even if in the file (like session | |
151 | # or profile). That's deliberate, to maintain the rc namespace clean. |
|
151 | # or profile). That's deliberate, to maintain the rc namespace clean. | |
152 |
|
152 | |||
153 | # Each set of options appears twice: under _conv only the names are |
|
153 | # Each set of options appears twice: under _conv only the names are | |
154 | # listed, indicating which type they must be converted to when reading the |
|
154 | # listed, indicating which type they must be converted to when reading the | |
155 | # ipythonrc file. And under DPyGetOpt they are listed with the regular |
|
155 | # ipythonrc file. And under DPyGetOpt they are listed with the regular | |
156 | # DPyGetOpt syntax (=s,=i,:f,etc). |
|
156 | # DPyGetOpt syntax (=s,=i,:f,etc). | |
157 |
|
157 | |||
158 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
158 | # Make sure there's a space before each end of line (they get auto-joined!) | |
159 | cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i ' |
|
159 | cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i ' | |
160 | 'c=s classic|cl color_info! colors=s confirm_exit! ' |
|
160 | 'c=s classic|cl color_info! colors=s confirm_exit! ' | |
161 | 'debug! deep_reload! editor=s log|l messages! nosep ' |
|
161 | 'debug! deep_reload! editor=s log|l messages! nosep ' | |
162 | 'object_info_string_level=i pdb! ' |
|
162 | 'object_info_string_level=i pdb! ' | |
163 | 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s ' |
|
163 | 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s ' | |
164 | 'pylab_import_all! ' |
|
164 | 'pylab_import_all! ' | |
165 | 'quick screen_length|sl=i prompts_pad_left=i ' |
|
165 | 'quick screen_length|sl=i prompts_pad_left=i ' | |
166 | 'logfile|lf=s logplay|lp=s profile|p=s ' |
|
166 | 'logfile|lf=s logplay|lp=s profile|p=s ' | |
167 | 'readline! readline_merge_completions! ' |
|
167 | 'readline! readline_merge_completions! ' | |
168 | 'readline_omit__names! ' |
|
168 | 'readline_omit__names! ' | |
169 | 'rcfile=s separate_in|si=s separate_out|so=s ' |
|
169 | 'rcfile=s separate_in|si=s separate_out|so=s ' | |
170 | 'separate_out2|so2=s xmode=s wildcards_case_sensitive! ' |
|
170 | 'separate_out2|so2=s xmode=s wildcards_case_sensitive! ' | |
171 | 'magic_docstrings system_verbose! ' |
|
171 | 'magic_docstrings system_verbose! ' | |
172 | 'multi_line_specials! ' |
|
172 | 'multi_line_specials! ' | |
173 | 'term_title! wxversion=s ' |
|
173 | 'term_title! wxversion=s ' | |
174 | 'autoedit_syntax!') |
|
174 | 'autoedit_syntax!') | |
175 |
|
175 | |||
176 | # Options that can *only* appear at the cmd line (not in rcfiles). |
|
176 | # Options that can *only* appear at the cmd line (not in rcfiles). | |
177 |
|
177 | |||
178 | # The "ignore" option is a kludge so that Emacs buffers don't crash, since |
|
178 | # The "ignore" option is a kludge so that Emacs buffers don't crash, since | |
179 | # the 'C-c !' command in emacs automatically appends a -i option at the end. |
|
179 | # the 'C-c !' command in emacs automatically appends a -i option at the end. | |
180 | cmdline_only = ('help interact|i ipythondir=s Version upgrade ' |
|
180 | cmdline_only = ('help interact|i ipythondir=s Version upgrade ' | |
181 | 'gthread! qthread! q4thread! wthread! pylab! tk!') |
|
181 | 'gthread! qthread! q4thread! wthread! pylab! tk!') | |
182 |
|
182 | |||
183 | # Build the actual name list to be used by DPyGetOpt |
|
183 | # Build the actual name list to be used by DPyGetOpt | |
184 | opts_names = qw(cmdline_opts) + qw(cmdline_only) |
|
184 | opts_names = qw(cmdline_opts) + qw(cmdline_only) | |
185 |
|
185 | |||
186 | # Set sensible command line defaults. |
|
186 | # Set sensible command line defaults. | |
187 | # This should have everything from cmdline_opts and cmdline_only |
|
187 | # This should have everything from cmdline_opts and cmdline_only | |
188 | opts_def = Struct(autocall = 1, |
|
188 | opts_def = Struct(autocall = 1, | |
189 | autoedit_syntax = 0, |
|
189 | autoedit_syntax = 0, | |
190 | autoindent = 0, |
|
190 | autoindent = 0, | |
191 | automagic = 1, |
|
191 | automagic = 1, | |
192 | banner = 1, |
|
192 | banner = 1, | |
193 | cache_size = 1000, |
|
193 | cache_size = 1000, | |
194 | c = '', |
|
194 | c = '', | |
195 | classic = 0, |
|
195 | classic = 0, | |
196 | colors = 'NoColor', |
|
196 | colors = 'NoColor', | |
197 | color_info = 0, |
|
197 | color_info = 0, | |
198 | confirm_exit = 1, |
|
198 | confirm_exit = 1, | |
199 | debug = 0, |
|
199 | debug = 0, | |
200 | deep_reload = 0, |
|
200 | deep_reload = 0, | |
201 | editor = '0', |
|
201 | editor = '0', | |
202 | help = 0, |
|
202 | help = 0, | |
203 | interact = 0, |
|
203 | interact = 0, | |
204 | ipythondir = ipythondir_def, |
|
204 | ipythondir = ipythondir_def, | |
205 | log = 0, |
|
205 | log = 0, | |
206 | logfile = '', |
|
206 | logfile = '', | |
207 | logplay = '', |
|
207 | logplay = '', | |
208 | multi_line_specials = 1, |
|
208 | multi_line_specials = 1, | |
209 | messages = 1, |
|
209 | messages = 1, | |
210 | object_info_string_level = 0, |
|
210 | object_info_string_level = 0, | |
211 | nosep = 0, |
|
211 | nosep = 0, | |
212 | pdb = 0, |
|
212 | pdb = 0, | |
213 | pprint = 0, |
|
213 | pprint = 0, | |
214 | profile = '', |
|
214 | profile = '', | |
215 | prompt_in1 = 'In [\\#]: ', |
|
215 | prompt_in1 = 'In [\\#]: ', | |
216 | prompt_in2 = ' .\\D.: ', |
|
216 | prompt_in2 = ' .\\D.: ', | |
217 | prompt_out = 'Out[\\#]: ', |
|
217 | prompt_out = 'Out[\\#]: ', | |
218 | prompts_pad_left = 1, |
|
218 | prompts_pad_left = 1, | |
219 | pylab_import_all = 1, |
|
219 | pylab_import_all = 1, | |
220 | quiet = 0, |
|
220 | quiet = 0, | |
221 | quick = 0, |
|
221 | quick = 0, | |
222 | readline = 1, |
|
222 | readline = 1, | |
223 | readline_merge_completions = 1, |
|
223 | readline_merge_completions = 1, | |
224 | readline_omit__names = 0, |
|
224 | readline_omit__names = 0, | |
225 | rcfile = 'ipythonrc' + rc_suffix, |
|
225 | rcfile = 'ipythonrc' + rc_suffix, | |
226 | screen_length = 0, |
|
226 | screen_length = 0, | |
227 | separate_in = '\n', |
|
227 | separate_in = '\n', | |
228 | separate_out = '\n', |
|
228 | separate_out = '\n', | |
229 | separate_out2 = '', |
|
229 | separate_out2 = '', | |
230 | system_header = 'IPython system call: ', |
|
230 | system_header = 'IPython system call: ', | |
231 | system_verbose = 0, |
|
231 | system_verbose = 0, | |
232 | gthread = 0, |
|
232 | gthread = 0, | |
233 | qthread = 0, |
|
233 | qthread = 0, | |
234 | q4thread = 0, |
|
234 | q4thread = 0, | |
235 | wthread = 0, |
|
235 | wthread = 0, | |
236 | pylab = 0, |
|
236 | pylab = 0, | |
237 | term_title = 1, |
|
237 | term_title = 1, | |
238 | tk = 0, |
|
238 | tk = 0, | |
239 | upgrade = 0, |
|
239 | upgrade = 0, | |
240 | Version = 0, |
|
240 | Version = 0, | |
241 | xmode = 'Verbose', |
|
241 | xmode = 'Verbose', | |
242 | wildcards_case_sensitive = 1, |
|
242 | wildcards_case_sensitive = 1, | |
243 | wxversion = '0', |
|
243 | wxversion = '0', | |
244 | magic_docstrings = 0, # undocumented, for doc generation |
|
244 | magic_docstrings = 0, # undocumented, for doc generation | |
245 | ) |
|
245 | ) | |
246 |
|
246 | |||
247 | # Things that will *only* appear in rcfiles (not at the command line). |
|
247 | # Things that will *only* appear in rcfiles (not at the command line). | |
248 | # Make sure there's a space before each end of line (they get auto-joined!) |
|
248 | # Make sure there's a space before each end of line (they get auto-joined!) | |
249 | rcfile_opts = { qwflat: 'include import_mod import_all execfile ', |
|
249 | rcfile_opts = { qwflat: 'include import_mod import_all execfile ', | |
250 | qw_lol: 'import_some ', |
|
250 | qw_lol: 'import_some ', | |
251 | # for things with embedded whitespace: |
|
251 | # for things with embedded whitespace: | |
252 | list_strings:'execute alias readline_parse_and_bind ', |
|
252 | list_strings:'execute alias readline_parse_and_bind ', | |
253 | # Regular strings need no conversion: |
|
253 | # Regular strings need no conversion: | |
254 | None:'readline_remove_delims ', |
|
254 | None:'readline_remove_delims ', | |
255 | } |
|
255 | } | |
256 | # Default values for these |
|
256 | # Default values for these | |
257 | rc_def = Struct(include = [], |
|
257 | rc_def = Struct(include = [], | |
258 | import_mod = [], |
|
258 | import_mod = [], | |
259 | import_all = [], |
|
259 | import_all = [], | |
260 | import_some = [[]], |
|
260 | import_some = [[]], | |
261 | execute = [], |
|
261 | execute = [], | |
262 | execfile = [], |
|
262 | execfile = [], | |
263 | alias = [], |
|
263 | alias = [], | |
264 | readline_parse_and_bind = [], |
|
264 | readline_parse_and_bind = [], | |
265 | readline_remove_delims = '', |
|
265 | readline_remove_delims = '', | |
266 | ) |
|
266 | ) | |
267 |
|
267 | |||
268 | # Build the type conversion dictionary from the above tables: |
|
268 | # Build the type conversion dictionary from the above tables: | |
269 | typeconv = rcfile_opts.copy() |
|
269 | typeconv = rcfile_opts.copy() | |
270 | typeconv.update(optstr2types(cmdline_opts)) |
|
270 | typeconv.update(optstr2types(cmdline_opts)) | |
271 |
|
271 | |||
272 | # FIXME: the None key appears in both, put that back together by hand. Ugly! |
|
272 | # FIXME: the None key appears in both, put that back together by hand. Ugly! | |
273 | typeconv[None] += ' ' + rcfile_opts[None] |
|
273 | typeconv[None] += ' ' + rcfile_opts[None] | |
274 |
|
274 | |||
275 | # Remove quotes at ends of all strings (used to protect spaces) |
|
275 | # Remove quotes at ends of all strings (used to protect spaces) | |
276 | typeconv[unquote_ends] = typeconv[None] |
|
276 | typeconv[unquote_ends] = typeconv[None] | |
277 | del typeconv[None] |
|
277 | del typeconv[None] | |
278 |
|
278 | |||
279 | # Build the list we'll use to make all config decisions with defaults: |
|
279 | # Build the list we'll use to make all config decisions with defaults: | |
280 | opts_all = opts_def.copy() |
|
280 | opts_all = opts_def.copy() | |
281 | opts_all.update(rc_def) |
|
281 | opts_all.update(rc_def) | |
282 |
|
282 | |||
283 | # Build conflict resolver for recursive loading of config files: |
|
283 | # Build conflict resolver for recursive loading of config files: | |
284 | # - preserve means the outermost file maintains the value, it is not |
|
284 | # - preserve means the outermost file maintains the value, it is not | |
285 | # overwritten if an included file has the same key. |
|
285 | # overwritten if an included file has the same key. | |
286 | # - add_flip applies + to the two values, so it better make sense to add |
|
286 | # - add_flip applies + to the two values, so it better make sense to add | |
287 | # those types of keys. But it flips them first so that things loaded |
|
287 | # those types of keys. But it flips them first so that things loaded | |
288 | # deeper in the inclusion chain have lower precedence. |
|
288 | # deeper in the inclusion chain have lower precedence. | |
289 | conflict = {'preserve': ' '.join([ typeconv[int], |
|
289 | conflict = {'preserve': ' '.join([ typeconv[int], | |
290 | typeconv[unquote_ends] ]), |
|
290 | typeconv[unquote_ends] ]), | |
291 | 'add_flip': ' '.join([ typeconv[qwflat], |
|
291 | 'add_flip': ' '.join([ typeconv[qwflat], | |
292 | typeconv[qw_lol], |
|
292 | typeconv[qw_lol], | |
293 | typeconv[list_strings] ]) |
|
293 | typeconv[list_strings] ]) | |
294 | } |
|
294 | } | |
295 |
|
295 | |||
296 | # Now actually process the command line |
|
296 | # Now actually process the command line | |
297 | getopt = DPyGetOpt.DPyGetOpt() |
|
297 | getopt = DPyGetOpt.DPyGetOpt() | |
298 | getopt.setIgnoreCase(0) |
|
298 | getopt.setIgnoreCase(0) | |
299 |
|
299 | |||
300 | getopt.parseConfiguration(opts_names) |
|
300 | getopt.parseConfiguration(opts_names) | |
301 |
|
301 | |||
302 | try: |
|
302 | try: | |
303 | getopt.processArguments(argv) |
|
303 | getopt.processArguments(argv) | |
304 | except: |
|
304 | except: | |
305 | print cmd_line_usage |
|
305 | print cmd_line_usage | |
306 | warn('\nError in Arguments: ' + `sys.exc_value`) |
|
306 | warn('\nError in Arguments: ' + `sys.exc_value`) | |
307 | sys.exit(1) |
|
307 | sys.exit(1) | |
308 |
|
308 | |||
309 | # convert the options dict to a struct for much lighter syntax later |
|
309 | # convert the options dict to a struct for much lighter syntax later | |
310 | opts = Struct(getopt.optionValues) |
|
310 | opts = Struct(getopt.optionValues) | |
311 | args = getopt.freeValues |
|
311 | args = getopt.freeValues | |
312 |
|
312 | |||
313 | # this is the struct (which has default values at this point) with which |
|
313 | # this is the struct (which has default values at this point) with which | |
314 | # we make all decisions: |
|
314 | # we make all decisions: | |
315 | opts_all.update(opts) |
|
315 | opts_all.update(opts) | |
316 |
|
316 | |||
317 | # Options that force an immediate exit |
|
317 | # Options that force an immediate exit | |
318 | if opts_all.help: |
|
318 | if opts_all.help: | |
319 | page(cmd_line_usage) |
|
319 | page(cmd_line_usage) | |
320 | sys.exit() |
|
320 | sys.exit() | |
321 |
|
321 | |||
322 | if opts_all.Version: |
|
322 | if opts_all.Version: | |
323 | print __version__ |
|
323 | print __version__ | |
324 | sys.exit() |
|
324 | sys.exit() | |
325 |
|
325 | |||
326 | if opts_all.magic_docstrings: |
|
326 | if opts_all.magic_docstrings: | |
327 | IP.magic_magic('-latex') |
|
327 | IP.magic_magic('-latex') | |
328 | sys.exit() |
|
328 | sys.exit() | |
329 |
|
329 | |||
330 | # add personal ipythondir to sys.path so that users can put things in |
|
330 | # add personal ipythondir to sys.path so that users can put things in | |
331 | # there for customization |
|
331 | # there for customization | |
332 | sys.path.append(os.path.abspath(opts_all.ipythondir)) |
|
332 | sys.path.append(os.path.abspath(opts_all.ipythondir)) | |
333 |
|
333 | |||
334 | # Create user config directory if it doesn't exist. This must be done |
|
334 | # Create user config directory if it doesn't exist. This must be done | |
335 | # *after* getting the cmd line options. |
|
335 | # *after* getting the cmd line options. | |
336 | if not os.path.isdir(opts_all.ipythondir): |
|
336 | if not os.path.isdir(opts_all.ipythondir): | |
337 | IP.user_setup(opts_all.ipythondir,rc_suffix,'install') |
|
337 | IP.user_setup(opts_all.ipythondir,rc_suffix,'install') | |
338 |
|
338 | |||
339 | # upgrade user config files while preserving a copy of the originals |
|
339 | # upgrade user config files while preserving a copy of the originals | |
340 | if opts_all.upgrade: |
|
340 | if opts_all.upgrade: | |
341 | IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade') |
|
341 | IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade') | |
342 |
|
342 | |||
343 | # check mutually exclusive options in the *original* command line |
|
343 | # check mutually exclusive options in the *original* command line | |
344 | mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'), |
|
344 | mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'), | |
345 | qw('classic profile'),qw('classic rcfile')]) |
|
345 | qw('classic profile'),qw('classic rcfile')]) | |
346 |
|
346 | |||
347 | #--------------------------------------------------------------------------- |
|
347 | #--------------------------------------------------------------------------- | |
348 | # Log replay |
|
348 | # Log replay | |
349 |
|
349 | |||
350 | # if -logplay, we need to 'become' the other session. That basically means |
|
350 | # if -logplay, we need to 'become' the other session. That basically means | |
351 | # replacing the current command line environment with that of the old |
|
351 | # replacing the current command line environment with that of the old | |
352 | # session and moving on. |
|
352 | # session and moving on. | |
353 |
|
353 | |||
354 | # this is needed so that later we know we're in session reload mode, as |
|
354 | # this is needed so that later we know we're in session reload mode, as | |
355 | # opts_all will get overwritten: |
|
355 | # opts_all will get overwritten: | |
356 | load_logplay = 0 |
|
356 | load_logplay = 0 | |
357 |
|
357 | |||
358 | if opts_all.logplay: |
|
358 | if opts_all.logplay: | |
359 | load_logplay = opts_all.logplay |
|
359 | load_logplay = opts_all.logplay | |
360 | opts_debug_save = opts_all.debug |
|
360 | opts_debug_save = opts_all.debug | |
361 | try: |
|
361 | try: | |
362 | logplay = open(opts_all.logplay) |
|
362 | logplay = open(opts_all.logplay) | |
363 | except IOError: |
|
363 | except IOError: | |
364 | if opts_all.debug: IP.InteractiveTB() |
|
364 | if opts_all.debug: IP.InteractiveTB() | |
365 | warn('Could not open logplay file '+`opts_all.logplay`) |
|
365 | warn('Could not open logplay file '+`opts_all.logplay`) | |
366 | # restore state as if nothing had happened and move on, but make |
|
366 | # restore state as if nothing had happened and move on, but make | |
367 | # sure that later we don't try to actually load the session file |
|
367 | # sure that later we don't try to actually load the session file | |
368 | logplay = None |
|
368 | logplay = None | |
369 | load_logplay = 0 |
|
369 | load_logplay = 0 | |
370 | del opts_all.logplay |
|
370 | del opts_all.logplay | |
371 | else: |
|
371 | else: | |
372 | try: |
|
372 | try: | |
373 | logplay.readline() |
|
373 | logplay.readline() | |
374 | logplay.readline(); |
|
374 | logplay.readline(); | |
375 | # this reloads that session's command line |
|
375 | # this reloads that session's command line | |
376 | cmd = logplay.readline()[6:] |
|
376 | cmd = logplay.readline()[6:] | |
377 | exec cmd |
|
377 | exec cmd | |
378 | # restore the true debug flag given so that the process of |
|
378 | # restore the true debug flag given so that the process of | |
379 | # session loading itself can be monitored. |
|
379 | # session loading itself can be monitored. | |
380 | opts.debug = opts_debug_save |
|
380 | opts.debug = opts_debug_save | |
381 | # save the logplay flag so later we don't overwrite the log |
|
381 | # save the logplay flag so later we don't overwrite the log | |
382 | opts.logplay = load_logplay |
|
382 | opts.logplay = load_logplay | |
383 | # now we must update our own structure with defaults |
|
383 | # now we must update our own structure with defaults | |
384 | opts_all.update(opts) |
|
384 | opts_all.update(opts) | |
385 | # now load args |
|
385 | # now load args | |
386 | cmd = logplay.readline()[6:] |
|
386 | cmd = logplay.readline()[6:] | |
387 | exec cmd |
|
387 | exec cmd | |
388 | logplay.close() |
|
388 | logplay.close() | |
389 | except: |
|
389 | except: | |
390 | logplay.close() |
|
390 | logplay.close() | |
391 | if opts_all.debug: IP.InteractiveTB() |
|
391 | if opts_all.debug: IP.InteractiveTB() | |
392 | warn("Logplay file lacking full configuration information.\n" |
|
392 | warn("Logplay file lacking full configuration information.\n" | |
393 | "I'll try to read it, but some things may not work.") |
|
393 | "I'll try to read it, but some things may not work.") | |
394 |
|
394 | |||
395 | #------------------------------------------------------------------------- |
|
395 | #------------------------------------------------------------------------- | |
396 | # set up output traps: catch all output from files, being run, modules |
|
396 | # set up output traps: catch all output from files, being run, modules | |
397 | # loaded, etc. Then give it to the user in a clean form at the end. |
|
397 | # loaded, etc. Then give it to the user in a clean form at the end. | |
398 |
|
398 | |||
399 | msg_out = 'Output messages. ' |
|
399 | msg_out = 'Output messages. ' | |
400 | msg_err = 'Error messages. ' |
|
400 | msg_err = 'Error messages. ' | |
401 | msg_sep = '\n' |
|
401 | msg_sep = '\n' | |
402 | msg = Struct(config = OutputTrap('Configuration Loader',msg_out, |
|
402 | msg = Struct(config = OutputTrap('Configuration Loader',msg_out, | |
403 | msg_err,msg_sep,debug, |
|
403 | msg_err,msg_sep,debug, | |
404 | quiet_out=1), |
|
404 | quiet_out=1), | |
405 | user_exec = OutputTrap('User File Execution',msg_out, |
|
405 | user_exec = OutputTrap('User File Execution',msg_out, | |
406 | msg_err,msg_sep,debug), |
|
406 | msg_err,msg_sep,debug), | |
407 | logplay = OutputTrap('Log Loader',msg_out, |
|
407 | logplay = OutputTrap('Log Loader',msg_out, | |
408 | msg_err,msg_sep,debug), |
|
408 | msg_err,msg_sep,debug), | |
409 | summary = '' |
|
409 | summary = '' | |
410 | ) |
|
410 | ) | |
411 |
|
411 | |||
412 | #------------------------------------------------------------------------- |
|
412 | #------------------------------------------------------------------------- | |
413 | # Process user ipythonrc-type configuration files |
|
413 | # Process user ipythonrc-type configuration files | |
414 |
|
414 | |||
415 | # turn on output trapping and log to msg.config |
|
415 | # turn on output trapping and log to msg.config | |
416 | # remember that with debug on, trapping is actually disabled |
|
416 | # remember that with debug on, trapping is actually disabled | |
417 | msg.config.trap_all() |
|
417 | msg.config.trap_all() | |
418 |
|
418 | |||
419 | # look for rcfile in current or default directory |
|
419 | # look for rcfile in current or default directory | |
420 | try: |
|
420 | try: | |
421 | opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir) |
|
421 | opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir) | |
422 | except IOError: |
|
422 | except IOError: | |
423 | if opts_all.debug: IP.InteractiveTB() |
|
423 | if opts_all.debug: IP.InteractiveTB() | |
424 | warn('Configuration file %s not found. Ignoring request.' |
|
424 | warn('Configuration file %s not found. Ignoring request.' | |
425 | % (opts_all.rcfile) ) |
|
425 | % (opts_all.rcfile) ) | |
426 |
|
426 | |||
427 | # 'profiles' are a shorthand notation for config filenames |
|
427 | # 'profiles' are a shorthand notation for config filenames | |
428 | profile_handled_by_legacy = False |
|
428 | profile_handled_by_legacy = False | |
429 | if opts_all.profile: |
|
429 | if opts_all.profile: | |
430 |
|
430 | |||
431 | try: |
|
431 | try: | |
432 | opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile |
|
432 | opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile | |
433 | + rc_suffix, |
|
433 | + rc_suffix, | |
434 | opts_all.ipythondir) |
|
434 | opts_all.ipythondir) | |
435 | profile_handled_by_legacy = True |
|
435 | profile_handled_by_legacy = True | |
436 | except IOError: |
|
436 | except IOError: | |
437 | if opts_all.debug: IP.InteractiveTB() |
|
437 | if opts_all.debug: IP.InteractiveTB() | |
438 | opts.profile = '' # remove profile from options if invalid |
|
438 | opts.profile = '' # remove profile from options if invalid | |
439 | # We won't warn anymore, primary method is ipy_profile_PROFNAME |
|
439 | # We won't warn anymore, primary method is ipy_profile_PROFNAME | |
440 | # which does trigger a warning. |
|
440 | # which does trigger a warning. | |
441 |
|
441 | |||
442 | # load the config file |
|
442 | # load the config file | |
443 | rcfiledata = None |
|
443 | rcfiledata = None | |
444 | if opts_all.quick: |
|
444 | if opts_all.quick: | |
445 | print 'Launching IPython in quick mode. No config file read.' |
|
445 | print 'Launching IPython in quick mode. No config file read.' | |
446 | elif opts_all.rcfile: |
|
446 | elif opts_all.rcfile: | |
447 | try: |
|
447 | try: | |
448 | cfg_loader = ConfigLoader(conflict) |
|
448 | cfg_loader = ConfigLoader(conflict) | |
449 | rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv, |
|
449 | rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv, | |
450 | 'include',opts_all.ipythondir, |
|
450 | 'include',opts_all.ipythondir, | |
451 | purge = 1, |
|
451 | purge = 1, | |
452 | unique = conflict['preserve']) |
|
452 | unique = conflict['preserve']) | |
453 | except: |
|
453 | except: | |
454 | IP.InteractiveTB() |
|
454 | IP.InteractiveTB() | |
455 | warn('Problems loading configuration file '+ |
|
455 | warn('Problems loading configuration file '+ | |
456 | `opts_all.rcfile`+ |
|
456 | `opts_all.rcfile`+ | |
457 | '\nStarting with default -bare bones- configuration.') |
|
457 | '\nStarting with default -bare bones- configuration.') | |
458 | else: |
|
458 | else: | |
459 | warn('No valid configuration file found in either currrent directory\n'+ |
|
459 | warn('No valid configuration file found in either currrent directory\n'+ | |
460 | 'or in the IPython config. directory: '+`opts_all.ipythondir`+ |
|
460 | 'or in the IPython config. directory: '+`opts_all.ipythondir`+ | |
461 | '\nProceeding with internal defaults.') |
|
461 | '\nProceeding with internal defaults.') | |
462 |
|
462 | |||
463 | #------------------------------------------------------------------------ |
|
463 | #------------------------------------------------------------------------ | |
464 | # Set exception handlers in mode requested by user. |
|
464 | # Set exception handlers in mode requested by user. | |
465 | otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode |
|
465 | otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode | |
466 | IP.magic_xmode(opts_all.xmode) |
|
466 | IP.magic_xmode(opts_all.xmode) | |
467 | otrap.release_out() |
|
467 | otrap.release_out() | |
468 |
|
468 | |||
469 | #------------------------------------------------------------------------ |
|
469 | #------------------------------------------------------------------------ | |
470 | # Execute user config |
|
470 | # Execute user config | |
471 |
|
471 | |||
472 | # Create a valid config structure with the right precedence order: |
|
472 | # Create a valid config structure with the right precedence order: | |
473 | # defaults < rcfile < command line. This needs to be in the instance, so |
|
473 | # defaults < rcfile < command line. This needs to be in the instance, so | |
474 | # that method calls below that rely on it find it. |
|
474 | # that method calls below that rely on it find it. | |
475 | IP.rc = rc_def.copy() |
|
475 | IP.rc = rc_def.copy() | |
476 |
|
476 | |||
477 | # Work with a local alias inside this routine to avoid unnecessary |
|
477 | # Work with a local alias inside this routine to avoid unnecessary | |
478 | # attribute lookups. |
|
478 | # attribute lookups. | |
479 | IP_rc = IP.rc |
|
479 | IP_rc = IP.rc | |
480 |
|
480 | |||
481 | IP_rc.update(opts_def) |
|
481 | IP_rc.update(opts_def) | |
482 | if rcfiledata: |
|
482 | if rcfiledata: | |
483 | # now we can update |
|
483 | # now we can update | |
484 | IP_rc.update(rcfiledata) |
|
484 | IP_rc.update(rcfiledata) | |
485 | IP_rc.update(opts) |
|
485 | IP_rc.update(opts) | |
486 | IP_rc.update(rc_override) |
|
486 | IP_rc.update(rc_override) | |
487 |
|
487 | |||
488 | # Store the original cmd line for reference: |
|
488 | # Store the original cmd line for reference: | |
489 | IP_rc.opts = opts |
|
489 | IP_rc.opts = opts | |
490 | IP_rc.args = args |
|
490 | IP_rc.args = args | |
491 |
|
491 | |||
492 | # create a *runtime* Struct like rc for holding parameters which may be |
|
492 | # create a *runtime* Struct like rc for holding parameters which may be | |
493 | # created and/or modified by runtime user extensions. |
|
493 | # created and/or modified by runtime user extensions. | |
494 | IP.runtime_rc = Struct() |
|
494 | IP.runtime_rc = Struct() | |
495 |
|
495 | |||
496 | # from this point on, all config should be handled through IP_rc, |
|
496 | # from this point on, all config should be handled through IP_rc, | |
497 | # opts* shouldn't be used anymore. |
|
497 | # opts* shouldn't be used anymore. | |
498 |
|
498 | |||
499 |
|
499 | |||
500 | # update IP_rc with some special things that need manual |
|
500 | # update IP_rc with some special things that need manual | |
501 | # tweaks. Basically options which affect other options. I guess this |
|
501 | # tweaks. Basically options which affect other options. I guess this | |
502 | # should just be written so that options are fully orthogonal and we |
|
502 | # should just be written so that options are fully orthogonal and we | |
503 | # wouldn't worry about this stuff! |
|
503 | # wouldn't worry about this stuff! | |
504 |
|
504 | |||
505 | if IP_rc.classic: |
|
505 | if IP_rc.classic: | |
506 | IP_rc.quick = 1 |
|
506 | IP_rc.quick = 1 | |
507 | IP_rc.cache_size = 0 |
|
507 | IP_rc.cache_size = 0 | |
508 | IP_rc.pprint = 0 |
|
508 | IP_rc.pprint = 0 | |
509 | IP_rc.prompt_in1 = '>>> ' |
|
509 | IP_rc.prompt_in1 = '>>> ' | |
510 | IP_rc.prompt_in2 = '... ' |
|
510 | IP_rc.prompt_in2 = '... ' | |
511 | IP_rc.prompt_out = '' |
|
511 | IP_rc.prompt_out = '' | |
512 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
512 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' | |
513 | IP_rc.colors = 'NoColor' |
|
513 | IP_rc.colors = 'NoColor' | |
514 | IP_rc.xmode = 'Plain' |
|
514 | IP_rc.xmode = 'Plain' | |
515 |
|
515 | |||
516 | IP.pre_config_initialization() |
|
516 | IP.pre_config_initialization() | |
517 | # configure readline |
|
517 | # configure readline | |
518 | # Define the history file for saving commands in between sessions |
|
518 | # Define the history file for saving commands in between sessions | |
519 | if IP_rc.profile: |
|
519 | if IP_rc.profile: | |
520 | histfname = 'history-%s' % IP_rc.profile |
|
520 | histfname = 'history-%s' % IP_rc.profile | |
521 | else: |
|
521 | else: | |
522 | histfname = 'history' |
|
522 | histfname = 'history' | |
523 | IP.histfile = os.path.join(opts_all.ipythondir,histfname) |
|
523 | IP.histfile = os.path.join(opts_all.ipythondir,histfname) | |
524 |
|
524 | |||
525 | # update exception handlers with rc file status |
|
525 | # update exception handlers with rc file status | |
526 | otrap.trap_out() # I don't want these messages ever. |
|
526 | otrap.trap_out() # I don't want these messages ever. | |
527 | IP.magic_xmode(IP_rc.xmode) |
|
527 | IP.magic_xmode(IP_rc.xmode) | |
528 | otrap.release_out() |
|
528 | otrap.release_out() | |
529 |
|
529 | |||
530 | # activate logging if requested and not reloading a log |
|
530 | # activate logging if requested and not reloading a log | |
531 | if IP_rc.logplay: |
|
531 | if IP_rc.logplay: | |
532 | IP.magic_logstart(IP_rc.logplay + ' append') |
|
532 | IP.magic_logstart(IP_rc.logplay + ' append') | |
533 | elif IP_rc.logfile: |
|
533 | elif IP_rc.logfile: | |
534 | IP.magic_logstart(IP_rc.logfile) |
|
534 | IP.magic_logstart(IP_rc.logfile) | |
535 | elif IP_rc.log: |
|
535 | elif IP_rc.log: | |
536 | IP.magic_logstart() |
|
536 | IP.magic_logstart() | |
537 |
|
537 | |||
538 | # find user editor so that it we don't have to look it up constantly |
|
538 | # find user editor so that it we don't have to look it up constantly | |
539 | if IP_rc.editor.strip()=='0': |
|
539 | if IP_rc.editor.strip()=='0': | |
540 | try: |
|
540 | try: | |
541 | ed = os.environ['EDITOR'] |
|
541 | ed = os.environ['EDITOR'] | |
542 | except KeyError: |
|
542 | except KeyError: | |
543 | if os.name == 'posix': |
|
543 | if os.name == 'posix': | |
544 | ed = 'vi' # the only one guaranteed to be there! |
|
544 | ed = 'vi' # the only one guaranteed to be there! | |
545 | else: |
|
545 | else: | |
546 | ed = 'notepad' # same in Windows! |
|
546 | ed = 'notepad' # same in Windows! | |
547 | IP_rc.editor = ed |
|
547 | IP_rc.editor = ed | |
548 |
|
548 | |||
549 | # Keep track of whether this is an embedded instance or not (useful for |
|
549 | # Keep track of whether this is an embedded instance or not (useful for | |
550 | # post-mortems). |
|
550 | # post-mortems). | |
551 | IP_rc.embedded = IP.embedded |
|
551 | IP_rc.embedded = IP.embedded | |
552 |
|
552 | |||
553 | # Recursive reload |
|
553 | # Recursive reload | |
554 | try: |
|
554 | try: | |
555 | from IPython import deep_reload |
|
555 | from IPython import deep_reload | |
556 | if IP_rc.deep_reload: |
|
556 | if IP_rc.deep_reload: | |
557 | __builtin__.reload = deep_reload.reload |
|
557 | __builtin__.reload = deep_reload.reload | |
558 | else: |
|
558 | else: | |
559 | __builtin__.dreload = deep_reload.reload |
|
559 | __builtin__.dreload = deep_reload.reload | |
560 | del deep_reload |
|
560 | del deep_reload | |
561 | except ImportError: |
|
561 | except ImportError: | |
562 | pass |
|
562 | pass | |
563 |
|
563 | |||
564 | # Save the current state of our namespace so that the interactive shell |
|
564 | # Save the current state of our namespace so that the interactive shell | |
565 | # can later know which variables have been created by us from config files |
|
565 | # can later know which variables have been created by us from config files | |
566 | # and loading. This way, loading a file (in any way) is treated just like |
|
566 | # and loading. This way, loading a file (in any way) is treated just like | |
567 | # defining things on the command line, and %who works as expected. |
|
567 | # defining things on the command line, and %who works as expected. | |
568 |
|
568 | |||
569 | # DON'T do anything that affects the namespace beyond this point! |
|
569 | # DON'T do anything that affects the namespace beyond this point! | |
570 | IP.internal_ns.update(__main__.__dict__) |
|
570 | IP.internal_ns.update(__main__.__dict__) | |
571 |
|
571 | |||
572 | #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who |
|
572 | #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who | |
573 |
|
573 | |||
574 | # Now run through the different sections of the users's config |
|
574 | # Now run through the different sections of the users's config | |
575 | if IP_rc.debug: |
|
575 | if IP_rc.debug: | |
576 | print 'Trying to execute the following configuration structure:' |
|
576 | print 'Trying to execute the following configuration structure:' | |
577 | print '(Things listed first are deeper in the inclusion tree and get' |
|
577 | print '(Things listed first are deeper in the inclusion tree and get' | |
578 | print 'loaded first).\n' |
|
578 | print 'loaded first).\n' | |
579 | pprint(IP_rc.__dict__) |
|
579 | pprint(IP_rc.__dict__) | |
580 |
|
580 | |||
581 | for mod in IP_rc.import_mod: |
|
581 | for mod in IP_rc.import_mod: | |
582 | try: |
|
582 | try: | |
583 | exec 'import '+mod in IP.user_ns |
|
583 | exec 'import '+mod in IP.user_ns | |
584 | except : |
|
584 | except : | |
585 | IP.InteractiveTB() |
|
585 | IP.InteractiveTB() | |
586 | import_fail_info(mod) |
|
586 | import_fail_info(mod) | |
587 |
|
587 | |||
588 | for mod_fn in IP_rc.import_some: |
|
588 | for mod_fn in IP_rc.import_some: | |
589 | if not mod_fn == []: |
|
589 | if not mod_fn == []: | |
590 | mod,fn = mod_fn[0],','.join(mod_fn[1:]) |
|
590 | mod,fn = mod_fn[0],','.join(mod_fn[1:]) | |
591 | try: |
|
591 | try: | |
592 | exec 'from '+mod+' import '+fn in IP.user_ns |
|
592 | exec 'from '+mod+' import '+fn in IP.user_ns | |
593 | except : |
|
593 | except : | |
594 | IP.InteractiveTB() |
|
594 | IP.InteractiveTB() | |
595 | import_fail_info(mod,fn) |
|
595 | import_fail_info(mod,fn) | |
596 |
|
596 | |||
597 | for mod in IP_rc.import_all: |
|
597 | for mod in IP_rc.import_all: | |
598 | try: |
|
598 | try: | |
599 | exec 'from '+mod+' import *' in IP.user_ns |
|
599 | exec 'from '+mod+' import *' in IP.user_ns | |
600 | except : |
|
600 | except : | |
601 | IP.InteractiveTB() |
|
601 | IP.InteractiveTB() | |
602 | import_fail_info(mod) |
|
602 | import_fail_info(mod) | |
603 |
|
603 | |||
604 | for code in IP_rc.execute: |
|
604 | for code in IP_rc.execute: | |
605 | try: |
|
605 | try: | |
606 | exec code in IP.user_ns |
|
606 | exec code in IP.user_ns | |
607 | except: |
|
607 | except: | |
608 | IP.InteractiveTB() |
|
608 | IP.InteractiveTB() | |
609 | warn('Failure executing code: ' + `code`) |
|
609 | warn('Failure executing code: ' + `code`) | |
610 |
|
610 | |||
611 | # Execute the files the user wants in ipythonrc |
|
611 | # Execute the files the user wants in ipythonrc | |
612 | for file in IP_rc.execfile: |
|
612 | for file in IP_rc.execfile: | |
613 | try: |
|
613 | try: | |
614 | file = filefind(file,sys.path+[IPython_dir]) |
|
614 | file = filefind(file,sys.path+[IPython_dir]) | |
615 | except IOError: |
|
615 | except IOError: | |
616 | warn(itpl('File $file not found. Skipping it.')) |
|
616 | warn(itpl('File $file not found. Skipping it.')) | |
617 | else: |
|
617 | else: | |
618 | IP.safe_execfile(os.path.expanduser(file),IP.user_ns) |
|
618 | IP.safe_execfile(os.path.expanduser(file),IP.user_ns) | |
619 |
|
619 | |||
620 | # finally, try importing ipy_*_conf for final configuration |
|
620 | # finally, try importing ipy_*_conf for final configuration | |
621 | try: |
|
621 | try: | |
622 | import ipy_system_conf |
|
622 | import ipy_system_conf | |
623 | except ImportError: |
|
623 | except ImportError: | |
624 | if opts_all.debug: IP.InteractiveTB() |
|
624 | if opts_all.debug: IP.InteractiveTB() | |
625 | warn("Could not import 'ipy_system_conf'") |
|
625 | warn("Could not import 'ipy_system_conf'") | |
626 | except: |
|
626 | except: | |
627 | IP.InteractiveTB() |
|
627 | IP.InteractiveTB() | |
628 | import_fail_info('ipy_system_conf') |
|
628 | import_fail_info('ipy_system_conf') | |
629 |
|
629 | |||
630 | # only import prof module if ipythonrc-PROF was not found |
|
630 | # only import prof module if ipythonrc-PROF was not found | |
631 | if opts_all.profile and not profile_handled_by_legacy: |
|
631 | if opts_all.profile and not profile_handled_by_legacy: | |
632 | profmodname = 'ipy_profile_' + opts_all.profile |
|
632 | profmodname = 'ipy_profile_' + opts_all.profile | |
633 | try: |
|
633 | try: | |
634 | __import__(profmodname) |
|
634 | __import__(profmodname) | |
635 | except: |
|
635 | except: | |
636 | IP.InteractiveTB() |
|
636 | IP.InteractiveTB() | |
637 | print "Error importing",profmodname,"- perhaps you should run %upgrade?" |
|
637 | print "Error importing",profmodname,"- perhaps you should run %upgrade?" | |
638 | import_fail_info(profmodname) |
|
638 | import_fail_info(profmodname) | |
639 | else: |
|
639 | else: | |
640 | import ipy_profile_none |
|
640 | import ipy_profile_none | |
641 | try: |
|
641 | try: | |
642 | import ipy_user_conf |
|
642 | import ipy_user_conf | |
643 |
|
643 | |||
644 | except: |
|
644 | except: | |
645 | conf = opts_all.ipythondir + "/ipy_user_conf.py" |
|
645 | conf = opts_all.ipythondir + "/ipy_user_conf.py" | |
646 | IP.InteractiveTB() |
|
646 | IP.InteractiveTB() | |
647 | if not os.path.isfile(conf): |
|
647 | if not os.path.isfile(conf): | |
648 | warn(conf + ' does not exist, please run %upgrade!') |
|
648 | warn(conf + ' does not exist, please run %upgrade!') | |
649 |
|
649 | |||
650 | import_fail_info("ipy_user_conf") |
|
650 | import_fail_info("ipy_user_conf") | |
651 |
|
651 | |||
652 | # finally, push the argv to options again to ensure highest priority |
|
652 | # finally, push the argv to options again to ensure highest priority | |
653 | IP_rc.update(opts) |
|
653 | IP_rc.update(opts) | |
654 |
|
654 | |||
655 | # release stdout and stderr and save config log into a global summary |
|
655 | # release stdout and stderr and save config log into a global summary | |
656 | msg.config.release_all() |
|
656 | msg.config.release_all() | |
657 | if IP_rc.messages: |
|
657 | if IP_rc.messages: | |
658 | msg.summary += msg.config.summary_all() |
|
658 | msg.summary += msg.config.summary_all() | |
659 |
|
659 | |||
660 | #------------------------------------------------------------------------ |
|
660 | #------------------------------------------------------------------------ | |
661 | # Setup interactive session |
|
661 | # Setup interactive session | |
662 |
|
662 | |||
663 | # Now we should be fully configured. We can then execute files or load |
|
663 | # Now we should be fully configured. We can then execute files or load | |
664 | # things only needed for interactive use. Then we'll open the shell. |
|
664 | # things only needed for interactive use. Then we'll open the shell. | |
665 |
|
665 | |||
666 | # Take a snapshot of the user namespace before opening the shell. That way |
|
666 | # Take a snapshot of the user namespace before opening the shell. That way | |
667 | # we'll be able to identify which things were interactively defined and |
|
667 | # we'll be able to identify which things were interactively defined and | |
668 | # which were defined through config files. |
|
668 | # which were defined through config files. | |
669 | IP.user_config_ns.update(IP.user_ns) |
|
669 | IP.user_config_ns.update(IP.user_ns) | |
670 |
|
670 | |||
671 | # Force reading a file as if it were a session log. Slower but safer. |
|
671 | # Force reading a file as if it were a session log. Slower but safer. | |
672 | if load_logplay: |
|
672 | if load_logplay: | |
673 | print 'Replaying log...' |
|
673 | print 'Replaying log...' | |
674 | try: |
|
674 | try: | |
675 | if IP_rc.debug: |
|
675 | if IP_rc.debug: | |
676 | logplay_quiet = 0 |
|
676 | logplay_quiet = 0 | |
677 | else: |
|
677 | else: | |
678 | logplay_quiet = 1 |
|
678 | logplay_quiet = 1 | |
679 |
|
679 | |||
680 | msg.logplay.trap_all() |
|
680 | msg.logplay.trap_all() | |
681 | IP.safe_execfile(load_logplay,IP.user_ns, |
|
681 | IP.safe_execfile(load_logplay,IP.user_ns, | |
682 | islog = 1, quiet = logplay_quiet) |
|
682 | islog = 1, quiet = logplay_quiet) | |
683 | msg.logplay.release_all() |
|
683 | msg.logplay.release_all() | |
684 | if IP_rc.messages: |
|
684 | if IP_rc.messages: | |
685 | msg.summary += msg.logplay.summary_all() |
|
685 | msg.summary += msg.logplay.summary_all() | |
686 | except: |
|
686 | except: | |
687 | warn('Problems replaying logfile %s.' % load_logplay) |
|
687 | warn('Problems replaying logfile %s.' % load_logplay) | |
688 | IP.InteractiveTB() |
|
688 | IP.InteractiveTB() | |
689 |
|
689 | |||
690 | # Load remaining files in command line |
|
690 | # Load remaining files in command line | |
691 | msg.user_exec.trap_all() |
|
691 | msg.user_exec.trap_all() | |
692 |
|
692 | |||
693 | # Do NOT execute files named in the command line as scripts to be loaded |
|
693 | # Do NOT execute files named in the command line as scripts to be loaded | |
694 | # by embedded instances. Doing so has the potential for an infinite |
|
694 | # by embedded instances. Doing so has the potential for an infinite | |
695 | # recursion if there are exceptions thrown in the process. |
|
695 | # recursion if there are exceptions thrown in the process. | |
696 |
|
696 | |||
697 | # XXX FIXME: the execution of user files should be moved out to after |
|
697 | # XXX FIXME: the execution of user files should be moved out to after | |
698 | # ipython is fully initialized, just as if they were run via %run at the |
|
698 | # ipython is fully initialized, just as if they were run via %run at the | |
699 | # ipython prompt. This would also give them the benefit of ipython's |
|
699 | # ipython prompt. This would also give them the benefit of ipython's | |
700 | # nice tracebacks. |
|
700 | # nice tracebacks. | |
701 |
|
701 | |||
702 | if (not embedded and IP_rc.args and |
|
702 | if (not embedded and IP_rc.args and | |
703 | not IP_rc.args[0].lower().endswith('.ipy')): |
|
703 | not IP_rc.args[0].lower().endswith('.ipy')): | |
704 | name_save = IP.user_ns['__name__'] |
|
704 | name_save = IP.user_ns['__name__'] | |
705 | IP.user_ns['__name__'] = '__main__' |
|
705 | IP.user_ns['__name__'] = '__main__' | |
706 | # Set our own excepthook in case the user code tries to call it |
|
706 | # Set our own excepthook in case the user code tries to call it | |
707 | # directly. This prevents triggering the IPython crash handler. |
|
707 | # directly. This prevents triggering the IPython crash handler. | |
708 | old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook |
|
708 | old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook | |
709 |
|
709 | |||
710 | save_argv = sys.argv[1:] # save it for later restoring |
|
710 | save_argv = sys.argv[1:] # save it for later restoring | |
711 |
|
711 | |||
712 | sys.argv = args |
|
712 | sys.argv = args | |
713 |
|
713 | |||
714 | try: |
|
714 | try: | |
715 | IP.safe_execfile(args[0], IP.user_ns) |
|
715 | IP.safe_execfile(args[0], IP.user_ns) | |
716 | finally: |
|
716 | finally: | |
717 | # Reset our crash handler in place |
|
717 | # Reset our crash handler in place | |
718 | sys.excepthook = old_excepthook |
|
718 | sys.excepthook = old_excepthook | |
719 | sys.argv[:] = save_argv |
|
719 | sys.argv[:] = save_argv | |
720 | IP.user_ns['__name__'] = name_save |
|
720 | IP.user_ns['__name__'] = name_save | |
721 |
|
721 | |||
722 | msg.user_exec.release_all() |
|
722 | msg.user_exec.release_all() | |
723 |
|
723 | |||
724 | if IP_rc.messages: |
|
724 | if IP_rc.messages: | |
725 | msg.summary += msg.user_exec.summary_all() |
|
725 | msg.summary += msg.user_exec.summary_all() | |
726 |
|
726 | |||
727 | # since we can't specify a null string on the cmd line, 0 is the equivalent: |
|
727 | # since we can't specify a null string on the cmd line, 0 is the equivalent: | |
728 | if IP_rc.nosep: |
|
728 | if IP_rc.nosep: | |
729 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' |
|
729 | IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0' | |
730 | if IP_rc.separate_in == '0': IP_rc.separate_in = '' |
|
730 | if IP_rc.separate_in == '0': IP_rc.separate_in = '' | |
731 | if IP_rc.separate_out == '0': IP_rc.separate_out = '' |
|
731 | if IP_rc.separate_out == '0': IP_rc.separate_out = '' | |
732 | if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = '' |
|
732 | if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = '' | |
733 | IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n') |
|
733 | IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n') | |
734 | IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n') |
|
734 | IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n') | |
735 | IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n') |
|
735 | IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n') | |
736 |
|
736 | |||
737 | # Determine how many lines at the bottom of the screen are needed for |
|
737 | # Determine how many lines at the bottom of the screen are needed for | |
738 | # showing prompts, so we can know wheter long strings are to be printed or |
|
738 | # showing prompts, so we can know wheter long strings are to be printed or | |
739 | # paged: |
|
739 | # paged: | |
740 | num_lines_bot = IP_rc.separate_in.count('\n')+1 |
|
740 | num_lines_bot = IP_rc.separate_in.count('\n')+1 | |
741 | IP_rc.screen_length = IP_rc.screen_length - num_lines_bot |
|
741 | IP_rc.screen_length = IP_rc.screen_length - num_lines_bot | |
742 |
|
742 | |||
743 | # configure startup banner |
|
743 | # configure startup banner | |
744 | if IP_rc.c: # regular python doesn't print the banner with -c |
|
744 | if IP_rc.c: # regular python doesn't print the banner with -c | |
745 | IP_rc.banner = 0 |
|
745 | IP_rc.banner = 0 | |
746 | if IP_rc.banner: |
|
746 | if IP_rc.banner: | |
747 | BANN_P = IP.BANNER_PARTS |
|
747 | BANN_P = IP.BANNER_PARTS | |
748 | else: |
|
748 | else: | |
749 | BANN_P = [] |
|
749 | BANN_P = [] | |
750 |
|
750 | |||
751 | if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile) |
|
751 | if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile) | |
752 |
|
752 | |||
753 | # add message log (possibly empty) |
|
753 | # add message log (possibly empty) | |
754 | if msg.summary: BANN_P.append(msg.summary) |
|
754 | if msg.summary: BANN_P.append(msg.summary) | |
755 | # Final banner is a string |
|
755 | # Final banner is a string | |
756 | IP.BANNER = '\n'.join(BANN_P) |
|
756 | IP.BANNER = '\n'.join(BANN_P) | |
757 |
|
757 | |||
758 | # Finalize the IPython instance. This assumes the rc structure is fully |
|
758 | # Finalize the IPython instance. This assumes the rc structure is fully | |
759 | # in place. |
|
759 | # in place. | |
760 | IP.post_config_initialization() |
|
760 | IP.post_config_initialization() | |
761 |
|
761 | |||
762 | return IP |
|
762 | return IP | |
763 | #************************ end of file <ipmaker.py> ************************** |
|
763 | #************************ end of file <ipmaker.py> ************************** |
@@ -1,652 +1,654 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | #***************************************************************************** |
|
2 | #***************************************************************************** | |
3 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> |
|
3 | # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu> | |
4 | # |
|
4 | # | |
5 | # Distributed under the terms of the BSD License. The full license is in |
|
5 | # Distributed under the terms of the BSD License. The full license is in | |
6 | # the file COPYING, distributed as part of this software. |
|
6 | # the file COPYING, distributed as part of this software. | |
7 | #***************************************************************************** |
|
7 | #***************************************************************************** | |
8 |
|
8 | |||
9 |
# $Id: usage.py 27 |
|
9 | # $Id: usage.py 2723 2007-09-07 07:44:16Z fperez $ | |
10 |
|
10 | |||
11 | from IPython import Release |
|
11 | from IPython import Release | |
12 | __author__ = '%s <%s>' % Release.authors['Fernando'] |
|
12 | __author__ = '%s <%s>' % Release.authors['Fernando'] | |
13 | __license__ = Release.license |
|
13 | __license__ = Release.license | |
14 | __version__ = Release.version |
|
14 | __version__ = Release.version | |
15 |
|
15 | |||
16 | __doc__ = """ |
|
16 | __doc__ = """ | |
17 | IPython -- An enhanced Interactive Python |
|
17 | IPython -- An enhanced Interactive Python | |
18 | ========================================= |
|
18 | ========================================= | |
19 |
|
19 | |||
20 | A Python shell with automatic history (input and output), dynamic object |
|
20 | A Python shell with automatic history (input and output), dynamic object | |
21 | introspection, easier configuration, command completion, access to the system |
|
21 | introspection, easier configuration, command completion, access to the system | |
22 | shell and more. |
|
22 | shell and more. | |
23 |
|
23 | |||
24 | IPython can also be embedded in running programs. See EMBEDDING below. |
|
24 | IPython can also be embedded in running programs. See EMBEDDING below. | |
25 |
|
25 | |||
26 |
|
26 | |||
27 | USAGE |
|
27 | USAGE | |
28 | ipython [options] files |
|
28 | ipython [options] files | |
29 |
|
29 | |||
30 | If invoked with no options, it executes all the files listed in |
|
30 | If invoked with no options, it executes all the files listed in | |
31 | sequence and drops you into the interpreter while still acknowledging |
|
31 | sequence and drops you into the interpreter while still acknowledging | |
32 | any options you may have set in your ipythonrc file. This behavior is |
|
32 | any options you may have set in your ipythonrc file. This behavior is | |
33 | different from standard Python, which when called as python -i will |
|
33 | different from standard Python, which when called as python -i will | |
34 | only execute one file and will ignore your configuration setup. |
|
34 | only execute one file and will ignore your configuration setup. | |
35 |
|
35 | |||
36 | Please note that some of the configuration options are not available at |
|
36 | Please note that some of the configuration options are not available at | |
37 | the command line, simply because they are not practical here. Look into |
|
37 | the command line, simply because they are not practical here. Look into | |
38 | your ipythonrc configuration file for details on those. This file |
|
38 | your ipythonrc configuration file for details on those. This file | |
39 | typically installed in the $HOME/.ipython directory. |
|
39 | typically installed in the $HOME/.ipython directory. | |
40 |
|
40 | |||
41 | For Windows users, $HOME resolves to C:\\Documents and |
|
41 | For Windows users, $HOME resolves to C:\\Documents and | |
42 | Settings\\YourUserName in most instances, and _ipython is used instead |
|
42 | Settings\\YourUserName in most instances, and _ipython is used instead | |
43 | of .ipython, since some Win32 programs have problems with dotted names |
|
43 | of .ipython, since some Win32 programs have problems with dotted names | |
44 | in directories. |
|
44 | in directories. | |
45 |
|
45 | |||
46 | In the rest of this text, we will refer to this directory as |
|
46 | In the rest of this text, we will refer to this directory as | |
47 | IPYTHONDIR. |
|
47 | IPYTHONDIR. | |
48 |
|
48 | |||
49 |
|
49 | |||
50 | SPECIAL THREADING OPTIONS |
|
50 | SPECIAL THREADING OPTIONS | |
51 | The following special options are ONLY valid at the beginning of the |
|
51 | The following special options are ONLY valid at the beginning of the | |
52 | command line, and not later. This is because they control the initial- |
|
52 | command line, and not later. This is because they control the initial- | |
53 | ization of ipython itself, before the normal option-handling mechanism |
|
53 | ization of ipython itself, before the normal option-handling mechanism | |
54 | is active. |
|
54 | is active. | |
55 |
|
55 | |||
56 | -gthread, -qthread, -q4thread, -wthread, -pylab |
|
56 | -gthread, -qthread, -q4thread, -wthread, -pylab | |
57 |
|
57 | |||
58 | Only ONE of these can be given, and it can only be given as the |
|
58 | Only ONE of these can be given, and it can only be given as the | |
59 | first option passed to IPython (it will have no effect in any |
|
59 | first option passed to IPython (it will have no effect in any | |
60 | other position). They provide threading support for the GTK, QT |
|
60 | other position). They provide threading support for the GTK, QT | |
61 | and WXWidgets toolkits, and for the matplotlib library. |
|
61 | and WXWidgets toolkits, and for the matplotlib library. | |
62 |
|
62 | |||
63 | With any of the first four options, IPython starts running a |
|
63 | With any of the first four options, IPython starts running a | |
64 | separate thread for the graphical toolkit's operation, so that |
|
64 | separate thread for the graphical toolkit's operation, so that | |
65 | you can open and control graphical elements from within an |
|
65 | you can open and control graphical elements from within an | |
66 | IPython command line, without blocking. All four provide |
|
66 | IPython command line, without blocking. All four provide | |
67 | essentially the same functionality, respectively for GTK, QT3, |
|
67 | essentially the same functionality, respectively for GTK, QT3, | |
68 | QT4 and WXWidgets (via their Python interfaces). |
|
68 | QT4 and WXWidgets (via their Python interfaces). | |
69 |
|
69 | |||
70 | Note that with -wthread, you can additionally use the -wxversion |
|
70 | Note that with -wthread, you can additionally use the -wxversion | |
71 | option to request a specific version of wx to be used. This |
|
71 | option to request a specific version of wx to be used. This | |
72 | requires that you have the 'wxversion' Python module installed, |
|
72 | requires that you have the 'wxversion' Python module installed, | |
73 | which is part of recent wxPython distributions. |
|
73 | which is part of recent wxPython distributions. | |
74 |
|
74 | |||
75 | If -pylab is given, IPython loads special support for the mat- |
|
75 | If -pylab is given, IPython loads special support for the mat- | |
76 | plotlib library (http://matplotlib.sourceforge.net), allowing |
|
76 | plotlib library (http://matplotlib.sourceforge.net), allowing | |
77 | interactive usage of any of its backends as defined in the |
|
77 | interactive usage of any of its backends as defined in the | |
78 | user's .matplotlibrc file. It automatically activates GTK, QT |
|
78 | user's .matplotlibrc file. It automatically activates GTK, QT | |
79 | or WX threading for IPyhton if the choice of matplotlib backend |
|
79 | or WX threading for IPyhton if the choice of matplotlib backend | |
80 | requires it. It also modifies the %run command to correctly |
|
80 | requires it. It also modifies the %run command to correctly | |
81 | execute (without blocking) any matplotlib-based script which |
|
81 | execute (without blocking) any matplotlib-based script which | |
82 | calls show() at the end. |
|
82 | calls show() at the end. | |
83 |
|
83 | |||
84 | -tk The -g/q/q4/wthread options, and -pylab (if matplotlib is |
|
84 | -tk The -g/q/q4/wthread options, and -pylab (if matplotlib is | |
85 | configured to use GTK, QT or WX), will normally block Tk |
|
85 | configured to use GTK, QT or WX), will normally block Tk | |
86 | graphical interfaces. This means that when GTK, QT or WX |
|
86 | graphical interfaces. This means that when GTK, QT or WX | |
87 | threading is active, any attempt to open a Tk GUI will result in |
|
87 | threading is active, any attempt to open a Tk GUI will result in | |
88 | a dead window, and possibly cause the Python interpreter to |
|
88 | a dead window, and possibly cause the Python interpreter to | |
89 | crash. An extra option, -tk, is available to address this |
|
89 | crash. An extra option, -tk, is available to address this | |
90 | issue. It can ONLY be given as a SECOND option after any of the |
|
90 | issue. It can ONLY be given as a SECOND option after any of the | |
91 | above (-gthread, -qthread, q4thread, -wthread or -pylab). |
|
91 | above (-gthread, -qthread, q4thread, -wthread or -pylab). | |
92 |
|
92 | |||
93 | If -tk is given, IPython will try to coordinate Tk threading |
|
93 | If -tk is given, IPython will try to coordinate Tk threading | |
94 | with GTK, QT or WX. This is however potentially unreliable, and |
|
94 | with GTK, QT or WX. This is however potentially unreliable, and | |
95 | you will have to test on your platform and Python configuration |
|
95 | you will have to test on your platform and Python configuration | |
96 | to determine whether it works for you. Debian users have |
|
96 | to determine whether it works for you. Debian users have | |
97 | reported success, apparently due to the fact that Debian builds |
|
97 | reported success, apparently due to the fact that Debian builds | |
98 | all of Tcl, Tk, Tkinter and Python with pthreads support. Under |
|
98 | all of Tcl, Tk, Tkinter and Python with pthreads support. Under | |
99 | other Linux environments (such as Fedora Core 2/3), this option |
|
99 | other Linux environments (such as Fedora Core 2/3), this option | |
100 | has caused random crashes and lockups of the Python interpreter. |
|
100 | has caused random crashes and lockups of the Python interpreter. | |
101 | Under other operating systems (Mac OSX and Windows), you'll need |
|
101 | Under other operating systems (Mac OSX and Windows), you'll need | |
102 | to try it to find out, since currently no user reports are |
|
102 | to try it to find out, since currently no user reports are | |
103 | available. |
|
103 | available. | |
104 |
|
104 | |||
105 | There is unfortunately no way for IPython to determine at run- |
|
105 | There is unfortunately no way for IPython to determine at run- | |
106 | time whether -tk will work reliably or not, so you will need to |
|
106 | time whether -tk will work reliably or not, so you will need to | |
107 | do some experiments before relying on it for regular work. |
|
107 | do some experiments before relying on it for regular work. | |
108 |
|
108 | |||
109 | A WARNING ABOUT SIGNALS AND THREADS |
|
109 | A WARNING ABOUT SIGNALS AND THREADS | |
110 |
|
110 | |||
111 | When any of the thread systems (GTK, QT or WX) are active, either |
|
111 | When any of the thread systems (GTK, QT or WX) are active, either | |
112 | directly or via -pylab with a threaded backend, it is impossible to |
|
112 | directly or via -pylab with a threaded backend, it is impossible to | |
113 | interrupt long-running Python code via Ctrl-C. IPython can not pass |
|
113 | interrupt long-running Python code via Ctrl-C. IPython can not pass | |
114 | the KeyboardInterrupt exception (or the underlying SIGINT) across |
|
114 | the KeyboardInterrupt exception (or the underlying SIGINT) across | |
115 | threads, so any long-running process started from IPython will run to |
|
115 | threads, so any long-running process started from IPython will run to | |
116 | completion, or will have to be killed via an external (OS-based) |
|
116 | completion, or will have to be killed via an external (OS-based) | |
117 | mechanism. |
|
117 | mechanism. | |
118 |
|
118 | |||
119 | To the best of my knowledge, this limitation is imposed by the Python |
|
119 | To the best of my knowledge, this limitation is imposed by the Python | |
120 | interpreter itself, and it comes from the difficulty of writing |
|
120 | interpreter itself, and it comes from the difficulty of writing | |
121 | portable signal/threaded code. If any user is an expert on this topic |
|
121 | portable signal/threaded code. If any user is an expert on this topic | |
122 | and can suggest a better solution, I would love to hear about it. In |
|
122 | and can suggest a better solution, I would love to hear about it. In | |
123 | the IPython sources, look at the Shell.py module, and in particular at |
|
123 | the IPython sources, look at the Shell.py module, and in particular at | |
124 | the runcode() method. |
|
124 | the runcode() method. | |
125 |
|
125 | |||
126 | REGULAR OPTIONS |
|
126 | REGULAR OPTIONS | |
127 | After the above threading options have been given, regular options can |
|
127 | After the above threading options have been given, regular options can | |
128 | follow in any order. All options can be abbreviated to their shortest |
|
128 | follow in any order. All options can be abbreviated to their shortest | |
129 | non-ambiguous form and are case-sensitive. One or two dashes can be |
|
129 | non-ambiguous form and are case-sensitive. One or two dashes can be | |
130 | used. Some options have an alternate short form, indicated after a |. |
|
130 | used. Some options have an alternate short form, indicated after a |. | |
131 |
|
131 | |||
132 | Most options can also be set from your ipythonrc configuration file. |
|
132 | Most options can also be set from your ipythonrc configuration file. | |
133 | See the provided examples for assistance. Options given on the comman- |
|
133 | See the provided examples for assistance. Options given on the comman- | |
134 | dline override the values set in the ipythonrc file. |
|
134 | dline override the values set in the ipythonrc file. | |
135 |
|
135 | |||
136 | All options with a [no] prepended can be specified in negated form |
|
136 | All options with a [no] prepended can be specified in negated form | |
137 | (using -nooption instead of -option) to turn the feature off. |
|
137 | (using -nooption instead of -option) to turn the feature off. | |
138 |
|
138 | |||
139 | -h, --help |
|
139 | -h, --help | |
140 | Show summary of options. |
|
140 | Show summary of options. | |
141 |
|
141 | |||
142 | -pylab This can only be given as the first option passed to IPython (it |
|
142 | -pylab This can only be given as the first option passed to IPython (it | |
143 | will have no effect in any other position). It adds special sup- |
|
143 | will have no effect in any other position). It adds special sup- | |
144 | port for the matplotlib library (http://matplotlib.source- |
|
144 | port for the matplotlib library (http://matplotlib.source- | |
145 | forge.net), allowing interactive usage of any of its backends as |
|
145 | forge.net), allowing interactive usage of any of its backends as | |
146 | defined in the user's .matplotlibrc file. It automatically |
|
146 | defined in the user's .matplotlibrc file. It automatically | |
147 | activates GTK or WX threading for IPyhton if the choice of mat- |
|
147 | activates GTK or WX threading for IPyhton if the choice of mat- | |
148 | plotlib backend requires it. It also modifies the @run command |
|
148 | plotlib backend requires it. It also modifies the @run command | |
149 | to correctly execute (without blocking) any matplotlib-based |
|
149 | to correctly execute (without blocking) any matplotlib-based | |
150 | script which calls show() at the end. |
|
150 | script which calls show() at the end. | |
151 |
|
151 | |||
152 | -autocall <val> |
|
152 | -autocall <val> | |
153 | Make IPython automatically call any callable object even if you |
|
153 | Make IPython automatically call any callable object even if you | |
154 | didn't type explicit parentheses. For example, 'str 43' becomes |
|
154 | didn't type explicit parentheses. For example, 'str 43' becomes | |
155 | 'str(43)' automatically. The value can be '0' to disable the |
|
155 | 'str(43)' automatically. The value can be '0' to disable the | |
156 | feature, '1' for 'smart' autocall, where it is not applied if |
|
156 | feature, '1' for 'smart' autocall, where it is not applied if | |
157 | there are no more arguments on the line, and '2' for 'full' |
|
157 | there are no more arguments on the line, and '2' for 'full' | |
158 | autocall, where all callable objects are automatically called |
|
158 | autocall, where all callable objects are automatically called | |
159 | (even if no arguments are present). The default is '1'. |
|
159 | (even if no arguments are present). The default is '1'. | |
160 |
|
160 | |||
161 | -[no]autoindent |
|
161 | -[no]autoindent | |
162 | Turn automatic indentation on/off. |
|
162 | Turn automatic indentation on/off. | |
163 |
|
163 | |||
164 | -[no]automagic |
|
164 | -[no]automagic | |
165 | Make magic commands automatic (without needing their first char- |
|
165 | Make magic commands automatic (without needing their first char- | |
166 | acter to be %). Type %magic at the IPython prompt for more |
|
166 | acter to be %). Type %magic at the IPython prompt for more | |
167 | information. |
|
167 | information. | |
168 |
|
168 | |||
169 | -[no]autoedit_syntax |
|
169 | -[no]autoedit_syntax | |
170 | When a syntax error occurs after editing a file, automatically |
|
170 | When a syntax error occurs after editing a file, automatically | |
171 | open the file to the trouble causing line for convenient fixing. |
|
171 | open the file to the trouble causing line for convenient fixing. | |
172 |
|
172 | |||
173 | -[no]banner |
|
173 | -[no]banner | |
174 | Print the intial information banner (default on). |
|
174 | Print the intial information banner (default on). | |
175 |
|
175 | |||
176 | -c <command> |
|
176 | -c <command> | |
177 | Execute the given command string, and set sys.argv to ['c']. |
|
177 | Execute the given command string, and set sys.argv to ['c']. | |
178 | This is similar to the -c option in the normal Python inter- |
|
178 | This is similar to the -c option in the normal Python inter- | |
179 | preter. |
|
179 | preter. | |
180 |
|
180 | |||
181 | -cache_size|cs <n> |
|
181 | -cache_size|cs <n> | |
182 | Size of the output cache (maximum number of entries to hold in |
|
182 | Size of the output cache (maximum number of entries to hold in | |
183 | memory). The default is 1000, you can change it permanently in |
|
183 | memory). The default is 1000, you can change it permanently in | |
184 | your config file. Setting it to 0 completely disables the |
|
184 | your config file. Setting it to 0 completely disables the | |
185 | caching system, and the minimum value accepted is 20 (if you |
|
185 | caching system, and the minimum value accepted is 20 (if you | |
186 | provide a value less than 20, it is reset to 0 and a warning is |
|
186 | provide a value less than 20, it is reset to 0 and a warning is | |
187 | issued). This limit is defined because otherwise you'll spend |
|
187 | issued). This limit is defined because otherwise you'll spend | |
188 | more time re-flushing a too small cache than working. |
|
188 | more time re-flushing a too small cache than working. | |
189 |
|
189 | |||
190 | -classic|cl |
|
190 | -classic|cl | |
191 | Gives IPython a similar feel to the classic Python prompt. |
|
191 | Gives IPython a similar feel to the classic Python prompt. | |
192 |
|
192 | |||
193 | -colors <scheme> |
|
193 | -colors <scheme> | |
194 | Color scheme for prompts and exception reporting. Currently |
|
194 | Color scheme for prompts and exception reporting. Currently | |
195 | implemented: NoColor, Linux, and LightBG. |
|
195 | implemented: NoColor, Linux, and LightBG. | |
196 |
|
196 | |||
197 | -[no]color_info |
|
197 | -[no]color_info | |
198 | IPython can display information about objects via a set of func- |
|
198 | IPython can display information about objects via a set of func- | |
199 | tions, and optionally can use colors for this, syntax highlight- |
|
199 | tions, and optionally can use colors for this, syntax highlight- | |
200 | ing source code and various other elements. However, because |
|
200 | ing source code and various other elements. However, because | |
201 | this information is passed through a pager (like 'less') and |
|
201 | this information is passed through a pager (like 'less') and | |
202 | many pagers get confused with color codes, this option is off by |
|
202 | many pagers get confused with color codes, this option is off by | |
203 | default. You can test it and turn it on permanently in your |
|
203 | default. You can test it and turn it on permanently in your | |
204 | ipythonrc file if it works for you. As a reference, the 'less' |
|
204 | ipythonrc file if it works for you. As a reference, the 'less' | |
205 | pager supplied with Mandrake 8.2 works ok, but that in RedHat |
|
205 | pager supplied with Mandrake 8.2 works ok, but that in RedHat | |
206 | 7.2 doesn't. |
|
206 | 7.2 doesn't. | |
207 |
|
207 | |||
208 | Test it and turn it on permanently if it works with your system. |
|
208 | Test it and turn it on permanently if it works with your system. | |
209 | The magic function @color_info allows you to toggle this inter- |
|
209 | The magic function @color_info allows you to toggle this inter- | |
210 | actively for testing. |
|
210 | actively for testing. | |
211 |
|
211 | |||
212 | -[no]confirm_exit |
|
212 | -[no]confirm_exit | |
213 | Set to confirm when you try to exit IPython with an EOF (Con- |
|
213 | Set to confirm when you try to exit IPython with an EOF (Con- | |
214 | trol-D in Unix, Control-Z/Enter in Windows). Note that using the |
|
214 | trol-D in Unix, Control-Z/Enter in Windows). Note that using the | |
215 | magic functions @Exit or @Quit you can force a direct exit, |
|
215 | magic functions @Exit or @Quit you can force a direct exit, | |
216 | bypassing any confirmation. |
|
216 | bypassing any confirmation. | |
217 |
|
217 | |||
218 | -[no]debug |
|
218 | -[no]debug | |
219 | Show information about the loading process. Very useful to pin |
|
219 | Show information about the loading process. Very useful to pin | |
220 | down problems with your configuration files or to get details |
|
220 | down problems with your configuration files or to get details | |
221 | about session restores. |
|
221 | about session restores. | |
222 |
|
222 | |||
223 | -[no]deep_reload |
|
223 | -[no]deep_reload | |
224 | IPython can use the deep_reload module which reloads changes in |
|
224 | IPython can use the deep_reload module which reloads changes in | |
225 | modules recursively (it replaces the reload() function, so you |
|
225 | modules recursively (it replaces the reload() function, so you | |
226 | don't need to change anything to use it). deep_reload() forces a |
|
226 | don't need to change anything to use it). deep_reload() forces a | |
227 | full reload of modules whose code may have changed, which the |
|
227 | full reload of modules whose code may have changed, which the | |
228 | default reload() function does not. |
|
228 | default reload() function does not. | |
229 |
|
229 | |||
230 | When deep_reload is off, IPython will use the normal reload(), |
|
230 | When deep_reload is off, IPython will use the normal reload(), | |
231 | but deep_reload will still be available as dreload(). This fea- |
|
231 | but deep_reload will still be available as dreload(). This fea- | |
232 | ture is off by default [which means that you have both normal |
|
232 | ture is off by default [which means that you have both normal | |
233 | reload() and dreload()]. |
|
233 | reload() and dreload()]. | |
234 |
|
234 | |||
235 | -editor <name> |
|
235 | -editor <name> | |
236 | Which editor to use with the @edit command. By default, IPython |
|
236 | Which editor to use with the @edit command. By default, IPython | |
237 | will honor your EDITOR environment variable (if not set, vi is |
|
237 | will honor your EDITOR environment variable (if not set, vi is | |
238 | the Unix default and notepad the Windows one). Since this editor |
|
238 | the Unix default and notepad the Windows one). Since this editor | |
239 | is invoked on the fly by IPython and is meant for editing small |
|
239 | is invoked on the fly by IPython and is meant for editing small | |
240 | code snippets, you may want to use a small, lightweight editor |
|
240 | code snippets, you may want to use a small, lightweight editor | |
241 | here (in case your default EDITOR is something like Emacs). |
|
241 | here (in case your default EDITOR is something like Emacs). | |
242 |
|
242 | |||
243 | -ipythondir <name> |
|
243 | -ipythondir <name> | |
244 | The name of your IPython configuration directory IPYTHONDIR. |
|
244 | The name of your IPython configuration directory IPYTHONDIR. | |
245 | This can also be specified through the environment variable |
|
245 | This can also be specified through the environment variable | |
246 | IPYTHONDIR. |
|
246 | IPYTHONDIR. | |
247 |
|
247 | |||
248 | -log|l Generate a log file of all input. The file is named |
|
248 | -log|l Generate a log file of all input. The file is named | |
249 | ipython_log.py in your current directory (which prevents logs |
|
249 | ipython_log.py in your current directory (which prevents logs | |
250 | from multiple IPython sessions from trampling each other). You |
|
250 | from multiple IPython sessions from trampling each other). You | |
251 | can use this to later restore a session by loading your logfile |
|
251 | can use this to later restore a session by loading your logfile | |
252 | as a file to be executed with option -logplay (see below). |
|
252 | as a file to be executed with option -logplay (see below). | |
253 |
|
253 | |||
254 | -logfile|lf |
|
254 | -logfile|lf | |
255 | Specify the name of your logfile. |
|
255 | Specify the name of your logfile. | |
256 |
|
256 | |||
257 | -logplay|lp |
|
257 | -logplay|lp | |
258 | Replay a previous log. For restoring a session as close as pos- |
|
258 | Replay a previous log. For restoring a session as close as pos- | |
259 | sible to the state you left it in, use this option (don't just |
|
259 | sible to the state you left it in, use this option (don't just | |
260 | run the logfile). With -logplay, IPython will try to reconstruct |
|
260 | run the logfile). With -logplay, IPython will try to reconstruct | |
261 | the previous working environment in full, not just execute the |
|
261 | the previous working environment in full, not just execute the | |
262 | commands in the logfile. |
|
262 | commands in the logfile. | |
263 | When a session is restored, logging is automatically turned on |
|
263 | When a session is restored, logging is automatically turned on | |
264 | again with the name of the logfile it was invoked with (it is |
|
264 | again with the name of the logfile it was invoked with (it is | |
265 | read from the log header). So once you've turned logging on for |
|
265 | read from the log header). So once you've turned logging on for | |
266 | a session, you can quit IPython and reload it as many times as |
|
266 | a session, you can quit IPython and reload it as many times as | |
267 | you want and it will continue to log its history and restore |
|
267 | you want and it will continue to log its history and restore | |
268 | from the beginning every time. |
|
268 | from the beginning every time. | |
269 |
|
269 | |||
270 | Caveats: there are limitations in this option. The history vari- |
|
270 | Caveats: there are limitations in this option. The history vari- | |
271 | ables _i*,_* and _dh don't get restored properly. In the future |
|
271 | ables _i*,_* and _dh don't get restored properly. In the future | |
272 | we will try to implement full session saving by writing and |
|
272 | we will try to implement full session saving by writing and | |
273 | retrieving a failed because of inherent limitations of Python's |
|
273 | retrieving a failed because of inherent limitations of Python's | |
274 | Pickle module, so this may have to wait. |
|
274 | Pickle module, so this may have to wait. | |
275 |
|
275 | |||
276 | -[no]messages |
|
276 | -[no]messages | |
277 | Print messages which IPython collects about its startup process |
|
277 | Print messages which IPython collects about its startup process | |
278 | (default on). |
|
278 | (default on). | |
279 |
|
279 | |||
280 | -[no]pdb |
|
280 | -[no]pdb | |
281 | Automatically call the pdb debugger after every uncaught excep- |
|
281 | Automatically call the pdb debugger after every uncaught excep- | |
282 | tion. If you are used to debugging using pdb, this puts you |
|
282 | tion. If you are used to debugging using pdb, this puts you | |
283 | automatically inside of it after any call (either in IPython or |
|
283 | automatically inside of it after any call (either in IPython or | |
284 | in code called by it) which triggers an exception which goes |
|
284 | in code called by it) which triggers an exception which goes | |
285 | uncaught. |
|
285 | uncaught. | |
286 |
|
286 | |||
287 | -[no]pprint |
|
287 | -[no]pprint | |
288 | IPython can optionally use the pprint (pretty printer) module |
|
288 | IPython can optionally use the pprint (pretty printer) module | |
289 | for displaying results. pprint tends to give a nicer display of |
|
289 | for displaying results. pprint tends to give a nicer display of | |
290 | nested data structures. If you like it, you can turn it on per- |
|
290 | nested data structures. If you like it, you can turn it on per- | |
291 | manently in your config file (default off). |
|
291 | manently in your config file (default off). | |
292 |
|
292 | |||
293 | -profile|p <name> |
|
293 | -profile|p <name> | |
294 | Assume that your config file is ipythonrc-<name> (looks in cur- |
|
294 | Assume that your config file is ipythonrc-<name> (looks in cur- | |
295 | rent dir first, then in IPYTHONDIR). This is a quick way to keep |
|
295 | rent dir first, then in IPYTHONDIR). This is a quick way to keep | |
296 | and load multiple config files for different tasks, especially |
|
296 | and load multiple config files for different tasks, especially | |
297 | if you use the include option of config files. You can keep a |
|
297 | if you use the include option of config files. You can keep a | |
298 | basic IPYTHONDIR/ipythonrc file and then have other 'profiles' |
|
298 | basic IPYTHONDIR/ipythonrc file and then have other 'profiles' | |
299 | which include this one and load extra things for particular |
|
299 | which include this one and load extra things for particular | |
300 | tasks. For example: |
|
300 | tasks. For example: | |
301 |
|
301 | |||
302 | 1) $HOME/.ipython/ipythonrc : load basic things you always want. |
|
302 | 1) $HOME/.ipython/ipythonrc : load basic things you always want. | |
303 | 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math- |
|
303 | 2) $HOME/.ipython/ipythonrc-math : load (1) and basic math- | |
304 | related modules. |
|
304 | related modules. | |
305 | 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and |
|
305 | 3) $HOME/.ipython/ipythonrc-numeric : load (1) and Numeric and | |
306 | plotting modules. |
|
306 | plotting modules. | |
307 |
|
307 | |||
308 | Since it is possible to create an endless loop by having circu- |
|
308 | Since it is possible to create an endless loop by having circu- | |
309 | lar file inclusions, IPython will stop if it reaches 15 recur- |
|
309 | lar file inclusions, IPython will stop if it reaches 15 recur- | |
310 | sive inclusions. |
|
310 | sive inclusions. | |
311 |
|
311 | |||
312 | -prompt_in1|pi1 <string> |
|
312 | -prompt_in1|pi1 <string> | |
313 | Specify the string used for input prompts. Note that if you are |
|
313 | Specify the string used for input prompts. Note that if you are | |
314 | using numbered prompts, the number is represented with a '\#' in |
|
314 | using numbered prompts, the number is represented with a '\#' in | |
315 | the string. Don't forget to quote strings with spaces embedded |
|
315 | the string. Don't forget to quote strings with spaces embedded | |
316 | in them. Default: 'In [\#]: '. |
|
316 | in them. Default: 'In [\#]: '. | |
317 |
|
317 | |||
318 | Most bash-like escapes can be used to customize IPython's |
|
318 | Most bash-like escapes can be used to customize IPython's | |
319 | prompts, as well as a few additional ones which are IPython-spe- |
|
319 | prompts, as well as a few additional ones which are IPython-spe- | |
320 | cific. All valid prompt escapes are described in detail in the |
|
320 | cific. All valid prompt escapes are described in detail in the | |
321 | Customization section of the IPython HTML/PDF manual. |
|
321 | Customization section of the IPython HTML/PDF manual. | |
322 |
|
322 | |||
323 | -prompt_in2|pi2 <string> |
|
323 | -prompt_in2|pi2 <string> | |
324 | Similar to the previous option, but used for the continuation |
|
324 | Similar to the previous option, but used for the continuation | |
325 | prompts. The special sequence '\D' is similar to '\#', but with |
|
325 | prompts. The special sequence '\D' is similar to '\#', but with | |
326 | all digits replaced dots (so you can have your continuation |
|
326 | all digits replaced dots (so you can have your continuation | |
327 | prompt aligned with your input prompt). Default: ' .\D.: ' |
|
327 | prompt aligned with your input prompt). Default: ' .\D.: ' | |
328 | (note three spaces at the start for alignment with 'In [\#]'). |
|
328 | (note three spaces at the start for alignment with 'In [\#]'). | |
329 |
|
329 | |||
330 | -prompt_out|po <string> |
|
330 | -prompt_out|po <string> | |
331 | String used for output prompts, also uses numbers like |
|
331 | String used for output prompts, also uses numbers like | |
332 | prompt_in1. Default: 'Out[\#]:'. |
|
332 | prompt_in1. Default: 'Out[\#]:'. | |
333 |
|
333 | |||
334 | -quick Start in bare bones mode (no config file loaded). |
|
334 | -quick Start in bare bones mode (no config file loaded). | |
335 |
|
335 | |||
336 | -rcfile <name> |
|
336 | -rcfile <name> | |
337 | Name of your IPython resource configuration file. normally |
|
337 | Name of your IPython resource configuration file. normally | |
338 | IPython loads ipythonrc (from current directory) or |
|
338 | IPython loads ipythonrc (from current directory) or | |
339 | IPYTHONDIR/ipythonrc. If the loading of your config file fails, |
|
339 | IPYTHONDIR/ipythonrc. If the loading of your config file fails, | |
340 | IPython starts with a bare bones configuration (no modules |
|
340 | IPython starts with a bare bones configuration (no modules | |
341 | loaded at all). |
|
341 | loaded at all). | |
342 |
|
342 | |||
343 | -[no]readline |
|
343 | -[no]readline | |
344 | Use the readline library, which is needed to support name com- |
|
344 | Use the readline library, which is needed to support name com- | |
345 | pletion and command history, among other things. It is enabled |
|
345 | pletion and command history, among other things. It is enabled | |
346 | by default, but may cause problems for users of X/Emacs in |
|
346 | by default, but may cause problems for users of X/Emacs in | |
347 | Python comint or shell buffers. |
|
347 | Python comint or shell buffers. | |
348 |
|
348 | |||
349 | Note that emacs 'eterm' buffers (opened with M-x term) support |
|
349 | Note that emacs 'eterm' buffers (opened with M-x term) support | |
350 | IPython's readline and syntax coloring fine, only 'emacs' (M-x |
|
350 | IPython's readline and syntax coloring fine, only 'emacs' (M-x | |
351 | shell and C-c !) buffers do not. |
|
351 | shell and C-c !) buffers do not. | |
352 |
|
352 | |||
353 | -screen_length|sl <n> |
|
353 | -screen_length|sl <n> | |
354 | Number of lines of your screen. This is used to control print- |
|
354 | Number of lines of your screen. This is used to control print- | |
355 | ing of very long strings. Strings longer than this number of |
|
355 | ing of very long strings. Strings longer than this number of | |
356 | lines will be sent through a pager instead of directly printed. |
|
356 | lines will be sent through a pager instead of directly printed. | |
357 |
|
357 | |||
358 | The default value for this is 0, which means IPython will auto- |
|
358 | The default value for this is 0, which means IPython will auto- | |
359 | detect your screen size every time it needs to print certain |
|
359 | detect your screen size every time it needs to print certain | |
360 | potentially long strings (this doesn't change the behavior of |
|
360 | potentially long strings (this doesn't change the behavior of | |
361 | the 'print' keyword, it's only triggered internally). If for |
|
361 | the 'print' keyword, it's only triggered internally). If for | |
362 | some reason this isn't working well (it needs curses support), |
|
362 | some reason this isn't working well (it needs curses support), | |
363 | specify it yourself. Otherwise don't change the default. |
|
363 | specify it yourself. Otherwise don't change the default. | |
364 |
|
364 | |||
365 | -separate_in|si <string> |
|
365 | -separate_in|si <string> | |
366 | Separator before input prompts. Default '0. |
|
366 | Separator before input prompts. Default '0. | |
367 |
|
367 | |||
368 | -separate_out|so <string> |
|
368 | -separate_out|so <string> | |
369 | Separator before output prompts. Default: 0 (nothing). |
|
369 | Separator before output prompts. Default: 0 (nothing). | |
370 |
|
370 | |||
371 | -separate_out2|so2 <string> |
|
371 | -separate_out2|so2 <string> | |
372 | Separator after output prompts. Default: 0 (nothing). |
|
372 | Separator after output prompts. Default: 0 (nothing). | |
373 |
|
373 | |||
374 | -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'. |
|
374 | -nosep Shorthand for '-separate_in 0 -separate_out 0 -separate_out2 0'. | |
375 | Simply removes all input/output separators. |
|
375 | Simply removes all input/output separators. | |
376 |
|
376 | |||
377 | -upgrade |
|
377 | -upgrade | |
378 | Allows you to upgrade your IPYTHONDIR configuration when you |
|
378 | Allows you to upgrade your IPYTHONDIR configuration when you | |
379 | install a new version of IPython. Since new versions may |
|
379 | install a new version of IPython. Since new versions may | |
380 | include new command lines options or example files, this copies |
|
380 | include new command lines options or example files, this copies | |
381 | updated ipythonrc-type files. However, it backs up (with a .old |
|
381 | updated ipythonrc-type files. However, it backs up (with a .old | |
382 | extension) all files which it overwrites so that you can merge |
|
382 | extension) all files which it overwrites so that you can merge | |
383 | back any custimizations you might have in your personal files. |
|
383 | back any custimizations you might have in your personal files. | |
384 |
|
384 | |||
385 | -Version |
|
385 | -Version | |
386 | Print version information and exit. |
|
386 | Print version information and exit. | |
387 |
|
387 | |||
388 | -wxversion <string> |
|
388 | -wxversion <string> | |
389 | Select a specific version of wxPython (used in conjunction with |
|
389 | Select a specific version of wxPython (used in conjunction with | |
390 | -wthread). Requires the wxversion module, part of recent |
|
390 | -wthread). Requires the wxversion module, part of recent | |
391 | wxPython distributions. |
|
391 | wxPython distributions. | |
392 |
|
392 | |||
393 | -xmode <modename> |
|
393 | -xmode <modename> | |
394 | Mode for exception reporting. The valid modes are Plain, Con- |
|
394 | Mode for exception reporting. The valid modes are Plain, Con- | |
395 | text, and Verbose. |
|
395 | text, and Verbose. | |
396 |
|
396 | |||
397 | - Plain: similar to python's normal traceback printing. |
|
397 | - Plain: similar to python's normal traceback printing. | |
398 |
|
398 | |||
399 | - Context: prints 5 lines of context source code around each |
|
399 | - Context: prints 5 lines of context source code around each | |
400 | line in the traceback. |
|
400 | line in the traceback. | |
401 |
|
401 | |||
402 | - Verbose: similar to Context, but additionally prints the vari- |
|
402 | - Verbose: similar to Context, but additionally prints the vari- | |
403 | ables currently visible where the exception happened (shortening |
|
403 | ables currently visible where the exception happened (shortening | |
404 | their strings if too long). This can potentially be very slow, |
|
404 | their strings if too long). This can potentially be very slow, | |
405 | if you happen to have a huge data structure whose string repre- |
|
405 | if you happen to have a huge data structure whose string repre- | |
406 | sentation is complex to compute. Your computer may appear to |
|
406 | sentation is complex to compute. Your computer may appear to | |
407 | freeze for a while with cpu usage at 100%. If this occurs, you |
|
407 | freeze for a while with cpu usage at 100%. If this occurs, you | |
408 | can cancel the traceback with Ctrl-C (maybe hitting it more than |
|
408 | can cancel the traceback with Ctrl-C (maybe hitting it more than | |
409 | once). |
|
409 | once). | |
410 |
|
410 | |||
411 |
|
411 | |||
412 | EMBEDDING |
|
412 | EMBEDDING | |
413 | It is possible to start an IPython instance inside your own Python pro- |
|
413 | It is possible to start an IPython instance inside your own Python pro- | |
414 | grams. In the documentation example files there are some illustrations |
|
414 | grams. In the documentation example files there are some illustrations | |
415 | on how to do this. |
|
415 | on how to do this. | |
416 |
|
416 | |||
417 | This feature allows you to evalutate dynamically the state of your |
|
417 | This feature allows you to evalutate dynamically the state of your | |
418 | code, operate with your variables, analyze them, etc. Note however |
|
418 | code, operate with your variables, analyze them, etc. Note however | |
419 | that any changes you make to values while in the shell do NOT propagate |
|
419 | that any changes you make to values while in the shell do NOT propagate | |
420 | back to the running code, so it is safe to modify your values because |
|
420 | back to the running code, so it is safe to modify your values because | |
421 | you won't break your code in bizarre ways by doing so. |
|
421 | you won't break your code in bizarre ways by doing so. | |
422 | """ |
|
422 | """ | |
423 |
|
423 | |||
424 | cmd_line_usage = __doc__ |
|
424 | cmd_line_usage = __doc__ | |
425 |
|
425 | |||
426 | #--------------------------------------------------------------------------- |
|
426 | #--------------------------------------------------------------------------- | |
427 | interactive_usage = """ |
|
427 | interactive_usage = """ | |
428 | IPython -- An enhanced Interactive Python |
|
428 | IPython -- An enhanced Interactive Python | |
429 | ========================================= |
|
429 | ========================================= | |
430 |
|
430 | |||
431 | IPython offers a combination of convenient shell features, special commands |
|
431 | IPython offers a combination of convenient shell features, special commands | |
432 | and a history mechanism for both input (command history) and output (results |
|
432 | and a history mechanism for both input (command history) and output (results | |
433 | caching, similar to Mathematica). It is intended to be a fully compatible |
|
433 | caching, similar to Mathematica). It is intended to be a fully compatible | |
434 | replacement for the standard Python interpreter, while offering vastly |
|
434 | replacement for the standard Python interpreter, while offering vastly | |
435 | improved functionality and flexibility. |
|
435 | improved functionality and flexibility. | |
436 |
|
436 | |||
437 | At your system command line, type 'ipython -help' to see the command line |
|
437 | At your system command line, type 'ipython -help' to see the command line | |
438 | options available. This document only describes interactive features. |
|
438 | options available. This document only describes interactive features. | |
439 |
|
439 | |||
440 | Warning: IPython relies on the existence of a global variable called __IP which |
|
440 | Warning: IPython relies on the existence of a global variable called __IP which | |
441 | controls the shell itself. If you redefine __IP to anything, bizarre behavior |
|
441 | controls the shell itself. If you redefine __IP to anything, bizarre behavior | |
442 | will quickly occur. |
|
442 | will quickly occur. | |
443 |
|
443 | |||
444 | MAIN FEATURES |
|
444 | MAIN FEATURES | |
445 |
|
445 | |||
446 | * Access to the standard Python help. As of Python 2.1, a help system is |
|
446 | * Access to the standard Python help. As of Python 2.1, a help system is | |
447 | available with access to object docstrings and the Python manuals. Simply |
|
447 | available with access to object docstrings and the Python manuals. Simply | |
448 | type 'help' (no quotes) to access it. |
|
448 | type 'help' (no quotes) to access it. | |
449 |
|
449 | |||
450 | * Magic commands: type %magic for information on the magic subsystem. |
|
450 | * Magic commands: type %magic for information on the magic subsystem. | |
451 |
|
451 | |||
452 | * System command aliases, via the %alias command or the ipythonrc config file. |
|
452 | * System command aliases, via the %alias command or the ipythonrc config file. | |
453 |
|
453 | |||
454 | * Dynamic object information: |
|
454 | * Dynamic object information: | |
455 |
|
455 | |||
456 | Typing ?word or word? prints detailed information about an object. If |
|
456 | Typing ?word or word? prints detailed information about an object. If | |
457 | certain strings in the object are too long (docstrings, code, etc.) they get |
|
457 | certain strings in the object are too long (docstrings, code, etc.) they get | |
458 | snipped in the center for brevity. |
|
458 | snipped in the center for brevity. | |
459 |
|
459 | |||
460 | Typing ??word or word?? gives access to the full information without |
|
460 | Typing ??word or word?? gives access to the full information without | |
461 | snipping long strings. Long strings are sent to the screen through the less |
|
461 | snipping long strings. Long strings are sent to the screen through the less | |
462 | pager if longer than the screen, printed otherwise. |
|
462 | pager if longer than the screen, printed otherwise. | |
463 |
|
463 | |||
464 | The ?/?? system gives access to the full source code for any object (if |
|
464 | The ?/?? system gives access to the full source code for any object (if | |
465 | available), shows function prototypes and other useful information. |
|
465 | available), shows function prototypes and other useful information. | |
466 |
|
466 | |||
467 | If you just want to see an object's docstring, type '%pdoc object' (without |
|
467 | If you just want to see an object's docstring, type '%pdoc object' (without | |
468 | quotes, and without % if you have automagic on). |
|
468 | quotes, and without % if you have automagic on). | |
469 |
|
469 | |||
470 | Both %pdoc and ?/?? give you access to documentation even on things which are |
|
470 | Both %pdoc and ?/?? give you access to documentation even on things which are | |
471 | not explicitely defined. Try for example typing {}.get? or after import os, |
|
471 | not explicitely defined. Try for example typing {}.get? or after import os, | |
472 | type os.path.abspath??. The magic functions %pdef, %source and %file operate |
|
472 | type os.path.abspath??. The magic functions %pdef, %source and %file operate | |
473 | similarly. |
|
473 | similarly. | |
474 |
|
474 | |||
475 | * Completion in the local namespace, by typing TAB at the prompt. |
|
475 | * Completion in the local namespace, by typing TAB at the prompt. | |
476 |
|
476 | |||
477 | At any time, hitting tab will complete any available python commands or |
|
477 | At any time, hitting tab will complete any available python commands or | |
478 | variable names, and show you a list of the possible completions if there's |
|
478 | variable names, and show you a list of the possible completions if there's | |
479 | no unambiguous one. It will also complete filenames in the current directory. |
|
479 | no unambiguous one. It will also complete filenames in the current directory. | |
480 |
|
480 | |||
481 | This feature requires the readline and rlcomplete modules, so it won't work |
|
481 | This feature requires the readline and rlcomplete modules, so it won't work | |
482 | if your Python lacks readline support (such as under Windows). |
|
482 | if your Python lacks readline support (such as under Windows). | |
483 |
|
483 | |||
484 | * Search previous command history in two ways (also requires readline): |
|
484 | * Search previous command history in two ways (also requires readline): | |
485 |
|
485 | |||
486 | - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to |
|
486 | - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to | |
487 | search through only the history items that match what you've typed so |
|
487 | search through only the history items that match what you've typed so | |
488 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like |
|
488 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like | |
489 | normal arrow keys. |
|
489 | normal arrow keys. | |
490 |
|
490 | |||
491 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches |
|
491 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches | |
492 | your history for lines that match what you've typed so far, completing as |
|
492 | your history for lines that match what you've typed so far, completing as | |
493 | much as it can. |
|
493 | much as it can. | |
494 |
|
494 | |||
495 | * Persistent command history across sessions (readline required). |
|
495 | * Persistent command history across sessions (readline required). | |
496 |
|
496 | |||
497 | * Logging of input with the ability to save and restore a working session. |
|
497 | * Logging of input with the ability to save and restore a working session. | |
498 |
|
498 | |||
499 | * System escape with !. Typing !ls will run 'ls' in the current directory. |
|
499 | * System escape with !. Typing !ls will run 'ls' in the current directory. | |
500 |
|
500 | |||
501 | * The reload command does a 'deep' reload of a module: changes made to the |
|
501 | * The reload command does a 'deep' reload of a module: changes made to the | |
502 | module since you imported will actually be available without having to exit. |
|
502 | module since you imported will actually be available without having to exit. | |
503 |
|
503 | |||
504 | * Verbose and colored exception traceback printouts. See the magic xmode and |
|
504 | * Verbose and colored exception traceback printouts. See the magic xmode and | |
505 | xcolor functions for details (just type %magic). |
|
505 | xcolor functions for details (just type %magic). | |
506 |
|
506 | |||
507 | * Input caching system: |
|
507 | * Input caching system: | |
508 |
|
508 | |||
509 | IPython offers numbered prompts (In/Out) with input and output caching. All |
|
509 | IPython offers numbered prompts (In/Out) with input and output caching. All | |
510 | input is saved and can be retrieved as variables (besides the usual arrow |
|
510 | input is saved and can be retrieved as variables (besides the usual arrow | |
511 | key recall). |
|
511 | key recall). | |
512 |
|
512 | |||
513 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
513 | The following GLOBAL variables always exist (so don't overwrite them!): | |
514 | _i: stores previous input. |
|
514 | _i: stores previous input. | |
515 | _ii: next previous. |
|
515 | _ii: next previous. | |
516 | _iii: next-next previous. |
|
516 | _iii: next-next previous. | |
517 | _ih : a list of all input _ih[n] is the input from line n. |
|
517 | _ih : a list of all input _ih[n] is the input from line n. | |
518 |
|
518 | |||
519 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
519 | Additionally, global variables named _i<n> are dynamically created (<n> | |
520 | being the prompt counter), such that _i<n> == _ih[<n>] |
|
520 | being the prompt counter), such that _i<n> == _ih[<n>] | |
521 |
|
521 | |||
522 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. |
|
522 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. | |
523 |
|
523 | |||
524 | You can create macros which contain multiple input lines from this history, |
|
524 | You can create macros which contain multiple input lines from this history, | |
525 | for later re-execution, with the %macro function. |
|
525 | for later re-execution, with the %macro function. | |
526 |
|
526 | |||
527 | The history function %hist allows you to see any part of your input history |
|
527 | The history function %hist allows you to see any part of your input history | |
528 | by printing a range of the _i variables. Note that inputs which contain |
|
528 | by printing a range of the _i variables. Note that inputs which contain | |
529 | magic functions (%) appear in the history with a prepended comment. This is |
|
529 | magic functions (%) appear in the history with a prepended comment. This is | |
530 | because they aren't really valid Python code, so you can't exec them. |
|
530 | because they aren't really valid Python code, so you can't exec them. | |
531 |
|
531 | |||
532 | * Output caching system: |
|
532 | * Output caching system: | |
533 |
|
533 | |||
534 | For output that is returned from actions, a system similar to the input |
|
534 | For output that is returned from actions, a system similar to the input | |
535 | cache exists but using _ instead of _i. Only actions that produce a result |
|
535 | cache exists but using _ instead of _i. Only actions that produce a result | |
536 | (NOT assignments, for example) are cached. If you are familiar with |
|
536 | (NOT assignments, for example) are cached. If you are familiar with | |
537 | Mathematica, IPython's _ variables behave exactly like Mathematica's % |
|
537 | Mathematica, IPython's _ variables behave exactly like Mathematica's % | |
538 | variables. |
|
538 | variables. | |
539 |
|
539 | |||
540 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
540 | The following GLOBAL variables always exist (so don't overwrite them!): | |
541 | _ (one underscore): previous output. |
|
541 | _ (one underscore): previous output. | |
542 | __ (two underscores): next previous. |
|
542 | __ (two underscores): next previous. | |
543 | ___ (three underscores): next-next previous. |
|
543 | ___ (three underscores): next-next previous. | |
544 |
|
544 | |||
545 | Global variables named _<n> are dynamically created (<n> being the prompt |
|
545 | Global variables named _<n> are dynamically created (<n> being the prompt | |
546 | counter), such that the result of output <n> is always available as _<n>. |
|
546 | counter), such that the result of output <n> is always available as _<n>. | |
547 |
|
547 | |||
548 | Finally, a global dictionary named _oh exists with entries for all lines |
|
548 | Finally, a global dictionary named _oh exists with entries for all lines | |
549 | which generated output. |
|
549 | which generated output. | |
550 |
|
550 | |||
551 | * Directory history: |
|
551 | * Directory history: | |
552 |
|
552 | |||
553 | Your history of visited directories is kept in the global list _dh, and the |
|
553 | Your history of visited directories is kept in the global list _dh, and the | |
554 | magic %cd command can be used to go to any entry in that list. |
|
554 | magic %cd command can be used to go to any entry in that list. | |
555 |
|
555 | |||
556 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) |
|
556 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) | |
557 |
|
557 | |||
558 | 1. Auto-parentheses |
|
558 | 1. Auto-parentheses | |
559 | Callable objects (i.e. functions, methods, etc) can be invoked like |
|
559 | Callable objects (i.e. functions, methods, etc) can be invoked like | |
560 | this (notice the commas between the arguments): |
|
560 | this (notice the commas between the arguments): | |
561 | >>> callable_ob arg1, arg2, arg3 |
|
561 | >>> callable_ob arg1, arg2, arg3 | |
562 | and the input will be translated to this: |
|
562 | and the input will be translated to this: | |
563 | --> callable_ob(arg1, arg2, arg3) |
|
563 | --> callable_ob(arg1, arg2, arg3) | |
564 | You can force auto-parentheses by using '/' as the first character |
|
564 | You can force auto-parentheses by using '/' as the first character | |
565 | of a line. For example: |
|
565 | of a line. For example: | |
566 | >>> /globals # becomes 'globals()' |
|
566 | >>> /globals # becomes 'globals()' | |
567 | Note that the '/' MUST be the first character on the line! This |
|
567 | Note that the '/' MUST be the first character on the line! This | |
568 | won't work: |
|
568 | won't work: | |
569 | >>> print /globals # syntax error |
|
569 | >>> print /globals # syntax error | |
570 |
|
570 | |||
571 | In most cases the automatic algorithm should work, so you should |
|
571 | In most cases the automatic algorithm should work, so you should | |
572 | rarely need to explicitly invoke /. One notable exception is if you |
|
572 | rarely need to explicitly invoke /. One notable exception is if you | |
573 | are trying to call a function with a list of tuples as arguments (the |
|
573 | are trying to call a function with a list of tuples as arguments (the | |
574 | parenthesis will confuse IPython): |
|
574 | parenthesis will confuse IPython): | |
575 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
575 | In [1]: zip (1,2,3),(4,5,6) # won't work | |
576 | but this will work: |
|
576 | but this will work: | |
577 | In [2]: /zip (1,2,3),(4,5,6) |
|
577 | In [2]: /zip (1,2,3),(4,5,6) | |
578 | ------> zip ((1,2,3),(4,5,6)) |
|
578 | ------> zip ((1,2,3),(4,5,6)) | |
579 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
579 | Out[2]= [(1, 4), (2, 5), (3, 6)] | |
580 |
|
580 | |||
581 | IPython tells you that it has altered your command line by |
|
581 | IPython tells you that it has altered your command line by | |
582 | displaying the new command line preceded by -->. e.g.: |
|
582 | displaying the new command line preceded by -->. e.g.: | |
583 | In [18]: callable list |
|
583 | In [18]: callable list | |
584 | -------> callable (list) |
|
584 | -------> callable (list) | |
585 |
|
585 | |||
586 | 2. Auto-Quoting |
|
586 | 2. Auto-Quoting | |
587 | You can force auto-quoting of a function's arguments by using ',' as |
|
587 | You can force auto-quoting of a function's arguments by using ',' as | |
588 | the first character of a line. For example: |
|
588 | the first character of a line. For example: | |
589 | >>> ,my_function /home/me # becomes my_function("/home/me") |
|
589 | >>> ,my_function /home/me # becomes my_function("/home/me") | |
590 |
|
590 | |||
591 | If you use ';' instead, the whole argument is quoted as a single |
|
591 | If you use ';' instead, the whole argument is quoted as a single | |
592 | string (while ',' splits on whitespace): |
|
592 | string (while ',' splits on whitespace): | |
593 | >>> ,my_function a b c # becomes my_function("a","b","c") |
|
593 | >>> ,my_function a b c # becomes my_function("a","b","c") | |
594 | >>> ;my_function a b c # becomes my_function("a b c") |
|
594 | >>> ;my_function a b c # becomes my_function("a b c") | |
595 |
|
595 | |||
596 | Note that the ',' MUST be the first character on the line! This |
|
596 | Note that the ',' MUST be the first character on the line! This | |
597 | won't work: |
|
597 | won't work: | |
598 | >>> x = ,my_function /home/me # syntax error |
|
598 | >>> x = ,my_function /home/me # syntax error | |
599 | """ |
|
599 | """ | |
600 |
|
600 | |||
601 | quick_reference = r""" |
|
601 | quick_reference = r""" | |
602 | IPython -- An enhanced Interactive Python - Quick Reference Card |
|
602 | IPython -- An enhanced Interactive Python - Quick Reference Card | |
603 | ================================================================ |
|
603 | ================================================================ | |
604 |
|
604 | |||
605 |
obj?, obj?? |
|
605 | obj?, obj?? : Get help, or more help for object (also works as | |
606 | ?os.p* : List names in os starting with p |
|
606 | ?obj, ??obj). | |
|
607 | ?foo.*abc* : List names in 'foo' containing 'abc' in them. | |||
|
608 | %magic : Information about IPython's 'magic' % functions. | |||
607 |
|
609 | |||
608 | Magic functions are prefixed by %, and typically take their arguments without |
|
610 | Magic functions are prefixed by %, and typically take their arguments without | |
609 | parentheses, quotes or even commas for convenience. |
|
611 | parentheses, quotes or even commas for convenience. | |
610 |
|
612 | |||
611 | Example magic function calls: |
|
613 | Example magic function calls: | |
612 |
|
614 | |||
613 | %alias d ls -F : 'd' is now an alias for 'ls -F' |
|
615 | %alias d ls -F : 'd' is now an alias for 'ls -F' | |
614 | alias d ls -F : Works if 'alias' not a python name |
|
616 | alias d ls -F : Works if 'alias' not a python name | |
615 | alist = %alias : Get list of aliases to 'alist' |
|
617 | alist = %alias : Get list of aliases to 'alist' | |
616 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. |
|
618 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. | |
617 | %cd?? : See help AND source for magic %cd |
|
619 | %cd?? : See help AND source for magic %cd | |
618 |
|
620 | |||
619 | System commands: |
|
621 | System commands: | |
620 |
|
622 | |||
621 | !cp a.txt b/ : System command escape, calls os.system() |
|
623 | !cp a.txt b/ : System command escape, calls os.system() | |
622 | cp a.txt b/ : after %rehashx, most system commands work without ! |
|
624 | cp a.txt b/ : after %rehashx, most system commands work without ! | |
623 | cp ${f}.txt $bar : Variable expansion in magics and system commands |
|
625 | cp ${f}.txt $bar : Variable expansion in magics and system commands | |
624 | files = !ls /usr : Capture sytem command output |
|
626 | files = !ls /usr : Capture sytem command output | |
625 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' |
|
627 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' | |
626 |
|
628 | |||
627 | History: |
|
629 | History: | |
628 |
|
630 | |||
629 | _i, _ii, _iii : Previous, next previous, next next previous input |
|
631 | _i, _ii, _iii : Previous, next previous, next next previous input | |
630 | _i4, _ih[2:5] : Input history line 4, lines 2-4 |
|
632 | _i4, _ih[2:5] : Input history line 4, lines 2-4 | |
631 | exec _i81 : Execute input history line #81 again |
|
633 | exec _i81 : Execute input history line #81 again | |
632 | %rep 81 : Edit input history line #81 |
|
634 | %rep 81 : Edit input history line #81 | |
633 | _, __, ___ : previous, next previous, next next previous output |
|
635 | _, __, ___ : previous, next previous, next next previous output | |
634 | _dh : Directory history |
|
636 | _dh : Directory history | |
635 | _oh : Output history |
|
637 | _oh : Output history | |
636 | %hist : Command history. '%hist -g foo' search history for 'foo' |
|
638 | %hist : Command history. '%hist -g foo' search history for 'foo' | |
637 |
|
639 | |||
638 | Autocall: |
|
640 | Autocall: | |
639 |
|
641 | |||
640 | f 1,2 : f(1,2) |
|
642 | f 1,2 : f(1,2) | |
641 | /f 1,2 : f(1,2) (forced autoparen) |
|
643 | /f 1,2 : f(1,2) (forced autoparen) | |
642 | ,f 1 2 : f("1","2") |
|
644 | ,f 1 2 : f("1","2") | |
643 | ;f 1 2 : f("1 2") |
|
645 | ;f 1 2 : f("1 2") | |
644 |
|
646 | |||
645 | Remember: TAB completion works in many contexts, not just file names |
|
647 | Remember: TAB completion works in many contexts, not just file names | |
646 | or python names. |
|
648 | or python names. | |
647 |
|
649 | |||
648 | The following magic functions are currently available: |
|
650 | The following magic functions are currently available: | |
649 |
|
651 | |||
650 | """ |
|
652 | """ | |
651 |
|
653 | |||
652 |
|
654 |
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
General Comments 0
You need to be logged in to leave comments.
Login now