##// END OF EJS Templates
moved many magics to ipy_legacy.py, moved profiles to Extension from UserConfig, added ipy_profile_none.py for default profile
vivainio -
Show More
@@ -0,0 +1,251 b''
1 """ Legacy stuff
2
3 Various stuff that are there for historical / familiarity reasons.
4
5 This is automatically imported by default profile, though not other profiles
6 (e.g. 'sh' profile).
7
8 Stuff that is considered obsolete / redundant is gradually moved here.
9
10 """
11
12 import IPython.ipapi
13 ip = IPython.ipapi.get()
14
15 import os,sys
16
17 from IPython.genutils import *
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
72
73 def magic_rehash(self, parameter_s = ''):
74 """Update the alias table with all entries in $PATH.
75
76 This version does no checks on execute permissions or whether the
77 contents of $PATH are truly files (instead of directories or something
78 else). For such a safer (but slower) version, use %rehashx."""
79
80 # This function (and rehashx) manipulate the alias_table directly
81 # rather than calling magic_alias, for speed reasons. A rehash on a
82 # typical Linux box involves several thousand entries, so efficiency
83 # here is a top concern.
84
85 path = filter(os.path.isdir,os.environ.get('PATH','').split(os.pathsep))
86 alias_table = self.shell.alias_table
87 for pdir in path:
88 for ff in os.listdir(pdir):
89 # each entry in the alias table must be (N,name), where
90 # N is the number of positional arguments of the alias.
91 alias_table[ff] = (0,ff)
92 # Make sure the alias table doesn't contain keywords or builtins
93 self.shell.alias_table_validate()
94 # Call again init_auto_alias() so we get 'rm -i' and other modified
95 # aliases since %rehash will probably clobber them
96 self.shell.init_auto_alias()
97
98 ip.expose_magic("rehash", magic_rehash)
99
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
135 def magic_Quit(self, parameter_s=''):
136 """Exit IPython without confirmation (like %Exit)."""
137
138 self.shell.exit_now = True
139
140 ip.expose_magic("Quit", magic_Quit)
141
142
143 # make it autocallable fn if you really need it
144 def magic_p(self, parameter_s=''):
145 """Just a short alias for Python's 'print'."""
146 exec 'print ' + parameter_s in self.shell.user_ns
147
148 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) No newline at end of file
@@ -0,0 +1,4 b''
1 """ Config file for 'default' profile """
2
3 # get various stuff that are there for historical / familiarity reasons
4 import ipy_legacy No newline at end of file
1 NO CONTENT: file renamed from IPython/UserConfig/ipy_profile_scipy.py to IPython/Extensions/ipy_profile_scipy.py
NO CONTENT: file renamed from IPython/UserConfig/ipy_profile_scipy.py to IPython/Extensions/ipy_profile_scipy.py
1 NO CONTENT: file renamed from IPython/UserConfig/ipy_profile_sh.py to IPython/Extensions/ipy_profile_sh.py
NO CONTENT: file renamed from IPython/UserConfig/ipy_profile_sh.py to IPython/Extensions/ipy_profile_sh.py
@@ -1,3137 +1,2944 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 2353 2007-05-15 19:27:14Z vivainio $"""
4 $Id: Magic.py 2380 2007-05-24 17:03:49Z vivainio $"""
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
38
39 # cProfile was added in Python2.5
39 # cProfile was added in Python2.5
40 try:
40 try:
41 import cProfile as profile
41 import cProfile as profile
42 import pstats
42 import pstats
43 except ImportError:
43 except ImportError:
44 # profile isn't bundled by default in Debian for license reasons
44 # profile isn't bundled by default in Debian for license reasons
45 try:
45 try:
46 import profile,pstats
46 import profile,pstats
47 except ImportError:
47 except ImportError:
48 profile = pstats = None
48 profile = pstats = None
49
49
50 # Homebrewed
50 # Homebrewed
51 import IPython
51 import IPython
52 from IPython import Debugger, OInspect, wildcard
52 from IPython import Debugger, OInspect, wildcard
53 from IPython.FakeModule import FakeModule
53 from IPython.FakeModule import FakeModule
54 from IPython.Itpl import Itpl, itpl, printpl,itplns
54 from IPython.Itpl import Itpl, itpl, printpl,itplns
55 from IPython.PyColorize import Parser
55 from IPython.PyColorize import Parser
56 from IPython.ipstruct import Struct
56 from IPython.ipstruct import Struct
57 from IPython.macro import Macro
57 from IPython.macro import Macro
58 from IPython.genutils import *
58 from IPython.genutils import *
59 from IPython import platutils
59 from IPython import platutils
60
60
61 #***************************************************************************
61 #***************************************************************************
62 # Utility functions
62 # Utility functions
63 def on_off(tag):
63 def on_off(tag):
64 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
64 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
65 return ['OFF','ON'][tag]
65 return ['OFF','ON'][tag]
66
66
67 class Bunch: pass
67 class Bunch: pass
68
68
69 #***************************************************************************
69 #***************************************************************************
70 # Main class implementing Magic functionality
70 # Main class implementing Magic functionality
71 class Magic:
71 class Magic:
72 """Magic functions for InteractiveShell.
72 """Magic functions for InteractiveShell.
73
73
74 Shell functions which can be reached as %function_name. All magic
74 Shell functions which can be reached as %function_name. All magic
75 functions should accept a string, which they can parse for their own
75 functions should accept a string, which they can parse for their own
76 needs. This can make some functions easier to type, eg `%cd ../`
76 needs. This can make some functions easier to type, eg `%cd ../`
77 vs. `%cd("../")`
77 vs. `%cd("../")`
78
78
79 ALL definitions MUST begin with the prefix magic_. The user won't need it
79 ALL definitions MUST begin with the prefix magic_. The user won't need it
80 at the command line, but it is is needed in the definition. """
80 at the command line, but it is is needed in the definition. """
81
81
82 # class globals
82 # class globals
83 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
83 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
84 'Automagic is ON, % prefix NOT needed for magic functions.']
84 'Automagic is ON, % prefix NOT needed for magic functions.']
85
85
86 #......................................................................
86 #......................................................................
87 # some utility functions
87 # some utility functions
88
88
89 def __init__(self,shell):
89 def __init__(self,shell):
90
90
91 self.options_table = {}
91 self.options_table = {}
92 if profile is None:
92 if profile is None:
93 self.magic_prun = self.profile_missing_notice
93 self.magic_prun = self.profile_missing_notice
94 self.shell = shell
94 self.shell = shell
95
95
96 # namespace for holding state we may need
96 # namespace for holding state we may need
97 self._magic_state = Bunch()
97 self._magic_state = Bunch()
98
98
99 def profile_missing_notice(self, *args, **kwargs):
99 def profile_missing_notice(self, *args, **kwargs):
100 error("""\
100 error("""\
101 The profile module could not be found. If you are a Debian user,
101 The profile module could not be found. If you are a Debian user,
102 it has been removed from the standard Debian package because of its non-free
102 it has been removed from the standard Debian package because of its non-free
103 license. To use profiling, please install"python2.3-profiler" from non-free.""")
103 license. To use profiling, please install"python2.3-profiler" from non-free.""")
104
104
105 def default_option(self,fn,optstr):
105 def default_option(self,fn,optstr):
106 """Make an entry in the options_table for fn, with value optstr"""
106 """Make an entry in the options_table for fn, with value optstr"""
107
107
108 if fn not in self.lsmagic():
108 if fn not in self.lsmagic():
109 error("%s is not a magic function" % fn)
109 error("%s is not a magic function" % fn)
110 self.options_table[fn] = optstr
110 self.options_table[fn] = optstr
111
111
112 def lsmagic(self):
112 def lsmagic(self):
113 """Return a list of currently available magic functions.
113 """Return a list of currently available magic functions.
114
114
115 Gives a list of the bare names after mangling (['ls','cd', ...], not
115 Gives a list of the bare names after mangling (['ls','cd', ...], not
116 ['magic_ls','magic_cd',...]"""
116 ['magic_ls','magic_cd',...]"""
117
117
118 # FIXME. This needs a cleanup, in the way the magics list is built.
118 # FIXME. This needs a cleanup, in the way the magics list is built.
119
119
120 # magics in class definition
120 # magics in class definition
121 class_magic = lambda fn: fn.startswith('magic_') and \
121 class_magic = lambda fn: fn.startswith('magic_') and \
122 callable(Magic.__dict__[fn])
122 callable(Magic.__dict__[fn])
123 # in instance namespace (run-time user additions)
123 # in instance namespace (run-time user additions)
124 inst_magic = lambda fn: fn.startswith('magic_') and \
124 inst_magic = lambda fn: fn.startswith('magic_') and \
125 callable(self.__dict__[fn])
125 callable(self.__dict__[fn])
126 # and bound magics by user (so they can access self):
126 # and bound magics by user (so they can access self):
127 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
127 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
128 callable(self.__class__.__dict__[fn])
128 callable(self.__class__.__dict__[fn])
129 magics = filter(class_magic,Magic.__dict__.keys()) + \
129 magics = filter(class_magic,Magic.__dict__.keys()) + \
130 filter(inst_magic,self.__dict__.keys()) + \
130 filter(inst_magic,self.__dict__.keys()) + \
131 filter(inst_bound_magic,self.__class__.__dict__.keys())
131 filter(inst_bound_magic,self.__class__.__dict__.keys())
132 out = []
132 out = []
133 for fn in magics:
133 for fn in magics:
134 out.append(fn.replace('magic_','',1))
134 out.append(fn.replace('magic_','',1))
135 out.sort()
135 out.sort()
136 return out
136 return out
137
137
138 def extract_input_slices(self,slices,raw=False):
138 def extract_input_slices(self,slices,raw=False):
139 """Return as a string a set of input history slices.
139 """Return as a string a set of input history slices.
140
140
141 Inputs:
141 Inputs:
142
142
143 - slices: the set of slices is given as a list of strings (like
143 - slices: the set of slices is given as a list of strings (like
144 ['1','4:8','9'], since this function is for use by magic functions
144 ['1','4:8','9'], since this function is for use by magic functions
145 which get their arguments as strings.
145 which get their arguments as strings.
146
146
147 Optional inputs:
147 Optional inputs:
148
148
149 - raw(False): by default, the processed input is used. If this is
149 - raw(False): by default, the processed input is used. If this is
150 true, the raw input history is used instead.
150 true, the raw input history is used instead.
151
151
152 Note that slices can be called with two notations:
152 Note that slices can be called with two notations:
153
153
154 N:M -> standard python form, means including items N...(M-1).
154 N:M -> standard python form, means including items N...(M-1).
155
155
156 N-M -> include items N..M (closed endpoint)."""
156 N-M -> include items N..M (closed endpoint)."""
157
157
158 if raw:
158 if raw:
159 hist = self.shell.input_hist_raw
159 hist = self.shell.input_hist_raw
160 else:
160 else:
161 hist = self.shell.input_hist
161 hist = self.shell.input_hist
162
162
163 cmds = []
163 cmds = []
164 for chunk in slices:
164 for chunk in slices:
165 if ':' in chunk:
165 if ':' in chunk:
166 ini,fin = map(int,chunk.split(':'))
166 ini,fin = map(int,chunk.split(':'))
167 elif '-' in chunk:
167 elif '-' in chunk:
168 ini,fin = map(int,chunk.split('-'))
168 ini,fin = map(int,chunk.split('-'))
169 fin += 1
169 fin += 1
170 else:
170 else:
171 ini = int(chunk)
171 ini = int(chunk)
172 fin = ini+1
172 fin = ini+1
173 cmds.append(hist[ini:fin])
173 cmds.append(hist[ini:fin])
174 return cmds
174 return cmds
175
175
176 def _ofind(self, oname, namespaces=None):
176 def _ofind(self, oname, namespaces=None):
177 """Find an object in the available namespaces.
177 """Find an object in the available namespaces.
178
178
179 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
179 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
180
180
181 Has special code to detect magic functions.
181 Has special code to detect magic functions.
182 """
182 """
183
183
184 oname = oname.strip()
184 oname = oname.strip()
185
185
186 alias_ns = None
186 alias_ns = None
187 if namespaces is None:
187 if namespaces is None:
188 # Namespaces to search in:
188 # Namespaces to search in:
189 # Put them in a list. The order is important so that we
189 # Put them in a list. The order is important so that we
190 # find things in the same order that Python finds them.
190 # find things in the same order that Python finds them.
191 namespaces = [ ('Interactive', self.shell.user_ns),
191 namespaces = [ ('Interactive', self.shell.user_ns),
192 ('IPython internal', self.shell.internal_ns),
192 ('IPython internal', self.shell.internal_ns),
193 ('Python builtin', __builtin__.__dict__),
193 ('Python builtin', __builtin__.__dict__),
194 ('Alias', self.shell.alias_table),
194 ('Alias', self.shell.alias_table),
195 ]
195 ]
196 alias_ns = self.shell.alias_table
196 alias_ns = self.shell.alias_table
197
197
198 # initialize results to 'null'
198 # initialize results to 'null'
199 found = 0; obj = None; ospace = None; ds = None;
199 found = 0; obj = None; ospace = None; ds = None;
200 ismagic = 0; isalias = 0; parent = None
200 ismagic = 0; isalias = 0; parent = None
201
201
202 # Look for the given name by splitting it in parts. If the head is
202 # Look for the given name by splitting it in parts. If the head is
203 # found, then we look for all the remaining parts as members, and only
203 # found, then we look for all the remaining parts as members, and only
204 # declare success if we can find them all.
204 # declare success if we can find them all.
205 oname_parts = oname.split('.')
205 oname_parts = oname.split('.')
206 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
206 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
207 for nsname,ns in namespaces:
207 for nsname,ns in namespaces:
208 try:
208 try:
209 obj = ns[oname_head]
209 obj = ns[oname_head]
210 except KeyError:
210 except KeyError:
211 continue
211 continue
212 else:
212 else:
213 #print 'oname_rest:', oname_rest # dbg
213 #print 'oname_rest:', oname_rest # dbg
214 for part in oname_rest:
214 for part in oname_rest:
215 try:
215 try:
216 parent = obj
216 parent = obj
217 obj = getattr(obj,part)
217 obj = getattr(obj,part)
218 except:
218 except:
219 # Blanket except b/c some badly implemented objects
219 # Blanket except b/c some badly implemented objects
220 # allow __getattr__ to raise exceptions other than
220 # allow __getattr__ to raise exceptions other than
221 # AttributeError, which then crashes IPython.
221 # AttributeError, which then crashes IPython.
222 break
222 break
223 else:
223 else:
224 # If we finish the for loop (no break), we got all members
224 # If we finish the for loop (no break), we got all members
225 found = 1
225 found = 1
226 ospace = nsname
226 ospace = nsname
227 if ns == alias_ns:
227 if ns == alias_ns:
228 isalias = 1
228 isalias = 1
229 break # namespace loop
229 break # namespace loop
230
230
231 # Try to see if it's magic
231 # Try to see if it's magic
232 if not found:
232 if not found:
233 if oname.startswith(self.shell.ESC_MAGIC):
233 if oname.startswith(self.shell.ESC_MAGIC):
234 oname = oname[1:]
234 oname = oname[1:]
235 obj = getattr(self,'magic_'+oname,None)
235 obj = getattr(self,'magic_'+oname,None)
236 if obj is not None:
236 if obj is not None:
237 found = 1
237 found = 1
238 ospace = 'IPython internal'
238 ospace = 'IPython internal'
239 ismagic = 1
239 ismagic = 1
240
240
241 # Last try: special-case some literals like '', [], {}, etc:
241 # Last try: special-case some literals like '', [], {}, etc:
242 if not found and oname_head in ["''",'""','[]','{}','()']:
242 if not found and oname_head in ["''",'""','[]','{}','()']:
243 obj = eval(oname_head)
243 obj = eval(oname_head)
244 found = 1
244 found = 1
245 ospace = 'Interactive'
245 ospace = 'Interactive'
246
246
247 return {'found':found, 'obj':obj, 'namespace':ospace,
247 return {'found':found, 'obj':obj, 'namespace':ospace,
248 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
248 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
249
249
250 def arg_err(self,func):
250 def arg_err(self,func):
251 """Print docstring if incorrect arguments were passed"""
251 """Print docstring if incorrect arguments were passed"""
252 print 'Error in arguments:'
252 print 'Error in arguments:'
253 print OInspect.getdoc(func)
253 print OInspect.getdoc(func)
254
254
255 def format_latex(self,strng):
255 def format_latex(self,strng):
256 """Format a string for latex inclusion."""
256 """Format a string for latex inclusion."""
257
257
258 # Characters that need to be escaped for latex:
258 # Characters that need to be escaped for latex:
259 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
259 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
260 # Magic command names as headers:
260 # Magic command names as headers:
261 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
261 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
262 re.MULTILINE)
262 re.MULTILINE)
263 # Magic commands
263 # Magic commands
264 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
264 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
265 re.MULTILINE)
265 re.MULTILINE)
266 # Paragraph continue
266 # Paragraph continue
267 par_re = re.compile(r'\\$',re.MULTILINE)
267 par_re = re.compile(r'\\$',re.MULTILINE)
268
268
269 # The "\n" symbol
269 # The "\n" symbol
270 newline_re = re.compile(r'\\n')
270 newline_re = re.compile(r'\\n')
271
271
272 # Now build the string for output:
272 # Now build the string for output:
273 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
273 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
274 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
274 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
275 strng)
275 strng)
276 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
276 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
277 strng = par_re.sub(r'\\\\',strng)
277 strng = par_re.sub(r'\\\\',strng)
278 strng = escape_re.sub(r'\\\1',strng)
278 strng = escape_re.sub(r'\\\1',strng)
279 strng = newline_re.sub(r'\\textbackslash{}n',strng)
279 strng = newline_re.sub(r'\\textbackslash{}n',strng)
280 return strng
280 return strng
281
281
282 def format_screen(self,strng):
282 def format_screen(self,strng):
283 """Format a string for screen printing.
283 """Format a string for screen printing.
284
284
285 This removes some latex-type format codes."""
285 This removes some latex-type format codes."""
286 # Paragraph continue
286 # Paragraph continue
287 par_re = re.compile(r'\\$',re.MULTILINE)
287 par_re = re.compile(r'\\$',re.MULTILINE)
288 strng = par_re.sub('',strng)
288 strng = par_re.sub('',strng)
289 return strng
289 return strng
290
290
291 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
291 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
292 """Parse options passed to an argument string.
292 """Parse options passed to an argument string.
293
293
294 The interface is similar to that of getopt(), but it returns back a
294 The interface is similar to that of getopt(), but it returns back a
295 Struct with the options as keys and the stripped argument string still
295 Struct with the options as keys and the stripped argument string still
296 as a string.
296 as a string.
297
297
298 arg_str is quoted as a true sys.argv vector by using shlex.split.
298 arg_str is quoted as a true sys.argv vector by using shlex.split.
299 This allows us to easily expand variables, glob files, quote
299 This allows us to easily expand variables, glob files, quote
300 arguments, etc.
300 arguments, etc.
301
301
302 Options:
302 Options:
303 -mode: default 'string'. If given as 'list', the argument string is
303 -mode: default 'string'. If given as 'list', the argument string is
304 returned as a list (split on whitespace) instead of a string.
304 returned as a list (split on whitespace) instead of a string.
305
305
306 -list_all: put all option values in lists. Normally only options
306 -list_all: put all option values in lists. Normally only options
307 appearing more than once are put in a list.
307 appearing more than once are put in a list.
308
308
309 -posix (True): whether to split the input line in POSIX mode or not,
309 -posix (True): whether to split the input line in POSIX mode or not,
310 as per the conventions outlined in the shlex module from the
310 as per the conventions outlined in the shlex module from the
311 standard library."""
311 standard library."""
312
312
313 # inject default options at the beginning of the input line
313 # inject default options at the beginning of the input line
314 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
314 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
315 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
315 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
316
316
317 mode = kw.get('mode','string')
317 mode = kw.get('mode','string')
318 if mode not in ['string','list']:
318 if mode not in ['string','list']:
319 raise ValueError,'incorrect mode given: %s' % mode
319 raise ValueError,'incorrect mode given: %s' % mode
320 # Get options
320 # Get options
321 list_all = kw.get('list_all',0)
321 list_all = kw.get('list_all',0)
322 posix = kw.get('posix',True)
322 posix = kw.get('posix',True)
323
323
324 # Check if we have more than one argument to warrant extra processing:
324 # Check if we have more than one argument to warrant extra processing:
325 odict = {} # Dictionary with options
325 odict = {} # Dictionary with options
326 args = arg_str.split()
326 args = arg_str.split()
327 if len(args) >= 1:
327 if len(args) >= 1:
328 # If the list of inputs only has 0 or 1 thing in it, there's no
328 # If the list of inputs only has 0 or 1 thing in it, there's no
329 # need to look for options
329 # need to look for options
330 argv = arg_split(arg_str,posix)
330 argv = arg_split(arg_str,posix)
331 # Do regular option processing
331 # Do regular option processing
332 try:
332 try:
333 opts,args = getopt(argv,opt_str,*long_opts)
333 opts,args = getopt(argv,opt_str,*long_opts)
334 except GetoptError,e:
334 except GetoptError,e:
335 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
335 raise GetoptError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
336 " ".join(long_opts)))
336 " ".join(long_opts)))
337 for o,a in opts:
337 for o,a in opts:
338 if o.startswith('--'):
338 if o.startswith('--'):
339 o = o[2:]
339 o = o[2:]
340 else:
340 else:
341 o = o[1:]
341 o = o[1:]
342 try:
342 try:
343 odict[o].append(a)
343 odict[o].append(a)
344 except AttributeError:
344 except AttributeError:
345 odict[o] = [odict[o],a]
345 odict[o] = [odict[o],a]
346 except KeyError:
346 except KeyError:
347 if list_all:
347 if list_all:
348 odict[o] = [a]
348 odict[o] = [a]
349 else:
349 else:
350 odict[o] = a
350 odict[o] = a
351
351
352 # Prepare opts,args for return
352 # Prepare opts,args for return
353 opts = Struct(odict)
353 opts = Struct(odict)
354 if mode == 'string':
354 if mode == 'string':
355 args = ' '.join(args)
355 args = ' '.join(args)
356
356
357 return opts,args
357 return opts,args
358
358
359 #......................................................................
359 #......................................................................
360 # And now the actual magic functions
360 # And now the actual magic functions
361
361
362 # Functions for IPython shell work (vars,funcs, config, etc)
362 # Functions for IPython shell work (vars,funcs, config, etc)
363 def magic_lsmagic(self, parameter_s = ''):
363 def magic_lsmagic(self, parameter_s = ''):
364 """List currently available magic functions."""
364 """List currently available magic functions."""
365 mesc = self.shell.ESC_MAGIC
365 mesc = self.shell.ESC_MAGIC
366 print 'Available magic functions:\n'+mesc+\
366 print 'Available magic functions:\n'+mesc+\
367 (' '+mesc).join(self.lsmagic())
367 (' '+mesc).join(self.lsmagic())
368 print '\n' + Magic.auto_status[self.shell.rc.automagic]
368 print '\n' + Magic.auto_status[self.shell.rc.automagic]
369 return None
369 return None
370
370
371 def magic_magic(self, parameter_s = ''):
371 def magic_magic(self, parameter_s = ''):
372 """Print information about the magic function system."""
372 """Print information about the magic function system."""
373
373
374 mode = ''
374 mode = ''
375 try:
375 try:
376 if parameter_s.split()[0] == '-latex':
376 if parameter_s.split()[0] == '-latex':
377 mode = 'latex'
377 mode = 'latex'
378 if parameter_s.split()[0] == '-brief':
378 if parameter_s.split()[0] == '-brief':
379 mode = 'brief'
379 mode = 'brief'
380 except:
380 except:
381 pass
381 pass
382
382
383 magic_docs = []
383 magic_docs = []
384 for fname in self.lsmagic():
384 for fname in self.lsmagic():
385 mname = 'magic_' + fname
385 mname = 'magic_' + fname
386 for space in (Magic,self,self.__class__):
386 for space in (Magic,self,self.__class__):
387 try:
387 try:
388 fn = space.__dict__[mname]
388 fn = space.__dict__[mname]
389 except KeyError:
389 except KeyError:
390 pass
390 pass
391 else:
391 else:
392 break
392 break
393 if mode == 'brief':
393 if mode == 'brief':
394 # only first line
394 # only first line
395 fndoc = fn.__doc__.split('\n',1)[0]
395 fndoc = fn.__doc__.split('\n',1)[0]
396 else:
396 else:
397 fndoc = fn.__doc__
397 fndoc = fn.__doc__
398
398
399 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
399 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
400 fname,fndoc))
400 fname,fndoc))
401 magic_docs = ''.join(magic_docs)
401 magic_docs = ''.join(magic_docs)
402
402
403 if mode == 'latex':
403 if mode == 'latex':
404 print self.format_latex(magic_docs)
404 print self.format_latex(magic_docs)
405 return
405 return
406 else:
406 else:
407 magic_docs = self.format_screen(magic_docs)
407 magic_docs = self.format_screen(magic_docs)
408 if mode == 'brief':
408 if mode == 'brief':
409 return magic_docs
409 return magic_docs
410
410
411 outmsg = """
411 outmsg = """
412 IPython's 'magic' functions
412 IPython's 'magic' functions
413 ===========================
413 ===========================
414
414
415 The magic function system provides a series of functions which allow you to
415 The magic function system provides a series of functions which allow you to
416 control the behavior of IPython itself, plus a lot of system-type
416 control the behavior of IPython itself, plus a lot of system-type
417 features. All these functions are prefixed with a % character, but parameters
417 features. All these functions are prefixed with a % character, but parameters
418 are given without parentheses or quotes.
418 are given without parentheses or quotes.
419
419
420 NOTE: If you have 'automagic' enabled (via the command line option or with the
420 NOTE: If you have 'automagic' enabled (via the command line option or with the
421 %automagic function), you don't need to type in the % explicitly. By default,
421 %automagic function), you don't need to type in the % explicitly. By default,
422 IPython ships with automagic on, so you should only rarely need the % escape.
422 IPython ships with automagic on, so you should only rarely need the % escape.
423
423
424 Example: typing '%cd mydir' (without the quotes) changes you working directory
424 Example: typing '%cd mydir' (without the quotes) changes you working directory
425 to 'mydir', if it exists.
425 to 'mydir', if it exists.
426
426
427 You can define your own magic functions to extend the system. See the supplied
427 You can define your own magic functions to extend the system. See the supplied
428 ipythonrc and example-magic.py files for details (in your ipython
428 ipythonrc and example-magic.py files for details (in your ipython
429 configuration directory, typically $HOME/.ipython/).
429 configuration directory, typically $HOME/.ipython/).
430
430
431 You can also define your own aliased names for magic functions. In your
431 You can also define your own aliased names for magic functions. In your
432 ipythonrc file, placing a line like:
432 ipythonrc file, placing a line like:
433
433
434 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
434 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
435
435
436 will define %pf as a new name for %profile.
436 will define %pf as a new name for %profile.
437
437
438 You can also call magics in code using the ipmagic() function, which IPython
438 You can also call magics in code using the ipmagic() function, which IPython
439 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
439 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
440
440
441 For a list of the available magic functions, use %lsmagic. For a description
441 For a list of the available magic functions, use %lsmagic. For a description
442 of any of them, type %magic_name?, e.g. '%cd?'.
442 of any of them, type %magic_name?, e.g. '%cd?'.
443
443
444 Currently the magic system has the following functions:\n"""
444 Currently the magic system has the following functions:\n"""
445
445
446 mesc = self.shell.ESC_MAGIC
446 mesc = self.shell.ESC_MAGIC
447 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
447 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
448 "\n\n%s%s\n\n%s" % (outmsg,
448 "\n\n%s%s\n\n%s" % (outmsg,
449 magic_docs,mesc,mesc,
449 magic_docs,mesc,mesc,
450 (' '+mesc).join(self.lsmagic()),
450 (' '+mesc).join(self.lsmagic()),
451 Magic.auto_status[self.shell.rc.automagic] ) )
451 Magic.auto_status[self.shell.rc.automagic] ) )
452
452
453 page(outmsg,screen_lines=self.shell.rc.screen_length)
453 page(outmsg,screen_lines=self.shell.rc.screen_length)
454
454
455 def magic_automagic(self, parameter_s = ''):
456 """Make magic functions callable without having to type the initial %.
457
458 Without argumentsl toggles on/off (when off, you must call it as
459 %automagic, of course). With arguments it sets the value, and you can
460 use any of (case insensitive):
461
462 - on,1,True: to activate
463
464 - off,0,False: to deactivate.
465
466 Note that magic functions have lowest priority, so if there's a
467 variable whose name collides with that of a magic fn, automagic won't
468 work for that function (you get the variable instead). However, if you
469 delete the variable (del var), the previously shadowed magic function
470 becomes visible to automagic again."""
471
472 rc = self.shell.rc
473 arg = parameter_s.lower()
474 if parameter_s in ('on','1','true'):
475 rc.automagic = True
476 elif parameter_s in ('off','0','false'):
477 rc.automagic = False
478 else:
479 rc.automagic = not rc.automagic
480 print '\n' + Magic.auto_status[rc.automagic]
481
482 def magic_autocall(self, parameter_s = ''):
483 """Make functions callable without having to type parentheses.
484
485 Usage:
486
487 %autocall [mode]
488
489 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
490 value is toggled on and off (remembering the previous state)."""
491
492 rc = self.shell.rc
493
494 if parameter_s:
495 arg = int(parameter_s)
496 else:
497 arg = 'toggle'
498
499 if not arg in (0,1,2,'toggle'):
500 error('Valid modes: (0->Off, 1->Smart, 2->Full')
501 return
502
503 if arg in (0,1,2):
504 rc.autocall = arg
505 else: # toggle
506 if rc.autocall:
507 self._magic_state.autocall_save = rc.autocall
508 rc.autocall = 0
509 else:
510 try:
511 rc.autocall = self._magic_state.autocall_save
512 except AttributeError:
513 rc.autocall = self._magic_state.autocall_save = 1
514
515 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
516
455
517 def magic_autoindent(self, parameter_s = ''):
456 def magic_autoindent(self, parameter_s = ''):
518 """Toggle autoindent on/off (if available)."""
457 """Toggle autoindent on/off (if available)."""
519
458
520 self.shell.set_autoindent()
459 self.shell.set_autoindent()
521 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
460 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
522
461
523 def magic_system_verbose(self, parameter_s = ''):
462 def magic_system_verbose(self, parameter_s = ''):
524 """Set verbose printing of system calls.
463 """Set verbose printing of system calls.
525
464
526 If called without an argument, act as a toggle"""
465 If called without an argument, act as a toggle"""
527
466
528 if parameter_s:
467 if parameter_s:
529 val = bool(eval(parameter_s))
468 val = bool(eval(parameter_s))
530 else:
469 else:
531 val = None
470 val = None
532
471
533 self.shell.rc_set_toggle('system_verbose',val)
472 self.shell.rc_set_toggle('system_verbose',val)
534 print "System verbose printing is:",\
473 print "System verbose printing is:",\
535 ['OFF','ON'][self.shell.rc.system_verbose]
474 ['OFF','ON'][self.shell.rc.system_verbose]
536
475
537 def magic_history(self, parameter_s = ''):
476 def magic_history(self, parameter_s = ''):
538 """Print input history (_i<n> variables), with most recent last.
477 """Print input history (_i<n> variables), with most recent last.
539
478
540 %history -> print at most 40 inputs (some may be multi-line)\\
479 %history -> print at most 40 inputs (some may be multi-line)\\
541 %history n -> print at most n inputs\\
480 %history n -> print at most n inputs\\
542 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
481 %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
543
482
544 Each input's number <n> is shown, and is accessible as the
483 Each input's number <n> is shown, and is accessible as the
545 automatically generated variable _i<n>. Multi-line statements are
484 automatically generated variable _i<n>. Multi-line statements are
546 printed starting at a new line for easy copy/paste.
485 printed starting at a new line for easy copy/paste.
547
486
548
487
549 Options:
488 Options:
550
489
551 -n: do NOT print line numbers. This is useful if you want to get a
490 -n: do NOT print line numbers. This is useful if you want to get a
552 printout of many lines which can be directly pasted into a text
491 printout of many lines which can be directly pasted into a text
553 editor.
492 editor.
554
493
555 This feature is only available if numbered prompts are in use.
494 This feature is only available if numbered prompts are in use.
556
495
557 -r: print the 'raw' history. IPython filters your input and
496 -n: print the 'native' history, as IPython understands it. IPython
558 converts it all into valid Python source before executing it (things
497 filters your input and converts it all into valid Python source before
559 like magics or aliases are turned into function calls, for
498 executing it (things like magics or aliases are turned into function
560 example). With this option, you'll see the unfiltered history
499 calls, for example). With this option, you'll see the native history
561 instead of the filtered version: '%cd /' will be seen as '%cd /'
500 instead of the user-entered version: '%cd /' will be seen as
562 instead of '_ip.magic("%cd /")'.
501 '_ip.magic("%cd /")' instead of '%cd /'.
563 """
502 """
564
503
565 shell = self.shell
504 shell = self.shell
566 if not shell.outputcache.do_full_cache:
505 if not shell.outputcache.do_full_cache:
567 print 'This feature is only available if numbered prompts are in use.'
506 print 'This feature is only available if numbered prompts are in use.'
568 return
507 return
569 opts,args = self.parse_options(parameter_s,'nr',mode='list')
508 opts,args = self.parse_options(parameter_s,'nr',mode='list')
570
509
571 if opts.has_key('r'):
510 if not opts.has_key('n'):
572 input_hist = shell.input_hist_raw
511 input_hist = shell.input_hist_raw
573 else:
512 else:
574 input_hist = shell.input_hist
513 input_hist = shell.input_hist
575
514
576 default_length = 40
515 default_length = 40
577 if len(args) == 0:
516 if len(args) == 0:
578 final = len(input_hist)
517 final = len(input_hist)
579 init = max(1,final-default_length)
518 init = max(1,final-default_length)
580 elif len(args) == 1:
519 elif len(args) == 1:
581 final = len(input_hist)
520 final = len(input_hist)
582 init = max(1,final-int(args[0]))
521 init = max(1,final-int(args[0]))
583 elif len(args) == 2:
522 elif len(args) == 2:
584 init,final = map(int,args)
523 init,final = map(int,args)
585 else:
524 else:
586 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
525 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
587 print self.magic_hist.__doc__
526 print self.magic_hist.__doc__
588 return
527 return
589 width = len(str(final))
528 width = len(str(final))
590 line_sep = ['','\n']
529 line_sep = ['','\n']
591 print_nums = not opts.has_key('n')
530 print_nums = not opts.has_key('n')
592 for in_num in range(init,final):
531 for in_num in range(init,final):
593 inline = input_hist[in_num]
532 inline = input_hist[in_num]
594 multiline = int(inline.count('\n') > 1)
533 multiline = int(inline.count('\n') > 1)
595 if print_nums:
534 if print_nums:
596 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
535 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
597 print inline,
536 print inline,
598
537
599 def magic_hist(self, parameter_s=''):
538 def magic_hist(self, parameter_s=''):
600 """Alternate name for %history."""
539 """Alternate name for %history."""
601 return self.magic_history(parameter_s)
540 return self.magic_history(parameter_s)
602
541
603 def magic_p(self, parameter_s=''):
604 """Just a short alias for Python's 'print'."""
605 exec 'print ' + parameter_s in self.shell.user_ns
606
607 def magic_r(self, parameter_s=''):
608 """Repeat previous input.
609
610 If given an argument, repeats the previous command which starts with
611 the same string, otherwise it just repeats the previous input.
612
613 Shell escaped commands (with ! as first character) are not recognized
614 by this system, only pure python code and magic commands.
615 """
616
617 start = parameter_s.strip()
618 esc_magic = self.shell.ESC_MAGIC
619 # Identify magic commands even if automagic is on (which means
620 # the in-memory version is different from that typed by the user).
621 if self.shell.rc.automagic:
622 start_magic = esc_magic+start
623 else:
624 start_magic = start
625 # Look through the input history in reverse
626 for n in range(len(self.shell.input_hist)-2,0,-1):
627 input = self.shell.input_hist[n]
628 # skip plain 'r' lines so we don't recurse to infinity
629 if input != '_ip.magic("r")\n' and \
630 (input.startswith(start) or input.startswith(start_magic)):
631 #print 'match',`input` # dbg
632 print 'Executing:',input,
633 self.shell.runlines(input)
634 return
635 print 'No previous input matching `%s` found.' % start
636
542
637 def magic_page(self, parameter_s=''):
543 def magic_page(self, parameter_s=''):
638 """Pretty print the object and display it through a pager.
544 """Pretty print the object and display it through a pager.
639
545
640 %page [options] OBJECT
546 %page [options] OBJECT
641
547
642 If no object is given, use _ (last output).
548 If no object is given, use _ (last output).
643
549
644 Options:
550 Options:
645
551
646 -r: page str(object), don't pretty-print it."""
552 -r: page str(object), don't pretty-print it."""
647
553
648 # After a function contributed by Olivier Aubert, slightly modified.
554 # After a function contributed by Olivier Aubert, slightly modified.
649
555
650 # Process options/args
556 # Process options/args
651 opts,args = self.parse_options(parameter_s,'r')
557 opts,args = self.parse_options(parameter_s,'r')
652 raw = 'r' in opts
558 raw = 'r' in opts
653
559
654 oname = args and args or '_'
560 oname = args and args or '_'
655 info = self._ofind(oname)
561 info = self._ofind(oname)
656 if info['found']:
562 if info['found']:
657 txt = (raw and str or pformat)( info['obj'] )
563 txt = (raw and str or pformat)( info['obj'] )
658 page(txt)
564 page(txt)
659 else:
565 else:
660 print 'Object `%s` not found' % oname
566 print 'Object `%s` not found' % oname
661
567
662 def magic_profile(self, parameter_s=''):
568 def magic_profile(self, parameter_s=''):
663 """Print your currently active IPyhton profile."""
569 """Print your currently active IPyhton profile."""
664 if self.shell.rc.profile:
570 if self.shell.rc.profile:
665 printpl('Current IPython profile: $self.shell.rc.profile.')
571 printpl('Current IPython profile: $self.shell.rc.profile.')
666 else:
572 else:
667 print 'No profile active.'
573 print 'No profile active.'
574
575 def magic_pinfo(self, parameter_s='', namespaces=None):
576 """Provide detailed information about an object.
577
578 '%pinfo object' is just a synonym for object? or ?object."""
579
580 #print 'pinfo par: <%s>' % parameter_s # dbg
581
582 # detail_level: 0 -> obj? , 1 -> obj??
583 detail_level = 0
584 # We need to detect if we got called as 'pinfo pinfo foo', which can
585 # happen if the user types 'pinfo foo?' at the cmd line.
586 pinfo,qmark1,oname,qmark2 = \
587 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
588 if pinfo or qmark1 or qmark2:
589 detail_level = 1
590 if "*" in oname:
591 self.magic_psearch(oname)
592 else:
593 self._inspect('pinfo', oname, detail_level=detail_level,
594 namespaces=namespaces)
668
595
669 def _inspect(self,meth,oname,namespaces=None,**kw):
596 def _inspect(self,meth,oname,namespaces=None,**kw):
670 """Generic interface to the inspector system.
597 """Generic interface to the inspector system.
671
598
672 This function is meant to be called by pdef, pdoc & friends."""
599 This function is meant to be called by pdef, pdoc & friends."""
673
600
674 #oname = oname.strip()
601 #oname = oname.strip()
675 #print '1- oname: <%r>' % oname # dbg
602 #print '1- oname: <%r>' % oname # dbg
676 try:
603 try:
677 oname = oname.strip().encode('ascii')
604 oname = oname.strip().encode('ascii')
678 #print '2- oname: <%r>' % oname # dbg
605 #print '2- oname: <%r>' % oname # dbg
679 except UnicodeEncodeError:
606 except UnicodeEncodeError:
680 print 'Python identifiers can only contain ascii characters.'
607 print 'Python identifiers can only contain ascii characters.'
681 return 'not found'
608 return 'not found'
682
609
683 info = Struct(self._ofind(oname, namespaces))
610 info = Struct(self._ofind(oname, namespaces))
684
611
685 if info.found:
612 if info.found:
686 # Get the docstring of the class property if it exists.
613 # Get the docstring of the class property if it exists.
687 path = oname.split('.')
614 path = oname.split('.')
688 root = '.'.join(path[:-1])
615 root = '.'.join(path[:-1])
689 if info.parent is not None:
616 if info.parent is not None:
690 try:
617 try:
691 target = getattr(info.parent, '__class__')
618 target = getattr(info.parent, '__class__')
692 # The object belongs to a class instance.
619 # The object belongs to a class instance.
693 try:
620 try:
694 target = getattr(target, path[-1])
621 target = getattr(target, path[-1])
695 # The class defines the object.
622 # The class defines the object.
696 if isinstance(target, property):
623 if isinstance(target, property):
697 oname = root + '.__class__.' + path[-1]
624 oname = root + '.__class__.' + path[-1]
698 info = Struct(self._ofind(oname))
625 info = Struct(self._ofind(oname))
699 except AttributeError: pass
626 except AttributeError: pass
700 except AttributeError: pass
627 except AttributeError: pass
701
628
702 pmethod = getattr(self.shell.inspector,meth)
629 pmethod = getattr(self.shell.inspector,meth)
703 formatter = info.ismagic and self.format_screen or None
630 formatter = info.ismagic and self.format_screen or None
704 if meth == 'pdoc':
631 if meth == 'pdoc':
705 pmethod(info.obj,oname,formatter)
632 pmethod(info.obj,oname,formatter)
706 elif meth == 'pinfo':
633 elif meth == 'pinfo':
707 pmethod(info.obj,oname,formatter,info,**kw)
634 pmethod(info.obj,oname,formatter,info,**kw)
708 else:
635 else:
709 pmethod(info.obj,oname)
636 pmethod(info.obj,oname)
710 else:
637 else:
711 print 'Object `%s` not found.' % oname
638 print 'Object `%s` not found.' % oname
712 return 'not found' # so callers can take other action
639 return 'not found' # so callers can take other action
713
640
714 def magic_pdef(self, parameter_s='', namespaces=None):
715 """Print the definition header for any callable object.
716
717 If the object is a class, print the constructor information."""
718 self._inspect('pdef',parameter_s, namespaces)
719
720 def magic_pdoc(self, parameter_s='', namespaces=None):
721 """Print the docstring for an object.
722
723 If the given object is a class, it will print both the class and the
724 constructor docstrings."""
725 self._inspect('pdoc',parameter_s, namespaces)
726
727 def magic_psource(self, parameter_s='', namespaces=None):
728 """Print (or run through pager) the source code for an object."""
729 self._inspect('psource',parameter_s, namespaces)
730
731 def magic_pfile(self, parameter_s=''):
732 """Print (or run through pager) the file where an object is defined.
733
734 The file opens at the line where the object definition begins. IPython
735 will honor the environment variable PAGER if set, and otherwise will
736 do its best to print the file in a convenient form.
737
738 If the given argument is not an object currently defined, IPython will
739 try to interpret it as a filename (automatically adding a .py extension
740 if needed). You can thus use %pfile as a syntax highlighting code
741 viewer."""
742
743 # first interpret argument as an object name
744 out = self._inspect('pfile',parameter_s)
745 # if not, try the input as a filename
746 if out == 'not found':
747 try:
748 filename = get_py_filename(parameter_s)
749 except IOError,msg:
750 print msg
751 return
752 page(self.shell.inspector.format(file(filename).read()))
753
754 def magic_pinfo(self, parameter_s='', namespaces=None):
755 """Provide detailed information about an object.
756
757 '%pinfo object' is just a synonym for object? or ?object."""
758
759 #print 'pinfo par: <%s>' % parameter_s # dbg
760
761 # detail_level: 0 -> obj? , 1 -> obj??
762 detail_level = 0
763 # We need to detect if we got called as 'pinfo pinfo foo', which can
764 # happen if the user types 'pinfo foo?' at the cmd line.
765 pinfo,qmark1,oname,qmark2 = \
766 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
767 if pinfo or qmark1 or qmark2:
768 detail_level = 1
769 if "*" in oname:
770 self.magic_psearch(oname)
771 else:
772 self._inspect('pinfo', oname, detail_level=detail_level,
773 namespaces=namespaces)
774
775 def magic_psearch(self, parameter_s=''):
641 def magic_psearch(self, parameter_s=''):
776 """Search for object in namespaces by wildcard.
642 """Search for object in namespaces by wildcard.
777
643
778 %psearch [options] PATTERN [OBJECT TYPE]
644 %psearch [options] PATTERN [OBJECT TYPE]
779
645
780 Note: ? can be used as a synonym for %psearch, at the beginning or at
646 Note: ? can be used as a synonym for %psearch, at the beginning or at
781 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
647 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
782 rest of the command line must be unchanged (options come first), so
648 rest of the command line must be unchanged (options come first), so
783 for example the following forms are equivalent
649 for example the following forms are equivalent
784
650
785 %psearch -i a* function
651 %psearch -i a* function
786 -i a* function?
652 -i a* function?
787 ?-i a* function
653 ?-i a* function
788
654
789 Arguments:
655 Arguments:
790
656
791 PATTERN
657 PATTERN
792
658
793 where PATTERN is a string containing * as a wildcard similar to its
659 where PATTERN is a string containing * as a wildcard similar to its
794 use in a shell. The pattern is matched in all namespaces on the
660 use in a shell. The pattern is matched in all namespaces on the
795 search path. By default objects starting with a single _ are not
661 search path. By default objects starting with a single _ are not
796 matched, many IPython generated objects have a single
662 matched, many IPython generated objects have a single
797 underscore. The default is case insensitive matching. Matching is
663 underscore. The default is case insensitive matching. Matching is
798 also done on the attributes of objects and not only on the objects
664 also done on the attributes of objects and not only on the objects
799 in a module.
665 in a module.
800
666
801 [OBJECT TYPE]
667 [OBJECT TYPE]
802
668
803 Is the name of a python type from the types module. The name is
669 Is the name of a python type from the types module. The name is
804 given in lowercase without the ending type, ex. StringType is
670 given in lowercase without the ending type, ex. StringType is
805 written string. By adding a type here only objects matching the
671 written string. By adding a type here only objects matching the
806 given type are matched. Using all here makes the pattern match all
672 given type are matched. Using all here makes the pattern match all
807 types (this is the default).
673 types (this is the default).
808
674
809 Options:
675 Options:
810
676
811 -a: makes the pattern match even objects whose names start with a
677 -a: makes the pattern match even objects whose names start with a
812 single underscore. These names are normally ommitted from the
678 single underscore. These names are normally ommitted from the
813 search.
679 search.
814
680
815 -i/-c: make the pattern case insensitive/sensitive. If neither of
681 -i/-c: make the pattern case insensitive/sensitive. If neither of
816 these options is given, the default is read from your ipythonrc
682 these options is given, the default is read from your ipythonrc
817 file. The option name which sets this value is
683 file. The option name which sets this value is
818 'wildcards_case_sensitive'. If this option is not specified in your
684 'wildcards_case_sensitive'. If this option is not specified in your
819 ipythonrc file, IPython's internal default is to do a case sensitive
685 ipythonrc file, IPython's internal default is to do a case sensitive
820 search.
686 search.
821
687
822 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
688 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
823 specifiy can be searched in any of the following namespaces:
689 specifiy can be searched in any of the following namespaces:
824 'builtin', 'user', 'user_global','internal', 'alias', where
690 'builtin', 'user', 'user_global','internal', 'alias', where
825 'builtin' and 'user' are the search defaults. Note that you should
691 'builtin' and 'user' are the search defaults. Note that you should
826 not use quotes when specifying namespaces.
692 not use quotes when specifying namespaces.
827
693
828 'Builtin' contains the python module builtin, 'user' contains all
694 'Builtin' contains the python module builtin, 'user' contains all
829 user data, 'alias' only contain the shell aliases and no python
695 user data, 'alias' only contain the shell aliases and no python
830 objects, 'internal' contains objects used by IPython. The
696 objects, 'internal' contains objects used by IPython. The
831 'user_global' namespace is only used by embedded IPython instances,
697 'user_global' namespace is only used by embedded IPython instances,
832 and it contains module-level globals. You can add namespaces to the
698 and it contains module-level globals. You can add namespaces to the
833 search with -s or exclude them with -e (these options can be given
699 search with -s or exclude them with -e (these options can be given
834 more than once).
700 more than once).
835
701
836 Examples:
702 Examples:
837
703
838 %psearch a* -> objects beginning with an a
704 %psearch a* -> objects beginning with an a
839 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
705 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
840 %psearch a* function -> all functions beginning with an a
706 %psearch a* function -> all functions beginning with an a
841 %psearch re.e* -> objects beginning with an e in module re
707 %psearch re.e* -> objects beginning with an e in module re
842 %psearch r*.e* -> objects that start with e in modules starting in r
708 %psearch r*.e* -> objects that start with e in modules starting in r
843 %psearch r*.* string -> all strings in modules beginning with r
709 %psearch r*.* string -> all strings in modules beginning with r
844
710
845 Case sensitve search:
711 Case sensitve search:
846
712
847 %psearch -c a* list all object beginning with lower case a
713 %psearch -c a* list all object beginning with lower case a
848
714
849 Show objects beginning with a single _:
715 Show objects beginning with a single _:
850
716
851 %psearch -a _* list objects beginning with a single underscore"""
717 %psearch -a _* list objects beginning with a single underscore"""
852 try:
718 try:
853 parameter_s = parameter_s.encode('ascii')
719 parameter_s = parameter_s.encode('ascii')
854 except UnicodeEncodeError:
720 except UnicodeEncodeError:
855 print 'Python identifiers can only contain ascii characters.'
721 print 'Python identifiers can only contain ascii characters.'
856 return
722 return
857
723
858 # default namespaces to be searched
724 # default namespaces to be searched
859 def_search = ['user','builtin']
725 def_search = ['user','builtin']
860
726
861 # Process options/args
727 # Process options/args
862 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
728 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
863 opt = opts.get
729 opt = opts.get
864 shell = self.shell
730 shell = self.shell
865 psearch = shell.inspector.psearch
731 psearch = shell.inspector.psearch
866
732
867 # select case options
733 # select case options
868 if opts.has_key('i'):
734 if opts.has_key('i'):
869 ignore_case = True
735 ignore_case = True
870 elif opts.has_key('c'):
736 elif opts.has_key('c'):
871 ignore_case = False
737 ignore_case = False
872 else:
738 else:
873 ignore_case = not shell.rc.wildcards_case_sensitive
739 ignore_case = not shell.rc.wildcards_case_sensitive
874
740
875 # Build list of namespaces to search from user options
741 # Build list of namespaces to search from user options
876 def_search.extend(opt('s',[]))
742 def_search.extend(opt('s',[]))
877 ns_exclude = ns_exclude=opt('e',[])
743 ns_exclude = ns_exclude=opt('e',[])
878 ns_search = [nm for nm in def_search if nm not in ns_exclude]
744 ns_search = [nm for nm in def_search if nm not in ns_exclude]
879
745
880 # Call the actual search
746 # Call the actual search
881 try:
747 try:
882 psearch(args,shell.ns_table,ns_search,
748 psearch(args,shell.ns_table,ns_search,
883 show_all=opt('a'),ignore_case=ignore_case)
749 show_all=opt('a'),ignore_case=ignore_case)
884 except:
750 except:
885 shell.showtraceback()
751 shell.showtraceback()
886
752
887 def magic_who_ls(self, parameter_s=''):
753 def magic_who_ls(self, parameter_s=''):
888 """Return a sorted list of all interactive variables.
754 """Return a sorted list of all interactive variables.
889
755
890 If arguments are given, only variables of types matching these
756 If arguments are given, only variables of types matching these
891 arguments are returned."""
757 arguments are returned."""
892
758
893 user_ns = self.shell.user_ns
759 user_ns = self.shell.user_ns
894 internal_ns = self.shell.internal_ns
760 internal_ns = self.shell.internal_ns
895 user_config_ns = self.shell.user_config_ns
761 user_config_ns = self.shell.user_config_ns
896 out = []
762 out = []
897 typelist = parameter_s.split()
763 typelist = parameter_s.split()
898
764
899 for i in user_ns:
765 for i in user_ns:
900 if not (i.startswith('_') or i.startswith('_i')) \
766 if not (i.startswith('_') or i.startswith('_i')) \
901 and not (i in internal_ns or i in user_config_ns):
767 and not (i in internal_ns or i in user_config_ns):
902 if typelist:
768 if typelist:
903 if type(user_ns[i]).__name__ in typelist:
769 if type(user_ns[i]).__name__ in typelist:
904 out.append(i)
770 out.append(i)
905 else:
771 else:
906 out.append(i)
772 out.append(i)
907 out.sort()
773 out.sort()
908 return out
774 return out
909
775
910 def magic_who(self, parameter_s=''):
776 def magic_who(self, parameter_s=''):
911 """Print all interactive variables, with some minimal formatting.
777 """Print all interactive variables, with some minimal formatting.
912
778
913 If any arguments are given, only variables whose type matches one of
779 If any arguments are given, only variables whose type matches one of
914 these are printed. For example:
780 these are printed. For example:
915
781
916 %who function str
782 %who function str
917
783
918 will only list functions and strings, excluding all other types of
784 will only list functions and strings, excluding all other types of
919 variables. To find the proper type names, simply use type(var) at a
785 variables. To find the proper type names, simply use type(var) at a
920 command line to see how python prints type names. For example:
786 command line to see how python prints type names. For example:
921
787
922 In [1]: type('hello')\\
788 In [1]: type('hello')\\
923 Out[1]: <type 'str'>
789 Out[1]: <type 'str'>
924
790
925 indicates that the type name for strings is 'str'.
791 indicates that the type name for strings is 'str'.
926
792
927 %who always excludes executed names loaded through your configuration
793 %who always excludes executed names loaded through your configuration
928 file and things which are internal to IPython.
794 file and things which are internal to IPython.
929
795
930 This is deliberate, as typically you may load many modules and the
796 This is deliberate, as typically you may load many modules and the
931 purpose of %who is to show you only what you've manually defined."""
797 purpose of %who is to show you only what you've manually defined."""
932
798
933 varlist = self.magic_who_ls(parameter_s)
799 varlist = self.magic_who_ls(parameter_s)
934 if not varlist:
800 if not varlist:
935 if parameter_s:
801 if parameter_s:
936 print 'No variables match your requested type.'
802 print 'No variables match your requested type.'
937 else:
803 else:
938 print 'Interactive namespace is empty.'
804 print 'Interactive namespace is empty.'
939 return
805 return
940
806
941 # if we have variables, move on...
807 # if we have variables, move on...
942 count = 0
808 count = 0
943 for i in varlist:
809 for i in varlist:
944 print i+'\t',
810 print i+'\t',
945 count += 1
811 count += 1
946 if count > 8:
812 if count > 8:
947 count = 0
813 count = 0
948 print
814 print
949 print
815 print
950
816
951 def magic_whos(self, parameter_s=''):
817 def magic_whos(self, parameter_s=''):
952 """Like %who, but gives some extra information about each variable.
818 """Like %who, but gives some extra information about each variable.
953
819
954 The same type filtering of %who can be applied here.
820 The same type filtering of %who can be applied here.
955
821
956 For all variables, the type is printed. Additionally it prints:
822 For all variables, the type is printed. Additionally it prints:
957
823
958 - For {},[],(): their length.
824 - For {},[],(): their length.
959
825
960 - For numpy and Numeric arrays, a summary with shape, number of
826 - For numpy and Numeric arrays, a summary with shape, number of
961 elements, typecode and size in memory.
827 elements, typecode and size in memory.
962
828
963 - Everything else: a string representation, snipping their middle if
829 - Everything else: a string representation, snipping their middle if
964 too long."""
830 too long."""
965
831
966 varnames = self.magic_who_ls(parameter_s)
832 varnames = self.magic_who_ls(parameter_s)
967 if not varnames:
833 if not varnames:
968 if parameter_s:
834 if parameter_s:
969 print 'No variables match your requested type.'
835 print 'No variables match your requested type.'
970 else:
836 else:
971 print 'Interactive namespace is empty.'
837 print 'Interactive namespace is empty.'
972 return
838 return
973
839
974 # if we have variables, move on...
840 # if we have variables, move on...
975
841
976 # for these types, show len() instead of data:
842 # for these types, show len() instead of data:
977 seq_types = [types.DictType,types.ListType,types.TupleType]
843 seq_types = [types.DictType,types.ListType,types.TupleType]
978
844
979 # for numpy/Numeric arrays, display summary info
845 # for numpy/Numeric arrays, display summary info
980 try:
846 try:
981 import numpy
847 import numpy
982 except ImportError:
848 except ImportError:
983 ndarray_type = None
849 ndarray_type = None
984 else:
850 else:
985 ndarray_type = numpy.ndarray.__name__
851 ndarray_type = numpy.ndarray.__name__
986 try:
852 try:
987 import Numeric
853 import Numeric
988 except ImportError:
854 except ImportError:
989 array_type = None
855 array_type = None
990 else:
856 else:
991 array_type = Numeric.ArrayType.__name__
857 array_type = Numeric.ArrayType.__name__
992
858
993 # Find all variable names and types so we can figure out column sizes
859 # Find all variable names and types so we can figure out column sizes
994 def get_vars(i):
860 def get_vars(i):
995 return self.shell.user_ns[i]
861 return self.shell.user_ns[i]
996
862
997 # some types are well known and can be shorter
863 # some types are well known and can be shorter
998 abbrevs = {'IPython.macro.Macro' : 'Macro'}
864 abbrevs = {'IPython.macro.Macro' : 'Macro'}
999 def type_name(v):
865 def type_name(v):
1000 tn = type(v).__name__
866 tn = type(v).__name__
1001 return abbrevs.get(tn,tn)
867 return abbrevs.get(tn,tn)
1002
868
1003 varlist = map(get_vars,varnames)
869 varlist = map(get_vars,varnames)
1004
870
1005 typelist = []
871 typelist = []
1006 for vv in varlist:
872 for vv in varlist:
1007 tt = type_name(vv)
873 tt = type_name(vv)
1008
874
1009 if tt=='instance':
875 if tt=='instance':
1010 typelist.append( abbrevs.get(str(vv.__class__),
876 typelist.append( abbrevs.get(str(vv.__class__),
1011 str(vv.__class__)))
877 str(vv.__class__)))
1012 else:
878 else:
1013 typelist.append(tt)
879 typelist.append(tt)
1014
880
1015 # column labels and # of spaces as separator
881 # column labels and # of spaces as separator
1016 varlabel = 'Variable'
882 varlabel = 'Variable'
1017 typelabel = 'Type'
883 typelabel = 'Type'
1018 datalabel = 'Data/Info'
884 datalabel = 'Data/Info'
1019 colsep = 3
885 colsep = 3
1020 # variable format strings
886 # variable format strings
1021 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
887 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1022 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
888 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1023 aformat = "%s: %s elems, type `%s`, %s bytes"
889 aformat = "%s: %s elems, type `%s`, %s bytes"
1024 # find the size of the columns to format the output nicely
890 # find the size of the columns to format the output nicely
1025 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
891 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1026 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
892 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1027 # table header
893 # table header
1028 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
894 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1029 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
895 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1030 # and the table itself
896 # and the table itself
1031 kb = 1024
897 kb = 1024
1032 Mb = 1048576 # kb**2
898 Mb = 1048576 # kb**2
1033 for vname,var,vtype in zip(varnames,varlist,typelist):
899 for vname,var,vtype in zip(varnames,varlist,typelist):
1034 print itpl(vformat),
900 print itpl(vformat),
1035 if vtype in seq_types:
901 if vtype in seq_types:
1036 print len(var)
902 print len(var)
1037 elif vtype in [array_type,ndarray_type]:
903 elif vtype in [array_type,ndarray_type]:
1038 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
904 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1039 if vtype==ndarray_type:
905 if vtype==ndarray_type:
1040 # numpy
906 # numpy
1041 vsize = var.size
907 vsize = var.size
1042 vbytes = vsize*var.itemsize
908 vbytes = vsize*var.itemsize
1043 vdtype = var.dtype
909 vdtype = var.dtype
1044 else:
910 else:
1045 # Numeric
911 # Numeric
1046 vsize = Numeric.size(var)
912 vsize = Numeric.size(var)
1047 vbytes = vsize*var.itemsize()
913 vbytes = vsize*var.itemsize()
1048 vdtype = var.typecode()
914 vdtype = var.typecode()
1049
915
1050 if vbytes < 100000:
916 if vbytes < 100000:
1051 print aformat % (vshape,vsize,vdtype,vbytes)
917 print aformat % (vshape,vsize,vdtype,vbytes)
1052 else:
918 else:
1053 print aformat % (vshape,vsize,vdtype,vbytes),
919 print aformat % (vshape,vsize,vdtype,vbytes),
1054 if vbytes < Mb:
920 if vbytes < Mb:
1055 print '(%s kb)' % (vbytes/kb,)
921 print '(%s kb)' % (vbytes/kb,)
1056 else:
922 else:
1057 print '(%s Mb)' % (vbytes/Mb,)
923 print '(%s Mb)' % (vbytes/Mb,)
1058 else:
924 else:
1059 try:
925 try:
1060 vstr = str(var)
926 vstr = str(var)
1061 except UnicodeEncodeError:
927 except UnicodeEncodeError:
1062 vstr = unicode(var).encode(sys.getdefaultencoding(),
928 vstr = unicode(var).encode(sys.getdefaultencoding(),
1063 'backslashreplace')
929 'backslashreplace')
1064 vstr = vstr.replace('\n','\\n')
930 vstr = vstr.replace('\n','\\n')
1065 if len(vstr) < 50:
931 if len(vstr) < 50:
1066 print vstr
932 print vstr
1067 else:
933 else:
1068 printpl(vfmt_short)
934 printpl(vfmt_short)
1069
935
1070 def magic_reset(self, parameter_s=''):
936 def magic_reset(self, parameter_s=''):
1071 """Resets the namespace by removing all names defined by the user.
937 """Resets the namespace by removing all names defined by the user.
1072
938
1073 Input/Output history are left around in case you need them."""
939 Input/Output history are left around in case you need them."""
1074
940
1075 ans = self.shell.ask_yes_no(
941 ans = self.shell.ask_yes_no(
1076 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
942 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1077 if not ans:
943 if not ans:
1078 print 'Nothing done.'
944 print 'Nothing done.'
1079 return
945 return
1080 user_ns = self.shell.user_ns
946 user_ns = self.shell.user_ns
1081 for i in self.magic_who_ls():
947 for i in self.magic_who_ls():
1082 del(user_ns[i])
948 del(user_ns[i])
1083
949
1084 def magic_logstart(self,parameter_s=''):
950 def magic_logstart(self,parameter_s=''):
1085 """Start logging anywhere in a session.
951 """Start logging anywhere in a session.
1086
952
1087 %logstart [-o|-r|-t] [log_name [log_mode]]
953 %logstart [-o|-r|-t] [log_name [log_mode]]
1088
954
1089 If no name is given, it defaults to a file named 'ipython_log.py' in your
955 If no name is given, it defaults to a file named 'ipython_log.py' in your
1090 current directory, in 'rotate' mode (see below).
956 current directory, in 'rotate' mode (see below).
1091
957
1092 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
958 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1093 history up to that point and then continues logging.
959 history up to that point and then continues logging.
1094
960
1095 %logstart takes a second optional parameter: logging mode. This can be one
961 %logstart takes a second optional parameter: logging mode. This can be one
1096 of (note that the modes are given unquoted):\\
962 of (note that the modes are given unquoted):\\
1097 append: well, that says it.\\
963 append: well, that says it.\\
1098 backup: rename (if exists) to name~ and start name.\\
964 backup: rename (if exists) to name~ and start name.\\
1099 global: single logfile in your home dir, appended to.\\
965 global: single logfile in your home dir, appended to.\\
1100 over : overwrite existing log.\\
966 over : overwrite existing log.\\
1101 rotate: create rotating logs name.1~, name.2~, etc.
967 rotate: create rotating logs name.1~, name.2~, etc.
1102
968
1103 Options:
969 Options:
1104
970
1105 -o: log also IPython's output. In this mode, all commands which
971 -o: log also IPython's output. In this mode, all commands which
1106 generate an Out[NN] prompt are recorded to the logfile, right after
972 generate an Out[NN] prompt are recorded to the logfile, right after
1107 their corresponding input line. The output lines are always
973 their corresponding input line. The output lines are always
1108 prepended with a '#[Out]# ' marker, so that the log remains valid
974 prepended with a '#[Out]# ' marker, so that the log remains valid
1109 Python code.
975 Python code.
1110
976
1111 Since this marker is always the same, filtering only the output from
977 Since this marker is always the same, filtering only the output from
1112 a log is very easy, using for example a simple awk call:
978 a log is very easy, using for example a simple awk call:
1113
979
1114 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
980 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1115
981
1116 -r: log 'raw' input. Normally, IPython's logs contain the processed
982 -r: log 'raw' input. Normally, IPython's logs contain the processed
1117 input, so that user lines are logged in their final form, converted
983 input, so that user lines are logged in their final form, converted
1118 into valid Python. For example, %Exit is logged as
984 into valid Python. For example, %Exit is logged as
1119 '_ip.magic("Exit"). If the -r flag is given, all input is logged
985 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1120 exactly as typed, with no transformations applied.
986 exactly as typed, with no transformations applied.
1121
987
1122 -t: put timestamps before each input line logged (these are put in
988 -t: put timestamps before each input line logged (these are put in
1123 comments)."""
989 comments)."""
1124
990
1125 opts,par = self.parse_options(parameter_s,'ort')
991 opts,par = self.parse_options(parameter_s,'ort')
1126 log_output = 'o' in opts
992 log_output = 'o' in opts
1127 log_raw_input = 'r' in opts
993 log_raw_input = 'r' in opts
1128 timestamp = 't' in opts
994 timestamp = 't' in opts
1129
995
1130 rc = self.shell.rc
996 rc = self.shell.rc
1131 logger = self.shell.logger
997 logger = self.shell.logger
1132
998
1133 # if no args are given, the defaults set in the logger constructor by
999 # if no args are given, the defaults set in the logger constructor by
1134 # ipytohn remain valid
1000 # ipytohn remain valid
1135 if par:
1001 if par:
1136 try:
1002 try:
1137 logfname,logmode = par.split()
1003 logfname,logmode = par.split()
1138 except:
1004 except:
1139 logfname = par
1005 logfname = par
1140 logmode = 'backup'
1006 logmode = 'backup'
1141 else:
1007 else:
1142 logfname = logger.logfname
1008 logfname = logger.logfname
1143 logmode = logger.logmode
1009 logmode = logger.logmode
1144 # put logfname into rc struct as if it had been called on the command
1010 # put logfname into rc struct as if it had been called on the command
1145 # line, so it ends up saved in the log header Save it in case we need
1011 # line, so it ends up saved in the log header Save it in case we need
1146 # to restore it...
1012 # to restore it...
1147 old_logfile = rc.opts.get('logfile','')
1013 old_logfile = rc.opts.get('logfile','')
1148 if logfname:
1014 if logfname:
1149 logfname = os.path.expanduser(logfname)
1015 logfname = os.path.expanduser(logfname)
1150 rc.opts.logfile = logfname
1016 rc.opts.logfile = logfname
1151 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1017 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1152 try:
1018 try:
1153 started = logger.logstart(logfname,loghead,logmode,
1019 started = logger.logstart(logfname,loghead,logmode,
1154 log_output,timestamp,log_raw_input)
1020 log_output,timestamp,log_raw_input)
1155 except:
1021 except:
1156 rc.opts.logfile = old_logfile
1022 rc.opts.logfile = old_logfile
1157 warn("Couldn't start log: %s" % sys.exc_info()[1])
1023 warn("Couldn't start log: %s" % sys.exc_info()[1])
1158 else:
1024 else:
1159 # log input history up to this point, optionally interleaving
1025 # log input history up to this point, optionally interleaving
1160 # output if requested
1026 # output if requested
1161
1027
1162 if timestamp:
1028 if timestamp:
1163 # disable timestamping for the previous history, since we've
1029 # disable timestamping for the previous history, since we've
1164 # lost those already (no time machine here).
1030 # lost those already (no time machine here).
1165 logger.timestamp = False
1031 logger.timestamp = False
1166
1032
1167 if log_raw_input:
1033 if log_raw_input:
1168 input_hist = self.shell.input_hist_raw
1034 input_hist = self.shell.input_hist_raw
1169 else:
1035 else:
1170 input_hist = self.shell.input_hist
1036 input_hist = self.shell.input_hist
1171
1037
1172 if log_output:
1038 if log_output:
1173 log_write = logger.log_write
1039 log_write = logger.log_write
1174 output_hist = self.shell.output_hist
1040 output_hist = self.shell.output_hist
1175 for n in range(1,len(input_hist)-1):
1041 for n in range(1,len(input_hist)-1):
1176 log_write(input_hist[n].rstrip())
1042 log_write(input_hist[n].rstrip())
1177 if n in output_hist:
1043 if n in output_hist:
1178 log_write(repr(output_hist[n]),'output')
1044 log_write(repr(output_hist[n]),'output')
1179 else:
1045 else:
1180 logger.log_write(input_hist[1:])
1046 logger.log_write(input_hist[1:])
1181 if timestamp:
1047 if timestamp:
1182 # re-enable timestamping
1048 # re-enable timestamping
1183 logger.timestamp = True
1049 logger.timestamp = True
1184
1050
1185 print ('Activating auto-logging. '
1051 print ('Activating auto-logging. '
1186 'Current session state plus future input saved.')
1052 'Current session state plus future input saved.')
1187 logger.logstate()
1053 logger.logstate()
1188
1054
1189 def magic_logoff(self,parameter_s=''):
1055 def magic_logoff(self,parameter_s=''):
1190 """Temporarily stop logging.
1056 """Temporarily stop logging.
1191
1057
1192 You must have previously started logging."""
1058 You must have previously started logging."""
1193 self.shell.logger.switch_log(0)
1059 self.shell.logger.switch_log(0)
1194
1060
1195 def magic_logon(self,parameter_s=''):
1061 def magic_logon(self,parameter_s=''):
1196 """Restart logging.
1062 """Restart logging.
1197
1063
1198 This function is for restarting logging which you've temporarily
1064 This function is for restarting logging which you've temporarily
1199 stopped with %logoff. For starting logging for the first time, you
1065 stopped with %logoff. For starting logging for the first time, you
1200 must use the %logstart function, which allows you to specify an
1066 must use the %logstart function, which allows you to specify an
1201 optional log filename."""
1067 optional log filename."""
1202
1068
1203 self.shell.logger.switch_log(1)
1069 self.shell.logger.switch_log(1)
1204
1070
1205 def magic_logstate(self,parameter_s=''):
1071 def magic_logstate(self,parameter_s=''):
1206 """Print the status of the logging system."""
1072 """Print the status of the logging system."""
1207
1073
1208 self.shell.logger.logstate()
1074 self.shell.logger.logstate()
1209
1075
1210 def magic_pdb(self, parameter_s=''):
1076 def magic_pdb(self, parameter_s=''):
1211 """Control the automatic calling of the pdb interactive debugger.
1077 """Control the automatic calling of the pdb interactive debugger.
1212
1078
1213 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1079 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1214 argument it works as a toggle.
1080 argument it works as a toggle.
1215
1081
1216 When an exception is triggered, IPython can optionally call the
1082 When an exception is triggered, IPython can optionally call the
1217 interactive pdb debugger after the traceback printout. %pdb toggles
1083 interactive pdb debugger after the traceback printout. %pdb toggles
1218 this feature on and off.
1084 this feature on and off.
1219
1085
1220 The initial state of this feature is set in your ipythonrc
1086 The initial state of this feature is set in your ipythonrc
1221 configuration file (the variable is called 'pdb').
1087 configuration file (the variable is called 'pdb').
1222
1088
1223 If you want to just activate the debugger AFTER an exception has fired,
1089 If you want to just activate the debugger AFTER an exception has fired,
1224 without having to type '%pdb on' and rerunning your code, you can use
1090 without having to type '%pdb on' and rerunning your code, you can use
1225 the %debug magic."""
1091 the %debug magic."""
1226
1092
1227 par = parameter_s.strip().lower()
1093 par = parameter_s.strip().lower()
1228
1094
1229 if par:
1095 if par:
1230 try:
1096 try:
1231 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1097 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1232 except KeyError:
1098 except KeyError:
1233 print ('Incorrect argument. Use on/1, off/0, '
1099 print ('Incorrect argument. Use on/1, off/0, '
1234 'or nothing for a toggle.')
1100 'or nothing for a toggle.')
1235 return
1101 return
1236 else:
1102 else:
1237 # toggle
1103 # toggle
1238 new_pdb = not self.shell.call_pdb
1104 new_pdb = not self.shell.call_pdb
1239
1105
1240 # set on the shell
1106 # set on the shell
1241 self.shell.call_pdb = new_pdb
1107 self.shell.call_pdb = new_pdb
1242 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1108 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1243
1109
1244 def magic_debug(self, parameter_s=''):
1110 def magic_debug(self, parameter_s=''):
1245 """Activate the interactive debugger in post-mortem mode.
1111 """Activate the interactive debugger in post-mortem mode.
1246
1112
1247 If an exception has just occurred, this lets you inspect its stack
1113 If an exception has just occurred, this lets you inspect its stack
1248 frames interactively. Note that this will always work only on the last
1114 frames interactively. Note that this will always work only on the last
1249 traceback that occurred, so you must call this quickly after an
1115 traceback that occurred, so you must call this quickly after an
1250 exception that you wish to inspect has fired, because if another one
1116 exception that you wish to inspect has fired, because if another one
1251 occurs, it clobbers the previous one.
1117 occurs, it clobbers the previous one.
1252
1118
1253 If you want IPython to automatically do this on every exception, see
1119 If you want IPython to automatically do this on every exception, see
1254 the %pdb magic for more details.
1120 the %pdb magic for more details.
1255 """
1121 """
1256
1122
1257 self.shell.debugger(force=True)
1123 self.shell.debugger(force=True)
1258
1124
1259 def magic_prun(self, parameter_s ='',user_mode=1,
1125 def magic_prun(self, parameter_s ='',user_mode=1,
1260 opts=None,arg_lst=None,prog_ns=None):
1126 opts=None,arg_lst=None,prog_ns=None):
1261
1127
1262 """Run a statement through the python code profiler.
1128 """Run a statement through the python code profiler.
1263
1129
1264 Usage:\\
1130 Usage:\\
1265 %prun [options] statement
1131 %prun [options] statement
1266
1132
1267 The given statement (which doesn't require quote marks) is run via the
1133 The given statement (which doesn't require quote marks) is run via the
1268 python profiler in a manner similar to the profile.run() function.
1134 python profiler in a manner similar to the profile.run() function.
1269 Namespaces are internally managed to work correctly; profile.run
1135 Namespaces are internally managed to work correctly; profile.run
1270 cannot be used in IPython because it makes certain assumptions about
1136 cannot be used in IPython because it makes certain assumptions about
1271 namespaces which do not hold under IPython.
1137 namespaces which do not hold under IPython.
1272
1138
1273 Options:
1139 Options:
1274
1140
1275 -l <limit>: you can place restrictions on what or how much of the
1141 -l <limit>: you can place restrictions on what or how much of the
1276 profile gets printed. The limit value can be:
1142 profile gets printed. The limit value can be:
1277
1143
1278 * A string: only information for function names containing this string
1144 * A string: only information for function names containing this string
1279 is printed.
1145 is printed.
1280
1146
1281 * An integer: only these many lines are printed.
1147 * An integer: only these many lines are printed.
1282
1148
1283 * A float (between 0 and 1): this fraction of the report is printed
1149 * A float (between 0 and 1): this fraction of the report is printed
1284 (for example, use a limit of 0.4 to see the topmost 40% only).
1150 (for example, use a limit of 0.4 to see the topmost 40% only).
1285
1151
1286 You can combine several limits with repeated use of the option. For
1152 You can combine several limits with repeated use of the option. For
1287 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1153 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1288 information about class constructors.
1154 information about class constructors.
1289
1155
1290 -r: return the pstats.Stats object generated by the profiling. This
1156 -r: return the pstats.Stats object generated by the profiling. This
1291 object has all the information about the profile in it, and you can
1157 object has all the information about the profile in it, and you can
1292 later use it for further analysis or in other functions.
1158 later use it for further analysis or in other functions.
1293
1159
1294 -s <key>: sort profile by given key. You can provide more than one key
1160 -s <key>: sort profile by given key. You can provide more than one key
1295 by using the option several times: '-s key1 -s key2 -s key3...'. The
1161 by using the option several times: '-s key1 -s key2 -s key3...'. The
1296 default sorting key is 'time'.
1162 default sorting key is 'time'.
1297
1163
1298 The following is copied verbatim from the profile documentation
1164 The following is copied verbatim from the profile documentation
1299 referenced below:
1165 referenced below:
1300
1166
1301 When more than one key is provided, additional keys are used as
1167 When more than one key is provided, additional keys are used as
1302 secondary criteria when the there is equality in all keys selected
1168 secondary criteria when the there is equality in all keys selected
1303 before them.
1169 before them.
1304
1170
1305 Abbreviations can be used for any key names, as long as the
1171 Abbreviations can be used for any key names, as long as the
1306 abbreviation is unambiguous. The following are the keys currently
1172 abbreviation is unambiguous. The following are the keys currently
1307 defined:
1173 defined:
1308
1174
1309 Valid Arg Meaning\\
1175 Valid Arg Meaning\\
1310 "calls" call count\\
1176 "calls" call count\\
1311 "cumulative" cumulative time\\
1177 "cumulative" cumulative time\\
1312 "file" file name\\
1178 "file" file name\\
1313 "module" file name\\
1179 "module" file name\\
1314 "pcalls" primitive call count\\
1180 "pcalls" primitive call count\\
1315 "line" line number\\
1181 "line" line number\\
1316 "name" function name\\
1182 "name" function name\\
1317 "nfl" name/file/line\\
1183 "nfl" name/file/line\\
1318 "stdname" standard name\\
1184 "stdname" standard name\\
1319 "time" internal time
1185 "time" internal time
1320
1186
1321 Note that all sorts on statistics are in descending order (placing
1187 Note that all sorts on statistics are in descending order (placing
1322 most time consuming items first), where as name, file, and line number
1188 most time consuming items first), where as name, file, and line number
1323 searches are in ascending order (i.e., alphabetical). The subtle
1189 searches are in ascending order (i.e., alphabetical). The subtle
1324 distinction between "nfl" and "stdname" is that the standard name is a
1190 distinction between "nfl" and "stdname" is that the standard name is a
1325 sort of the name as printed, which means that the embedded line
1191 sort of the name as printed, which means that the embedded line
1326 numbers get compared in an odd way. For example, lines 3, 20, and 40
1192 numbers get compared in an odd way. For example, lines 3, 20, and 40
1327 would (if the file names were the same) appear in the string order
1193 would (if the file names were the same) appear in the string order
1328 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1194 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1329 line numbers. In fact, sort_stats("nfl") is the same as
1195 line numbers. In fact, sort_stats("nfl") is the same as
1330 sort_stats("name", "file", "line").
1196 sort_stats("name", "file", "line").
1331
1197
1332 -T <filename>: save profile results as shown on screen to a text
1198 -T <filename>: save profile results as shown on screen to a text
1333 file. The profile is still shown on screen.
1199 file. The profile is still shown on screen.
1334
1200
1335 -D <filename>: save (via dump_stats) profile statistics to given
1201 -D <filename>: save (via dump_stats) profile statistics to given
1336 filename. This data is in a format understod by the pstats module, and
1202 filename. This data is in a format understod by the pstats module, and
1337 is generated by a call to the dump_stats() method of profile
1203 is generated by a call to the dump_stats() method of profile
1338 objects. The profile is still shown on screen.
1204 objects. The profile is still shown on screen.
1339
1205
1340 If you want to run complete programs under the profiler's control, use
1206 If you want to run complete programs under the profiler's control, use
1341 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1207 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1342 contains profiler specific options as described here.
1208 contains profiler specific options as described here.
1343
1209
1344 You can read the complete documentation for the profile module with:\\
1210 You can read the complete documentation for the profile module with:\\
1345 In [1]: import profile; profile.help() """
1211 In [1]: import profile; profile.help() """
1346
1212
1347 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1213 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1348 # protect user quote marks
1214 # protect user quote marks
1349 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1215 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1350
1216
1351 if user_mode: # regular user call
1217 if user_mode: # regular user call
1352 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1218 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1353 list_all=1)
1219 list_all=1)
1354 namespace = self.shell.user_ns
1220 namespace = self.shell.user_ns
1355 else: # called to run a program by %run -p
1221 else: # called to run a program by %run -p
1356 try:
1222 try:
1357 filename = get_py_filename(arg_lst[0])
1223 filename = get_py_filename(arg_lst[0])
1358 except IOError,msg:
1224 except IOError,msg:
1359 error(msg)
1225 error(msg)
1360 return
1226 return
1361
1227
1362 arg_str = 'execfile(filename,prog_ns)'
1228 arg_str = 'execfile(filename,prog_ns)'
1363 namespace = locals()
1229 namespace = locals()
1364
1230
1365 opts.merge(opts_def)
1231 opts.merge(opts_def)
1366
1232
1367 prof = profile.Profile()
1233 prof = profile.Profile()
1368 try:
1234 try:
1369 prof = prof.runctx(arg_str,namespace,namespace)
1235 prof = prof.runctx(arg_str,namespace,namespace)
1370 sys_exit = ''
1236 sys_exit = ''
1371 except SystemExit:
1237 except SystemExit:
1372 sys_exit = """*** SystemExit exception caught in code being profiled."""
1238 sys_exit = """*** SystemExit exception caught in code being profiled."""
1373
1239
1374 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1240 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1375
1241
1376 lims = opts.l
1242 lims = opts.l
1377 if lims:
1243 if lims:
1378 lims = [] # rebuild lims with ints/floats/strings
1244 lims = [] # rebuild lims with ints/floats/strings
1379 for lim in opts.l:
1245 for lim in opts.l:
1380 try:
1246 try:
1381 lims.append(int(lim))
1247 lims.append(int(lim))
1382 except ValueError:
1248 except ValueError:
1383 try:
1249 try:
1384 lims.append(float(lim))
1250 lims.append(float(lim))
1385 except ValueError:
1251 except ValueError:
1386 lims.append(lim)
1252 lims.append(lim)
1387
1253
1388 # Trap output.
1254 # Trap output.
1389 stdout_trap = StringIO()
1255 stdout_trap = StringIO()
1390
1256
1391 if hasattr(stats,'stream'):
1257 if hasattr(stats,'stream'):
1392 # In newer versions of python, the stats object has a 'stream'
1258 # In newer versions of python, the stats object has a 'stream'
1393 # attribute to write into.
1259 # attribute to write into.
1394 stats.stream = stdout_trap
1260 stats.stream = stdout_trap
1395 stats.print_stats(*lims)
1261 stats.print_stats(*lims)
1396 else:
1262 else:
1397 # For older versions, we manually redirect stdout during printing
1263 # For older versions, we manually redirect stdout during printing
1398 sys_stdout = sys.stdout
1264 sys_stdout = sys.stdout
1399 try:
1265 try:
1400 sys.stdout = stdout_trap
1266 sys.stdout = stdout_trap
1401 stats.print_stats(*lims)
1267 stats.print_stats(*lims)
1402 finally:
1268 finally:
1403 sys.stdout = sys_stdout
1269 sys.stdout = sys_stdout
1404
1270
1405 output = stdout_trap.getvalue()
1271 output = stdout_trap.getvalue()
1406 output = output.rstrip()
1272 output = output.rstrip()
1407
1273
1408 page(output,screen_lines=self.shell.rc.screen_length)
1274 page(output,screen_lines=self.shell.rc.screen_length)
1409 print sys_exit,
1275 print sys_exit,
1410
1276
1411 dump_file = opts.D[0]
1277 dump_file = opts.D[0]
1412 text_file = opts.T[0]
1278 text_file = opts.T[0]
1413 if dump_file:
1279 if dump_file:
1414 prof.dump_stats(dump_file)
1280 prof.dump_stats(dump_file)
1415 print '\n*** Profile stats marshalled to file',\
1281 print '\n*** Profile stats marshalled to file',\
1416 `dump_file`+'.',sys_exit
1282 `dump_file`+'.',sys_exit
1417 if text_file:
1283 if text_file:
1418 pfile = file(text_file,'w')
1284 pfile = file(text_file,'w')
1419 pfile.write(output)
1285 pfile.write(output)
1420 pfile.close()
1286 pfile.close()
1421 print '\n*** Profile printout saved to text file',\
1287 print '\n*** Profile printout saved to text file',\
1422 `text_file`+'.',sys_exit
1288 `text_file`+'.',sys_exit
1423
1289
1424 if opts.has_key('r'):
1290 if opts.has_key('r'):
1425 return stats
1291 return stats
1426 else:
1292 else:
1427 return None
1293 return None
1428
1294
1429 def magic_run(self, parameter_s ='',runner=None):
1295 def magic_run(self, parameter_s ='',runner=None):
1430 """Run the named file inside IPython as a program.
1296 """Run the named file inside IPython as a program.
1431
1297
1432 Usage:\\
1298 Usage:\\
1433 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1299 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1434
1300
1435 Parameters after the filename are passed as command-line arguments to
1301 Parameters after the filename are passed as command-line arguments to
1436 the program (put in sys.argv). Then, control returns to IPython's
1302 the program (put in sys.argv). Then, control returns to IPython's
1437 prompt.
1303 prompt.
1438
1304
1439 This is similar to running at a system prompt:\\
1305 This is similar to running at a system prompt:\\
1440 $ python file args\\
1306 $ python file args\\
1441 but with the advantage of giving you IPython's tracebacks, and of
1307 but with the advantage of giving you IPython's tracebacks, and of
1442 loading all variables into your interactive namespace for further use
1308 loading all variables into your interactive namespace for further use
1443 (unless -p is used, see below).
1309 (unless -p is used, see below).
1444
1310
1445 The file is executed in a namespace initially consisting only of
1311 The file is executed in a namespace initially consisting only of
1446 __name__=='__main__' and sys.argv constructed as indicated. It thus
1312 __name__=='__main__' and sys.argv constructed as indicated. It thus
1447 sees its environment as if it were being run as a stand-alone
1313 sees its environment as if it were being run as a stand-alone
1448 program. But after execution, the IPython interactive namespace gets
1314 program. But after execution, the IPython interactive namespace gets
1449 updated with all variables defined in the program (except for __name__
1315 updated with all variables defined in the program (except for __name__
1450 and sys.argv). This allows for very convenient loading of code for
1316 and sys.argv). This allows for very convenient loading of code for
1451 interactive work, while giving each program a 'clean sheet' to run in.
1317 interactive work, while giving each program a 'clean sheet' to run in.
1452
1318
1453 Options:
1319 Options:
1454
1320
1455 -n: __name__ is NOT set to '__main__', but to the running file's name
1321 -n: __name__ is NOT set to '__main__', but to the running file's name
1456 without extension (as python does under import). This allows running
1322 without extension (as python does under import). This allows running
1457 scripts and reloading the definitions in them without calling code
1323 scripts and reloading the definitions in them without calling code
1458 protected by an ' if __name__ == "__main__" ' clause.
1324 protected by an ' if __name__ == "__main__" ' clause.
1459
1325
1460 -i: run the file in IPython's namespace instead of an empty one. This
1326 -i: run the file in IPython's namespace instead of an empty one. This
1461 is useful if you are experimenting with code written in a text editor
1327 is useful if you are experimenting with code written in a text editor
1462 which depends on variables defined interactively.
1328 which depends on variables defined interactively.
1463
1329
1464 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1330 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1465 being run. This is particularly useful if IPython is being used to
1331 being run. This is particularly useful if IPython is being used to
1466 run unittests, which always exit with a sys.exit() call. In such
1332 run unittests, which always exit with a sys.exit() call. In such
1467 cases you are interested in the output of the test results, not in
1333 cases you are interested in the output of the test results, not in
1468 seeing a traceback of the unittest module.
1334 seeing a traceback of the unittest module.
1469
1335
1470 -t: print timing information at the end of the run. IPython will give
1336 -t: print timing information at the end of the run. IPython will give
1471 you an estimated CPU time consumption for your script, which under
1337 you an estimated CPU time consumption for your script, which under
1472 Unix uses the resource module to avoid the wraparound problems of
1338 Unix uses the resource module to avoid the wraparound problems of
1473 time.clock(). Under Unix, an estimate of time spent on system tasks
1339 time.clock(). Under Unix, an estimate of time spent on system tasks
1474 is also given (for Windows platforms this is reported as 0.0).
1340 is also given (for Windows platforms this is reported as 0.0).
1475
1341
1476 If -t is given, an additional -N<N> option can be given, where <N>
1342 If -t is given, an additional -N<N> option can be given, where <N>
1477 must be an integer indicating how many times you want the script to
1343 must be an integer indicating how many times you want the script to
1478 run. The final timing report will include total and per run results.
1344 run. The final timing report will include total and per run results.
1479
1345
1480 For example (testing the script uniq_stable.py):
1346 For example (testing the script uniq_stable.py):
1481
1347
1482 In [1]: run -t uniq_stable
1348 In [1]: run -t uniq_stable
1483
1349
1484 IPython CPU timings (estimated):\\
1350 IPython CPU timings (estimated):\\
1485 User : 0.19597 s.\\
1351 User : 0.19597 s.\\
1486 System: 0.0 s.\\
1352 System: 0.0 s.\\
1487
1353
1488 In [2]: run -t -N5 uniq_stable
1354 In [2]: run -t -N5 uniq_stable
1489
1355
1490 IPython CPU timings (estimated):\\
1356 IPython CPU timings (estimated):\\
1491 Total runs performed: 5\\
1357 Total runs performed: 5\\
1492 Times : Total Per run\\
1358 Times : Total Per run\\
1493 User : 0.910862 s, 0.1821724 s.\\
1359 User : 0.910862 s, 0.1821724 s.\\
1494 System: 0.0 s, 0.0 s.
1360 System: 0.0 s, 0.0 s.
1495
1361
1496 -d: run your program under the control of pdb, the Python debugger.
1362 -d: run your program under the control of pdb, the Python debugger.
1497 This allows you to execute your program step by step, watch variables,
1363 This allows you to execute your program step by step, watch variables,
1498 etc. Internally, what IPython does is similar to calling:
1364 etc. Internally, what IPython does is similar to calling:
1499
1365
1500 pdb.run('execfile("YOURFILENAME")')
1366 pdb.run('execfile("YOURFILENAME")')
1501
1367
1502 with a breakpoint set on line 1 of your file. You can change the line
1368 with a breakpoint set on line 1 of your file. You can change the line
1503 number for this automatic breakpoint to be <N> by using the -bN option
1369 number for this automatic breakpoint to be <N> by using the -bN option
1504 (where N must be an integer). For example:
1370 (where N must be an integer). For example:
1505
1371
1506 %run -d -b40 myscript
1372 %run -d -b40 myscript
1507
1373
1508 will set the first breakpoint at line 40 in myscript.py. Note that
1374 will set the first breakpoint at line 40 in myscript.py. Note that
1509 the first breakpoint must be set on a line which actually does
1375 the first breakpoint must be set on a line which actually does
1510 something (not a comment or docstring) for it to stop execution.
1376 something (not a comment or docstring) for it to stop execution.
1511
1377
1512 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1378 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1513 first enter 'c' (without qoutes) to start execution up to the first
1379 first enter 'c' (without qoutes) to start execution up to the first
1514 breakpoint.
1380 breakpoint.
1515
1381
1516 Entering 'help' gives information about the use of the debugger. You
1382 Entering 'help' gives information about the use of the debugger. You
1517 can easily see pdb's full documentation with "import pdb;pdb.help()"
1383 can easily see pdb's full documentation with "import pdb;pdb.help()"
1518 at a prompt.
1384 at a prompt.
1519
1385
1520 -p: run program under the control of the Python profiler module (which
1386 -p: run program under the control of the Python profiler module (which
1521 prints a detailed report of execution times, function calls, etc).
1387 prints a detailed report of execution times, function calls, etc).
1522
1388
1523 You can pass other options after -p which affect the behavior of the
1389 You can pass other options after -p which affect the behavior of the
1524 profiler itself. See the docs for %prun for details.
1390 profiler itself. See the docs for %prun for details.
1525
1391
1526 In this mode, the program's variables do NOT propagate back to the
1392 In this mode, the program's variables do NOT propagate back to the
1527 IPython interactive namespace (because they remain in the namespace
1393 IPython interactive namespace (because they remain in the namespace
1528 where the profiler executes them).
1394 where the profiler executes them).
1529
1395
1530 Internally this triggers a call to %prun, see its documentation for
1396 Internally this triggers a call to %prun, see its documentation for
1531 details on the options available specifically for profiling.
1397 details on the options available specifically for profiling.
1532
1398
1533 There is one special usage for which the text above doesn't apply:
1399 There is one special usage for which the text above doesn't apply:
1534 if the filename ends with .ipy, the file is run as ipython script,
1400 if the filename ends with .ipy, the file is run as ipython script,
1535 just as if the commands were written on IPython prompt.
1401 just as if the commands were written on IPython prompt.
1536 """
1402 """
1537
1403
1538 # get arguments and set sys.argv for program to be run.
1404 # get arguments and set sys.argv for program to be run.
1539 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1405 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1540 mode='list',list_all=1)
1406 mode='list',list_all=1)
1541
1407
1542 try:
1408 try:
1543 filename = get_py_filename(arg_lst[0])
1409 filename = get_py_filename(arg_lst[0])
1544 except IndexError:
1410 except IndexError:
1545 warn('you must provide at least a filename.')
1411 warn('you must provide at least a filename.')
1546 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1412 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1547 return
1413 return
1548 except IOError,msg:
1414 except IOError,msg:
1549 error(msg)
1415 error(msg)
1550 return
1416 return
1551
1417
1552 if filename.lower().endswith('.ipy'):
1418 if filename.lower().endswith('.ipy'):
1553 self.api.runlines(open(filename).read())
1419 self.api.runlines(open(filename).read())
1554 return
1420 return
1555
1421
1556 # Control the response to exit() calls made by the script being run
1422 # Control the response to exit() calls made by the script being run
1557 exit_ignore = opts.has_key('e')
1423 exit_ignore = opts.has_key('e')
1558
1424
1559 # Make sure that the running script gets a proper sys.argv as if it
1425 # Make sure that the running script gets a proper sys.argv as if it
1560 # were run from a system shell.
1426 # were run from a system shell.
1561 save_argv = sys.argv # save it for later restoring
1427 save_argv = sys.argv # save it for later restoring
1562 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1428 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1563
1429
1564 if opts.has_key('i'):
1430 if opts.has_key('i'):
1565 prog_ns = self.shell.user_ns
1431 prog_ns = self.shell.user_ns
1566 __name__save = self.shell.user_ns['__name__']
1432 __name__save = self.shell.user_ns['__name__']
1567 prog_ns['__name__'] = '__main__'
1433 prog_ns['__name__'] = '__main__'
1568 else:
1434 else:
1569 if opts.has_key('n'):
1435 if opts.has_key('n'):
1570 name = os.path.splitext(os.path.basename(filename))[0]
1436 name = os.path.splitext(os.path.basename(filename))[0]
1571 else:
1437 else:
1572 name = '__main__'
1438 name = '__main__'
1573 prog_ns = {'__name__':name}
1439 prog_ns = {'__name__':name}
1574
1440
1575 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1441 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1576 # set the __file__ global in the script's namespace
1442 # set the __file__ global in the script's namespace
1577 prog_ns['__file__'] = filename
1443 prog_ns['__file__'] = filename
1578
1444
1579 # pickle fix. See iplib for an explanation. But we need to make sure
1445 # pickle fix. See iplib for an explanation. But we need to make sure
1580 # that, if we overwrite __main__, we replace it at the end
1446 # that, if we overwrite __main__, we replace it at the end
1581 if prog_ns['__name__'] == '__main__':
1447 if prog_ns['__name__'] == '__main__':
1582 restore_main = sys.modules['__main__']
1448 restore_main = sys.modules['__main__']
1583 else:
1449 else:
1584 restore_main = False
1450 restore_main = False
1585
1451
1586 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1452 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1587
1453
1588 stats = None
1454 stats = None
1589 try:
1455 try:
1590 if self.shell.has_readline:
1456 if self.shell.has_readline:
1591 self.shell.savehist()
1457 self.shell.savehist()
1592
1458
1593 if opts.has_key('p'):
1459 if opts.has_key('p'):
1594 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1460 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1595 else:
1461 else:
1596 if opts.has_key('d'):
1462 if opts.has_key('d'):
1597 deb = Debugger.Pdb(self.shell.rc.colors)
1463 deb = Debugger.Pdb(self.shell.rc.colors)
1598 # reset Breakpoint state, which is moronically kept
1464 # reset Breakpoint state, which is moronically kept
1599 # in a class
1465 # in a class
1600 bdb.Breakpoint.next = 1
1466 bdb.Breakpoint.next = 1
1601 bdb.Breakpoint.bplist = {}
1467 bdb.Breakpoint.bplist = {}
1602 bdb.Breakpoint.bpbynumber = [None]
1468 bdb.Breakpoint.bpbynumber = [None]
1603 # Set an initial breakpoint to stop execution
1469 # Set an initial breakpoint to stop execution
1604 maxtries = 10
1470 maxtries = 10
1605 bp = int(opts.get('b',[1])[0])
1471 bp = int(opts.get('b',[1])[0])
1606 checkline = deb.checkline(filename,bp)
1472 checkline = deb.checkline(filename,bp)
1607 if not checkline:
1473 if not checkline:
1608 for bp in range(bp+1,bp+maxtries+1):
1474 for bp in range(bp+1,bp+maxtries+1):
1609 if deb.checkline(filename,bp):
1475 if deb.checkline(filename,bp):
1610 break
1476 break
1611 else:
1477 else:
1612 msg = ("\nI failed to find a valid line to set "
1478 msg = ("\nI failed to find a valid line to set "
1613 "a breakpoint\n"
1479 "a breakpoint\n"
1614 "after trying up to line: %s.\n"
1480 "after trying up to line: %s.\n"
1615 "Please set a valid breakpoint manually "
1481 "Please set a valid breakpoint manually "
1616 "with the -b option." % bp)
1482 "with the -b option." % bp)
1617 error(msg)
1483 error(msg)
1618 return
1484 return
1619 # if we find a good linenumber, set the breakpoint
1485 # if we find a good linenumber, set the breakpoint
1620 deb.do_break('%s:%s' % (filename,bp))
1486 deb.do_break('%s:%s' % (filename,bp))
1621 # Start file run
1487 # Start file run
1622 print "NOTE: Enter 'c' at the",
1488 print "NOTE: Enter 'c' at the",
1623 print "%s prompt to start your script." % deb.prompt
1489 print "%s prompt to start your script." % deb.prompt
1624 try:
1490 try:
1625 deb.run('execfile("%s")' % filename,prog_ns)
1491 deb.run('execfile("%s")' % filename,prog_ns)
1626
1492
1627 except:
1493 except:
1628 etype, value, tb = sys.exc_info()
1494 etype, value, tb = sys.exc_info()
1629 # Skip three frames in the traceback: the %run one,
1495 # Skip three frames in the traceback: the %run one,
1630 # one inside bdb.py, and the command-line typed by the
1496 # one inside bdb.py, and the command-line typed by the
1631 # user (run by exec in pdb itself).
1497 # user (run by exec in pdb itself).
1632 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1498 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1633 else:
1499 else:
1634 if runner is None:
1500 if runner is None:
1635 runner = self.shell.safe_execfile
1501 runner = self.shell.safe_execfile
1636 if opts.has_key('t'):
1502 if opts.has_key('t'):
1637 try:
1503 try:
1638 nruns = int(opts['N'][0])
1504 nruns = int(opts['N'][0])
1639 if nruns < 1:
1505 if nruns < 1:
1640 error('Number of runs must be >=1')
1506 error('Number of runs must be >=1')
1641 return
1507 return
1642 except (KeyError):
1508 except (KeyError):
1643 nruns = 1
1509 nruns = 1
1644 if nruns == 1:
1510 if nruns == 1:
1645 t0 = clock2()
1511 t0 = clock2()
1646 runner(filename,prog_ns,prog_ns,
1512 runner(filename,prog_ns,prog_ns,
1647 exit_ignore=exit_ignore)
1513 exit_ignore=exit_ignore)
1648 t1 = clock2()
1514 t1 = clock2()
1649 t_usr = t1[0]-t0[0]
1515 t_usr = t1[0]-t0[0]
1650 t_sys = t1[1]-t1[1]
1516 t_sys = t1[1]-t1[1]
1651 print "\nIPython CPU timings (estimated):"
1517 print "\nIPython CPU timings (estimated):"
1652 print " User : %10s s." % t_usr
1518 print " User : %10s s." % t_usr
1653 print " System: %10s s." % t_sys
1519 print " System: %10s s." % t_sys
1654 else:
1520 else:
1655 runs = range(nruns)
1521 runs = range(nruns)
1656 t0 = clock2()
1522 t0 = clock2()
1657 for nr in runs:
1523 for nr in runs:
1658 runner(filename,prog_ns,prog_ns,
1524 runner(filename,prog_ns,prog_ns,
1659 exit_ignore=exit_ignore)
1525 exit_ignore=exit_ignore)
1660 t1 = clock2()
1526 t1 = clock2()
1661 t_usr = t1[0]-t0[0]
1527 t_usr = t1[0]-t0[0]
1662 t_sys = t1[1]-t1[1]
1528 t_sys = t1[1]-t1[1]
1663 print "\nIPython CPU timings (estimated):"
1529 print "\nIPython CPU timings (estimated):"
1664 print "Total runs performed:",nruns
1530 print "Total runs performed:",nruns
1665 print " Times : %10s %10s" % ('Total','Per run')
1531 print " Times : %10s %10s" % ('Total','Per run')
1666 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1532 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1667 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1533 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1668
1534
1669 else:
1535 else:
1670 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1536 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1671 if opts.has_key('i'):
1537 if opts.has_key('i'):
1672 self.shell.user_ns['__name__'] = __name__save
1538 self.shell.user_ns['__name__'] = __name__save
1673 else:
1539 else:
1674 # update IPython interactive namespace
1540 # update IPython interactive namespace
1675 del prog_ns['__name__']
1541 del prog_ns['__name__']
1676 self.shell.user_ns.update(prog_ns)
1542 self.shell.user_ns.update(prog_ns)
1677 finally:
1543 finally:
1678 sys.argv = save_argv
1544 sys.argv = save_argv
1679 if restore_main:
1545 if restore_main:
1680 sys.modules['__main__'] = restore_main
1546 sys.modules['__main__'] = restore_main
1681 self.shell.reloadhist()
1547 self.shell.reloadhist()
1682
1548
1683 return stats
1549 return stats
1684
1550
1685 def magic_runlog(self, parameter_s =''):
1551 def magic_runlog(self, parameter_s =''):
1686 """Run files as logs.
1552 """Run files as logs.
1687
1553
1688 Usage:\\
1554 Usage:\\
1689 %runlog file1 file2 ...
1555 %runlog file1 file2 ...
1690
1556
1691 Run the named files (treating them as log files) in sequence inside
1557 Run the named files (treating them as log files) in sequence inside
1692 the interpreter, and return to the prompt. This is much slower than
1558 the interpreter, and return to the prompt. This is much slower than
1693 %run because each line is executed in a try/except block, but it
1559 %run because each line is executed in a try/except block, but it
1694 allows running files with syntax errors in them.
1560 allows running files with syntax errors in them.
1695
1561
1696 Normally IPython will guess when a file is one of its own logfiles, so
1562 Normally IPython will guess when a file is one of its own logfiles, so
1697 you can typically use %run even for logs. This shorthand allows you to
1563 you can typically use %run even for logs. This shorthand allows you to
1698 force any file to be treated as a log file."""
1564 force any file to be treated as a log file."""
1699
1565
1700 for f in parameter_s.split():
1566 for f in parameter_s.split():
1701 self.shell.safe_execfile(f,self.shell.user_ns,
1567 self.shell.safe_execfile(f,self.shell.user_ns,
1702 self.shell.user_ns,islog=1)
1568 self.shell.user_ns,islog=1)
1703
1569
1704 def magic_timeit(self, parameter_s =''):
1570 def magic_timeit(self, parameter_s =''):
1705 """Time execution of a Python statement or expression
1571 """Time execution of a Python statement or expression
1706
1572
1707 Usage:\\
1573 Usage:\\
1708 %timeit [-n<N> -r<R> [-t|-c]] statement
1574 %timeit [-n<N> -r<R> [-t|-c]] statement
1709
1575
1710 Time execution of a Python statement or expression using the timeit
1576 Time execution of a Python statement or expression using the timeit
1711 module.
1577 module.
1712
1578
1713 Options:
1579 Options:
1714 -n<N>: execute the given statement <N> times in a loop. If this value
1580 -n<N>: execute the given statement <N> times in a loop. If this value
1715 is not given, a fitting value is chosen.
1581 is not given, a fitting value is chosen.
1716
1582
1717 -r<R>: repeat the loop iteration <R> times and take the best result.
1583 -r<R>: repeat the loop iteration <R> times and take the best result.
1718 Default: 3
1584 Default: 3
1719
1585
1720 -t: use time.time to measure the time, which is the default on Unix.
1586 -t: use time.time to measure the time, which is the default on Unix.
1721 This function measures wall time.
1587 This function measures wall time.
1722
1588
1723 -c: use time.clock to measure the time, which is the default on
1589 -c: use time.clock to measure the time, which is the default on
1724 Windows and measures wall time. On Unix, resource.getrusage is used
1590 Windows and measures wall time. On Unix, resource.getrusage is used
1725 instead and returns the CPU user time.
1591 instead and returns the CPU user time.
1726
1592
1727 -p<P>: use a precision of <P> digits to display the timing result.
1593 -p<P>: use a precision of <P> digits to display the timing result.
1728 Default: 3
1594 Default: 3
1729
1595
1730
1596
1731 Examples:\\
1597 Examples:\\
1732 In [1]: %timeit pass
1598 In [1]: %timeit pass
1733 10000000 loops, best of 3: 53.3 ns per loop
1599 10000000 loops, best of 3: 53.3 ns per loop
1734
1600
1735 In [2]: u = None
1601 In [2]: u = None
1736
1602
1737 In [3]: %timeit u is None
1603 In [3]: %timeit u is None
1738 10000000 loops, best of 3: 184 ns per loop
1604 10000000 loops, best of 3: 184 ns per loop
1739
1605
1740 In [4]: %timeit -r 4 u == None
1606 In [4]: %timeit -r 4 u == None
1741 1000000 loops, best of 4: 242 ns per loop
1607 1000000 loops, best of 4: 242 ns per loop
1742
1608
1743 In [5]: import time
1609 In [5]: import time
1744
1610
1745 In [6]: %timeit -n1 time.sleep(2)
1611 In [6]: %timeit -n1 time.sleep(2)
1746 1 loops, best of 3: 2 s per loop
1612 1 loops, best of 3: 2 s per loop
1747
1613
1748
1614
1749 The times reported by %timeit will be slightly higher than those
1615 The times reported by %timeit will be slightly higher than those
1750 reported by the timeit.py script when variables are accessed. This is
1616 reported by the timeit.py script when variables are accessed. This is
1751 due to the fact that %timeit executes the statement in the namespace
1617 due to the fact that %timeit executes the statement in the namespace
1752 of the shell, compared with timeit.py, which uses a single setup
1618 of the shell, compared with timeit.py, which uses a single setup
1753 statement to import function or create variables. Generally, the bias
1619 statement to import function or create variables. Generally, the bias
1754 does not matter as long as results from timeit.py are not mixed with
1620 does not matter as long as results from timeit.py are not mixed with
1755 those from %timeit."""
1621 those from %timeit."""
1756
1622
1757 import timeit
1623 import timeit
1758 import math
1624 import math
1759
1625
1760 units = ["s", "ms", "\xc2\xb5s", "ns"]
1626 units = ["s", "ms", "\xc2\xb5s", "ns"]
1761 scaling = [1, 1e3, 1e6, 1e9]
1627 scaling = [1, 1e3, 1e6, 1e9]
1762
1628
1763 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1629 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1764 posix=False)
1630 posix=False)
1765 if stmt == "":
1631 if stmt == "":
1766 return
1632 return
1767 timefunc = timeit.default_timer
1633 timefunc = timeit.default_timer
1768 number = int(getattr(opts, "n", 0))
1634 number = int(getattr(opts, "n", 0))
1769 repeat = int(getattr(opts, "r", timeit.default_repeat))
1635 repeat = int(getattr(opts, "r", timeit.default_repeat))
1770 precision = int(getattr(opts, "p", 3))
1636 precision = int(getattr(opts, "p", 3))
1771 if hasattr(opts, "t"):
1637 if hasattr(opts, "t"):
1772 timefunc = time.time
1638 timefunc = time.time
1773 if hasattr(opts, "c"):
1639 if hasattr(opts, "c"):
1774 timefunc = clock
1640 timefunc = clock
1775
1641
1776 timer = timeit.Timer(timer=timefunc)
1642 timer = timeit.Timer(timer=timefunc)
1777 # this code has tight coupling to the inner workings of timeit.Timer,
1643 # this code has tight coupling to the inner workings of timeit.Timer,
1778 # but is there a better way to achieve that the code stmt has access
1644 # but is there a better way to achieve that the code stmt has access
1779 # to the shell namespace?
1645 # to the shell namespace?
1780
1646
1781 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1647 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1782 'setup': "pass"}
1648 'setup': "pass"}
1783 code = compile(src, "<magic-timeit>", "exec")
1649 code = compile(src, "<magic-timeit>", "exec")
1784 ns = {}
1650 ns = {}
1785 exec code in self.shell.user_ns, ns
1651 exec code in self.shell.user_ns, ns
1786 timer.inner = ns["inner"]
1652 timer.inner = ns["inner"]
1787
1653
1788 if number == 0:
1654 if number == 0:
1789 # determine number so that 0.2 <= total time < 2.0
1655 # determine number so that 0.2 <= total time < 2.0
1790 number = 1
1656 number = 1
1791 for i in range(1, 10):
1657 for i in range(1, 10):
1792 number *= 10
1658 number *= 10
1793 if timer.timeit(number) >= 0.2:
1659 if timer.timeit(number) >= 0.2:
1794 break
1660 break
1795
1661
1796 best = min(timer.repeat(repeat, number)) / number
1662 best = min(timer.repeat(repeat, number)) / number
1797
1663
1798 if best > 0.0:
1664 if best > 0.0:
1799 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1665 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1800 else:
1666 else:
1801 order = 3
1667 order = 3
1802 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1668 print "%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1803 precision,
1669 precision,
1804 best * scaling[order],
1670 best * scaling[order],
1805 units[order])
1671 units[order])
1806
1672
1807 def magic_time(self,parameter_s = ''):
1673 def magic_time(self,parameter_s = ''):
1808 """Time execution of a Python statement or expression.
1674 """Time execution of a Python statement or expression.
1809
1675
1810 The CPU and wall clock times are printed, and the value of the
1676 The CPU and wall clock times are printed, and the value of the
1811 expression (if any) is returned. Note that under Win32, system time
1677 expression (if any) is returned. Note that under Win32, system time
1812 is always reported as 0, since it can not be measured.
1678 is always reported as 0, since it can not be measured.
1813
1679
1814 This function provides very basic timing functionality. In Python
1680 This function provides very basic timing functionality. In Python
1815 2.3, the timeit module offers more control and sophistication, so this
1681 2.3, the timeit module offers more control and sophistication, so this
1816 could be rewritten to use it (patches welcome).
1682 could be rewritten to use it (patches welcome).
1817
1683
1818 Some examples:
1684 Some examples:
1819
1685
1820 In [1]: time 2**128
1686 In [1]: time 2**128
1821 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1687 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1822 Wall time: 0.00
1688 Wall time: 0.00
1823 Out[1]: 340282366920938463463374607431768211456L
1689 Out[1]: 340282366920938463463374607431768211456L
1824
1690
1825 In [2]: n = 1000000
1691 In [2]: n = 1000000
1826
1692
1827 In [3]: time sum(range(n))
1693 In [3]: time sum(range(n))
1828 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1694 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1829 Wall time: 1.37
1695 Wall time: 1.37
1830 Out[3]: 499999500000L
1696 Out[3]: 499999500000L
1831
1697
1832 In [4]: time print 'hello world'
1698 In [4]: time print 'hello world'
1833 hello world
1699 hello world
1834 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1700 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1835 Wall time: 0.00
1701 Wall time: 0.00
1836 """
1702 """
1837
1703
1838 # fail immediately if the given expression can't be compiled
1704 # fail immediately if the given expression can't be compiled
1839 try:
1705 try:
1840 mode = 'eval'
1706 mode = 'eval'
1841 code = compile(parameter_s,'<timed eval>',mode)
1707 code = compile(parameter_s,'<timed eval>',mode)
1842 except SyntaxError:
1708 except SyntaxError:
1843 mode = 'exec'
1709 mode = 'exec'
1844 code = compile(parameter_s,'<timed exec>',mode)
1710 code = compile(parameter_s,'<timed exec>',mode)
1845 # skew measurement as little as possible
1711 # skew measurement as little as possible
1846 glob = self.shell.user_ns
1712 glob = self.shell.user_ns
1847 clk = clock2
1713 clk = clock2
1848 wtime = time.time
1714 wtime = time.time
1849 # time execution
1715 # time execution
1850 wall_st = wtime()
1716 wall_st = wtime()
1851 if mode=='eval':
1717 if mode=='eval':
1852 st = clk()
1718 st = clk()
1853 out = eval(code,glob)
1719 out = eval(code,glob)
1854 end = clk()
1720 end = clk()
1855 else:
1721 else:
1856 st = clk()
1722 st = clk()
1857 exec code in glob
1723 exec code in glob
1858 end = clk()
1724 end = clk()
1859 out = None
1725 out = None
1860 wall_end = wtime()
1726 wall_end = wtime()
1861 # Compute actual times and report
1727 # Compute actual times and report
1862 wall_time = wall_end-wall_st
1728 wall_time = wall_end-wall_st
1863 cpu_user = end[0]-st[0]
1729 cpu_user = end[0]-st[0]
1864 cpu_sys = end[1]-st[1]
1730 cpu_sys = end[1]-st[1]
1865 cpu_tot = cpu_user+cpu_sys
1731 cpu_tot = cpu_user+cpu_sys
1866 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1732 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1867 (cpu_user,cpu_sys,cpu_tot)
1733 (cpu_user,cpu_sys,cpu_tot)
1868 print "Wall time: %.2f" % wall_time
1734 print "Wall time: %.2f" % wall_time
1869 return out
1735 return out
1870
1736
1871 def magic_macro(self,parameter_s = ''):
1737 def magic_macro(self,parameter_s = ''):
1872 """Define a set of input lines as a macro for future re-execution.
1738 """Define a set of input lines as a macro for future re-execution.
1873
1739
1874 Usage:\\
1740 Usage:\\
1875 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1741 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1876
1742
1877 Options:
1743 Options:
1878
1744
1879 -r: use 'raw' input. By default, the 'processed' history is used,
1745 -r: use 'raw' input. By default, the 'processed' history is used,
1880 so that magics are loaded in their transformed version to valid
1746 so that magics are loaded in their transformed version to valid
1881 Python. If this option is given, the raw input as typed as the
1747 Python. If this option is given, the raw input as typed as the
1882 command line is used instead.
1748 command line is used instead.
1883
1749
1884 This will define a global variable called `name` which is a string
1750 This will define a global variable called `name` which is a string
1885 made of joining the slices and lines you specify (n1,n2,... numbers
1751 made of joining the slices and lines you specify (n1,n2,... numbers
1886 above) from your input history into a single string. This variable
1752 above) from your input history into a single string. This variable
1887 acts like an automatic function which re-executes those lines as if
1753 acts like an automatic function which re-executes those lines as if
1888 you had typed them. You just type 'name' at the prompt and the code
1754 you had typed them. You just type 'name' at the prompt and the code
1889 executes.
1755 executes.
1890
1756
1891 The notation for indicating number ranges is: n1-n2 means 'use line
1757 The notation for indicating number ranges is: n1-n2 means 'use line
1892 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1758 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1893 using the lines numbered 5,6 and 7.
1759 using the lines numbered 5,6 and 7.
1894
1760
1895 Note: as a 'hidden' feature, you can also use traditional python slice
1761 Note: as a 'hidden' feature, you can also use traditional python slice
1896 notation, where N:M means numbers N through M-1.
1762 notation, where N:M means numbers N through M-1.
1897
1763
1898 For example, if your history contains (%hist prints it):
1764 For example, if your history contains (%hist prints it):
1899
1765
1900 44: x=1\\
1766 44: x=1\\
1901 45: y=3\\
1767 45: y=3\\
1902 46: z=x+y\\
1768 46: z=x+y\\
1903 47: print x\\
1769 47: print x\\
1904 48: a=5\\
1770 48: a=5\\
1905 49: print 'x',x,'y',y\\
1771 49: print 'x',x,'y',y\\
1906
1772
1907 you can create a macro with lines 44 through 47 (included) and line 49
1773 you can create a macro with lines 44 through 47 (included) and line 49
1908 called my_macro with:
1774 called my_macro with:
1909
1775
1910 In [51]: %macro my_macro 44-47 49
1776 In [51]: %macro my_macro 44-47 49
1911
1777
1912 Now, typing `my_macro` (without quotes) will re-execute all this code
1778 Now, typing `my_macro` (without quotes) will re-execute all this code
1913 in one pass.
1779 in one pass.
1914
1780
1915 You don't need to give the line-numbers in order, and any given line
1781 You don't need to give the line-numbers in order, and any given line
1916 number can appear multiple times. You can assemble macros with any
1782 number can appear multiple times. You can assemble macros with any
1917 lines from your input history in any order.
1783 lines from your input history in any order.
1918
1784
1919 The macro is a simple object which holds its value in an attribute,
1785 The macro is a simple object which holds its value in an attribute,
1920 but IPython's display system checks for macros and executes them as
1786 but IPython's display system checks for macros and executes them as
1921 code instead of printing them when you type their name.
1787 code instead of printing them when you type their name.
1922
1788
1923 You can view a macro's contents by explicitly printing it with:
1789 You can view a macro's contents by explicitly printing it with:
1924
1790
1925 'print macro_name'.
1791 'print macro_name'.
1926
1792
1927 For one-off cases which DON'T contain magic function calls in them you
1793 For one-off cases which DON'T contain magic function calls in them you
1928 can obtain similar results by explicitly executing slices from your
1794 can obtain similar results by explicitly executing slices from your
1929 input history with:
1795 input history with:
1930
1796
1931 In [60]: exec In[44:48]+In[49]"""
1797 In [60]: exec In[44:48]+In[49]"""
1932
1798
1933 opts,args = self.parse_options(parameter_s,'r',mode='list')
1799 opts,args = self.parse_options(parameter_s,'r',mode='list')
1934 name,ranges = args[0], args[1:]
1800 name,ranges = args[0], args[1:]
1935 #print 'rng',ranges # dbg
1801 #print 'rng',ranges # dbg
1936 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1802 lines = self.extract_input_slices(ranges,opts.has_key('r'))
1937 macro = Macro(lines)
1803 macro = Macro(lines)
1938 self.shell.user_ns.update({name:macro})
1804 self.shell.user_ns.update({name:macro})
1939 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1805 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1940 print 'Macro contents:'
1806 print 'Macro contents:'
1941 print macro,
1807 print macro,
1942
1808
1943 def magic_save(self,parameter_s = ''):
1809 def magic_save(self,parameter_s = ''):
1944 """Save a set of lines to a given filename.
1810 """Save a set of lines to a given filename.
1945
1811
1946 Usage:\\
1812 Usage:\\
1947 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1813 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
1948
1814
1949 Options:
1815 Options:
1950
1816
1951 -r: use 'raw' input. By default, the 'processed' history is used,
1817 -r: use 'raw' input. By default, the 'processed' history is used,
1952 so that magics are loaded in their transformed version to valid
1818 so that magics are loaded in their transformed version to valid
1953 Python. If this option is given, the raw input as typed as the
1819 Python. If this option is given, the raw input as typed as the
1954 command line is used instead.
1820 command line is used instead.
1955
1821
1956 This function uses the same syntax as %macro for line extraction, but
1822 This function uses the same syntax as %macro for line extraction, but
1957 instead of creating a macro it saves the resulting string to the
1823 instead of creating a macro it saves the resulting string to the
1958 filename you specify.
1824 filename you specify.
1959
1825
1960 It adds a '.py' extension to the file if you don't do so yourself, and
1826 It adds a '.py' extension to the file if you don't do so yourself, and
1961 it asks for confirmation before overwriting existing files."""
1827 it asks for confirmation before overwriting existing files."""
1962
1828
1963 opts,args = self.parse_options(parameter_s,'r',mode='list')
1829 opts,args = self.parse_options(parameter_s,'r',mode='list')
1964 fname,ranges = args[0], args[1:]
1830 fname,ranges = args[0], args[1:]
1965 if not fname.endswith('.py'):
1831 if not fname.endswith('.py'):
1966 fname += '.py'
1832 fname += '.py'
1967 if os.path.isfile(fname):
1833 if os.path.isfile(fname):
1968 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1834 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1969 if ans.lower() not in ['y','yes']:
1835 if ans.lower() not in ['y','yes']:
1970 print 'Operation cancelled.'
1836 print 'Operation cancelled.'
1971 return
1837 return
1972 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1838 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
1973 f = file(fname,'w')
1839 f = file(fname,'w')
1974 f.write(cmds)
1840 f.write(cmds)
1975 f.close()
1841 f.close()
1976 print 'The following commands were written to file `%s`:' % fname
1842 print 'The following commands were written to file `%s`:' % fname
1977 print cmds
1843 print cmds
1978
1844
1979 def _edit_macro(self,mname,macro):
1845 def _edit_macro(self,mname,macro):
1980 """open an editor with the macro data in a file"""
1846 """open an editor with the macro data in a file"""
1981 filename = self.shell.mktempfile(macro.value)
1847 filename = self.shell.mktempfile(macro.value)
1982 self.shell.hooks.editor(filename)
1848 self.shell.hooks.editor(filename)
1983
1849
1984 # and make a new macro object, to replace the old one
1850 # and make a new macro object, to replace the old one
1985 mfile = open(filename)
1851 mfile = open(filename)
1986 mvalue = mfile.read()
1852 mvalue = mfile.read()
1987 mfile.close()
1853 mfile.close()
1988 self.shell.user_ns[mname] = Macro(mvalue)
1854 self.shell.user_ns[mname] = Macro(mvalue)
1989
1855
1990 def magic_ed(self,parameter_s=''):
1856 def magic_ed(self,parameter_s=''):
1991 """Alias to %edit."""
1857 """Alias to %edit."""
1992 return self.magic_edit(parameter_s)
1858 return self.magic_edit(parameter_s)
1993
1859
1994 def magic_edit(self,parameter_s='',last_call=['','']):
1860 def magic_edit(self,parameter_s='',last_call=['','']):
1995 """Bring up an editor and execute the resulting code.
1861 """Bring up an editor and execute the resulting code.
1996
1862
1997 Usage:
1863 Usage:
1998 %edit [options] [args]
1864 %edit [options] [args]
1999
1865
2000 %edit runs IPython's editor hook. The default version of this hook is
1866 %edit runs IPython's editor hook. The default version of this hook is
2001 set to call the __IPYTHON__.rc.editor command. This is read from your
1867 set to call the __IPYTHON__.rc.editor command. This is read from your
2002 environment variable $EDITOR. If this isn't found, it will default to
1868 environment variable $EDITOR. If this isn't found, it will default to
2003 vi under Linux/Unix and to notepad under Windows. See the end of this
1869 vi under Linux/Unix and to notepad under Windows. See the end of this
2004 docstring for how to change the editor hook.
1870 docstring for how to change the editor hook.
2005
1871
2006 You can also set the value of this editor via the command line option
1872 You can also set the value of this editor via the command line option
2007 '-editor' or in your ipythonrc file. This is useful if you wish to use
1873 '-editor' or in your ipythonrc file. This is useful if you wish to use
2008 specifically for IPython an editor different from your typical default
1874 specifically for IPython an editor different from your typical default
2009 (and for Windows users who typically don't set environment variables).
1875 (and for Windows users who typically don't set environment variables).
2010
1876
2011 This command allows you to conveniently edit multi-line code right in
1877 This command allows you to conveniently edit multi-line code right in
2012 your IPython session.
1878 your IPython session.
2013
1879
2014 If called without arguments, %edit opens up an empty editor with a
1880 If called without arguments, %edit opens up an empty editor with a
2015 temporary file and will execute the contents of this file when you
1881 temporary file and will execute the contents of this file when you
2016 close it (don't forget to save it!).
1882 close it (don't forget to save it!).
2017
1883
2018
1884
2019 Options:
1885 Options:
2020
1886
2021 -n <number>: open the editor at a specified line number. By default,
1887 -n <number>: open the editor at a specified line number. By default,
2022 the IPython editor hook uses the unix syntax 'editor +N filename', but
1888 the IPython editor hook uses the unix syntax 'editor +N filename', but
2023 you can configure this by providing your own modified hook if your
1889 you can configure this by providing your own modified hook if your
2024 favorite editor supports line-number specifications with a different
1890 favorite editor supports line-number specifications with a different
2025 syntax.
1891 syntax.
2026
1892
2027 -p: this will call the editor with the same data as the previous time
1893 -p: this will call the editor with the same data as the previous time
2028 it was used, regardless of how long ago (in your current session) it
1894 it was used, regardless of how long ago (in your current session) it
2029 was.
1895 was.
2030
1896
2031 -r: use 'raw' input. This option only applies to input taken from the
1897 -r: use 'raw' input. This option only applies to input taken from the
2032 user's history. By default, the 'processed' history is used, so that
1898 user's history. By default, the 'processed' history is used, so that
2033 magics are loaded in their transformed version to valid Python. If
1899 magics are loaded in their transformed version to valid Python. If
2034 this option is given, the raw input as typed as the command line is
1900 this option is given, the raw input as typed as the command line is
2035 used instead. When you exit the editor, it will be executed by
1901 used instead. When you exit the editor, it will be executed by
2036 IPython's own processor.
1902 IPython's own processor.
2037
1903
2038 -x: do not execute the edited code immediately upon exit. This is
1904 -x: do not execute the edited code immediately upon exit. This is
2039 mainly useful if you are editing programs which need to be called with
1905 mainly useful if you are editing programs which need to be called with
2040 command line arguments, which you can then do using %run.
1906 command line arguments, which you can then do using %run.
2041
1907
2042
1908
2043 Arguments:
1909 Arguments:
2044
1910
2045 If arguments are given, the following possibilites exist:
1911 If arguments are given, the following possibilites exist:
2046
1912
2047 - The arguments are numbers or pairs of colon-separated numbers (like
1913 - The arguments are numbers or pairs of colon-separated numbers (like
2048 1 4:8 9). These are interpreted as lines of previous input to be
1914 1 4:8 9). These are interpreted as lines of previous input to be
2049 loaded into the editor. The syntax is the same of the %macro command.
1915 loaded into the editor. The syntax is the same of the %macro command.
2050
1916
2051 - If the argument doesn't start with a number, it is evaluated as a
1917 - If the argument doesn't start with a number, it is evaluated as a
2052 variable and its contents loaded into the editor. You can thus edit
1918 variable and its contents loaded into the editor. You can thus edit
2053 any string which contains python code (including the result of
1919 any string which contains python code (including the result of
2054 previous edits).
1920 previous edits).
2055
1921
2056 - If the argument is the name of an object (other than a string),
1922 - If the argument is the name of an object (other than a string),
2057 IPython will try to locate the file where it was defined and open the
1923 IPython will try to locate the file where it was defined and open the
2058 editor at the point where it is defined. You can use `%edit function`
1924 editor at the point where it is defined. You can use `%edit function`
2059 to load an editor exactly at the point where 'function' is defined,
1925 to load an editor exactly at the point where 'function' is defined,
2060 edit it and have the file be executed automatically.
1926 edit it and have the file be executed automatically.
2061
1927
2062 If the object is a macro (see %macro for details), this opens up your
1928 If the object is a macro (see %macro for details), this opens up your
2063 specified editor with a temporary file containing the macro's data.
1929 specified editor with a temporary file containing the macro's data.
2064 Upon exit, the macro is reloaded with the contents of the file.
1930 Upon exit, the macro is reloaded with the contents of the file.
2065
1931
2066 Note: opening at an exact line is only supported under Unix, and some
1932 Note: opening at an exact line is only supported under Unix, and some
2067 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1933 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2068 '+NUMBER' parameter necessary for this feature. Good editors like
1934 '+NUMBER' parameter necessary for this feature. Good editors like
2069 (X)Emacs, vi, jed, pico and joe all do.
1935 (X)Emacs, vi, jed, pico and joe all do.
2070
1936
2071 - If the argument is not found as a variable, IPython will look for a
1937 - If the argument is not found as a variable, IPython will look for a
2072 file with that name (adding .py if necessary) and load it into the
1938 file with that name (adding .py if necessary) and load it into the
2073 editor. It will execute its contents with execfile() when you exit,
1939 editor. It will execute its contents with execfile() when you exit,
2074 loading any code in the file into your interactive namespace.
1940 loading any code in the file into your interactive namespace.
2075
1941
2076 After executing your code, %edit will return as output the code you
1942 After executing your code, %edit will return as output the code you
2077 typed in the editor (except when it was an existing file). This way
1943 typed in the editor (except when it was an existing file). This way
2078 you can reload the code in further invocations of %edit as a variable,
1944 you can reload the code in further invocations of %edit as a variable,
2079 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1945 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2080 the output.
1946 the output.
2081
1947
2082 Note that %edit is also available through the alias %ed.
1948 Note that %edit is also available through the alias %ed.
2083
1949
2084 This is an example of creating a simple function inside the editor and
1950 This is an example of creating a simple function inside the editor and
2085 then modifying it. First, start up the editor:
1951 then modifying it. First, start up the editor:
2086
1952
2087 In [1]: ed\\
1953 In [1]: ed\\
2088 Editing... done. Executing edited code...\\
1954 Editing... done. Executing edited code...\\
2089 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1955 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
2090
1956
2091 We can then call the function foo():
1957 We can then call the function foo():
2092
1958
2093 In [2]: foo()\\
1959 In [2]: foo()\\
2094 foo() was defined in an editing session
1960 foo() was defined in an editing session
2095
1961
2096 Now we edit foo. IPython automatically loads the editor with the
1962 Now we edit foo. IPython automatically loads the editor with the
2097 (temporary) file where foo() was previously defined:
1963 (temporary) file where foo() was previously defined:
2098
1964
2099 In [3]: ed foo\\
1965 In [3]: ed foo\\
2100 Editing... done. Executing edited code...
1966 Editing... done. Executing edited code...
2101
1967
2102 And if we call foo() again we get the modified version:
1968 And if we call foo() again we get the modified version:
2103
1969
2104 In [4]: foo()\\
1970 In [4]: foo()\\
2105 foo() has now been changed!
1971 foo() has now been changed!
2106
1972
2107 Here is an example of how to edit a code snippet successive
1973 Here is an example of how to edit a code snippet successive
2108 times. First we call the editor:
1974 times. First we call the editor:
2109
1975
2110 In [8]: ed\\
1976 In [8]: ed\\
2111 Editing... done. Executing edited code...\\
1977 Editing... done. Executing edited code...\\
2112 hello\\
1978 hello\\
2113 Out[8]: "print 'hello'\\n"
1979 Out[8]: "print 'hello'\\n"
2114
1980
2115 Now we call it again with the previous output (stored in _):
1981 Now we call it again with the previous output (stored in _):
2116
1982
2117 In [9]: ed _\\
1983 In [9]: ed _\\
2118 Editing... done. Executing edited code...\\
1984 Editing... done. Executing edited code...\\
2119 hello world\\
1985 hello world\\
2120 Out[9]: "print 'hello world'\\n"
1986 Out[9]: "print 'hello world'\\n"
2121
1987
2122 Now we call it with the output #8 (stored in _8, also as Out[8]):
1988 Now we call it with the output #8 (stored in _8, also as Out[8]):
2123
1989
2124 In [10]: ed _8\\
1990 In [10]: ed _8\\
2125 Editing... done. Executing edited code...\\
1991 Editing... done. Executing edited code...\\
2126 hello again\\
1992 hello again\\
2127 Out[10]: "print 'hello again'\\n"
1993 Out[10]: "print 'hello again'\\n"
2128
1994
2129
1995
2130 Changing the default editor hook:
1996 Changing the default editor hook:
2131
1997
2132 If you wish to write your own editor hook, you can put it in a
1998 If you wish to write your own editor hook, you can put it in a
2133 configuration file which you load at startup time. The default hook
1999 configuration file which you load at startup time. The default hook
2134 is defined in the IPython.hooks module, and you can use that as a
2000 is defined in the IPython.hooks module, and you can use that as a
2135 starting example for further modifications. That file also has
2001 starting example for further modifications. That file also has
2136 general instructions on how to set a new hook for use once you've
2002 general instructions on how to set a new hook for use once you've
2137 defined it."""
2003 defined it."""
2138
2004
2139 # FIXME: This function has become a convoluted mess. It needs a
2005 # FIXME: This function has become a convoluted mess. It needs a
2140 # ground-up rewrite with clean, simple logic.
2006 # ground-up rewrite with clean, simple logic.
2141
2007
2142 def make_filename(arg):
2008 def make_filename(arg):
2143 "Make a filename from the given args"
2009 "Make a filename from the given args"
2144 try:
2010 try:
2145 filename = get_py_filename(arg)
2011 filename = get_py_filename(arg)
2146 except IOError:
2012 except IOError:
2147 if args.endswith('.py'):
2013 if args.endswith('.py'):
2148 filename = arg
2014 filename = arg
2149 else:
2015 else:
2150 filename = None
2016 filename = None
2151 return filename
2017 return filename
2152
2018
2153 # custom exceptions
2019 # custom exceptions
2154 class DataIsObject(Exception): pass
2020 class DataIsObject(Exception): pass
2155
2021
2156 opts,args = self.parse_options(parameter_s,'prxn:')
2022 opts,args = self.parse_options(parameter_s,'prxn:')
2157 # Set a few locals from the options for convenience:
2023 # Set a few locals from the options for convenience:
2158 opts_p = opts.has_key('p')
2024 opts_p = opts.has_key('p')
2159 opts_r = opts.has_key('r')
2025 opts_r = opts.has_key('r')
2160
2026
2161 # Default line number value
2027 # Default line number value
2162 lineno = opts.get('n',None)
2028 lineno = opts.get('n',None)
2163
2029
2164 if opts_p:
2030 if opts_p:
2165 args = '_%s' % last_call[0]
2031 args = '_%s' % last_call[0]
2166 if not self.shell.user_ns.has_key(args):
2032 if not self.shell.user_ns.has_key(args):
2167 args = last_call[1]
2033 args = last_call[1]
2168
2034
2169 # use last_call to remember the state of the previous call, but don't
2035 # use last_call to remember the state of the previous call, but don't
2170 # let it be clobbered by successive '-p' calls.
2036 # let it be clobbered by successive '-p' calls.
2171 try:
2037 try:
2172 last_call[0] = self.shell.outputcache.prompt_count
2038 last_call[0] = self.shell.outputcache.prompt_count
2173 if not opts_p:
2039 if not opts_p:
2174 last_call[1] = parameter_s
2040 last_call[1] = parameter_s
2175 except:
2041 except:
2176 pass
2042 pass
2177
2043
2178 # by default this is done with temp files, except when the given
2044 # by default this is done with temp files, except when the given
2179 # arg is a filename
2045 # arg is a filename
2180 use_temp = 1
2046 use_temp = 1
2181
2047
2182 if re.match(r'\d',args):
2048 if re.match(r'\d',args):
2183 # Mode where user specifies ranges of lines, like in %macro.
2049 # Mode where user specifies ranges of lines, like in %macro.
2184 # This means that you can't edit files whose names begin with
2050 # This means that you can't edit files whose names begin with
2185 # numbers this way. Tough.
2051 # numbers this way. Tough.
2186 ranges = args.split()
2052 ranges = args.split()
2187 data = ''.join(self.extract_input_slices(ranges,opts_r))
2053 data = ''.join(self.extract_input_slices(ranges,opts_r))
2188 elif args.endswith('.py'):
2054 elif args.endswith('.py'):
2189 filename = make_filename(args)
2055 filename = make_filename(args)
2190 data = ''
2056 data = ''
2191 use_temp = 0
2057 use_temp = 0
2192 elif args:
2058 elif args:
2193 try:
2059 try:
2194 # Load the parameter given as a variable. If not a string,
2060 # Load the parameter given as a variable. If not a string,
2195 # process it as an object instead (below)
2061 # process it as an object instead (below)
2196
2062
2197 #print '*** args',args,'type',type(args) # dbg
2063 #print '*** args',args,'type',type(args) # dbg
2198 data = eval(args,self.shell.user_ns)
2064 data = eval(args,self.shell.user_ns)
2199 if not type(data) in StringTypes:
2065 if not type(data) in StringTypes:
2200 raise DataIsObject
2066 raise DataIsObject
2201
2067
2202 except (NameError,SyntaxError):
2068 except (NameError,SyntaxError):
2203 # given argument is not a variable, try as a filename
2069 # given argument is not a variable, try as a filename
2204 filename = make_filename(args)
2070 filename = make_filename(args)
2205 if filename is None:
2071 if filename is None:
2206 warn("Argument given (%s) can't be found as a variable "
2072 warn("Argument given (%s) can't be found as a variable "
2207 "or as a filename." % args)
2073 "or as a filename." % args)
2208 return
2074 return
2209
2075
2210 data = ''
2076 data = ''
2211 use_temp = 0
2077 use_temp = 0
2212 except DataIsObject:
2078 except DataIsObject:
2213
2079
2214 # macros have a special edit function
2080 # macros have a special edit function
2215 if isinstance(data,Macro):
2081 if isinstance(data,Macro):
2216 self._edit_macro(args,data)
2082 self._edit_macro(args,data)
2217 return
2083 return
2218
2084
2219 # For objects, try to edit the file where they are defined
2085 # For objects, try to edit the file where they are defined
2220 try:
2086 try:
2221 filename = inspect.getabsfile(data)
2087 filename = inspect.getabsfile(data)
2222 datafile = 1
2088 datafile = 1
2223 except TypeError:
2089 except TypeError:
2224 filename = make_filename(args)
2090 filename = make_filename(args)
2225 datafile = 1
2091 datafile = 1
2226 warn('Could not find file where `%s` is defined.\n'
2092 warn('Could not find file where `%s` is defined.\n'
2227 'Opening a file named `%s`' % (args,filename))
2093 'Opening a file named `%s`' % (args,filename))
2228 # Now, make sure we can actually read the source (if it was in
2094 # Now, make sure we can actually read the source (if it was in
2229 # a temp file it's gone by now).
2095 # a temp file it's gone by now).
2230 if datafile:
2096 if datafile:
2231 try:
2097 try:
2232 if lineno is None:
2098 if lineno is None:
2233 lineno = inspect.getsourcelines(data)[1]
2099 lineno = inspect.getsourcelines(data)[1]
2234 except IOError:
2100 except IOError:
2235 filename = make_filename(args)
2101 filename = make_filename(args)
2236 if filename is None:
2102 if filename is None:
2237 warn('The file `%s` where `%s` was defined cannot '
2103 warn('The file `%s` where `%s` was defined cannot '
2238 'be read.' % (filename,data))
2104 'be read.' % (filename,data))
2239 return
2105 return
2240 use_temp = 0
2106 use_temp = 0
2241 else:
2107 else:
2242 data = ''
2108 data = ''
2243
2109
2244 if use_temp:
2110 if use_temp:
2245 filename = self.shell.mktempfile(data)
2111 filename = self.shell.mktempfile(data)
2246 print 'IPython will make a temporary file named:',filename
2112 print 'IPython will make a temporary file named:',filename
2247
2113
2248 # do actual editing here
2114 # do actual editing here
2249 print 'Editing...',
2115 print 'Editing...',
2250 sys.stdout.flush()
2116 sys.stdout.flush()
2251 self.shell.hooks.editor(filename,lineno)
2117 self.shell.hooks.editor(filename,lineno)
2252 if opts.has_key('x'): # -x prevents actual execution
2118 if opts.has_key('x'): # -x prevents actual execution
2253 print
2119 print
2254 else:
2120 else:
2255 print 'done. Executing edited code...'
2121 print 'done. Executing edited code...'
2256 if opts_r:
2122 if opts_r:
2257 self.shell.runlines(file_read(filename))
2123 self.shell.runlines(file_read(filename))
2258 else:
2124 else:
2259 self.shell.safe_execfile(filename,self.shell.user_ns,
2125 self.shell.safe_execfile(filename,self.shell.user_ns,
2260 self.shell.user_ns)
2126 self.shell.user_ns)
2261 if use_temp:
2127 if use_temp:
2262 try:
2128 try:
2263 return open(filename).read()
2129 return open(filename).read()
2264 except IOError,msg:
2130 except IOError,msg:
2265 if msg.filename == filename:
2131 if msg.filename == filename:
2266 warn('File not found. Did you forget to save?')
2132 warn('File not found. Did you forget to save?')
2267 return
2133 return
2268 else:
2134 else:
2269 self.shell.showtraceback()
2135 self.shell.showtraceback()
2270
2136
2271 def magic_xmode(self,parameter_s = ''):
2137 def magic_xmode(self,parameter_s = ''):
2272 """Switch modes for the exception handlers.
2138 """Switch modes for the exception handlers.
2273
2139
2274 Valid modes: Plain, Context and Verbose.
2140 Valid modes: Plain, Context and Verbose.
2275
2141
2276 If called without arguments, acts as a toggle."""
2142 If called without arguments, acts as a toggle."""
2277
2143
2278 def xmode_switch_err(name):
2144 def xmode_switch_err(name):
2279 warn('Error changing %s exception modes.\n%s' %
2145 warn('Error changing %s exception modes.\n%s' %
2280 (name,sys.exc_info()[1]))
2146 (name,sys.exc_info()[1]))
2281
2147
2282 shell = self.shell
2148 shell = self.shell
2283 new_mode = parameter_s.strip().capitalize()
2149 new_mode = parameter_s.strip().capitalize()
2284 try:
2150 try:
2285 shell.InteractiveTB.set_mode(mode=new_mode)
2151 shell.InteractiveTB.set_mode(mode=new_mode)
2286 print 'Exception reporting mode:',shell.InteractiveTB.mode
2152 print 'Exception reporting mode:',shell.InteractiveTB.mode
2287 except:
2153 except:
2288 xmode_switch_err('user')
2154 xmode_switch_err('user')
2289
2155
2290 # threaded shells use a special handler in sys.excepthook
2156 # threaded shells use a special handler in sys.excepthook
2291 if shell.isthreaded:
2157 if shell.isthreaded:
2292 try:
2158 try:
2293 shell.sys_excepthook.set_mode(mode=new_mode)
2159 shell.sys_excepthook.set_mode(mode=new_mode)
2294 except:
2160 except:
2295 xmode_switch_err('threaded')
2161 xmode_switch_err('threaded')
2296
2162
2297 def magic_colors(self,parameter_s = ''):
2163 def magic_colors(self,parameter_s = ''):
2298 """Switch color scheme for prompts, info system and exception handlers.
2164 """Switch color scheme for prompts, info system and exception handlers.
2299
2165
2300 Currently implemented schemes: NoColor, Linux, LightBG.
2166 Currently implemented schemes: NoColor, Linux, LightBG.
2301
2167
2302 Color scheme names are not case-sensitive."""
2168 Color scheme names are not case-sensitive."""
2303
2169
2304 def color_switch_err(name):
2170 def color_switch_err(name):
2305 warn('Error changing %s color schemes.\n%s' %
2171 warn('Error changing %s color schemes.\n%s' %
2306 (name,sys.exc_info()[1]))
2172 (name,sys.exc_info()[1]))
2307
2173
2308
2174
2309 new_scheme = parameter_s.strip()
2175 new_scheme = parameter_s.strip()
2310 if not new_scheme:
2176 if not new_scheme:
2311 print 'You must specify a color scheme.'
2177 print 'You must specify a color scheme.'
2312 return
2178 return
2313 import IPython.rlineimpl as readline
2179 import IPython.rlineimpl as readline
2314 if not readline.have_readline:
2180 if not readline.have_readline:
2315 msg = """\
2181 msg = """\
2316 Proper color support under MS Windows requires the pyreadline library.
2182 Proper color support under MS Windows requires the pyreadline library.
2317 You can find it at:
2183 You can find it at:
2318 http://ipython.scipy.org/moin/PyReadline/Intro
2184 http://ipython.scipy.org/moin/PyReadline/Intro
2319 Gary's readline needs the ctypes module, from:
2185 Gary's readline needs the ctypes module, from:
2320 http://starship.python.net/crew/theller/ctypes
2186 http://starship.python.net/crew/theller/ctypes
2321 (Note that ctypes is already part of Python versions 2.5 and newer).
2187 (Note that ctypes is already part of Python versions 2.5 and newer).
2322
2188
2323 Defaulting color scheme to 'NoColor'"""
2189 Defaulting color scheme to 'NoColor'"""
2324 new_scheme = 'NoColor'
2190 new_scheme = 'NoColor'
2325 warn(msg)
2191 warn(msg)
2326 # local shortcut
2192 # local shortcut
2327 shell = self.shell
2193 shell = self.shell
2328
2194
2329 # Set prompt colors
2195 # Set prompt colors
2330 try:
2196 try:
2331 shell.outputcache.set_colors(new_scheme)
2197 shell.outputcache.set_colors(new_scheme)
2332 except:
2198 except:
2333 color_switch_err('prompt')
2199 color_switch_err('prompt')
2334 else:
2200 else:
2335 shell.rc.colors = \
2201 shell.rc.colors = \
2336 shell.outputcache.color_table.active_scheme_name
2202 shell.outputcache.color_table.active_scheme_name
2337 # Set exception colors
2203 # Set exception colors
2338 try:
2204 try:
2339 shell.InteractiveTB.set_colors(scheme = new_scheme)
2205 shell.InteractiveTB.set_colors(scheme = new_scheme)
2340 shell.SyntaxTB.set_colors(scheme = new_scheme)
2206 shell.SyntaxTB.set_colors(scheme = new_scheme)
2341 except:
2207 except:
2342 color_switch_err('exception')
2208 color_switch_err('exception')
2343
2209
2344 # threaded shells use a verbose traceback in sys.excepthook
2210 # threaded shells use a verbose traceback in sys.excepthook
2345 if shell.isthreaded:
2211 if shell.isthreaded:
2346 try:
2212 try:
2347 shell.sys_excepthook.set_colors(scheme=new_scheme)
2213 shell.sys_excepthook.set_colors(scheme=new_scheme)
2348 except:
2214 except:
2349 color_switch_err('system exception handler')
2215 color_switch_err('system exception handler')
2350
2216
2351 # Set info (for 'object?') colors
2217 # Set info (for 'object?') colors
2352 if shell.rc.color_info:
2218 if shell.rc.color_info:
2353 try:
2219 try:
2354 shell.inspector.set_active_scheme(new_scheme)
2220 shell.inspector.set_active_scheme(new_scheme)
2355 except:
2221 except:
2356 color_switch_err('object inspector')
2222 color_switch_err('object inspector')
2357 else:
2223 else:
2358 shell.inspector.set_active_scheme('NoColor')
2224 shell.inspector.set_active_scheme('NoColor')
2359
2225
2360 def magic_color_info(self,parameter_s = ''):
2226 def magic_color_info(self,parameter_s = ''):
2361 """Toggle color_info.
2227 """Toggle color_info.
2362
2228
2363 The color_info configuration parameter controls whether colors are
2229 The color_info configuration parameter controls whether colors are
2364 used for displaying object details (by things like %psource, %pfile or
2230 used for displaying object details (by things like %psource, %pfile or
2365 the '?' system). This function toggles this value with each call.
2231 the '?' system). This function toggles this value with each call.
2366
2232
2367 Note that unless you have a fairly recent pager (less works better
2233 Note that unless you have a fairly recent pager (less works better
2368 than more) in your system, using colored object information displays
2234 than more) in your system, using colored object information displays
2369 will not work properly. Test it and see."""
2235 will not work properly. Test it and see."""
2370
2236
2371 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2237 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2372 self.magic_colors(self.shell.rc.colors)
2238 self.magic_colors(self.shell.rc.colors)
2373 print 'Object introspection functions have now coloring:',
2239 print 'Object introspection functions have now coloring:',
2374 print ['OFF','ON'][self.shell.rc.color_info]
2240 print ['OFF','ON'][self.shell.rc.color_info]
2375
2241
2376 def magic_Pprint(self, parameter_s=''):
2242 def magic_Pprint(self, parameter_s=''):
2377 """Toggle pretty printing on/off."""
2243 """Toggle pretty printing on/off."""
2378
2244
2379 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2245 self.shell.rc.pprint = 1 - self.shell.rc.pprint
2380 print 'Pretty printing has been turned', \
2246 print 'Pretty printing has been turned', \
2381 ['OFF','ON'][self.shell.rc.pprint]
2247 ['OFF','ON'][self.shell.rc.pprint]
2382
2248
2383 def magic_exit(self, parameter_s=''):
2249 def magic_exit(self, parameter_s=''):
2384 """Exit IPython, confirming if configured to do so.
2250 """Exit IPython, confirming if configured to do so.
2385
2251
2386 You can configure whether IPython asks for confirmation upon exit by
2252 You can configure whether IPython asks for confirmation upon exit by
2387 setting the confirm_exit flag in the ipythonrc file."""
2253 setting the confirm_exit flag in the ipythonrc file."""
2388
2254
2389 self.shell.exit()
2255 self.shell.exit()
2390
2256
2391 def magic_quit(self, parameter_s=''):
2257 def magic_quit(self, parameter_s=''):
2392 """Exit IPython, confirming if configured to do so (like %exit)"""
2258 """Exit IPython, confirming if configured to do so (like %exit)"""
2393
2259
2394 self.shell.exit()
2260 self.shell.exit()
2395
2261
2396 def magic_Exit(self, parameter_s=''):
2262 def magic_Exit(self, parameter_s=''):
2397 """Exit IPython without confirmation."""
2263 """Exit IPython without confirmation."""
2398
2264
2399 self.shell.exit_now = True
2265 self.shell.exit_now = True
2400
2266
2401 def magic_Quit(self, parameter_s=''):
2402 """Exit IPython without confirmation (like %Exit)."""
2403
2404 self.shell.exit_now = True
2405
2406 #......................................................................
2267 #......................................................................
2407 # Functions to implement unix shell-type things
2268 # Functions to implement unix shell-type things
2408
2269
2409 def magic_alias(self, parameter_s = ''):
2270 def magic_alias(self, parameter_s = ''):
2410 """Define an alias for a system command.
2271 """Define an alias for a system command.
2411
2272
2412 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2273 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2413
2274
2414 Then, typing 'alias_name params' will execute the system command 'cmd
2275 Then, typing 'alias_name params' will execute the system command 'cmd
2415 params' (from your underlying operating system).
2276 params' (from your underlying operating system).
2416
2277
2417 Aliases have lower precedence than magic functions and Python normal
2278 Aliases have lower precedence than magic functions and Python normal
2418 variables, so if 'foo' is both a Python variable and an alias, the
2279 variables, so if 'foo' is both a Python variable and an alias, the
2419 alias can not be executed until 'del foo' removes the Python variable.
2280 alias can not be executed until 'del foo' removes the Python variable.
2420
2281
2421 You can use the %l specifier in an alias definition to represent the
2282 You can use the %l specifier in an alias definition to represent the
2422 whole line when the alias is called. For example:
2283 whole line when the alias is called. For example:
2423
2284
2424 In [2]: alias all echo "Input in brackets: <%l>"\\
2285 In [2]: alias all echo "Input in brackets: <%l>"\\
2425 In [3]: all hello world\\
2286 In [3]: all hello world\\
2426 Input in brackets: <hello world>
2287 Input in brackets: <hello world>
2427
2288
2428 You can also define aliases with parameters using %s specifiers (one
2289 You can also define aliases with parameters using %s specifiers (one
2429 per parameter):
2290 per parameter):
2430
2291
2431 In [1]: alias parts echo first %s second %s\\
2292 In [1]: alias parts echo first %s second %s\\
2432 In [2]: %parts A B\\
2293 In [2]: %parts A B\\
2433 first A second B\\
2294 first A second B\\
2434 In [3]: %parts A\\
2295 In [3]: %parts A\\
2435 Incorrect number of arguments: 2 expected.\\
2296 Incorrect number of arguments: 2 expected.\\
2436 parts is an alias to: 'echo first %s second %s'
2297 parts is an alias to: 'echo first %s second %s'
2437
2298
2438 Note that %l and %s are mutually exclusive. You can only use one or
2299 Note that %l and %s are mutually exclusive. You can only use one or
2439 the other in your aliases.
2300 the other in your aliases.
2440
2301
2441 Aliases expand Python variables just like system calls using ! or !!
2302 Aliases expand Python variables just like system calls using ! or !!
2442 do: all expressions prefixed with '$' get expanded. For details of
2303 do: all expressions prefixed with '$' get expanded. For details of
2443 the semantic rules, see PEP-215:
2304 the semantic rules, see PEP-215:
2444 http://www.python.org/peps/pep-0215.html. This is the library used by
2305 http://www.python.org/peps/pep-0215.html. This is the library used by
2445 IPython for variable expansion. If you want to access a true shell
2306 IPython for variable expansion. If you want to access a true shell
2446 variable, an extra $ is necessary to prevent its expansion by IPython:
2307 variable, an extra $ is necessary to prevent its expansion by IPython:
2447
2308
2448 In [6]: alias show echo\\
2309 In [6]: alias show echo\\
2449 In [7]: PATH='A Python string'\\
2310 In [7]: PATH='A Python string'\\
2450 In [8]: show $PATH\\
2311 In [8]: show $PATH\\
2451 A Python string\\
2312 A Python string\\
2452 In [9]: show $$PATH\\
2313 In [9]: show $$PATH\\
2453 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2314 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2454
2315
2455 You can use the alias facility to acess all of $PATH. See the %rehash
2316 You can use the alias facility to acess all of $PATH. See the %rehash
2456 and %rehashx functions, which automatically create aliases for the
2317 and %rehashx functions, which automatically create aliases for the
2457 contents of your $PATH.
2318 contents of your $PATH.
2458
2319
2459 If called with no parameters, %alias prints the current alias table."""
2320 If called with no parameters, %alias prints the current alias table."""
2460
2321
2461 par = parameter_s.strip()
2322 par = parameter_s.strip()
2462 if not par:
2323 if not par:
2463 stored = self.db.get('stored_aliases', {} )
2324 stored = self.db.get('stored_aliases', {} )
2464 atab = self.shell.alias_table
2325 atab = self.shell.alias_table
2465 aliases = atab.keys()
2326 aliases = atab.keys()
2466 aliases.sort()
2327 aliases.sort()
2467 res = []
2328 res = []
2468 showlast = []
2329 showlast = []
2469 for alias in aliases:
2330 for alias in aliases:
2470 tgt = atab[alias][1]
2331 tgt = atab[alias][1]
2471 # 'interesting' aliases
2332 # 'interesting' aliases
2472 if (alias in stored or
2333 if (alias in stored or
2473 alias.lower() != os.path.splitext(tgt)[0].lower() or
2334 alias.lower() != os.path.splitext(tgt)[0].lower() or
2474 ' ' in tgt):
2335 ' ' in tgt):
2475 showlast.append((alias, tgt))
2336 showlast.append((alias, tgt))
2476 else:
2337 else:
2477 res.append((alias, tgt ))
2338 res.append((alias, tgt ))
2478
2339
2479 # show most interesting aliases last
2340 # show most interesting aliases last
2480 res.extend(showlast)
2341 res.extend(showlast)
2481 print "Total number of aliases:",len(aliases)
2342 print "Total number of aliases:",len(aliases)
2482 return res
2343 return res
2483 try:
2344 try:
2484 alias,cmd = par.split(None,1)
2345 alias,cmd = par.split(None,1)
2485 except:
2346 except:
2486 print OInspect.getdoc(self.magic_alias)
2347 print OInspect.getdoc(self.magic_alias)
2487 else:
2348 else:
2488 nargs = cmd.count('%s')
2349 nargs = cmd.count('%s')
2489 if nargs>0 and cmd.find('%l')>=0:
2350 if nargs>0 and cmd.find('%l')>=0:
2490 error('The %s and %l specifiers are mutually exclusive '
2351 error('The %s and %l specifiers are mutually exclusive '
2491 'in alias definitions.')
2352 'in alias definitions.')
2492 else: # all looks OK
2353 else: # all looks OK
2493 self.shell.alias_table[alias] = (nargs,cmd)
2354 self.shell.alias_table[alias] = (nargs,cmd)
2494 self.shell.alias_table_validate(verbose=0)
2355 self.shell.alias_table_validate(verbose=0)
2495 # end magic_alias
2356 # end magic_alias
2496
2357
2497 def magic_unalias(self, parameter_s = ''):
2358 def magic_unalias(self, parameter_s = ''):
2498 """Remove an alias"""
2359 """Remove an alias"""
2499
2360
2500 aname = parameter_s.strip()
2361 aname = parameter_s.strip()
2501 if aname in self.shell.alias_table:
2362 if aname in self.shell.alias_table:
2502 del self.shell.alias_table[aname]
2363 del self.shell.alias_table[aname]
2503 stored = self.db.get('stored_aliases', {} )
2364 stored = self.db.get('stored_aliases', {} )
2504 if aname in stored:
2365 if aname in stored:
2505 print "Removing %stored alias",aname
2366 print "Removing %stored alias",aname
2506 del stored[aname]
2367 del stored[aname]
2507 self.db['stored_aliases'] = stored
2368 self.db['stored_aliases'] = stored
2508
2369
2509 def magic_rehash(self, parameter_s = ''):
2510 """Update the alias table with all entries in $PATH.
2511
2512 This version does no checks on execute permissions or whether the
2513 contents of $PATH are truly files (instead of directories or something
2514 else). For such a safer (but slower) version, use %rehashx."""
2515
2516 # This function (and rehashx) manipulate the alias_table directly
2517 # rather than calling magic_alias, for speed reasons. A rehash on a
2518 # typical Linux box involves several thousand entries, so efficiency
2519 # here is a top concern.
2520
2521 path = filter(os.path.isdir,os.environ.get('PATH','').split(os.pathsep))
2522 alias_table = self.shell.alias_table
2523 for pdir in path:
2524 for ff in os.listdir(pdir):
2525 # each entry in the alias table must be (N,name), where
2526 # N is the number of positional arguments of the alias.
2527 alias_table[ff] = (0,ff)
2528 # Make sure the alias table doesn't contain keywords or builtins
2529 self.shell.alias_table_validate()
2530 # Call again init_auto_alias() so we get 'rm -i' and other modified
2531 # aliases since %rehash will probably clobber them
2532 self.shell.init_auto_alias()
2533
2370
2534 def magic_rehashx(self, parameter_s = ''):
2371 def magic_rehashx(self, parameter_s = ''):
2535 """Update the alias table with all executable files in $PATH.
2372 """Update the alias table with all executable files in $PATH.
2536
2373
2537 This version explicitly checks that every entry in $PATH is a file
2374 This version explicitly checks that every entry in $PATH is a file
2538 with execute access (os.X_OK), so it is much slower than %rehash.
2375 with execute access (os.X_OK), so it is much slower than %rehash.
2539
2376
2540 Under Windows, it checks executability as a match agains a
2377 Under Windows, it checks executability as a match agains a
2541 '|'-separated string of extensions, stored in the IPython config
2378 '|'-separated string of extensions, stored in the IPython config
2542 variable win_exec_ext. This defaults to 'exe|com|bat'.
2379 variable win_exec_ext. This defaults to 'exe|com|bat'.
2543
2380
2544 This function also resets the root module cache of module completer,
2381 This function also resets the root module cache of module completer,
2545 used on slow filesystems.
2382 used on slow filesystems.
2546 """
2383 """
2547
2384
2548
2385
2549 ip = self.api
2386 ip = self.api
2550
2387
2551 # for the benefit of module completer in ipy_completers.py
2388 # for the benefit of module completer in ipy_completers.py
2552 del ip.db['rootmodules']
2389 del ip.db['rootmodules']
2553
2390
2554 path = [os.path.abspath(os.path.expanduser(p)) for p in
2391 path = [os.path.abspath(os.path.expanduser(p)) for p in
2555 os.environ.get('PATH','').split(os.pathsep)]
2392 os.environ.get('PATH','').split(os.pathsep)]
2556 path = filter(os.path.isdir,path)
2393 path = filter(os.path.isdir,path)
2557
2394
2558 alias_table = self.shell.alias_table
2395 alias_table = self.shell.alias_table
2559 syscmdlist = []
2396 syscmdlist = []
2560 if os.name == 'posix':
2397 if os.name == 'posix':
2561 isexec = lambda fname:os.path.isfile(fname) and \
2398 isexec = lambda fname:os.path.isfile(fname) and \
2562 os.access(fname,os.X_OK)
2399 os.access(fname,os.X_OK)
2563 else:
2400 else:
2564
2401
2565 try:
2402 try:
2566 winext = os.environ['pathext'].replace(';','|').replace('.','')
2403 winext = os.environ['pathext'].replace(';','|').replace('.','')
2567 except KeyError:
2404 except KeyError:
2568 winext = 'exe|com|bat|py'
2405 winext = 'exe|com|bat|py'
2569 if 'py' not in winext:
2406 if 'py' not in winext:
2570 winext += '|py'
2407 winext += '|py'
2571 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2408 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2572 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2409 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2573 savedir = os.getcwd()
2410 savedir = os.getcwd()
2574 try:
2411 try:
2575 # write the whole loop for posix/Windows so we don't have an if in
2412 # write the whole loop for posix/Windows so we don't have an if in
2576 # the innermost part
2413 # the innermost part
2577 if os.name == 'posix':
2414 if os.name == 'posix':
2578 for pdir in path:
2415 for pdir in path:
2579 os.chdir(pdir)
2416 os.chdir(pdir)
2580 for ff in os.listdir(pdir):
2417 for ff in os.listdir(pdir):
2581 if isexec(ff) and ff not in self.shell.no_alias:
2418 if isexec(ff) and ff not in self.shell.no_alias:
2582 # each entry in the alias table must be (N,name),
2419 # each entry in the alias table must be (N,name),
2583 # where N is the number of positional arguments of the
2420 # where N is the number of positional arguments of the
2584 # alias.
2421 # alias.
2585 alias_table[ff] = (0,ff)
2422 alias_table[ff] = (0,ff)
2586 syscmdlist.append(ff)
2423 syscmdlist.append(ff)
2587 else:
2424 else:
2588 for pdir in path:
2425 for pdir in path:
2589 os.chdir(pdir)
2426 os.chdir(pdir)
2590 for ff in os.listdir(pdir):
2427 for ff in os.listdir(pdir):
2591 base, ext = os.path.splitext(ff)
2428 base, ext = os.path.splitext(ff)
2592 if isexec(ff) and base not in self.shell.no_alias:
2429 if isexec(ff) and base not in self.shell.no_alias:
2593 if ext.lower() == '.exe':
2430 if ext.lower() == '.exe':
2594 ff = base
2431 ff = base
2595 alias_table[base.lower()] = (0,ff)
2432 alias_table[base.lower()] = (0,ff)
2596 syscmdlist.append(ff)
2433 syscmdlist.append(ff)
2597 # Make sure the alias table doesn't contain keywords or builtins
2434 # Make sure the alias table doesn't contain keywords or builtins
2598 self.shell.alias_table_validate()
2435 self.shell.alias_table_validate()
2599 # Call again init_auto_alias() so we get 'rm -i' and other
2436 # Call again init_auto_alias() so we get 'rm -i' and other
2600 # modified aliases since %rehashx will probably clobber them
2437 # modified aliases since %rehashx will probably clobber them
2601 self.shell.init_auto_alias()
2438 self.shell.init_auto_alias()
2602 db = ip.db
2439 db = ip.db
2603 db['syscmdlist'] = syscmdlist
2440 db['syscmdlist'] = syscmdlist
2604 finally:
2441 finally:
2605 os.chdir(savedir)
2442 os.chdir(savedir)
2606
2443
2607 def magic_pwd(self, parameter_s = ''):
2444 def magic_pwd(self, parameter_s = ''):
2608 """Return the current working directory path."""
2445 """Return the current working directory path."""
2609 return os.getcwd()
2446 return os.getcwd()
2610
2447
2611 def magic_cd(self, parameter_s=''):
2448 def magic_cd(self, parameter_s=''):
2612 """Change the current working directory.
2449 """Change the current working directory.
2613
2450
2614 This command automatically maintains an internal list of directories
2451 This command automatically maintains an internal list of directories
2615 you visit during your IPython session, in the variable _dh. The
2452 you visit during your IPython session, in the variable _dh. The
2616 command %dhist shows this history nicely formatted. You can also
2453 command %dhist shows this history nicely formatted. You can also
2617 do 'cd -<tab>' to see directory history conveniently.
2454 do 'cd -<tab>' to see directory history conveniently.
2618
2455
2619 Usage:
2456 Usage:
2620
2457
2621 cd 'dir': changes to directory 'dir'.
2458 cd 'dir': changes to directory 'dir'.
2622
2459
2623 cd -: changes to the last visited directory.
2460 cd -: changes to the last visited directory.
2624
2461
2625 cd -<n>: changes to the n-th directory in the directory history.
2462 cd -<n>: changes to the n-th directory in the directory history.
2626
2463
2627 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2464 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2628 (note: cd <bookmark_name> is enough if there is no
2465 (note: cd <bookmark_name> is enough if there is no
2629 directory <bookmark_name>, but a bookmark with the name exists.)
2466 directory <bookmark_name>, but a bookmark with the name exists.)
2630 'cd -b <tab>' allows you to tab-complete bookmark names.
2467 'cd -b <tab>' allows you to tab-complete bookmark names.
2631
2468
2632 Options:
2469 Options:
2633
2470
2634 -q: quiet. Do not print the working directory after the cd command is
2471 -q: quiet. Do not print the working directory after the cd command is
2635 executed. By default IPython's cd command does print this directory,
2472 executed. By default IPython's cd command does print this directory,
2636 since the default prompts do not display path information.
2473 since the default prompts do not display path information.
2637
2474
2638 Note that !cd doesn't work for this purpose because the shell where
2475 Note that !cd doesn't work for this purpose because the shell where
2639 !command runs is immediately discarded after executing 'command'."""
2476 !command runs is immediately discarded after executing 'command'."""
2640
2477
2641 parameter_s = parameter_s.strip()
2478 parameter_s = parameter_s.strip()
2642 #bkms = self.shell.persist.get("bookmarks",{})
2479 #bkms = self.shell.persist.get("bookmarks",{})
2643
2480
2644 numcd = re.match(r'(-)(\d+)$',parameter_s)
2481 numcd = re.match(r'(-)(\d+)$',parameter_s)
2645 # jump in directory history by number
2482 # jump in directory history by number
2646 if numcd:
2483 if numcd:
2647 nn = int(numcd.group(2))
2484 nn = int(numcd.group(2))
2648 try:
2485 try:
2649 ps = self.shell.user_ns['_dh'][nn]
2486 ps = self.shell.user_ns['_dh'][nn]
2650 except IndexError:
2487 except IndexError:
2651 print 'The requested directory does not exist in history.'
2488 print 'The requested directory does not exist in history.'
2652 return
2489 return
2653 else:
2490 else:
2654 opts = {}
2491 opts = {}
2655 else:
2492 else:
2656 #turn all non-space-escaping backslashes to slashes,
2493 #turn all non-space-escaping backslashes to slashes,
2657 # for c:\windows\directory\names\
2494 # for c:\windows\directory\names\
2658 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2495 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2659 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2496 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2660 # jump to previous
2497 # jump to previous
2661 if ps == '-':
2498 if ps == '-':
2662 try:
2499 try:
2663 ps = self.shell.user_ns['_dh'][-2]
2500 ps = self.shell.user_ns['_dh'][-2]
2664 except IndexError:
2501 except IndexError:
2665 print 'No previous directory to change to.'
2502 print 'No previous directory to change to.'
2666 return
2503 return
2667 # jump to bookmark if needed
2504 # jump to bookmark if needed
2668 else:
2505 else:
2669 if not os.path.isdir(ps) or opts.has_key('b'):
2506 if not os.path.isdir(ps) or opts.has_key('b'):
2670 bkms = self.db.get('bookmarks', {})
2507 bkms = self.db.get('bookmarks', {})
2671
2508
2672 if bkms.has_key(ps):
2509 if bkms.has_key(ps):
2673 target = bkms[ps]
2510 target = bkms[ps]
2674 print '(bookmark:%s) -> %s' % (ps,target)
2511 print '(bookmark:%s) -> %s' % (ps,target)
2675 ps = target
2512 ps = target
2676 else:
2513 else:
2677 if opts.has_key('b'):
2514 if opts.has_key('b'):
2678 error("Bookmark '%s' not found. "
2515 error("Bookmark '%s' not found. "
2679 "Use '%%bookmark -l' to see your bookmarks." % ps)
2516 "Use '%%bookmark -l' to see your bookmarks." % ps)
2680 return
2517 return
2681
2518
2682 # at this point ps should point to the target dir
2519 # at this point ps should point to the target dir
2683 if ps:
2520 if ps:
2684 try:
2521 try:
2685 os.chdir(os.path.expanduser(ps))
2522 os.chdir(os.path.expanduser(ps))
2686 if self.shell.rc.term_title:
2523 if self.shell.rc.term_title:
2687 #print 'set term title:',self.shell.rc.term_title # dbg
2524 #print 'set term title:',self.shell.rc.term_title # dbg
2688 ttitle = ("IPy:" + (
2525 ttitle = ("IPy:" + (
2689 os.getcwd() == '/' and '/' or \
2526 os.getcwd() == '/' and '/' or \
2690 os.path.basename(os.getcwd())))
2527 os.path.basename(os.getcwd())))
2691 platutils.set_term_title(ttitle)
2528 platutils.set_term_title(ttitle)
2692 except OSError:
2529 except OSError:
2693 print sys.exc_info()[1]
2530 print sys.exc_info()[1]
2694 else:
2531 else:
2695 self.shell.user_ns['_dh'].append(os.getcwd())
2532 self.shell.user_ns['_dh'].append(os.getcwd())
2696 else:
2533 else:
2697 os.chdir(self.shell.home_dir)
2534 os.chdir(self.shell.home_dir)
2698 if self.shell.rc.term_title:
2535 if self.shell.rc.term_title:
2699 platutils.set_term_title("IPy:~")
2536 platutils.set_term_title("IPy:~")
2700 self.shell.user_ns['_dh'].append(os.getcwd())
2537 self.shell.user_ns['_dh'].append(os.getcwd())
2701 if not 'q' in opts:
2538 if not 'q' in opts:
2702 print self.shell.user_ns['_dh'][-1]
2539 print self.shell.user_ns['_dh'][-1]
2703
2540
2704 def magic_dhist(self, parameter_s=''):
2705 """Print your history of visited directories.
2706
2707 %dhist -> print full history\\
2708 %dhist n -> print last n entries only\\
2709 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2710
2711 This history is automatically maintained by the %cd command, and
2712 always available as the global list variable _dh. You can use %cd -<n>
2713 to go to directory number <n>."""
2714
2715 dh = self.shell.user_ns['_dh']
2716 if parameter_s:
2717 try:
2718 args = map(int,parameter_s.split())
2719 except:
2720 self.arg_err(Magic.magic_dhist)
2721 return
2722 if len(args) == 1:
2723 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2724 elif len(args) == 2:
2725 ini,fin = args
2726 else:
2727 self.arg_err(Magic.magic_dhist)
2728 return
2729 else:
2730 ini,fin = 0,len(dh)
2731 nlprint(dh,
2732 header = 'Directory history (kept in _dh)',
2733 start=ini,stop=fin)
2734
2541
2735 def magic_env(self, parameter_s=''):
2542 def magic_env(self, parameter_s=''):
2736 """List environment variables."""
2543 """List environment variables."""
2737
2544
2738 return os.environ.data
2545 return os.environ.data
2739
2546
2740 def magic_pushd(self, parameter_s=''):
2547 def magic_pushd(self, parameter_s=''):
2741 """Place the current dir on stack and change directory.
2548 """Place the current dir on stack and change directory.
2742
2549
2743 Usage:\\
2550 Usage:\\
2744 %pushd ['dirname']
2551 %pushd ['dirname']
2745
2552
2746 %pushd with no arguments does a %pushd to your home directory.
2553 %pushd with no arguments does a %pushd to your home directory.
2747 """
2554 """
2748 if parameter_s == '': parameter_s = '~'
2555 if parameter_s == '': parameter_s = '~'
2749 dir_s = self.shell.dir_stack
2556 dir_s = self.shell.dir_stack
2750 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2557 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2751 os.path.expanduser(self.shell.dir_stack[0]):
2558 os.path.expanduser(self.shell.dir_stack[0]):
2752 try:
2559 try:
2753 self.magic_cd(parameter_s)
2560 self.magic_cd(parameter_s)
2754 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2561 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2755 self.magic_dirs()
2562 self.magic_dirs()
2756 except:
2563 except:
2757 print 'Invalid directory'
2564 print 'Invalid directory'
2758 else:
2565 else:
2759 print 'You are already there!'
2566 print 'You are already there!'
2760
2567
2761 def magic_popd(self, parameter_s=''):
2568 def magic_popd(self, parameter_s=''):
2762 """Change to directory popped off the top of the stack.
2569 """Change to directory popped off the top of the stack.
2763 """
2570 """
2764 if len (self.shell.dir_stack) > 1:
2571 if len (self.shell.dir_stack) > 1:
2765 self.shell.dir_stack.pop(0)
2572 self.shell.dir_stack.pop(0)
2766 self.magic_cd(self.shell.dir_stack[0])
2573 self.magic_cd(self.shell.dir_stack[0])
2767 print self.shell.dir_stack[0]
2574 print self.shell.dir_stack[0]
2768 else:
2575 else:
2769 print "You can't remove the starting directory from the stack:",\
2576 print "You can't remove the starting directory from the stack:",\
2770 self.shell.dir_stack
2577 self.shell.dir_stack
2771
2578
2772 def magic_dirs(self, parameter_s=''):
2579 def magic_dirs(self, parameter_s=''):
2773 """Return the current directory stack."""
2580 """Return the current directory stack."""
2774
2581
2775 return self.shell.dir_stack[:]
2582 return self.shell.dir_stack[:]
2776
2583
2777 def magic_sc(self, parameter_s=''):
2584 def magic_sc(self, parameter_s=''):
2778 """Shell capture - execute a shell command and capture its output.
2585 """Shell capture - execute a shell command and capture its output.
2779
2586
2780 DEPRECATED. Suboptimal, retained for backwards compatibility.
2587 DEPRECATED. Suboptimal, retained for backwards compatibility.
2781
2588
2782 You should use the form 'var = !command' instead. Example:
2589 You should use the form 'var = !command' instead. Example:
2783
2590
2784 "%sc -l myfiles = ls ~" should now be written as
2591 "%sc -l myfiles = ls ~" should now be written as
2785
2592
2786 "myfiles = !ls ~"
2593 "myfiles = !ls ~"
2787
2594
2788 myfiles.s, myfiles.l and myfiles.n still apply as documented
2595 myfiles.s, myfiles.l and myfiles.n still apply as documented
2789 below.
2596 below.
2790
2597
2791 --
2598 --
2792 %sc [options] varname=command
2599 %sc [options] varname=command
2793
2600
2794 IPython will run the given command using commands.getoutput(), and
2601 IPython will run the given command using commands.getoutput(), and
2795 will then update the user's interactive namespace with a variable
2602 will then update the user's interactive namespace with a variable
2796 called varname, containing the value of the call. Your command can
2603 called varname, containing the value of the call. Your command can
2797 contain shell wildcards, pipes, etc.
2604 contain shell wildcards, pipes, etc.
2798
2605
2799 The '=' sign in the syntax is mandatory, and the variable name you
2606 The '=' sign in the syntax is mandatory, and the variable name you
2800 supply must follow Python's standard conventions for valid names.
2607 supply must follow Python's standard conventions for valid names.
2801
2608
2802 (A special format without variable name exists for internal use)
2609 (A special format without variable name exists for internal use)
2803
2610
2804 Options:
2611 Options:
2805
2612
2806 -l: list output. Split the output on newlines into a list before
2613 -l: list output. Split the output on newlines into a list before
2807 assigning it to the given variable. By default the output is stored
2614 assigning it to the given variable. By default the output is stored
2808 as a single string.
2615 as a single string.
2809
2616
2810 -v: verbose. Print the contents of the variable.
2617 -v: verbose. Print the contents of the variable.
2811
2618
2812 In most cases you should not need to split as a list, because the
2619 In most cases you should not need to split as a list, because the
2813 returned value is a special type of string which can automatically
2620 returned value is a special type of string which can automatically
2814 provide its contents either as a list (split on newlines) or as a
2621 provide its contents either as a list (split on newlines) or as a
2815 space-separated string. These are convenient, respectively, either
2622 space-separated string. These are convenient, respectively, either
2816 for sequential processing or to be passed to a shell command.
2623 for sequential processing or to be passed to a shell command.
2817
2624
2818 For example:
2625 For example:
2819
2626
2820 # Capture into variable a
2627 # Capture into variable a
2821 In [9]: sc a=ls *py
2628 In [9]: sc a=ls *py
2822
2629
2823 # a is a string with embedded newlines
2630 # a is a string with embedded newlines
2824 In [10]: a
2631 In [10]: a
2825 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2632 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2826
2633
2827 # which can be seen as a list:
2634 # which can be seen as a list:
2828 In [11]: a.l
2635 In [11]: a.l
2829 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2636 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2830
2637
2831 # or as a whitespace-separated string:
2638 # or as a whitespace-separated string:
2832 In [12]: a.s
2639 In [12]: a.s
2833 Out[12]: 'setup.py win32_manual_post_install.py'
2640 Out[12]: 'setup.py win32_manual_post_install.py'
2834
2641
2835 # a.s is useful to pass as a single command line:
2642 # a.s is useful to pass as a single command line:
2836 In [13]: !wc -l $a.s
2643 In [13]: !wc -l $a.s
2837 146 setup.py
2644 146 setup.py
2838 130 win32_manual_post_install.py
2645 130 win32_manual_post_install.py
2839 276 total
2646 276 total
2840
2647
2841 # while the list form is useful to loop over:
2648 # while the list form is useful to loop over:
2842 In [14]: for f in a.l:
2649 In [14]: for f in a.l:
2843 ....: !wc -l $f
2650 ....: !wc -l $f
2844 ....:
2651 ....:
2845 146 setup.py
2652 146 setup.py
2846 130 win32_manual_post_install.py
2653 130 win32_manual_post_install.py
2847
2654
2848 Similiarly, the lists returned by the -l option are also special, in
2655 Similiarly, the lists returned by the -l option are also special, in
2849 the sense that you can equally invoke the .s attribute on them to
2656 the sense that you can equally invoke the .s attribute on them to
2850 automatically get a whitespace-separated string from their contents:
2657 automatically get a whitespace-separated string from their contents:
2851
2658
2852 In [1]: sc -l b=ls *py
2659 In [1]: sc -l b=ls *py
2853
2660
2854 In [2]: b
2661 In [2]: b
2855 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2662 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2856
2663
2857 In [3]: b.s
2664 In [3]: b.s
2858 Out[3]: 'setup.py win32_manual_post_install.py'
2665 Out[3]: 'setup.py win32_manual_post_install.py'
2859
2666
2860 In summary, both the lists and strings used for ouptut capture have
2667 In summary, both the lists and strings used for ouptut capture have
2861 the following special attributes:
2668 the following special attributes:
2862
2669
2863 .l (or .list) : value as list.
2670 .l (or .list) : value as list.
2864 .n (or .nlstr): value as newline-separated string.
2671 .n (or .nlstr): value as newline-separated string.
2865 .s (or .spstr): value as space-separated string.
2672 .s (or .spstr): value as space-separated string.
2866 """
2673 """
2867
2674
2868 opts,args = self.parse_options(parameter_s,'lv')
2675 opts,args = self.parse_options(parameter_s,'lv')
2869 # Try to get a variable name and command to run
2676 # Try to get a variable name and command to run
2870 try:
2677 try:
2871 # the variable name must be obtained from the parse_options
2678 # the variable name must be obtained from the parse_options
2872 # output, which uses shlex.split to strip options out.
2679 # output, which uses shlex.split to strip options out.
2873 var,_ = args.split('=',1)
2680 var,_ = args.split('=',1)
2874 var = var.strip()
2681 var = var.strip()
2875 # But the the command has to be extracted from the original input
2682 # But the the command has to be extracted from the original input
2876 # parameter_s, not on what parse_options returns, to avoid the
2683 # parameter_s, not on what parse_options returns, to avoid the
2877 # quote stripping which shlex.split performs on it.
2684 # quote stripping which shlex.split performs on it.
2878 _,cmd = parameter_s.split('=',1)
2685 _,cmd = parameter_s.split('=',1)
2879 except ValueError:
2686 except ValueError:
2880 var,cmd = '',''
2687 var,cmd = '',''
2881 # If all looks ok, proceed
2688 # If all looks ok, proceed
2882 out,err = self.shell.getoutputerror(cmd)
2689 out,err = self.shell.getoutputerror(cmd)
2883 if err:
2690 if err:
2884 print >> Term.cerr,err
2691 print >> Term.cerr,err
2885 if opts.has_key('l'):
2692 if opts.has_key('l'):
2886 out = SList(out.split('\n'))
2693 out = SList(out.split('\n'))
2887 else:
2694 else:
2888 out = LSString(out)
2695 out = LSString(out)
2889 if opts.has_key('v'):
2696 if opts.has_key('v'):
2890 print '%s ==\n%s' % (var,pformat(out))
2697 print '%s ==\n%s' % (var,pformat(out))
2891 if var:
2698 if var:
2892 self.shell.user_ns.update({var:out})
2699 self.shell.user_ns.update({var:out})
2893 else:
2700 else:
2894 return out
2701 return out
2895
2702
2896 def magic_sx(self, parameter_s=''):
2703 def magic_sx(self, parameter_s=''):
2897 """Shell execute - run a shell command and capture its output.
2704 """Shell execute - run a shell command and capture its output.
2898
2705
2899 %sx command
2706 %sx command
2900
2707
2901 IPython will run the given command using commands.getoutput(), and
2708 IPython will run the given command using commands.getoutput(), and
2902 return the result formatted as a list (split on '\\n'). Since the
2709 return the result formatted as a list (split on '\\n'). Since the
2903 output is _returned_, it will be stored in ipython's regular output
2710 output is _returned_, it will be stored in ipython's regular output
2904 cache Out[N] and in the '_N' automatic variables.
2711 cache Out[N] and in the '_N' automatic variables.
2905
2712
2906 Notes:
2713 Notes:
2907
2714
2908 1) If an input line begins with '!!', then %sx is automatically
2715 1) If an input line begins with '!!', then %sx is automatically
2909 invoked. That is, while:
2716 invoked. That is, while:
2910 !ls
2717 !ls
2911 causes ipython to simply issue system('ls'), typing
2718 causes ipython to simply issue system('ls'), typing
2912 !!ls
2719 !!ls
2913 is a shorthand equivalent to:
2720 is a shorthand equivalent to:
2914 %sx ls
2721 %sx ls
2915
2722
2916 2) %sx differs from %sc in that %sx automatically splits into a list,
2723 2) %sx differs from %sc in that %sx automatically splits into a list,
2917 like '%sc -l'. The reason for this is to make it as easy as possible
2724 like '%sc -l'. The reason for this is to make it as easy as possible
2918 to process line-oriented shell output via further python commands.
2725 to process line-oriented shell output via further python commands.
2919 %sc is meant to provide much finer control, but requires more
2726 %sc is meant to provide much finer control, but requires more
2920 typing.
2727 typing.
2921
2728
2922 3) Just like %sc -l, this is a list with special attributes:
2729 3) Just like %sc -l, this is a list with special attributes:
2923
2730
2924 .l (or .list) : value as list.
2731 .l (or .list) : value as list.
2925 .n (or .nlstr): value as newline-separated string.
2732 .n (or .nlstr): value as newline-separated string.
2926 .s (or .spstr): value as whitespace-separated string.
2733 .s (or .spstr): value as whitespace-separated string.
2927
2734
2928 This is very useful when trying to use such lists as arguments to
2735 This is very useful when trying to use such lists as arguments to
2929 system commands."""
2736 system commands."""
2930
2737
2931 if parameter_s:
2738 if parameter_s:
2932 out,err = self.shell.getoutputerror(parameter_s)
2739 out,err = self.shell.getoutputerror(parameter_s)
2933 if err:
2740 if err:
2934 print >> Term.cerr,err
2741 print >> Term.cerr,err
2935 return SList(out.split('\n'))
2742 return SList(out.split('\n'))
2936
2743
2937 def magic_bg(self, parameter_s=''):
2744 def magic_bg(self, parameter_s=''):
2938 """Run a job in the background, in a separate thread.
2745 """Run a job in the background, in a separate thread.
2939
2746
2940 For example,
2747 For example,
2941
2748
2942 %bg myfunc(x,y,z=1)
2749 %bg myfunc(x,y,z=1)
2943
2750
2944 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2751 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2945 execution starts, a message will be printed indicating the job
2752 execution starts, a message will be printed indicating the job
2946 number. If your job number is 5, you can use
2753 number. If your job number is 5, you can use
2947
2754
2948 myvar = jobs.result(5) or myvar = jobs[5].result
2755 myvar = jobs.result(5) or myvar = jobs[5].result
2949
2756
2950 to assign this result to variable 'myvar'.
2757 to assign this result to variable 'myvar'.
2951
2758
2952 IPython has a job manager, accessible via the 'jobs' object. You can
2759 IPython has a job manager, accessible via the 'jobs' object. You can
2953 type jobs? to get more information about it, and use jobs.<TAB> to see
2760 type jobs? to get more information about it, and use jobs.<TAB> to see
2954 its attributes. All attributes not starting with an underscore are
2761 its attributes. All attributes not starting with an underscore are
2955 meant for public use.
2762 meant for public use.
2956
2763
2957 In particular, look at the jobs.new() method, which is used to create
2764 In particular, look at the jobs.new() method, which is used to create
2958 new jobs. This magic %bg function is just a convenience wrapper
2765 new jobs. This magic %bg function is just a convenience wrapper
2959 around jobs.new(), for expression-based jobs. If you want to create a
2766 around jobs.new(), for expression-based jobs. If you want to create a
2960 new job with an explicit function object and arguments, you must call
2767 new job with an explicit function object and arguments, you must call
2961 jobs.new() directly.
2768 jobs.new() directly.
2962
2769
2963 The jobs.new docstring also describes in detail several important
2770 The jobs.new docstring also describes in detail several important
2964 caveats associated with a thread-based model for background job
2771 caveats associated with a thread-based model for background job
2965 execution. Type jobs.new? for details.
2772 execution. Type jobs.new? for details.
2966
2773
2967 You can check the status of all jobs with jobs.status().
2774 You can check the status of all jobs with jobs.status().
2968
2775
2969 The jobs variable is set by IPython into the Python builtin namespace.
2776 The jobs variable is set by IPython into the Python builtin namespace.
2970 If you ever declare a variable named 'jobs', you will shadow this
2777 If you ever declare a variable named 'jobs', you will shadow this
2971 name. You can either delete your global jobs variable to regain
2778 name. You can either delete your global jobs variable to regain
2972 access to the job manager, or make a new name and assign it manually
2779 access to the job manager, or make a new name and assign it manually
2973 to the manager (stored in IPython's namespace). For example, to
2780 to the manager (stored in IPython's namespace). For example, to
2974 assign the job manager to the Jobs name, use:
2781 assign the job manager to the Jobs name, use:
2975
2782
2976 Jobs = __builtins__.jobs"""
2783 Jobs = __builtins__.jobs"""
2977
2784
2978 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2785 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2979
2786
2980
2787
2981 def magic_bookmark(self, parameter_s=''):
2788 def magic_bookmark(self, parameter_s=''):
2982 """Manage IPython's bookmark system.
2789 """Manage IPython's bookmark system.
2983
2790
2984 %bookmark <name> - set bookmark to current dir
2791 %bookmark <name> - set bookmark to current dir
2985 %bookmark <name> <dir> - set bookmark to <dir>
2792 %bookmark <name> <dir> - set bookmark to <dir>
2986 %bookmark -l - list all bookmarks
2793 %bookmark -l - list all bookmarks
2987 %bookmark -d <name> - remove bookmark
2794 %bookmark -d <name> - remove bookmark
2988 %bookmark -r - remove all bookmarks
2795 %bookmark -r - remove all bookmarks
2989
2796
2990 You can later on access a bookmarked folder with:
2797 You can later on access a bookmarked folder with:
2991 %cd -b <name>
2798 %cd -b <name>
2992 or simply '%cd <name>' if there is no directory called <name> AND
2799 or simply '%cd <name>' if there is no directory called <name> AND
2993 there is such a bookmark defined.
2800 there is such a bookmark defined.
2994
2801
2995 Your bookmarks persist through IPython sessions, but they are
2802 Your bookmarks persist through IPython sessions, but they are
2996 associated with each profile."""
2803 associated with each profile."""
2997
2804
2998 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2805 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2999 if len(args) > 2:
2806 if len(args) > 2:
3000 error('You can only give at most two arguments')
2807 error('You can only give at most two arguments')
3001 return
2808 return
3002
2809
3003 bkms = self.db.get('bookmarks',{})
2810 bkms = self.db.get('bookmarks',{})
3004
2811
3005 if opts.has_key('d'):
2812 if opts.has_key('d'):
3006 try:
2813 try:
3007 todel = args[0]
2814 todel = args[0]
3008 except IndexError:
2815 except IndexError:
3009 error('You must provide a bookmark to delete')
2816 error('You must provide a bookmark to delete')
3010 else:
2817 else:
3011 try:
2818 try:
3012 del bkms[todel]
2819 del bkms[todel]
3013 except:
2820 except:
3014 error("Can't delete bookmark '%s'" % todel)
2821 error("Can't delete bookmark '%s'" % todel)
3015 elif opts.has_key('r'):
2822 elif opts.has_key('r'):
3016 bkms = {}
2823 bkms = {}
3017 elif opts.has_key('l'):
2824 elif opts.has_key('l'):
3018 bks = bkms.keys()
2825 bks = bkms.keys()
3019 bks.sort()
2826 bks.sort()
3020 if bks:
2827 if bks:
3021 size = max(map(len,bks))
2828 size = max(map(len,bks))
3022 else:
2829 else:
3023 size = 0
2830 size = 0
3024 fmt = '%-'+str(size)+'s -> %s'
2831 fmt = '%-'+str(size)+'s -> %s'
3025 print 'Current bookmarks:'
2832 print 'Current bookmarks:'
3026 for bk in bks:
2833 for bk in bks:
3027 print fmt % (bk,bkms[bk])
2834 print fmt % (bk,bkms[bk])
3028 else:
2835 else:
3029 if not args:
2836 if not args:
3030 error("You must specify the bookmark name")
2837 error("You must specify the bookmark name")
3031 elif len(args)==1:
2838 elif len(args)==1:
3032 bkms[args[0]] = os.getcwd()
2839 bkms[args[0]] = os.getcwd()
3033 elif len(args)==2:
2840 elif len(args)==2:
3034 bkms[args[0]] = args[1]
2841 bkms[args[0]] = args[1]
3035 self.db['bookmarks'] = bkms
2842 self.db['bookmarks'] = bkms
3036
2843
3037 def magic_pycat(self, parameter_s=''):
2844 def magic_pycat(self, parameter_s=''):
3038 """Show a syntax-highlighted file through a pager.
2845 """Show a syntax-highlighted file through a pager.
3039
2846
3040 This magic is similar to the cat utility, but it will assume the file
2847 This magic is similar to the cat utility, but it will assume the file
3041 to be Python source and will show it with syntax highlighting. """
2848 to be Python source and will show it with syntax highlighting. """
3042
2849
3043 try:
2850 try:
3044 filename = get_py_filename(parameter_s)
2851 filename = get_py_filename(parameter_s)
3045 cont = file_read(filename)
2852 cont = file_read(filename)
3046 except IOError:
2853 except IOError:
3047 try:
2854 try:
3048 cont = eval(parameter_s,self.user_ns)
2855 cont = eval(parameter_s,self.user_ns)
3049 except NameError:
2856 except NameError:
3050 cont = None
2857 cont = None
3051 if cont is None:
2858 if cont is None:
3052 print "Error: no such file or variable"
2859 print "Error: no such file or variable"
3053 return
2860 return
3054
2861
3055 page(self.shell.pycolorize(cont),
2862 page(self.shell.pycolorize(cont),
3056 screen_lines=self.shell.rc.screen_length)
2863 screen_lines=self.shell.rc.screen_length)
3057
2864
3058 def magic_cpaste(self, parameter_s=''):
2865 def magic_cpaste(self, parameter_s=''):
3059 """Allows you to paste & execute a pre-formatted code block from clipboard
2866 """Allows you to paste & execute a pre-formatted code block from clipboard
3060
2867
3061 You must terminate the block with '--' (two minus-signs) alone on the
2868 You must terminate the block with '--' (two minus-signs) alone on the
3062 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
2869 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3063 is the new sentinel for this operation)
2870 is the new sentinel for this operation)
3064
2871
3065 The block is dedented prior to execution to enable execution of
2872 The block is dedented prior to execution to enable execution of
3066 method definitions. '>' characters at the beginning of a line is
2873 method definitions. '>' characters at the beginning of a line is
3067 ignored, to allow pasting directly from e-mails. The executed block
2874 ignored, to allow pasting directly from e-mails. The executed block
3068 is also assigned to variable named 'pasted_block' for later editing
2875 is also assigned to variable named 'pasted_block' for later editing
3069 with '%edit pasted_block'.
2876 with '%edit pasted_block'.
3070
2877
3071 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
2878 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3072 This assigns the pasted block to variable 'foo' as string, without
2879 This assigns the pasted block to variable 'foo' as string, without
3073 dedenting or executing it.
2880 dedenting or executing it.
3074
2881
3075 Do not be alarmed by garbled output on Windows (it's a readline bug).
2882 Do not be alarmed by garbled output on Windows (it's a readline bug).
3076 Just press enter and type -- (and press enter again) and the block
2883 Just press enter and type -- (and press enter again) and the block
3077 will be what was just pasted.
2884 will be what was just pasted.
3078
2885
3079 IPython statements (magics, shell escapes) are not supported (yet).
2886 IPython statements (magics, shell escapes) are not supported (yet).
3080 """
2887 """
3081 opts,args = self.parse_options(parameter_s,'s:',mode='string')
2888 opts,args = self.parse_options(parameter_s,'s:',mode='string')
3082 par = args.strip()
2889 par = args.strip()
3083 sentinel = opts.get('s','--')
2890 sentinel = opts.get('s','--')
3084
2891
3085 from IPython import iplib
2892 from IPython import iplib
3086 lines = []
2893 lines = []
3087 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
2894 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3088 while 1:
2895 while 1:
3089 l = iplib.raw_input_original(':')
2896 l = iplib.raw_input_original(':')
3090 if l ==sentinel:
2897 if l ==sentinel:
3091 break
2898 break
3092 lines.append(l.lstrip('>'))
2899 lines.append(l.lstrip('>'))
3093 block = "\n".join(lines) + '\n'
2900 block = "\n".join(lines) + '\n'
3094 #print "block:\n",block
2901 #print "block:\n",block
3095 if not par:
2902 if not par:
3096 b = textwrap.dedent(block)
2903 b = textwrap.dedent(block)
3097 exec b in self.user_ns
2904 exec b in self.user_ns
3098 self.user_ns['pasted_block'] = b
2905 self.user_ns['pasted_block'] = b
3099 else:
2906 else:
3100 self.user_ns[par] = block
2907 self.user_ns[par] = block
3101 print "Block assigned to '%s'" % par
2908 print "Block assigned to '%s'" % par
3102
2909
3103 def magic_quickref(self,arg):
2910 def magic_quickref(self,arg):
3104 """ Show a quick reference sheet """
2911 """ Show a quick reference sheet """
3105 import IPython.usage
2912 import IPython.usage
3106 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
2913 qr = IPython.usage.quick_reference + self.magic_magic('-brief')
3107
2914
3108 page(qr)
2915 page(qr)
3109
2916
3110 def magic_upgrade(self,arg):
2917 def magic_upgrade(self,arg):
3111 """ Upgrade your IPython installation
2918 """ Upgrade your IPython installation
3112
2919
3113 This will copy the config files that don't yet exist in your
2920 This will copy the config files that don't yet exist in your
3114 ipython dir from the system config dir. Use this after upgrading
2921 ipython dir from the system config dir. Use this after upgrading
3115 IPython if you don't wish to delete your .ipython dir.
2922 IPython if you don't wish to delete your .ipython dir.
3116
2923
3117 Call with -nolegacy to get rid of ipythonrc* files (recommended for
2924 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3118 new users)
2925 new users)
3119
2926
3120 """
2927 """
3121 ip = self.getapi()
2928 ip = self.getapi()
3122 ipinstallation = path(IPython.__file__).dirname()
2929 ipinstallation = path(IPython.__file__).dirname()
3123 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
2930 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'upgrade_dir.py')
3124 src_config = ipinstallation / 'UserConfig'
2931 src_config = ipinstallation / 'UserConfig'
3125 userdir = path(ip.options.ipythondir)
2932 userdir = path(ip.options.ipythondir)
3126 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
2933 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3127 print ">",cmd
2934 print ">",cmd
3128 shell(cmd)
2935 shell(cmd)
3129 if arg == '-nolegacy':
2936 if arg == '-nolegacy':
3130 legacy = userdir.files('ipythonrc*')
2937 legacy = userdir.files('ipythonrc*')
3131 print "Nuking legacy files:",legacy
2938 print "Nuking legacy files:",legacy
3132
2939
3133 [p.remove() for p in legacy]
2940 [p.remove() for p in legacy]
3134 suffix = (sys.platform == 'win32' and '.ini' or '')
2941 suffix = (sys.platform == 'win32' and '.ini' or '')
3135 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
2942 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3136
2943
3137 # end Magic
2944 # end Magic
@@ -1,761 +1,762 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 2156 2007-03-19 02:32:19Z fperez $"""
9 $Id: ipmaker.py 2380 2007-05-24 17:03:49Z vivainio $"""
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_ns['help'] = _Helper()
99 IP.user_ns['help'] = _Helper()
100
100
101
101
102 if DEVDEBUG:
102 if DEVDEBUG:
103 # For developer debugging only (global flag)
103 # For developer debugging only (global flag)
104 from IPython import ultraTB
104 from IPython import ultraTB
105 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
105 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
106
106
107 IP.BANNER_PARTS = ['Python %s\n'
107 IP.BANNER_PARTS = ['Python %s\n'
108 'Type "copyright", "credits" or "license" '
108 'Type "copyright", "credits" or "license" '
109 'for more information.\n'
109 'for more information.\n'
110 % (sys.version.split('\n')[0],),
110 % (sys.version.split('\n')[0],),
111 "IPython %s -- An enhanced Interactive Python."
111 "IPython %s -- An enhanced Interactive Python."
112 % (__version__,),
112 % (__version__,),
113 """? -> Introduction to IPython's features.
113 """? -> Introduction to IPython's features.
114 %magic -> Information about IPython's 'magic' % functions.
114 %magic -> Information about IPython's 'magic' % functions.
115 help -> Python's own help system.
115 help -> Python's own help system.
116 object? -> Details about 'object'. ?object also works, ?? prints more.
116 object? -> Details about 'object'. ?object also works, ?? prints more.
117 """ ]
117 """ ]
118
118
119 IP.usage = interactive_usage
119 IP.usage = interactive_usage
120
120
121 # Platform-dependent suffix and directory names. We use _ipython instead
121 # Platform-dependent suffix and directory names. We use _ipython instead
122 # of .ipython under win32 b/c there's software that breaks with .named
122 # of .ipython under win32 b/c there's software that breaks with .named
123 # directories on that platform.
123 # directories on that platform.
124 if os.name == 'posix':
124 if os.name == 'posix':
125 rc_suffix = ''
125 rc_suffix = ''
126 ipdir_def = '.ipython'
126 ipdir_def = '.ipython'
127 else:
127 else:
128 rc_suffix = '.ini'
128 rc_suffix = '.ini'
129 ipdir_def = '_ipython'
129 ipdir_def = '_ipython'
130
130
131 # default directory for configuration
131 # default directory for configuration
132 ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR',
132 ipythondir_def = os.path.abspath(os.environ.get('IPYTHONDIR',
133 os.path.join(IP.home_dir,ipdir_def)))
133 os.path.join(IP.home_dir,ipdir_def)))
134
134
135 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
135 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
136
136
137 # we need the directory where IPython itself is installed
137 # we need the directory where IPython itself is installed
138 import IPython
138 import IPython
139 IPython_dir = os.path.dirname(IPython.__file__)
139 IPython_dir = os.path.dirname(IPython.__file__)
140 del IPython
140 del IPython
141
141
142 #-------------------------------------------------------------------------
142 #-------------------------------------------------------------------------
143 # Command line handling
143 # Command line handling
144
144
145 # Valid command line options (uses DPyGetOpt syntax, like Perl's
145 # Valid command line options (uses DPyGetOpt syntax, like Perl's
146 # GetOpt::Long)
146 # GetOpt::Long)
147
147
148 # Any key not listed here gets deleted even if in the file (like session
148 # Any key not listed here gets deleted even if in the file (like session
149 # or profile). That's deliberate, to maintain the rc namespace clean.
149 # or profile). That's deliberate, to maintain the rc namespace clean.
150
150
151 # Each set of options appears twice: under _conv only the names are
151 # Each set of options appears twice: under _conv only the names are
152 # listed, indicating which type they must be converted to when reading the
152 # listed, indicating which type they must be converted to when reading the
153 # ipythonrc file. And under DPyGetOpt they are listed with the regular
153 # ipythonrc file. And under DPyGetOpt they are listed with the regular
154 # DPyGetOpt syntax (=s,=i,:f,etc).
154 # DPyGetOpt syntax (=s,=i,:f,etc).
155
155
156 # Make sure there's a space before each end of line (they get auto-joined!)
156 # Make sure there's a space before each end of line (they get auto-joined!)
157 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
157 cmdline_opts = ('autocall=i autoindent! automagic! banner! cache_size|cs=i '
158 'c=s classic|cl color_info! colors=s confirm_exit! '
158 'c=s classic|cl color_info! colors=s confirm_exit! '
159 'debug! deep_reload! editor=s log|l messages! nosep '
159 'debug! deep_reload! editor=s log|l messages! nosep '
160 'object_info_string_level=i pdb! '
160 'object_info_string_level=i pdb! '
161 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
161 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
162 'pylab_import_all! '
162 'pylab_import_all! '
163 'quick screen_length|sl=i prompts_pad_left=i '
163 'quick screen_length|sl=i prompts_pad_left=i '
164 'logfile|lf=s logplay|lp=s profile|p=s '
164 'logfile|lf=s logplay|lp=s profile|p=s '
165 'readline! readline_merge_completions! '
165 'readline! readline_merge_completions! '
166 'readline_omit__names! '
166 'readline_omit__names! '
167 'rcfile=s separate_in|si=s separate_out|so=s '
167 'rcfile=s separate_in|si=s separate_out|so=s '
168 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
168 'separate_out2|so2=s xmode=s wildcards_case_sensitive! '
169 'magic_docstrings system_verbose! '
169 'magic_docstrings system_verbose! '
170 'multi_line_specials! '
170 'multi_line_specials! '
171 'term_title! wxversion=s '
171 'term_title! wxversion=s '
172 'autoedit_syntax!')
172 'autoedit_syntax!')
173
173
174 # Options that can *only* appear at the cmd line (not in rcfiles).
174 # Options that can *only* appear at the cmd line (not in rcfiles).
175
175
176 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
176 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
177 # the 'C-c !' command in emacs automatically appends a -i option at the end.
177 # the 'C-c !' command in emacs automatically appends a -i option at the end.
178 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
178 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
179 'gthread! qthread! q4thread! wthread! pylab! tk!')
179 'gthread! qthread! q4thread! wthread! pylab! tk!')
180
180
181 # Build the actual name list to be used by DPyGetOpt
181 # Build the actual name list to be used by DPyGetOpt
182 opts_names = qw(cmdline_opts) + qw(cmdline_only)
182 opts_names = qw(cmdline_opts) + qw(cmdline_only)
183
183
184 # Set sensible command line defaults.
184 # Set sensible command line defaults.
185 # This should have everything from cmdline_opts and cmdline_only
185 # This should have everything from cmdline_opts and cmdline_only
186 opts_def = Struct(autocall = 1,
186 opts_def = Struct(autocall = 1,
187 autoedit_syntax = 0,
187 autoedit_syntax = 0,
188 autoindent = 0,
188 autoindent = 0,
189 automagic = 1,
189 automagic = 1,
190 banner = 1,
190 banner = 1,
191 cache_size = 1000,
191 cache_size = 1000,
192 c = '',
192 c = '',
193 classic = 0,
193 classic = 0,
194 colors = 'NoColor',
194 colors = 'NoColor',
195 color_info = 0,
195 color_info = 0,
196 confirm_exit = 1,
196 confirm_exit = 1,
197 debug = 0,
197 debug = 0,
198 deep_reload = 0,
198 deep_reload = 0,
199 editor = '0',
199 editor = '0',
200 help = 0,
200 help = 0,
201 ignore = 0,
201 ignore = 0,
202 ipythondir = ipythondir_def,
202 ipythondir = ipythondir_def,
203 log = 0,
203 log = 0,
204 logfile = '',
204 logfile = '',
205 logplay = '',
205 logplay = '',
206 multi_line_specials = 1,
206 multi_line_specials = 1,
207 messages = 1,
207 messages = 1,
208 object_info_string_level = 0,
208 object_info_string_level = 0,
209 nosep = 0,
209 nosep = 0,
210 pdb = 0,
210 pdb = 0,
211 pprint = 0,
211 pprint = 0,
212 profile = '',
212 profile = '',
213 prompt_in1 = 'In [\\#]: ',
213 prompt_in1 = 'In [\\#]: ',
214 prompt_in2 = ' .\\D.: ',
214 prompt_in2 = ' .\\D.: ',
215 prompt_out = 'Out[\\#]: ',
215 prompt_out = 'Out[\\#]: ',
216 prompts_pad_left = 1,
216 prompts_pad_left = 1,
217 pylab_import_all = 1,
217 pylab_import_all = 1,
218 quiet = 0,
218 quiet = 0,
219 quick = 0,
219 quick = 0,
220 readline = 1,
220 readline = 1,
221 readline_merge_completions = 1,
221 readline_merge_completions = 1,
222 readline_omit__names = 0,
222 readline_omit__names = 0,
223 rcfile = 'ipythonrc' + rc_suffix,
223 rcfile = 'ipythonrc' + rc_suffix,
224 screen_length = 0,
224 screen_length = 0,
225 separate_in = '\n',
225 separate_in = '\n',
226 separate_out = '\n',
226 separate_out = '\n',
227 separate_out2 = '',
227 separate_out2 = '',
228 system_header = 'IPython system call: ',
228 system_header = 'IPython system call: ',
229 system_verbose = 0,
229 system_verbose = 0,
230 gthread = 0,
230 gthread = 0,
231 qthread = 0,
231 qthread = 0,
232 q4thread = 0,
232 q4thread = 0,
233 wthread = 0,
233 wthread = 0,
234 pylab = 0,
234 pylab = 0,
235 term_title = 1,
235 term_title = 1,
236 tk = 0,
236 tk = 0,
237 upgrade = 0,
237 upgrade = 0,
238 Version = 0,
238 Version = 0,
239 xmode = 'Verbose',
239 xmode = 'Verbose',
240 wildcards_case_sensitive = 1,
240 wildcards_case_sensitive = 1,
241 wxversion = '0',
241 wxversion = '0',
242 magic_docstrings = 0, # undocumented, for doc generation
242 magic_docstrings = 0, # undocumented, for doc generation
243 )
243 )
244
244
245 # Things that will *only* appear in rcfiles (not at the command line).
245 # Things that will *only* appear in rcfiles (not at the command line).
246 # Make sure there's a space before each end of line (they get auto-joined!)
246 # Make sure there's a space before each end of line (they get auto-joined!)
247 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
247 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
248 qw_lol: 'import_some ',
248 qw_lol: 'import_some ',
249 # for things with embedded whitespace:
249 # for things with embedded whitespace:
250 list_strings:'execute alias readline_parse_and_bind ',
250 list_strings:'execute alias readline_parse_and_bind ',
251 # Regular strings need no conversion:
251 # Regular strings need no conversion:
252 None:'readline_remove_delims ',
252 None:'readline_remove_delims ',
253 }
253 }
254 # Default values for these
254 # Default values for these
255 rc_def = Struct(include = [],
255 rc_def = Struct(include = [],
256 import_mod = [],
256 import_mod = [],
257 import_all = [],
257 import_all = [],
258 import_some = [[]],
258 import_some = [[]],
259 execute = [],
259 execute = [],
260 execfile = [],
260 execfile = [],
261 alias = [],
261 alias = [],
262 readline_parse_and_bind = [],
262 readline_parse_and_bind = [],
263 readline_remove_delims = '',
263 readline_remove_delims = '',
264 )
264 )
265
265
266 # Build the type conversion dictionary from the above tables:
266 # Build the type conversion dictionary from the above tables:
267 typeconv = rcfile_opts.copy()
267 typeconv = rcfile_opts.copy()
268 typeconv.update(optstr2types(cmdline_opts))
268 typeconv.update(optstr2types(cmdline_opts))
269
269
270 # FIXME: the None key appears in both, put that back together by hand. Ugly!
270 # FIXME: the None key appears in both, put that back together by hand. Ugly!
271 typeconv[None] += ' ' + rcfile_opts[None]
271 typeconv[None] += ' ' + rcfile_opts[None]
272
272
273 # Remove quotes at ends of all strings (used to protect spaces)
273 # Remove quotes at ends of all strings (used to protect spaces)
274 typeconv[unquote_ends] = typeconv[None]
274 typeconv[unquote_ends] = typeconv[None]
275 del typeconv[None]
275 del typeconv[None]
276
276
277 # Build the list we'll use to make all config decisions with defaults:
277 # Build the list we'll use to make all config decisions with defaults:
278 opts_all = opts_def.copy()
278 opts_all = opts_def.copy()
279 opts_all.update(rc_def)
279 opts_all.update(rc_def)
280
280
281 # Build conflict resolver for recursive loading of config files:
281 # Build conflict resolver for recursive loading of config files:
282 # - preserve means the outermost file maintains the value, it is not
282 # - preserve means the outermost file maintains the value, it is not
283 # overwritten if an included file has the same key.
283 # overwritten if an included file has the same key.
284 # - add_flip applies + to the two values, so it better make sense to add
284 # - add_flip applies + to the two values, so it better make sense to add
285 # those types of keys. But it flips them first so that things loaded
285 # those types of keys. But it flips them first so that things loaded
286 # deeper in the inclusion chain have lower precedence.
286 # deeper in the inclusion chain have lower precedence.
287 conflict = {'preserve': ' '.join([ typeconv[int],
287 conflict = {'preserve': ' '.join([ typeconv[int],
288 typeconv[unquote_ends] ]),
288 typeconv[unquote_ends] ]),
289 'add_flip': ' '.join([ typeconv[qwflat],
289 'add_flip': ' '.join([ typeconv[qwflat],
290 typeconv[qw_lol],
290 typeconv[qw_lol],
291 typeconv[list_strings] ])
291 typeconv[list_strings] ])
292 }
292 }
293
293
294 # Now actually process the command line
294 # Now actually process the command line
295 getopt = DPyGetOpt.DPyGetOpt()
295 getopt = DPyGetOpt.DPyGetOpt()
296 getopt.setIgnoreCase(0)
296 getopt.setIgnoreCase(0)
297
297
298 getopt.parseConfiguration(opts_names)
298 getopt.parseConfiguration(opts_names)
299
299
300 try:
300 try:
301 getopt.processArguments(argv)
301 getopt.processArguments(argv)
302 except:
302 except:
303 print cmd_line_usage
303 print cmd_line_usage
304 warn('\nError in Arguments: ' + `sys.exc_value`)
304 warn('\nError in Arguments: ' + `sys.exc_value`)
305 sys.exit(1)
305 sys.exit(1)
306
306
307 # convert the options dict to a struct for much lighter syntax later
307 # convert the options dict to a struct for much lighter syntax later
308 opts = Struct(getopt.optionValues)
308 opts = Struct(getopt.optionValues)
309 args = getopt.freeValues
309 args = getopt.freeValues
310
310
311 # this is the struct (which has default values at this point) with which
311 # this is the struct (which has default values at this point) with which
312 # we make all decisions:
312 # we make all decisions:
313 opts_all.update(opts)
313 opts_all.update(opts)
314
314
315 # Options that force an immediate exit
315 # Options that force an immediate exit
316 if opts_all.help:
316 if opts_all.help:
317 page(cmd_line_usage)
317 page(cmd_line_usage)
318 sys.exit()
318 sys.exit()
319
319
320 if opts_all.Version:
320 if opts_all.Version:
321 print __version__
321 print __version__
322 sys.exit()
322 sys.exit()
323
323
324 if opts_all.magic_docstrings:
324 if opts_all.magic_docstrings:
325 IP.magic_magic('-latex')
325 IP.magic_magic('-latex')
326 sys.exit()
326 sys.exit()
327
327
328 # add personal ipythondir to sys.path so that users can put things in
328 # add personal ipythondir to sys.path so that users can put things in
329 # there for customization
329 # there for customization
330 sys.path.append(os.path.abspath(opts_all.ipythondir))
330 sys.path.append(os.path.abspath(opts_all.ipythondir))
331
331
332 # Create user config directory if it doesn't exist. This must be done
332 # Create user config directory if it doesn't exist. This must be done
333 # *after* getting the cmd line options.
333 # *after* getting the cmd line options.
334 if not os.path.isdir(opts_all.ipythondir):
334 if not os.path.isdir(opts_all.ipythondir):
335 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
335 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
336
336
337 # upgrade user config files while preserving a copy of the originals
337 # upgrade user config files while preserving a copy of the originals
338 if opts_all.upgrade:
338 if opts_all.upgrade:
339 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
339 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
340
340
341 # check mutually exclusive options in the *original* command line
341 # check mutually exclusive options in the *original* command line
342 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
342 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
343 qw('classic profile'),qw('classic rcfile')])
343 qw('classic profile'),qw('classic rcfile')])
344
344
345 #---------------------------------------------------------------------------
345 #---------------------------------------------------------------------------
346 # Log replay
346 # Log replay
347
347
348 # if -logplay, we need to 'become' the other session. That basically means
348 # if -logplay, we need to 'become' the other session. That basically means
349 # replacing the current command line environment with that of the old
349 # replacing the current command line environment with that of the old
350 # session and moving on.
350 # session and moving on.
351
351
352 # this is needed so that later we know we're in session reload mode, as
352 # this is needed so that later we know we're in session reload mode, as
353 # opts_all will get overwritten:
353 # opts_all will get overwritten:
354 load_logplay = 0
354 load_logplay = 0
355
355
356 if opts_all.logplay:
356 if opts_all.logplay:
357 load_logplay = opts_all.logplay
357 load_logplay = opts_all.logplay
358 opts_debug_save = opts_all.debug
358 opts_debug_save = opts_all.debug
359 try:
359 try:
360 logplay = open(opts_all.logplay)
360 logplay = open(opts_all.logplay)
361 except IOError:
361 except IOError:
362 if opts_all.debug: IP.InteractiveTB()
362 if opts_all.debug: IP.InteractiveTB()
363 warn('Could not open logplay file '+`opts_all.logplay`)
363 warn('Could not open logplay file '+`opts_all.logplay`)
364 # restore state as if nothing had happened and move on, but make
364 # restore state as if nothing had happened and move on, but make
365 # sure that later we don't try to actually load the session file
365 # sure that later we don't try to actually load the session file
366 logplay = None
366 logplay = None
367 load_logplay = 0
367 load_logplay = 0
368 del opts_all.logplay
368 del opts_all.logplay
369 else:
369 else:
370 try:
370 try:
371 logplay.readline()
371 logplay.readline()
372 logplay.readline();
372 logplay.readline();
373 # this reloads that session's command line
373 # this reloads that session's command line
374 cmd = logplay.readline()[6:]
374 cmd = logplay.readline()[6:]
375 exec cmd
375 exec cmd
376 # restore the true debug flag given so that the process of
376 # restore the true debug flag given so that the process of
377 # session loading itself can be monitored.
377 # session loading itself can be monitored.
378 opts.debug = opts_debug_save
378 opts.debug = opts_debug_save
379 # save the logplay flag so later we don't overwrite the log
379 # save the logplay flag so later we don't overwrite the log
380 opts.logplay = load_logplay
380 opts.logplay = load_logplay
381 # now we must update our own structure with defaults
381 # now we must update our own structure with defaults
382 opts_all.update(opts)
382 opts_all.update(opts)
383 # now load args
383 # now load args
384 cmd = logplay.readline()[6:]
384 cmd = logplay.readline()[6:]
385 exec cmd
385 exec cmd
386 logplay.close()
386 logplay.close()
387 except:
387 except:
388 logplay.close()
388 logplay.close()
389 if opts_all.debug: IP.InteractiveTB()
389 if opts_all.debug: IP.InteractiveTB()
390 warn("Logplay file lacking full configuration information.\n"
390 warn("Logplay file lacking full configuration information.\n"
391 "I'll try to read it, but some things may not work.")
391 "I'll try to read it, but some things may not work.")
392
392
393 #-------------------------------------------------------------------------
393 #-------------------------------------------------------------------------
394 # set up output traps: catch all output from files, being run, modules
394 # set up output traps: catch all output from files, being run, modules
395 # loaded, etc. Then give it to the user in a clean form at the end.
395 # loaded, etc. Then give it to the user in a clean form at the end.
396
396
397 msg_out = 'Output messages. '
397 msg_out = 'Output messages. '
398 msg_err = 'Error messages. '
398 msg_err = 'Error messages. '
399 msg_sep = '\n'
399 msg_sep = '\n'
400 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
400 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
401 msg_err,msg_sep,debug,
401 msg_err,msg_sep,debug,
402 quiet_out=1),
402 quiet_out=1),
403 user_exec = OutputTrap('User File Execution',msg_out,
403 user_exec = OutputTrap('User File Execution',msg_out,
404 msg_err,msg_sep,debug),
404 msg_err,msg_sep,debug),
405 logplay = OutputTrap('Log Loader',msg_out,
405 logplay = OutputTrap('Log Loader',msg_out,
406 msg_err,msg_sep,debug),
406 msg_err,msg_sep,debug),
407 summary = ''
407 summary = ''
408 )
408 )
409
409
410 #-------------------------------------------------------------------------
410 #-------------------------------------------------------------------------
411 # Process user ipythonrc-type configuration files
411 # Process user ipythonrc-type configuration files
412
412
413 # turn on output trapping and log to msg.config
413 # turn on output trapping and log to msg.config
414 # remember that with debug on, trapping is actually disabled
414 # remember that with debug on, trapping is actually disabled
415 msg.config.trap_all()
415 msg.config.trap_all()
416
416
417 # look for rcfile in current or default directory
417 # look for rcfile in current or default directory
418 try:
418 try:
419 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
419 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
420 except IOError:
420 except IOError:
421 if opts_all.debug: IP.InteractiveTB()
421 if opts_all.debug: IP.InteractiveTB()
422 warn('Configuration file %s not found. Ignoring request.'
422 warn('Configuration file %s not found. Ignoring request.'
423 % (opts_all.rcfile) )
423 % (opts_all.rcfile) )
424
424
425 # 'profiles' are a shorthand notation for config filenames
425 # 'profiles' are a shorthand notation for config filenames
426 if opts_all.profile:
426 if opts_all.profile:
427
427
428 try:
428 try:
429 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
429 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
430 + rc_suffix,
430 + rc_suffix,
431 opts_all.ipythondir)
431 opts_all.ipythondir)
432 except IOError:
432 except IOError:
433 if opts_all.debug: IP.InteractiveTB()
433 if opts_all.debug: IP.InteractiveTB()
434 opts.profile = '' # remove profile from options if invalid
434 opts.profile = '' # remove profile from options if invalid
435 # We won't warn anymore, primary method is ipy_profile_PROFNAME
435 # We won't warn anymore, primary method is ipy_profile_PROFNAME
436 # which does trigger a warning.
436 # which does trigger a warning.
437
437
438 # load the config file
438 # load the config file
439 rcfiledata = None
439 rcfiledata = None
440 if opts_all.quick:
440 if opts_all.quick:
441 print 'Launching IPython in quick mode. No config file read.'
441 print 'Launching IPython in quick mode. No config file read.'
442 elif opts_all.rcfile:
442 elif opts_all.rcfile:
443 try:
443 try:
444 cfg_loader = ConfigLoader(conflict)
444 cfg_loader = ConfigLoader(conflict)
445 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
445 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
446 'include',opts_all.ipythondir,
446 'include',opts_all.ipythondir,
447 purge = 1,
447 purge = 1,
448 unique = conflict['preserve'])
448 unique = conflict['preserve'])
449 except:
449 except:
450 IP.InteractiveTB()
450 IP.InteractiveTB()
451 warn('Problems loading configuration file '+
451 warn('Problems loading configuration file '+
452 `opts_all.rcfile`+
452 `opts_all.rcfile`+
453 '\nStarting with default -bare bones- configuration.')
453 '\nStarting with default -bare bones- configuration.')
454 else:
454 else:
455 warn('No valid configuration file found in either currrent directory\n'+
455 warn('No valid configuration file found in either currrent directory\n'+
456 'or in the IPython config. directory: '+`opts_all.ipythondir`+
456 'or in the IPython config. directory: '+`opts_all.ipythondir`+
457 '\nProceeding with internal defaults.')
457 '\nProceeding with internal defaults.')
458
458
459 #------------------------------------------------------------------------
459 #------------------------------------------------------------------------
460 # Set exception handlers in mode requested by user.
460 # Set exception handlers in mode requested by user.
461 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
461 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
462 IP.magic_xmode(opts_all.xmode)
462 IP.magic_xmode(opts_all.xmode)
463 otrap.release_out()
463 otrap.release_out()
464
464
465 #------------------------------------------------------------------------
465 #------------------------------------------------------------------------
466 # Execute user config
466 # Execute user config
467
467
468 # Create a valid config structure with the right precedence order:
468 # Create a valid config structure with the right precedence order:
469 # defaults < rcfile < command line. This needs to be in the instance, so
469 # defaults < rcfile < command line. This needs to be in the instance, so
470 # that method calls below that rely on it find it.
470 # that method calls below that rely on it find it.
471 IP.rc = rc_def.copy()
471 IP.rc = rc_def.copy()
472
472
473 # Work with a local alias inside this routine to avoid unnecessary
473 # Work with a local alias inside this routine to avoid unnecessary
474 # attribute lookups.
474 # attribute lookups.
475 IP_rc = IP.rc
475 IP_rc = IP.rc
476
476
477 IP_rc.update(opts_def)
477 IP_rc.update(opts_def)
478 if rcfiledata:
478 if rcfiledata:
479 # now we can update
479 # now we can update
480 IP_rc.update(rcfiledata)
480 IP_rc.update(rcfiledata)
481 IP_rc.update(opts)
481 IP_rc.update(opts)
482 IP_rc.update(rc_override)
482 IP_rc.update(rc_override)
483
483
484 # Store the original cmd line for reference:
484 # Store the original cmd line for reference:
485 IP_rc.opts = opts
485 IP_rc.opts = opts
486 IP_rc.args = args
486 IP_rc.args = args
487
487
488 # create a *runtime* Struct like rc for holding parameters which may be
488 # create a *runtime* Struct like rc for holding parameters which may be
489 # created and/or modified by runtime user extensions.
489 # created and/or modified by runtime user extensions.
490 IP.runtime_rc = Struct()
490 IP.runtime_rc = Struct()
491
491
492 # from this point on, all config should be handled through IP_rc,
492 # from this point on, all config should be handled through IP_rc,
493 # opts* shouldn't be used anymore.
493 # opts* shouldn't be used anymore.
494
494
495
495
496 # update IP_rc with some special things that need manual
496 # update IP_rc with some special things that need manual
497 # tweaks. Basically options which affect other options. I guess this
497 # tweaks. Basically options which affect other options. I guess this
498 # should just be written so that options are fully orthogonal and we
498 # should just be written so that options are fully orthogonal and we
499 # wouldn't worry about this stuff!
499 # wouldn't worry about this stuff!
500
500
501 if IP_rc.classic:
501 if IP_rc.classic:
502 IP_rc.quick = 1
502 IP_rc.quick = 1
503 IP_rc.cache_size = 0
503 IP_rc.cache_size = 0
504 IP_rc.pprint = 0
504 IP_rc.pprint = 0
505 IP_rc.prompt_in1 = '>>> '
505 IP_rc.prompt_in1 = '>>> '
506 IP_rc.prompt_in2 = '... '
506 IP_rc.prompt_in2 = '... '
507 IP_rc.prompt_out = ''
507 IP_rc.prompt_out = ''
508 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
508 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
509 IP_rc.colors = 'NoColor'
509 IP_rc.colors = 'NoColor'
510 IP_rc.xmode = 'Plain'
510 IP_rc.xmode = 'Plain'
511
511
512 IP.pre_config_initialization()
512 IP.pre_config_initialization()
513 # configure readline
513 # configure readline
514 # Define the history file for saving commands in between sessions
514 # Define the history file for saving commands in between sessions
515 if IP_rc.profile:
515 if IP_rc.profile:
516 histfname = 'history-%s' % IP_rc.profile
516 histfname = 'history-%s' % IP_rc.profile
517 else:
517 else:
518 histfname = 'history'
518 histfname = 'history'
519 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
519 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
520
520
521 # update exception handlers with rc file status
521 # update exception handlers with rc file status
522 otrap.trap_out() # I don't want these messages ever.
522 otrap.trap_out() # I don't want these messages ever.
523 IP.magic_xmode(IP_rc.xmode)
523 IP.magic_xmode(IP_rc.xmode)
524 otrap.release_out()
524 otrap.release_out()
525
525
526 # activate logging if requested and not reloading a log
526 # activate logging if requested and not reloading a log
527 if IP_rc.logplay:
527 if IP_rc.logplay:
528 IP.magic_logstart(IP_rc.logplay + ' append')
528 IP.magic_logstart(IP_rc.logplay + ' append')
529 elif IP_rc.logfile:
529 elif IP_rc.logfile:
530 IP.magic_logstart(IP_rc.logfile)
530 IP.magic_logstart(IP_rc.logfile)
531 elif IP_rc.log:
531 elif IP_rc.log:
532 IP.magic_logstart()
532 IP.magic_logstart()
533
533
534 # find user editor so that it we don't have to look it up constantly
534 # find user editor so that it we don't have to look it up constantly
535 if IP_rc.editor.strip()=='0':
535 if IP_rc.editor.strip()=='0':
536 try:
536 try:
537 ed = os.environ['EDITOR']
537 ed = os.environ['EDITOR']
538 except KeyError:
538 except KeyError:
539 if os.name == 'posix':
539 if os.name == 'posix':
540 ed = 'vi' # the only one guaranteed to be there!
540 ed = 'vi' # the only one guaranteed to be there!
541 else:
541 else:
542 ed = 'notepad' # same in Windows!
542 ed = 'notepad' # same in Windows!
543 IP_rc.editor = ed
543 IP_rc.editor = ed
544
544
545 # Keep track of whether this is an embedded instance or not (useful for
545 # Keep track of whether this is an embedded instance or not (useful for
546 # post-mortems).
546 # post-mortems).
547 IP_rc.embedded = IP.embedded
547 IP_rc.embedded = IP.embedded
548
548
549 # Recursive reload
549 # Recursive reload
550 try:
550 try:
551 from IPython import deep_reload
551 from IPython import deep_reload
552 if IP_rc.deep_reload:
552 if IP_rc.deep_reload:
553 __builtin__.reload = deep_reload.reload
553 __builtin__.reload = deep_reload.reload
554 else:
554 else:
555 __builtin__.dreload = deep_reload.reload
555 __builtin__.dreload = deep_reload.reload
556 del deep_reload
556 del deep_reload
557 except ImportError:
557 except ImportError:
558 pass
558 pass
559
559
560 # Save the current state of our namespace so that the interactive shell
560 # Save the current state of our namespace so that the interactive shell
561 # can later know which variables have been created by us from config files
561 # can later know which variables have been created by us from config files
562 # and loading. This way, loading a file (in any way) is treated just like
562 # and loading. This way, loading a file (in any way) is treated just like
563 # defining things on the command line, and %who works as expected.
563 # defining things on the command line, and %who works as expected.
564
564
565 # DON'T do anything that affects the namespace beyond this point!
565 # DON'T do anything that affects the namespace beyond this point!
566 IP.internal_ns.update(__main__.__dict__)
566 IP.internal_ns.update(__main__.__dict__)
567
567
568 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
568 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
569
569
570 # Now run through the different sections of the users's config
570 # Now run through the different sections of the users's config
571 if IP_rc.debug:
571 if IP_rc.debug:
572 print 'Trying to execute the following configuration structure:'
572 print 'Trying to execute the following configuration structure:'
573 print '(Things listed first are deeper in the inclusion tree and get'
573 print '(Things listed first are deeper in the inclusion tree and get'
574 print 'loaded first).\n'
574 print 'loaded first).\n'
575 pprint(IP_rc.__dict__)
575 pprint(IP_rc.__dict__)
576
576
577 for mod in IP_rc.import_mod:
577 for mod in IP_rc.import_mod:
578 try:
578 try:
579 exec 'import '+mod in IP.user_ns
579 exec 'import '+mod in IP.user_ns
580 except :
580 except :
581 IP.InteractiveTB()
581 IP.InteractiveTB()
582 import_fail_info(mod)
582 import_fail_info(mod)
583
583
584 for mod_fn in IP_rc.import_some:
584 for mod_fn in IP_rc.import_some:
585 if not mod_fn == []:
585 if not mod_fn == []:
586 mod,fn = mod_fn[0],','.join(mod_fn[1:])
586 mod,fn = mod_fn[0],','.join(mod_fn[1:])
587 try:
587 try:
588 exec 'from '+mod+' import '+fn in IP.user_ns
588 exec 'from '+mod+' import '+fn in IP.user_ns
589 except :
589 except :
590 IP.InteractiveTB()
590 IP.InteractiveTB()
591 import_fail_info(mod,fn)
591 import_fail_info(mod,fn)
592
592
593 for mod in IP_rc.import_all:
593 for mod in IP_rc.import_all:
594 try:
594 try:
595 exec 'from '+mod+' import *' in IP.user_ns
595 exec 'from '+mod+' import *' in IP.user_ns
596 except :
596 except :
597 IP.InteractiveTB()
597 IP.InteractiveTB()
598 import_fail_info(mod)
598 import_fail_info(mod)
599
599
600 for code in IP_rc.execute:
600 for code in IP_rc.execute:
601 try:
601 try:
602 exec code in IP.user_ns
602 exec code in IP.user_ns
603 except:
603 except:
604 IP.InteractiveTB()
604 IP.InteractiveTB()
605 warn('Failure executing code: ' + `code`)
605 warn('Failure executing code: ' + `code`)
606
606
607 # Execute the files the user wants in ipythonrc
607 # Execute the files the user wants in ipythonrc
608 for file in IP_rc.execfile:
608 for file in IP_rc.execfile:
609 try:
609 try:
610 file = filefind(file,sys.path+[IPython_dir])
610 file = filefind(file,sys.path+[IPython_dir])
611 except IOError:
611 except IOError:
612 warn(itpl('File $file not found. Skipping it.'))
612 warn(itpl('File $file not found. Skipping it.'))
613 else:
613 else:
614 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
614 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
615
615
616 # finally, try importing ipy_*_conf for final configuration
616 # finally, try importing ipy_*_conf for final configuration
617 try:
617 try:
618 import ipy_system_conf
618 import ipy_system_conf
619 except ImportError:
619 except ImportError:
620 if opts_all.debug: IP.InteractiveTB()
620 if opts_all.debug: IP.InteractiveTB()
621 warn("Could not import 'ipy_system_conf'")
621 warn("Could not import 'ipy_system_conf'")
622 except:
622 except:
623 IP.InteractiveTB()
623 IP.InteractiveTB()
624 import_fail_info('ipy_system_conf')
624 import_fail_info('ipy_system_conf')
625
625
626 if opts_all.profile:
626 if opts_all.profile:
627 profmodname = 'ipy_profile_' + opts_all.profile
627 profmodname = 'ipy_profile_' + opts_all.profile
628 try:
628 try:
629 __import__(profmodname)
629 __import__(profmodname)
630 except ImportError:
630 except ImportError:
631 # only warn if ipythonrc-PROFNAME didn't exist
631 # only warn if ipythonrc-PROFNAME didn't exist
632 if opts.profile =='':
632 if opts.profile =='':
633 warn("Could not start with profile '%s'!\n"
633 warn("Could not start with profile '%s'!\n"
634 "('%s/%s.py' does not exist? run '%%upgrade')" %
634 "('%s/%s.py' does not exist? run '%%upgrade')" %
635 (opts_all.profile, opts_all.ipythondir, profmodname) )
635 (opts_all.profile, opts_all.ipythondir, profmodname) )
636 except:
636 except:
637 print "Error importing",profmodname,"- perhaps you should run %upgrade?"
637 print "Error importing",profmodname,"- perhaps you should run %upgrade?"
638 IP.InteractiveTB()
638 IP.InteractiveTB()
639 import_fail_info(profmodname)
639 import_fail_info(profmodname)
640
640 else:
641 import ipy_profile_none
641 try:
642 try:
642 import ipy_user_conf
643 import ipy_user_conf
643 except ImportError:
644 except ImportError:
644 if opts_all.debug: IP.InteractiveTB()
645 if opts_all.debug: IP.InteractiveTB()
645 warn("Could not import user config!\n "
646 warn("Could not import user config!\n "
646 "('%s/ipy_user_conf.py' does not exist? Please run '%%upgrade')\n"
647 "('%s/ipy_user_conf.py' does not exist? Please run '%%upgrade')\n"
647 % opts_all.ipythondir)
648 % opts_all.ipythondir)
648 except:
649 except:
649 print "Error importing ipy_user_conf - perhaps you should run %upgrade?"
650 print "Error importing ipy_user_conf - perhaps you should run %upgrade?"
650 IP.InteractiveTB()
651 IP.InteractiveTB()
651 import_fail_info("ipy_user_conf")
652 import_fail_info("ipy_user_conf")
652
653
653 # release stdout and stderr and save config log into a global summary
654 # release stdout and stderr and save config log into a global summary
654 msg.config.release_all()
655 msg.config.release_all()
655 if IP_rc.messages:
656 if IP_rc.messages:
656 msg.summary += msg.config.summary_all()
657 msg.summary += msg.config.summary_all()
657
658
658 #------------------------------------------------------------------------
659 #------------------------------------------------------------------------
659 # Setup interactive session
660 # Setup interactive session
660
661
661 # Now we should be fully configured. We can then execute files or load
662 # Now we should be fully configured. We can then execute files or load
662 # things only needed for interactive use. Then we'll open the shell.
663 # things only needed for interactive use. Then we'll open the shell.
663
664
664 # Take a snapshot of the user namespace before opening the shell. That way
665 # Take a snapshot of the user namespace before opening the shell. That way
665 # we'll be able to identify which things were interactively defined and
666 # we'll be able to identify which things were interactively defined and
666 # which were defined through config files.
667 # which were defined through config files.
667 IP.user_config_ns = IP.user_ns.copy()
668 IP.user_config_ns = IP.user_ns.copy()
668
669
669 # Force reading a file as if it were a session log. Slower but safer.
670 # Force reading a file as if it were a session log. Slower but safer.
670 if load_logplay:
671 if load_logplay:
671 print 'Replaying log...'
672 print 'Replaying log...'
672 try:
673 try:
673 if IP_rc.debug:
674 if IP_rc.debug:
674 logplay_quiet = 0
675 logplay_quiet = 0
675 else:
676 else:
676 logplay_quiet = 1
677 logplay_quiet = 1
677
678
678 msg.logplay.trap_all()
679 msg.logplay.trap_all()
679 IP.safe_execfile(load_logplay,IP.user_ns,
680 IP.safe_execfile(load_logplay,IP.user_ns,
680 islog = 1, quiet = logplay_quiet)
681 islog = 1, quiet = logplay_quiet)
681 msg.logplay.release_all()
682 msg.logplay.release_all()
682 if IP_rc.messages:
683 if IP_rc.messages:
683 msg.summary += msg.logplay.summary_all()
684 msg.summary += msg.logplay.summary_all()
684 except:
685 except:
685 warn('Problems replaying logfile %s.' % load_logplay)
686 warn('Problems replaying logfile %s.' % load_logplay)
686 IP.InteractiveTB()
687 IP.InteractiveTB()
687
688
688 # Load remaining files in command line
689 # Load remaining files in command line
689 msg.user_exec.trap_all()
690 msg.user_exec.trap_all()
690
691
691 # Do NOT execute files named in the command line as scripts to be loaded
692 # Do NOT execute files named in the command line as scripts to be loaded
692 # by embedded instances. Doing so has the potential for an infinite
693 # by embedded instances. Doing so has the potential for an infinite
693 # recursion if there are exceptions thrown in the process.
694 # recursion if there are exceptions thrown in the process.
694
695
695 # XXX FIXME: the execution of user files should be moved out to after
696 # XXX FIXME: the execution of user files should be moved out to after
696 # ipython is fully initialized, just as if they were run via %run at the
697 # ipython is fully initialized, just as if they were run via %run at the
697 # ipython prompt. This would also give them the benefit of ipython's
698 # ipython prompt. This would also give them the benefit of ipython's
698 # nice tracebacks.
699 # nice tracebacks.
699
700
700 if (not embedded and IP_rc.args and
701 if (not embedded and IP_rc.args and
701 not IP_rc.args[0].lower().endswith('.ipy')):
702 not IP_rc.args[0].lower().endswith('.ipy')):
702 name_save = IP.user_ns['__name__']
703 name_save = IP.user_ns['__name__']
703 IP.user_ns['__name__'] = '__main__'
704 IP.user_ns['__name__'] = '__main__'
704 # Set our own excepthook in case the user code tries to call it
705 # Set our own excepthook in case the user code tries to call it
705 # directly. This prevents triggering the IPython crash handler.
706 # directly. This prevents triggering the IPython crash handler.
706 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
707 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
707
708
708 save_argv = sys.argv[1:] # save it for later restoring
709 save_argv = sys.argv[1:] # save it for later restoring
709
710
710 sys.argv = args
711 sys.argv = args
711
712
712 try:
713 try:
713 IP.safe_execfile(args[0], IP.user_ns)
714 IP.safe_execfile(args[0], IP.user_ns)
714 finally:
715 finally:
715 # Reset our crash handler in place
716 # Reset our crash handler in place
716 sys.excepthook = old_excepthook
717 sys.excepthook = old_excepthook
717 sys.argv[:] = save_argv
718 sys.argv[:] = save_argv
718 IP.user_ns['__name__'] = name_save
719 IP.user_ns['__name__'] = name_save
719
720
720 msg.user_exec.release_all()
721 msg.user_exec.release_all()
721
722
722 if IP_rc.messages:
723 if IP_rc.messages:
723 msg.summary += msg.user_exec.summary_all()
724 msg.summary += msg.user_exec.summary_all()
724
725
725 # since we can't specify a null string on the cmd line, 0 is the equivalent:
726 # since we can't specify a null string on the cmd line, 0 is the equivalent:
726 if IP_rc.nosep:
727 if IP_rc.nosep:
727 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
728 IP_rc.separate_in = IP_rc.separate_out = IP_rc.separate_out2 = '0'
728 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
729 if IP_rc.separate_in == '0': IP_rc.separate_in = ''
729 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
730 if IP_rc.separate_out == '0': IP_rc.separate_out = ''
730 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
731 if IP_rc.separate_out2 == '0': IP_rc.separate_out2 = ''
731 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
732 IP_rc.separate_in = IP_rc.separate_in.replace('\\n','\n')
732 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
733 IP_rc.separate_out = IP_rc.separate_out.replace('\\n','\n')
733 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
734 IP_rc.separate_out2 = IP_rc.separate_out2.replace('\\n','\n')
734
735
735 # Determine how many lines at the bottom of the screen are needed for
736 # Determine how many lines at the bottom of the screen are needed for
736 # showing prompts, so we can know wheter long strings are to be printed or
737 # showing prompts, so we can know wheter long strings are to be printed or
737 # paged:
738 # paged:
738 num_lines_bot = IP_rc.separate_in.count('\n')+1
739 num_lines_bot = IP_rc.separate_in.count('\n')+1
739 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
740 IP_rc.screen_length = IP_rc.screen_length - num_lines_bot
740
741
741 # configure startup banner
742 # configure startup banner
742 if IP_rc.c: # regular python doesn't print the banner with -c
743 if IP_rc.c: # regular python doesn't print the banner with -c
743 IP_rc.banner = 0
744 IP_rc.banner = 0
744 if IP_rc.banner:
745 if IP_rc.banner:
745 BANN_P = IP.BANNER_PARTS
746 BANN_P = IP.BANNER_PARTS
746 else:
747 else:
747 BANN_P = []
748 BANN_P = []
748
749
749 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
750 if IP_rc.profile: BANN_P.append('IPython profile: %s\n' % IP_rc.profile)
750
751
751 # add message log (possibly empty)
752 # add message log (possibly empty)
752 if msg.summary: BANN_P.append(msg.summary)
753 if msg.summary: BANN_P.append(msg.summary)
753 # Final banner is a string
754 # Final banner is a string
754 IP.BANNER = '\n'.join(BANN_P)
755 IP.BANNER = '\n'.join(BANN_P)
755
756
756 # Finalize the IPython instance. This assumes the rc structure is fully
757 # Finalize the IPython instance. This assumes the rc structure is fully
757 # in place.
758 # in place.
758 IP.post_config_initialization()
759 IP.post_config_initialization()
759
760
760 return IP
761 return IP
761 #************************ end of file <ipmaker.py> **************************
762 #************************ end of file <ipmaker.py> **************************
General Comments 0
You need to be logged in to leave comments. Login now