##// END OF EJS Templates
doc fixes to logging
fperez -
Show More
@@ -1,221 +1,221 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Logger class for IPython's logging facilities.
3 Logger class for IPython's logging facilities.
4
4
5 $Id: Logger.py 966 2005-12-29 08:34:07Z fperez $
5 $Id: Logger.py 974 2005-12-29 19:48:33Z fperez $
6 """
6 """
7
7
8 #*****************************************************************************
8 #*****************************************************************************
9 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
9 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
10 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 #****************************************************************************
16 #****************************************************************************
17 # Modules and globals
17 # Modules and globals
18
18
19 from IPython import Release
19 from IPython import Release
20 __author__ = '%s <%s>\n%s <%s>' % \
20 __author__ = '%s <%s>\n%s <%s>' % \
21 ( Release.authors['Janko'] + Release.authors['Fernando'] )
21 ( Release.authors['Janko'] + Release.authors['Fernando'] )
22 __license__ = Release.license
22 __license__ = Release.license
23
23
24 # Python standard modules
24 # Python standard modules
25 import glob
25 import glob
26 import os
26 import os
27 import time
27 import time
28
28
29 #****************************************************************************
29 #****************************************************************************
30 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
30 # FIXME: This class isn't a mixin anymore, but it still needs attributes from
31 # ipython and does input cache management. Finish cleanup later...
31 # ipython and does input cache management. Finish cleanup later...
32
32
33 class Logger(object):
33 class Logger(object):
34 """A Logfile class with different policies for file creation"""
34 """A Logfile class with different policies for file creation"""
35
35
36 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
36 def __init__(self,shell,logfname='Logger.log',loghead='',logmode='over'):
37
37
38 self._i00,self._i,self._ii,self._iii = '','','',''
38 self._i00,self._i,self._ii,self._iii = '','','',''
39
39
40 # this is the full ipython instance, we need some attributes from it
40 # this is the full ipython instance, we need some attributes from it
41 # which won't exist until later. What a mess, clean up later...
41 # which won't exist until later. What a mess, clean up later...
42 self.shell = shell
42 self.shell = shell
43
43
44 self.logfname = logfname
44 self.logfname = logfname
45 self.loghead = loghead
45 self.loghead = loghead
46 self.logmode = logmode
46 self.logmode = logmode
47 self.logfile = None
47 self.logfile = None
48
48
49 # whether to also log output
49 # whether to also log output
50 self.log_output = False
50 self.log_output = False
51
51
52 # whether to put timestamps before each log entry
52 # whether to put timestamps before each log entry
53 self.timestamp = False
53 self.timestamp = False
54
54
55 # activity control flags
55 # activity control flags
56 self.log_active = False
56 self.log_active = False
57
57
58 # logmode is a validated property
58 # logmode is a validated property
59 def _set_mode(self,mode):
59 def _set_mode(self,mode):
60 if mode not in ['append','backup','global','over','rotate']:
60 if mode not in ['append','backup','global','over','rotate']:
61 raise ValueError,'invalid log mode %s given' % mode
61 raise ValueError,'invalid log mode %s given' % mode
62 self._logmode = mode
62 self._logmode = mode
63
63
64 def _get_mode(self):
64 def _get_mode(self):
65 return self._logmode
65 return self._logmode
66
66
67 logmode = property(_get_mode,_set_mode)
67 logmode = property(_get_mode,_set_mode)
68
68
69 def logstart(self,logfname=None,loghead=None,logmode=None,
69 def logstart(self,logfname=None,loghead=None,logmode=None,
70 log_output=False,timestamp=False):
70 log_output=False,timestamp=False):
71 """Generate a new log-file with a default header.
71 """Generate a new log-file with a default header.
72
72
73 Raises RuntimeError if the log has already been started"""
73 Raises RuntimeError if the log has already been started"""
74
74
75 if self.logfile is not None:
75 if self.logfile is not None:
76 raise RuntimeError('Log file is already active: %s' %
76 raise RuntimeError('Log file is already active: %s' %
77 self.logfname)
77 self.logfname)
78
78
79 self.log_active = True
79 self.log_active = True
80
80
81 # The three parameters can override constructor defaults
81 # The three parameters can override constructor defaults
82 if logfname: self.logfname = logfname
82 if logfname: self.logfname = logfname
83 if loghead: self.loghead = loghead
83 if loghead: self.loghead = loghead
84 if logmode: self.logmode = logmode
84 if logmode: self.logmode = logmode
85 self.timestamp = timestamp
85 self.timestamp = timestamp
86 self.log_output = log_output
86 self.log_output = log_output
87
87
88 # init depending on the log mode requested
88 # init depending on the log mode requested
89 isfile = os.path.isfile
89 isfile = os.path.isfile
90 logmode = self.logmode
90 logmode = self.logmode
91
91
92 if logmode == 'append':
92 if logmode == 'append':
93 self.logfile = open(self.logfname,'a')
93 self.logfile = open(self.logfname,'a')
94
94
95 elif logmode == 'backup':
95 elif logmode == 'backup':
96 if isfile(self.logfname):
96 if isfile(self.logfname):
97 backup_logname = self.logfname+'~'
97 backup_logname = self.logfname+'~'
98 # Manually remove any old backup, since os.rename may fail
98 # Manually remove any old backup, since os.rename may fail
99 # under Windows.
99 # under Windows.
100 if isfile(backup_logname):
100 if isfile(backup_logname):
101 os.remove(backup_logname)
101 os.remove(backup_logname)
102 os.rename(self.logfname,backup_logname)
102 os.rename(self.logfname,backup_logname)
103 self.logfile = open(self.logfname,'w')
103 self.logfile = open(self.logfname,'w')
104
104
105 elif logmode == 'global':
105 elif logmode == 'global':
106 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
106 self.logfname = os.path.join(self.shell.home_dir,self.logfname)
107 self.logfile = open(self.logfname, 'a')
107 self.logfile = open(self.logfname, 'a')
108
108
109 elif logmode == 'over':
109 elif logmode == 'over':
110 if isfile(self.logfname):
110 if isfile(self.logfname):
111 os.remove(self.logfname)
111 os.remove(self.logfname)
112 self.logfile = open(self.logfname,'w')
112 self.logfile = open(self.logfname,'w')
113
113
114 elif logmode == 'rotate':
114 elif logmode == 'rotate':
115 if isfile(self.logfname):
115 if isfile(self.logfname):
116 if isfile(self.logfname+'.001~'):
116 if isfile(self.logfname+'.001~'):
117 old = glob.glob(self.logfname+'.*~')
117 old = glob.glob(self.logfname+'.*~')
118 old.sort()
118 old.sort()
119 old.reverse()
119 old.reverse()
120 for f in old:
120 for f in old:
121 root, ext = os.path.splitext(f)
121 root, ext = os.path.splitext(f)
122 num = int(ext[1:-1])+1
122 num = int(ext[1:-1])+1
123 os.rename(f, root+'.'+`num`.zfill(3)+'~')
123 os.rename(f, root+'.'+`num`.zfill(3)+'~')
124 os.rename(self.logfname, self.logfname+'.001~')
124 os.rename(self.logfname, self.logfname+'.001~')
125 self.logfile = open(self.logfname,'w')
125 self.logfile = open(self.logfname,'w')
126
126
127 if logmode != 'append':
127 if logmode != 'append':
128 self.logfile.write(self.loghead)
128 self.logfile.write(self.loghead)
129
129
130 self.logfile.flush()
130 self.logfile.flush()
131
131
132 def switch_log(self,val):
132 def switch_log(self,val):
133 """Switch logging on/off. val should be ONLY a boolean."""
133 """Switch logging on/off. val should be ONLY a boolean."""
134
134
135 if val not in [False,True,0,1]:
135 if val not in [False,True,0,1]:
136 raise ValueError, \
136 raise ValueError, \
137 'Call switch_log ONLY with a boolean argument, not with:',val
137 'Call switch_log ONLY with a boolean argument, not with:',val
138
138
139 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
139 label = {0:'OFF',1:'ON',False:'OFF',True:'ON'}
140
140
141 if self.logfile is None:
141 if self.logfile is None:
142 print """
142 print """
143 Logging hasn't been started yet (use logstart for that).
143 Logging hasn't been started yet (use logstart for that).
144
144
145 %logon/%logoff are for temporarily starting and stopping logging for a logfile
145 %logon/%logoff are for temporarily starting and stopping logging for a logfile
146 which already exists. But you must first start the logging process with
146 which already exists. But you must first start the logging process with
147 %logstart (optionally giving a logfile name)."""
147 %logstart (optionally giving a logfile name)."""
148
148
149 else:
149 else:
150 if self.log_active == val:
150 if self.log_active == val:
151 print 'Logging is already',label[val]
151 print 'Logging is already',label[val]
152 else:
152 else:
153 print 'Switching logging',label[val]
153 print 'Switching logging',label[val]
154 self.log_active = not self.log_active
154 self.log_active = not self.log_active
155 self.log_active_out = self.log_active
155 self.log_active_out = self.log_active
156
156
157 def logstate(self):
157 def logstate(self):
158 """Print a status message about the logger."""
158 """Print a status message about the logger."""
159 if self.logfile is None:
159 if self.logfile is None:
160 print 'Logging has not been activated.'
160 print 'Logging has not been activated.'
161 else:
161 else:
162 state = self.log_active and 'active' or 'temporarily suspended'
162 state = self.log_active and 'active' or 'temporarily suspended'
163 print 'Filename :',self.logfname
163 print 'Filename :',self.logfname
164 print 'Mode :',self.logmode
164 print 'Mode :',self.logmode
165 print 'Output logging:',self.log_output
165 print 'Output logging :',self.log_output
166 print 'Timestamping :',self.timestamp
166 print 'Timestamping :',self.timestamp
167 print 'State :',state
167 print 'State :',state
168
168
169 def log(self, line,continuation=None):
169 def log(self, line,continuation=None):
170 """Write the line to a log and create input cache variables _i*."""
170 """Write the line to a log and create input cache variables _i*."""
171
171
172 # update the auto _i tables
172 # update the auto _i tables
173 #print '***logging line',line # dbg
173 #print '***logging line',line # dbg
174 #print '***cache_count', self.shell.outputcache.prompt_count # dbg
174 #print '***cache_count', self.shell.outputcache.prompt_count # dbg
175 input_hist = self.shell.user_ns['_ih']
175 input_hist = self.shell.user_ns['_ih']
176 if not continuation and line:
176 if not continuation and line:
177 self._iii = self._ii
177 self._iii = self._ii
178 self._ii = self._i
178 self._ii = self._i
179 self._i = self._i00
179 self._i = self._i00
180 # put back the final \n of every input line
180 # put back the final \n of every input line
181 self._i00 = line+'\n'
181 self._i00 = line+'\n'
182 #print 'Logging input:<%s>' % line # dbg
182 #print 'Logging input:<%s>' % line # dbg
183 input_hist.append(self._i00)
183 input_hist.append(self._i00)
184
184
185 # hackish access to top-level namespace to create _i1,_i2... dynamically
185 # hackish access to top-level namespace to create _i1,_i2... dynamically
186 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
186 to_main = {'_i':self._i,'_ii':self._ii,'_iii':self._iii}
187 if self.shell.outputcache.do_full_cache:
187 if self.shell.outputcache.do_full_cache:
188 in_num = self.shell.outputcache.prompt_count
188 in_num = self.shell.outputcache.prompt_count
189 # add blank lines if the input cache fell out of sync. This can
189 # add blank lines if the input cache fell out of sync. This can
190 # happen for embedded instances which get killed via C-D and then
190 # happen for embedded instances which get killed via C-D and then
191 # get resumed.
191 # get resumed.
192 while in_num >= len(input_hist):
192 while in_num >= len(input_hist):
193 input_hist.append('\n')
193 input_hist.append('\n')
194 new_i = '_i%s' % in_num
194 new_i = '_i%s' % in_num
195 if continuation:
195 if continuation:
196 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line)
196 self._i00 = '%s%s\n' % (self.shell.user_ns[new_i],line)
197 input_hist[in_num] = self._i00
197 input_hist[in_num] = self._i00
198 to_main[new_i] = self._i00
198 to_main[new_i] = self._i00
199 self.shell.user_ns.update(to_main)
199 self.shell.user_ns.update(to_main)
200 self.log_write(line)
200 self.log_write(line)
201
201
202 def log_write(self,data,kind='input'):
202 def log_write(self,data,kind='input'):
203 """Write data to the log file, if active"""
203 """Write data to the log file, if active"""
204
204
205 if self.log_active and data:
205 if self.log_active and data:
206 write = self.logfile.write
206 write = self.logfile.write
207 if kind=='input':
207 if kind=='input':
208 if self.timestamp:
208 if self.timestamp:
209 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
209 write(time.strftime('# %a, %d %b %Y %H:%M:%S\n',
210 time.localtime()))
210 time.localtime()))
211 write('%s\n' % data)
211 write('%s\n' % data)
212 elif kind=='output' and self.log_output:
212 elif kind=='output' and self.log_output:
213 odata = '\n'.join(['#[Out]# %s' % s
213 odata = '\n'.join(['#[Out]# %s' % s
214 for s in data.split('\n')])
214 for s in data.split('\n')])
215 write('%s\n' % odata)
215 write('%s\n' % odata)
216 self.logfile.flush()
216 self.logfile.flush()
217
217
218 def close_log(self):
218 def close_log(self):
219 self.logfile.close()
219 self.logfile.close()
220 self.logfile = None
220 self.logfile = None
221 self.logfname = ''
221 self.logfname = ''
@@ -1,2671 +1,2676 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 973 2005-12-29 18:51:56Z fperez $"""
4 $Id: Magic.py 974 2005-12-29 19:48:33Z fperez $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2004 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 from cStringIO import StringIO
34 from cStringIO import StringIO
35 from getopt import getopt
35 from getopt import getopt
36 from pprint import pprint, pformat
36 from pprint import pprint, pformat
37
37
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # Homebrewed
44 # Homebrewed
45 from IPython import Debugger, OInspect, wildcard
45 from IPython import Debugger, OInspect, wildcard
46 from IPython.FakeModule import FakeModule
46 from IPython.FakeModule import FakeModule
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
47 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.PyColorize import Parser
48 from IPython.PyColorize import Parser
49 from IPython.Struct import Struct
49 from IPython.Struct import Struct
50 from IPython.genutils import *
50 from IPython.genutils import *
51
51
52 #***************************************************************************
52 #***************************************************************************
53 # Utility functions
53 # Utility functions
54 def on_off(tag):
54 def on_off(tag):
55 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
55 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
56 return ['OFF','ON'][tag]
56 return ['OFF','ON'][tag]
57
57
58
58
59 #****************************************************************************
59 #****************************************************************************
60 # Utility classes
60 # Utility classes
61 class Macro(list):
61 class Macro(list):
62 """Simple class to store the value of macros as strings.
62 """Simple class to store the value of macros as strings.
63
63
64 This allows us to later exec them by checking when something is an
64 This allows us to later exec them by checking when something is an
65 instance of this class."""
65 instance of this class."""
66
66
67 def __init__(self,data):
67 def __init__(self,data):
68 list.__init__(self,data)
68 list.__init__(self,data)
69 self.value = ''.join(data)
69 self.value = ''.join(data)
70
70
71 #***************************************************************************
71 #***************************************************************************
72 # Main class implementing Magic functionality
72 # Main class implementing Magic functionality
73 class Magic:
73 class Magic:
74 """Magic functions for InteractiveShell.
74 """Magic functions for InteractiveShell.
75
75
76 Shell functions which can be reached as %function_name. All magic
76 Shell functions which can be reached as %function_name. All magic
77 functions should accept a string, which they can parse for their own
77 functions should accept a string, which they can parse for their own
78 needs. This can make some functions easier to type, eg `%cd ../`
78 needs. This can make some functions easier to type, eg `%cd ../`
79 vs. `%cd("../")`
79 vs. `%cd("../")`
80
80
81 ALL definitions MUST begin with the prefix magic_. The user won't need it
81 ALL definitions MUST begin with the prefix magic_. The user won't need it
82 at the command line, but it is is needed in the definition. """
82 at the command line, but it is is needed in the definition. """
83
83
84 # class globals
84 # class globals
85 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
85 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
86 'Automagic is ON, % prefix NOT needed for magic functions.']
86 'Automagic is ON, % prefix NOT needed for magic functions.']
87
87
88 #......................................................................
88 #......................................................................
89 # some utility functions
89 # some utility functions
90
90
91 def __init__(self,shell):
91 def __init__(self,shell):
92
92
93 self.options_table = {}
93 self.options_table = {}
94 if profile is None:
94 if profile is None:
95 self.magic_prun = self.profile_missing_notice
95 self.magic_prun = self.profile_missing_notice
96 self.shell = shell
96 self.shell = shell
97
97
98 def profile_missing_notice(self, *args, **kwargs):
98 def profile_missing_notice(self, *args, **kwargs):
99 error("""\
99 error("""\
100 The profile module could not be found. If you are a Debian user,
100 The profile module could not be found. If you are a Debian user,
101 it has been removed from the standard Debian package because of its non-free
101 it has been removed from the standard Debian package because of its non-free
102 license. To use profiling, please install"python2.3-profiler" from non-free.""")
102 license. To use profiling, please install"python2.3-profiler" from non-free.""")
103
103
104 def default_option(self,fn,optstr):
104 def default_option(self,fn,optstr):
105 """Make an entry in the options_table for fn, with value optstr"""
105 """Make an entry in the options_table for fn, with value optstr"""
106
106
107 if fn not in self.lsmagic():
107 if fn not in self.lsmagic():
108 error("%s is not a magic function" % fn)
108 error("%s is not a magic function" % fn)
109 self.options_table[fn] = optstr
109 self.options_table[fn] = optstr
110
110
111 def lsmagic(self):
111 def lsmagic(self):
112 """Return a list of currently available magic functions.
112 """Return a list of currently available magic functions.
113
113
114 Gives a list of the bare names after mangling (['ls','cd', ...], not
114 Gives a list of the bare names after mangling (['ls','cd', ...], not
115 ['magic_ls','magic_cd',...]"""
115 ['magic_ls','magic_cd',...]"""
116
116
117 # FIXME. This needs a cleanup, in the way the magics list is built.
117 # FIXME. This needs a cleanup, in the way the magics list is built.
118
118
119 # magics in class definition
119 # magics in class definition
120 class_magic = lambda fn: fn.startswith('magic_') and \
120 class_magic = lambda fn: fn.startswith('magic_') and \
121 callable(Magic.__dict__[fn])
121 callable(Magic.__dict__[fn])
122 # in instance namespace (run-time user additions)
122 # in instance namespace (run-time user additions)
123 inst_magic = lambda fn: fn.startswith('magic_') and \
123 inst_magic = lambda fn: fn.startswith('magic_') and \
124 callable(self.__dict__[fn])
124 callable(self.__dict__[fn])
125 # and bound magics by user (so they can access self):
125 # and bound magics by user (so they can access self):
126 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
126 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
127 callable(self.__class__.__dict__[fn])
127 callable(self.__class__.__dict__[fn])
128 magics = filter(class_magic,Magic.__dict__.keys()) + \
128 magics = filter(class_magic,Magic.__dict__.keys()) + \
129 filter(inst_magic,self.__dict__.keys()) + \
129 filter(inst_magic,self.__dict__.keys()) + \
130 filter(inst_bound_magic,self.__class__.__dict__.keys())
130 filter(inst_bound_magic,self.__class__.__dict__.keys())
131 out = []
131 out = []
132 for fn in magics:
132 for fn in magics:
133 out.append(fn.replace('magic_','',1))
133 out.append(fn.replace('magic_','',1))
134 out.sort()
134 out.sort()
135 return out
135 return out
136
136
137 def extract_input_slices(self,slices):
137 def extract_input_slices(self,slices):
138 """Return as a string a set of input history slices.
138 """Return as a string a set of input history slices.
139
139
140 The set of slices is given as a list of strings (like ['1','4:8','9'],
140 The set of slices is given as a list of strings (like ['1','4:8','9'],
141 since this function is for use by magic functions which get their
141 since this function is for use by magic functions which get their
142 arguments as strings."""
142 arguments as strings."""
143
143
144 cmds = []
144 cmds = []
145 for chunk in slices:
145 for chunk in slices:
146 if ':' in chunk:
146 if ':' in chunk:
147 ini,fin = map(int,chunk.split(':'))
147 ini,fin = map(int,chunk.split(':'))
148 else:
148 else:
149 ini = int(chunk)
149 ini = int(chunk)
150 fin = ini+1
150 fin = ini+1
151 cmds.append(self.shell.input_hist[ini:fin])
151 cmds.append(self.shell.input_hist[ini:fin])
152 return cmds
152 return cmds
153
153
154 def _ofind(self,oname):
154 def _ofind(self,oname):
155 """Find an object in the available namespaces.
155 """Find an object in the available namespaces.
156
156
157 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
157 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
158
158
159 Has special code to detect magic functions.
159 Has special code to detect magic functions.
160 """
160 """
161
161
162 oname = oname.strip()
162 oname = oname.strip()
163
163
164 # Namespaces to search in:
164 # Namespaces to search in:
165 user_ns = self.shell.user_ns
165 user_ns = self.shell.user_ns
166 internal_ns = self.shell.internal_ns
166 internal_ns = self.shell.internal_ns
167 builtin_ns = __builtin__.__dict__
167 builtin_ns = __builtin__.__dict__
168 alias_ns = self.shell.alias_table
168 alias_ns = self.shell.alias_table
169
169
170 # Put them in a list. The order is important so that we find things in
170 # Put them in a list. The order is important so that we find things in
171 # the same order that Python finds them.
171 # the same order that Python finds them.
172 namespaces = [ ('Interactive',user_ns),
172 namespaces = [ ('Interactive',user_ns),
173 ('IPython internal',internal_ns),
173 ('IPython internal',internal_ns),
174 ('Python builtin',builtin_ns),
174 ('Python builtin',builtin_ns),
175 ('Alias',alias_ns),
175 ('Alias',alias_ns),
176 ]
176 ]
177
177
178 # initialize results to 'null'
178 # initialize results to 'null'
179 found = 0; obj = None; ospace = None; ds = None;
179 found = 0; obj = None; ospace = None; ds = None;
180 ismagic = 0; isalias = 0
180 ismagic = 0; isalias = 0
181
181
182 # Look for the given name by splitting it in parts. If the head is
182 # Look for the given name by splitting it in parts. If the head is
183 # found, then we look for all the remaining parts as members, and only
183 # found, then we look for all the remaining parts as members, and only
184 # declare success if we can find them all.
184 # declare success if we can find them all.
185 oname_parts = oname.split('.')
185 oname_parts = oname.split('.')
186 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
186 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
187 for nsname,ns in namespaces:
187 for nsname,ns in namespaces:
188 try:
188 try:
189 obj = ns[oname_head]
189 obj = ns[oname_head]
190 except KeyError:
190 except KeyError:
191 continue
191 continue
192 else:
192 else:
193 for part in oname_rest:
193 for part in oname_rest:
194 try:
194 try:
195 obj = getattr(obj,part)
195 obj = getattr(obj,part)
196 except:
196 except:
197 # Blanket except b/c some badly implemented objects
197 # Blanket except b/c some badly implemented objects
198 # allow __getattr__ to raise exceptions other than
198 # allow __getattr__ to raise exceptions other than
199 # AttributeError, which then crashes IPython.
199 # AttributeError, which then crashes IPython.
200 break
200 break
201 else:
201 else:
202 # If we finish the for loop (no break), we got all members
202 # If we finish the for loop (no break), we got all members
203 found = 1
203 found = 1
204 ospace = nsname
204 ospace = nsname
205 if ns == alias_ns:
205 if ns == alias_ns:
206 isalias = 1
206 isalias = 1
207 break # namespace loop
207 break # namespace loop
208
208
209 # Try to see if it's magic
209 # Try to see if it's magic
210 if not found:
210 if not found:
211 if oname.startswith(self.shell.ESC_MAGIC):
211 if oname.startswith(self.shell.ESC_MAGIC):
212 oname = oname[1:]
212 oname = oname[1:]
213 obj = getattr(self,'magic_'+oname,None)
213 obj = getattr(self,'magic_'+oname,None)
214 if obj is not None:
214 if obj is not None:
215 found = 1
215 found = 1
216 ospace = 'IPython internal'
216 ospace = 'IPython internal'
217 ismagic = 1
217 ismagic = 1
218
218
219 # Last try: special-case some literals like '', [], {}, etc:
219 # Last try: special-case some literals like '', [], {}, etc:
220 if not found and oname_head in ["''",'""','[]','{}','()']:
220 if not found and oname_head in ["''",'""','[]','{}','()']:
221 obj = eval(oname_head)
221 obj = eval(oname_head)
222 found = 1
222 found = 1
223 ospace = 'Interactive'
223 ospace = 'Interactive'
224
224
225 return {'found':found, 'obj':obj, 'namespace':ospace,
225 return {'found':found, 'obj':obj, 'namespace':ospace,
226 'ismagic':ismagic, 'isalias':isalias}
226 'ismagic':ismagic, 'isalias':isalias}
227
227
228 def arg_err(self,func):
228 def arg_err(self,func):
229 """Print docstring if incorrect arguments were passed"""
229 """Print docstring if incorrect arguments were passed"""
230 print 'Error in arguments:'
230 print 'Error in arguments:'
231 print OInspect.getdoc(func)
231 print OInspect.getdoc(func)
232
232
233
233
234 def format_latex(self,strng):
234 def format_latex(self,strng):
235 """Format a string for latex inclusion."""
235 """Format a string for latex inclusion."""
236
236
237 # Characters that need to be escaped for latex:
237 # Characters that need to be escaped for latex:
238 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
238 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
239 # Magic command names as headers:
239 # Magic command names as headers:
240 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
240 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
241 re.MULTILINE)
241 re.MULTILINE)
242 # Magic commands
242 # Magic commands
243 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
243 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
244 re.MULTILINE)
244 re.MULTILINE)
245 # Paragraph continue
245 # Paragraph continue
246 par_re = re.compile(r'\\$',re.MULTILINE)
246 par_re = re.compile(r'\\$',re.MULTILINE)
247
247
248 # The "\n" symbol
248 # The "\n" symbol
249 newline_re = re.compile(r'\\n')
249 newline_re = re.compile(r'\\n')
250
250
251 # Now build the string for output:
251 # Now build the string for output:
252 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
252 strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
253 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
253 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
254 strng = par_re.sub(r'\\\\',strng)
254 strng = par_re.sub(r'\\\\',strng)
255 strng = escape_re.sub(r'\\\1',strng)
255 strng = escape_re.sub(r'\\\1',strng)
256 strng = newline_re.sub(r'\\textbackslash{}n',strng)
256 strng = newline_re.sub(r'\\textbackslash{}n',strng)
257 return strng
257 return strng
258
258
259 def format_screen(self,strng):
259 def format_screen(self,strng):
260 """Format a string for screen printing.
260 """Format a string for screen printing.
261
261
262 This removes some latex-type format codes."""
262 This removes some latex-type format codes."""
263 # Paragraph continue
263 # Paragraph continue
264 par_re = re.compile(r'\\$',re.MULTILINE)
264 par_re = re.compile(r'\\$',re.MULTILINE)
265 strng = par_re.sub('',strng)
265 strng = par_re.sub('',strng)
266 return strng
266 return strng
267
267
268 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
268 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
269 """Parse options passed to an argument string.
269 """Parse options passed to an argument string.
270
270
271 The interface is similar to that of getopt(), but it returns back a
271 The interface is similar to that of getopt(), but it returns back a
272 Struct with the options as keys and the stripped argument string still
272 Struct with the options as keys and the stripped argument string still
273 as a string.
273 as a string.
274
274
275 arg_str is quoted as a true sys.argv vector by using shlex.split.
275 arg_str is quoted as a true sys.argv vector by using shlex.split.
276 This allows us to easily expand variables, glob files, quote
276 This allows us to easily expand variables, glob files, quote
277 arguments, etc.
277 arguments, etc.
278
278
279 Options:
279 Options:
280 -mode: default 'string'. If given as 'list', the argument string is
280 -mode: default 'string'. If given as 'list', the argument string is
281 returned as a list (split on whitespace) instead of a string.
281 returned as a list (split on whitespace) instead of a string.
282
282
283 -list_all: put all option values in lists. Normally only options
283 -list_all: put all option values in lists. Normally only options
284 appearing more than once are put in a list."""
284 appearing more than once are put in a list."""
285
285
286 # inject default options at the beginning of the input line
286 # inject default options at the beginning of the input line
287 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
287 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
288 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
288 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
289
289
290 mode = kw.get('mode','string')
290 mode = kw.get('mode','string')
291 if mode not in ['string','list']:
291 if mode not in ['string','list']:
292 raise ValueError,'incorrect mode given: %s' % mode
292 raise ValueError,'incorrect mode given: %s' % mode
293 # Get options
293 # Get options
294 list_all = kw.get('list_all',0)
294 list_all = kw.get('list_all',0)
295
295
296 # Check if we have more than one argument to warrant extra processing:
296 # Check if we have more than one argument to warrant extra processing:
297 odict = {} # Dictionary with options
297 odict = {} # Dictionary with options
298 args = arg_str.split()
298 args = arg_str.split()
299 if len(args) >= 1:
299 if len(args) >= 1:
300 # If the list of inputs only has 0 or 1 thing in it, there's no
300 # If the list of inputs only has 0 or 1 thing in it, there's no
301 # need to look for options
301 # need to look for options
302 argv = shlex_split(arg_str)
302 argv = shlex_split(arg_str)
303 # Do regular option processing
303 # Do regular option processing
304 opts,args = getopt(argv,opt_str,*long_opts)
304 opts,args = getopt(argv,opt_str,*long_opts)
305 for o,a in opts:
305 for o,a in opts:
306 if o.startswith('--'):
306 if o.startswith('--'):
307 o = o[2:]
307 o = o[2:]
308 else:
308 else:
309 o = o[1:]
309 o = o[1:]
310 try:
310 try:
311 odict[o].append(a)
311 odict[o].append(a)
312 except AttributeError:
312 except AttributeError:
313 odict[o] = [odict[o],a]
313 odict[o] = [odict[o],a]
314 except KeyError:
314 except KeyError:
315 if list_all:
315 if list_all:
316 odict[o] = [a]
316 odict[o] = [a]
317 else:
317 else:
318 odict[o] = a
318 odict[o] = a
319
319
320 # Prepare opts,args for return
320 # Prepare opts,args for return
321 opts = Struct(odict)
321 opts = Struct(odict)
322 if mode == 'string':
322 if mode == 'string':
323 args = ' '.join(args)
323 args = ' '.join(args)
324
324
325 return opts,args
325 return opts,args
326
326
327 #......................................................................
327 #......................................................................
328 # And now the actual magic functions
328 # And now the actual magic functions
329
329
330 # Functions for IPython shell work (vars,funcs, config, etc)
330 # Functions for IPython shell work (vars,funcs, config, etc)
331 def magic_lsmagic(self, parameter_s = ''):
331 def magic_lsmagic(self, parameter_s = ''):
332 """List currently available magic functions."""
332 """List currently available magic functions."""
333 mesc = self.shell.ESC_MAGIC
333 mesc = self.shell.ESC_MAGIC
334 print 'Available magic functions:\n'+mesc+\
334 print 'Available magic functions:\n'+mesc+\
335 (' '+mesc).join(self.lsmagic())
335 (' '+mesc).join(self.lsmagic())
336 print '\n' + Magic.auto_status[self.shell.rc.automagic]
336 print '\n' + Magic.auto_status[self.shell.rc.automagic]
337 return None
337 return None
338
338
339 def magic_magic(self, parameter_s = ''):
339 def magic_magic(self, parameter_s = ''):
340 """Print information about the magic function system."""
340 """Print information about the magic function system."""
341
341
342 mode = ''
342 mode = ''
343 try:
343 try:
344 if parameter_s.split()[0] == '-latex':
344 if parameter_s.split()[0] == '-latex':
345 mode = 'latex'
345 mode = 'latex'
346 except:
346 except:
347 pass
347 pass
348
348
349 magic_docs = []
349 magic_docs = []
350 for fname in self.lsmagic():
350 for fname in self.lsmagic():
351 mname = 'magic_' + fname
351 mname = 'magic_' + fname
352 for space in (Magic,self,self.__class__):
352 for space in (Magic,self,self.__class__):
353 try:
353 try:
354 fn = space.__dict__[mname]
354 fn = space.__dict__[mname]
355 except KeyError:
355 except KeyError:
356 pass
356 pass
357 else:
357 else:
358 break
358 break
359 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
359 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
360 fname,fn.__doc__))
360 fname,fn.__doc__))
361 magic_docs = ''.join(magic_docs)
361 magic_docs = ''.join(magic_docs)
362
362
363 if mode == 'latex':
363 if mode == 'latex':
364 print self.format_latex(magic_docs)
364 print self.format_latex(magic_docs)
365 return
365 return
366 else:
366 else:
367 magic_docs = self.format_screen(magic_docs)
367 magic_docs = self.format_screen(magic_docs)
368
368
369 outmsg = """
369 outmsg = """
370 IPython's 'magic' functions
370 IPython's 'magic' functions
371 ===========================
371 ===========================
372
372
373 The magic function system provides a series of functions which allow you to
373 The magic function system provides a series of functions which allow you to
374 control the behavior of IPython itself, plus a lot of system-type
374 control the behavior of IPython itself, plus a lot of system-type
375 features. All these functions are prefixed with a % character, but parameters
375 features. All these functions are prefixed with a % character, but parameters
376 are given without parentheses or quotes.
376 are given without parentheses or quotes.
377
377
378 NOTE: If you have 'automagic' enabled (via the command line option or with the
378 NOTE: If you have 'automagic' enabled (via the command line option or with the
379 %automagic function), you don't need to type in the % explicitly. By default,
379 %automagic function), you don't need to type in the % explicitly. By default,
380 IPython ships with automagic on, so you should only rarely need the % escape.
380 IPython ships with automagic on, so you should only rarely need the % escape.
381
381
382 Example: typing '%cd mydir' (without the quotes) changes you working directory
382 Example: typing '%cd mydir' (without the quotes) changes you working directory
383 to 'mydir', if it exists.
383 to 'mydir', if it exists.
384
384
385 You can define your own magic functions to extend the system. See the supplied
385 You can define your own magic functions to extend the system. See the supplied
386 ipythonrc and example-magic.py files for details (in your ipython
386 ipythonrc and example-magic.py files for details (in your ipython
387 configuration directory, typically $HOME/.ipython/).
387 configuration directory, typically $HOME/.ipython/).
388
388
389 You can also define your own aliased names for magic functions. In your
389 You can also define your own aliased names for magic functions. In your
390 ipythonrc file, placing a line like:
390 ipythonrc file, placing a line like:
391
391
392 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
392 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
393
393
394 will define %pf as a new name for %profile.
394 will define %pf as a new name for %profile.
395
395
396 You can also call magics in code using the ipmagic() function, which IPython
396 You can also call magics in code using the ipmagic() function, which IPython
397 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
397 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
398
398
399 For a list of the available magic functions, use %lsmagic. For a description
399 For a list of the available magic functions, use %lsmagic. For a description
400 of any of them, type %magic_name?, e.g. '%cd?'.
400 of any of them, type %magic_name?, e.g. '%cd?'.
401
401
402 Currently the magic system has the following functions:\n"""
402 Currently the magic system has the following functions:\n"""
403
403
404 mesc = self.shell.ESC_MAGIC
404 mesc = self.shell.ESC_MAGIC
405 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
405 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
406 "\n\n%s%s\n\n%s" % (outmsg,
406 "\n\n%s%s\n\n%s" % (outmsg,
407 magic_docs,mesc,mesc,
407 magic_docs,mesc,mesc,
408 (' '+mesc).join(self.lsmagic()),
408 (' '+mesc).join(self.lsmagic()),
409 Magic.auto_status[self.shell.rc.automagic] ) )
409 Magic.auto_status[self.shell.rc.automagic] ) )
410
410
411 page(outmsg,screen_lines=self.shell.rc.screen_length)
411 page(outmsg,screen_lines=self.shell.rc.screen_length)
412
412
413 def magic_automagic(self, parameter_s = ''):
413 def magic_automagic(self, parameter_s = ''):
414 """Make magic functions callable without having to type the initial %.
414 """Make magic functions callable without having to type the initial %.
415
415
416 Toggles on/off (when off, you must call it as %automagic, of
416 Toggles on/off (when off, you must call it as %automagic, of
417 course). Note that magic functions have lowest priority, so if there's
417 course). Note that magic functions have lowest priority, so if there's
418 a variable whose name collides with that of a magic fn, automagic
418 a variable whose name collides with that of a magic fn, automagic
419 won't work for that function (you get the variable instead). However,
419 won't work for that function (you get the variable instead). However,
420 if you delete the variable (del var), the previously shadowed magic
420 if you delete the variable (del var), the previously shadowed magic
421 function becomes visible to automagic again."""
421 function becomes visible to automagic again."""
422
422
423 rc = self.shell.rc
423 rc = self.shell.rc
424 rc.automagic = not rc.automagic
424 rc.automagic = not rc.automagic
425 print '\n' + Magic.auto_status[rc.automagic]
425 print '\n' + Magic.auto_status[rc.automagic]
426
426
427 def magic_autocall(self, parameter_s = ''):
427 def magic_autocall(self, parameter_s = ''):
428 """Make functions callable without having to type parentheses.
428 """Make functions callable without having to type parentheses.
429
429
430 This toggles the autocall command line option on and off."""
430 This toggles the autocall command line option on and off."""
431
431
432 rc = self.shell.rc
432 rc = self.shell.rc
433 rc.autocall = not rc.autocall
433 rc.autocall = not rc.autocall
434 print "Automatic calling is:",['OFF','ON'][rc.autocall]
434 print "Automatic calling is:",['OFF','ON'][rc.autocall]
435
435
436 def magic_autoindent(self, parameter_s = ''):
436 def magic_autoindent(self, parameter_s = ''):
437 """Toggle autoindent on/off (if available)."""
437 """Toggle autoindent on/off (if available)."""
438
438
439 self.shell.set_autoindent()
439 self.shell.set_autoindent()
440 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
440 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
441
441
442 def magic_system_verbose(self, parameter_s = ''):
442 def magic_system_verbose(self, parameter_s = ''):
443 """Toggle verbose printing of system calls on/off."""
443 """Toggle verbose printing of system calls on/off."""
444
444
445 self.shell.rc_set_toggle('system_verbose')
445 self.shell.rc_set_toggle('system_verbose')
446 print "System verbose printing is:",\
446 print "System verbose printing is:",\
447 ['OFF','ON'][self.shell.rc.system_verbose]
447 ['OFF','ON'][self.shell.rc.system_verbose]
448
448
449 def magic_history(self, parameter_s = ''):
449 def magic_history(self, parameter_s = ''):
450 """Print input history (_i<n> variables), with most recent last.
450 """Print input history (_i<n> variables), with most recent last.
451
451
452 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
452 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
453 %history [-n] n -> print at most n inputs\\
453 %history [-n] n -> print at most n inputs\\
454 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
454 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
455
455
456 Each input's number <n> is shown, and is accessible as the
456 Each input's number <n> is shown, and is accessible as the
457 automatically generated variable _i<n>. Multi-line statements are
457 automatically generated variable _i<n>. Multi-line statements are
458 printed starting at a new line for easy copy/paste.
458 printed starting at a new line for easy copy/paste.
459
459
460 If option -n is used, input numbers are not printed. This is useful if
460 If option -n is used, input numbers are not printed. This is useful if
461 you want to get a printout of many lines which can be directly pasted
461 you want to get a printout of many lines which can be directly pasted
462 into a text editor.
462 into a text editor.
463
463
464 This feature is only available if numbered prompts are in use."""
464 This feature is only available if numbered prompts are in use."""
465
465
466 if not self.shell.outputcache.do_full_cache:
466 if not self.shell.outputcache.do_full_cache:
467 print 'This feature is only available if numbered prompts are in use.'
467 print 'This feature is only available if numbered prompts are in use.'
468 return
468 return
469 opts,args = self.parse_options(parameter_s,'n',mode='list')
469 opts,args = self.parse_options(parameter_s,'n',mode='list')
470
470
471 default_length = 40
471 default_length = 40
472 if len(args) == 0:
472 if len(args) == 0:
473 final = self.shell.outputcache.prompt_count
473 final = self.shell.outputcache.prompt_count
474 init = max(1,final-default_length)
474 init = max(1,final-default_length)
475 elif len(args) == 1:
475 elif len(args) == 1:
476 final = self.shell.outputcache.prompt_count
476 final = self.shell.outputcache.prompt_count
477 init = max(1,final-int(args[0]))
477 init = max(1,final-int(args[0]))
478 elif len(args) == 2:
478 elif len(args) == 2:
479 init,final = map(int,args)
479 init,final = map(int,args)
480 else:
480 else:
481 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
481 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
482 print self.magic_hist.__doc__
482 print self.magic_hist.__doc__
483 return
483 return
484 width = len(str(final))
484 width = len(str(final))
485 line_sep = ['','\n']
485 line_sep = ['','\n']
486 input_hist = self.shell.input_hist
486 input_hist = self.shell.input_hist
487 print_nums = not opts.has_key('n')
487 print_nums = not opts.has_key('n')
488 for in_num in range(init,final):
488 for in_num in range(init,final):
489 inline = input_hist[in_num]
489 inline = input_hist[in_num]
490 multiline = inline.count('\n') > 1
490 multiline = inline.count('\n') > 1
491 if print_nums:
491 if print_nums:
492 print str(in_num).ljust(width)+':'+ line_sep[multiline],
492 print str(in_num).ljust(width)+':'+ line_sep[multiline],
493 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
493 if inline.startswith('#'+self.shell.ESC_MAGIC) or \
494 inline.startswith('#!'):
494 inline.startswith('#!'):
495 print inline[1:],
495 print inline[1:],
496 else:
496 else:
497 print inline,
497 print inline,
498
498
499 def magic_hist(self, parameter_s=''):
499 def magic_hist(self, parameter_s=''):
500 """Alternate name for %history."""
500 """Alternate name for %history."""
501 return self.magic_history(parameter_s)
501 return self.magic_history(parameter_s)
502
502
503 def magic_p(self, parameter_s=''):
503 def magic_p(self, parameter_s=''):
504 """Just a short alias for Python's 'print'."""
504 """Just a short alias for Python's 'print'."""
505 exec 'print ' + parameter_s in self.shell.user_ns
505 exec 'print ' + parameter_s in self.shell.user_ns
506
506
507 def magic_r(self, parameter_s=''):
507 def magic_r(self, parameter_s=''):
508 """Repeat previous input.
508 """Repeat previous input.
509
509
510 If given an argument, repeats the previous command which starts with
510 If given an argument, repeats the previous command which starts with
511 the same string, otherwise it just repeats the previous input.
511 the same string, otherwise it just repeats the previous input.
512
512
513 Shell escaped commands (with ! as first character) are not recognized
513 Shell escaped commands (with ! as first character) are not recognized
514 by this system, only pure python code and magic commands.
514 by this system, only pure python code and magic commands.
515 """
515 """
516
516
517 start = parameter_s.strip()
517 start = parameter_s.strip()
518 esc_magic = self.shell.ESC_MAGIC
518 esc_magic = self.shell.ESC_MAGIC
519 # Identify magic commands even if automagic is on (which means
519 # Identify magic commands even if automagic is on (which means
520 # the in-memory version is different from that typed by the user).
520 # the in-memory version is different from that typed by the user).
521 if self.shell.rc.automagic:
521 if self.shell.rc.automagic:
522 start_magic = esc_magic+start
522 start_magic = esc_magic+start
523 else:
523 else:
524 start_magic = start
524 start_magic = start
525 # Look through the input history in reverse
525 # Look through the input history in reverse
526 for n in range(len(self.shell.input_hist)-2,0,-1):
526 for n in range(len(self.shell.input_hist)-2,0,-1):
527 input = self.shell.input_hist[n]
527 input = self.shell.input_hist[n]
528 # skip plain 'r' lines so we don't recurse to infinity
528 # skip plain 'r' lines so we don't recurse to infinity
529 if input != 'ipmagic("r")\n' and \
529 if input != 'ipmagic("r")\n' and \
530 (input.startswith(start) or input.startswith(start_magic)):
530 (input.startswith(start) or input.startswith(start_magic)):
531 #print 'match',`input` # dbg
531 #print 'match',`input` # dbg
532 print 'Executing:',input,
532 print 'Executing:',input,
533 self.shell.runlines(input)
533 self.shell.runlines(input)
534 return
534 return
535 print 'No previous input matching `%s` found.' % start
535 print 'No previous input matching `%s` found.' % start
536
536
537 def magic_page(self, parameter_s=''):
537 def magic_page(self, parameter_s=''):
538 """Pretty print the object and display it through a pager.
538 """Pretty print the object and display it through a pager.
539
539
540 If no parameter is given, use _ (last output)."""
540 If no parameter is given, use _ (last output)."""
541 # After a function contributed by Olivier Aubert, slightly modified.
541 # After a function contributed by Olivier Aubert, slightly modified.
542
542
543 oname = parameter_s and parameter_s or '_'
543 oname = parameter_s and parameter_s or '_'
544 info = self._ofind(oname)
544 info = self._ofind(oname)
545 if info['found']:
545 if info['found']:
546 page(pformat(info['obj']))
546 page(pformat(info['obj']))
547 else:
547 else:
548 print 'Object `%s` not found' % oname
548 print 'Object `%s` not found' % oname
549
549
550 def magic_profile(self, parameter_s=''):
550 def magic_profile(self, parameter_s=''):
551 """Print your currently active IPyhton profile."""
551 """Print your currently active IPyhton profile."""
552 if self.shell.rc.profile:
552 if self.shell.rc.profile:
553 printpl('Current IPython profile: $self.shell.rc.profile.')
553 printpl('Current IPython profile: $self.shell.rc.profile.')
554 else:
554 else:
555 print 'No profile active.'
555 print 'No profile active.'
556
556
557 def _inspect(self,meth,oname,**kw):
557 def _inspect(self,meth,oname,**kw):
558 """Generic interface to the inspector system.
558 """Generic interface to the inspector system.
559
559
560 This function is meant to be called by pdef, pdoc & friends."""
560 This function is meant to be called by pdef, pdoc & friends."""
561
561
562 oname = oname.strip()
562 oname = oname.strip()
563 info = Struct(self._ofind(oname))
563 info = Struct(self._ofind(oname))
564 if info.found:
564 if info.found:
565 pmethod = getattr(self.shell.inspector,meth)
565 pmethod = getattr(self.shell.inspector,meth)
566 formatter = info.ismagic and self.format_screen or None
566 formatter = info.ismagic and self.format_screen or None
567 if meth == 'pdoc':
567 if meth == 'pdoc':
568 pmethod(info.obj,oname,formatter)
568 pmethod(info.obj,oname,formatter)
569 elif meth == 'pinfo':
569 elif meth == 'pinfo':
570 pmethod(info.obj,oname,formatter,info,**kw)
570 pmethod(info.obj,oname,formatter,info,**kw)
571 else:
571 else:
572 pmethod(info.obj,oname)
572 pmethod(info.obj,oname)
573 else:
573 else:
574 print 'Object `%s` not found.' % oname
574 print 'Object `%s` not found.' % oname
575 return 'not found' # so callers can take other action
575 return 'not found' # so callers can take other action
576
576
577 def magic_pdef(self, parameter_s=''):
577 def magic_pdef(self, parameter_s=''):
578 """Print the definition header for any callable object.
578 """Print the definition header for any callable object.
579
579
580 If the object is a class, print the constructor information."""
580 If the object is a class, print the constructor information."""
581 self._inspect('pdef',parameter_s)
581 self._inspect('pdef',parameter_s)
582
582
583 def magic_pdoc(self, parameter_s=''):
583 def magic_pdoc(self, parameter_s=''):
584 """Print the docstring for an object.
584 """Print the docstring for an object.
585
585
586 If the given object is a class, it will print both the class and the
586 If the given object is a class, it will print both the class and the
587 constructor docstrings."""
587 constructor docstrings."""
588 self._inspect('pdoc',parameter_s)
588 self._inspect('pdoc',parameter_s)
589
589
590 def magic_psource(self, parameter_s=''):
590 def magic_psource(self, parameter_s=''):
591 """Print (or run through pager) the source code for an object."""
591 """Print (or run through pager) the source code for an object."""
592 self._inspect('psource',parameter_s)
592 self._inspect('psource',parameter_s)
593
593
594 def magic_pfile(self, parameter_s=''):
594 def magic_pfile(self, parameter_s=''):
595 """Print (or run through pager) the file where an object is defined.
595 """Print (or run through pager) the file where an object is defined.
596
596
597 The file opens at the line where the object definition begins. IPython
597 The file opens at the line where the object definition begins. IPython
598 will honor the environment variable PAGER if set, and otherwise will
598 will honor the environment variable PAGER if set, and otherwise will
599 do its best to print the file in a convenient form.
599 do its best to print the file in a convenient form.
600
600
601 If the given argument is not an object currently defined, IPython will
601 If the given argument is not an object currently defined, IPython will
602 try to interpret it as a filename (automatically adding a .py extension
602 try to interpret it as a filename (automatically adding a .py extension
603 if needed). You can thus use %pfile as a syntax highlighting code
603 if needed). You can thus use %pfile as a syntax highlighting code
604 viewer."""
604 viewer."""
605
605
606 # first interpret argument as an object name
606 # first interpret argument as an object name
607 out = self._inspect('pfile',parameter_s)
607 out = self._inspect('pfile',parameter_s)
608 # if not, try the input as a filename
608 # if not, try the input as a filename
609 if out == 'not found':
609 if out == 'not found':
610 try:
610 try:
611 filename = get_py_filename(parameter_s)
611 filename = get_py_filename(parameter_s)
612 except IOError,msg:
612 except IOError,msg:
613 print msg
613 print msg
614 return
614 return
615 page(self.shell.inspector.format(file(filename).read()))
615 page(self.shell.inspector.format(file(filename).read()))
616
616
617 def magic_pinfo(self, parameter_s=''):
617 def magic_pinfo(self, parameter_s=''):
618 """Provide detailed information about an object.
618 """Provide detailed information about an object.
619
619
620 '%pinfo object' is just a synonym for object? or ?object."""
620 '%pinfo object' is just a synonym for object? or ?object."""
621
621
622 #print 'pinfo par: <%s>' % parameter_s # dbg
622 #print 'pinfo par: <%s>' % parameter_s # dbg
623
623
624 # detail_level: 0 -> obj? , 1 -> obj??
624 # detail_level: 0 -> obj? , 1 -> obj??
625 detail_level = 0
625 detail_level = 0
626 # We need to detect if we got called as 'pinfo pinfo foo', which can
626 # We need to detect if we got called as 'pinfo pinfo foo', which can
627 # happen if the user types 'pinfo foo?' at the cmd line.
627 # happen if the user types 'pinfo foo?' at the cmd line.
628 pinfo,qmark1,oname,qmark2 = \
628 pinfo,qmark1,oname,qmark2 = \
629 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
629 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
630 if pinfo or qmark1 or qmark2:
630 if pinfo or qmark1 or qmark2:
631 detail_level = 1
631 detail_level = 1
632 if "*" in oname:
632 if "*" in oname:
633 self.magic_psearch(oname)
633 self.magic_psearch(oname)
634 else:
634 else:
635 self._inspect('pinfo',oname,detail_level=detail_level)
635 self._inspect('pinfo',oname,detail_level=detail_level)
636
636
637 def magic_psearch(self, parameter_s=''):
637 def magic_psearch(self, parameter_s=''):
638 """Search for object in namespaces by wildcard.
638 """Search for object in namespaces by wildcard.
639
639
640 %psearch [options] PATTERN [OBJECT TYPE]
640 %psearch [options] PATTERN [OBJECT TYPE]
641
641
642 Note: ? can be used as a synonym for %psearch, at the beginning or at
642 Note: ? can be used as a synonym for %psearch, at the beginning or at
643 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
643 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
644 rest of the command line must be unchanged (options come first), so
644 rest of the command line must be unchanged (options come first), so
645 for example the following forms are equivalent
645 for example the following forms are equivalent
646
646
647 %psearch -i a* function
647 %psearch -i a* function
648 -i a* function?
648 -i a* function?
649 ?-i a* function
649 ?-i a* function
650
650
651 Arguments:
651 Arguments:
652
652
653 PATTERN
653 PATTERN
654
654
655 where PATTERN is a string containing * as a wildcard similar to its
655 where PATTERN is a string containing * as a wildcard similar to its
656 use in a shell. The pattern is matched in all namespaces on the
656 use in a shell. The pattern is matched in all namespaces on the
657 search path. By default objects starting with a single _ are not
657 search path. By default objects starting with a single _ are not
658 matched, many IPython generated objects have a single
658 matched, many IPython generated objects have a single
659 underscore. The default is case insensitive matching. Matching is
659 underscore. The default is case insensitive matching. Matching is
660 also done on the attributes of objects and not only on the objects
660 also done on the attributes of objects and not only on the objects
661 in a module.
661 in a module.
662
662
663 [OBJECT TYPE]
663 [OBJECT TYPE]
664
664
665 Is the name of a python type from the types module. The name is
665 Is the name of a python type from the types module. The name is
666 given in lowercase without the ending type, ex. StringType is
666 given in lowercase without the ending type, ex. StringType is
667 written string. By adding a type here only objects matching the
667 written string. By adding a type here only objects matching the
668 given type are matched. Using all here makes the pattern match all
668 given type are matched. Using all here makes the pattern match all
669 types (this is the default).
669 types (this is the default).
670
670
671 Options:
671 Options:
672
672
673 -a: makes the pattern match even objects whose names start with a
673 -a: makes the pattern match even objects whose names start with a
674 single underscore. These names are normally ommitted from the
674 single underscore. These names are normally ommitted from the
675 search.
675 search.
676
676
677 -i/-c: make the pattern case insensitive/sensitive. If neither of
677 -i/-c: make the pattern case insensitive/sensitive. If neither of
678 these options is given, the default is read from your ipythonrc
678 these options is given, the default is read from your ipythonrc
679 file. The option name which sets this value is
679 file. The option name which sets this value is
680 'wildcards_case_sensitive'. If this option is not specified in your
680 'wildcards_case_sensitive'. If this option is not specified in your
681 ipythonrc file, IPython's internal default is to do a case sensitive
681 ipythonrc file, IPython's internal default is to do a case sensitive
682 search.
682 search.
683
683
684 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
684 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
685 specifiy can be searched in any of the following namespaces:
685 specifiy can be searched in any of the following namespaces:
686 'builtin', 'user', 'user_global','internal', 'alias', where
686 'builtin', 'user', 'user_global','internal', 'alias', where
687 'builtin' and 'user' are the search defaults. Note that you should
687 'builtin' and 'user' are the search defaults. Note that you should
688 not use quotes when specifying namespaces.
688 not use quotes when specifying namespaces.
689
689
690 'Builtin' contains the python module builtin, 'user' contains all
690 'Builtin' contains the python module builtin, 'user' contains all
691 user data, 'alias' only contain the shell aliases and no python
691 user data, 'alias' only contain the shell aliases and no python
692 objects, 'internal' contains objects used by IPython. The
692 objects, 'internal' contains objects used by IPython. The
693 'user_global' namespace is only used by embedded IPython instances,
693 'user_global' namespace is only used by embedded IPython instances,
694 and it contains module-level globals. You can add namespaces to the
694 and it contains module-level globals. You can add namespaces to the
695 search with -s or exclude them with -e (these options can be given
695 search with -s or exclude them with -e (these options can be given
696 more than once).
696 more than once).
697
697
698 Examples:
698 Examples:
699
699
700 %psearch a* -> objects beginning with an a
700 %psearch a* -> objects beginning with an a
701 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
701 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
702 %psearch a* function -> all functions beginning with an a
702 %psearch a* function -> all functions beginning with an a
703 %psearch re.e* -> objects beginning with an e in module re
703 %psearch re.e* -> objects beginning with an e in module re
704 %psearch r*.e* -> objects that start with e in modules starting in r
704 %psearch r*.e* -> objects that start with e in modules starting in r
705 %psearch r*.* string -> all strings in modules beginning with r
705 %psearch r*.* string -> all strings in modules beginning with r
706
706
707 Case sensitve search:
707 Case sensitve search:
708
708
709 %psearch -c a* list all object beginning with lower case a
709 %psearch -c a* list all object beginning with lower case a
710
710
711 Show objects beginning with a single _:
711 Show objects beginning with a single _:
712
712
713 %psearch -a _* list objects beginning with a single underscore"""
713 %psearch -a _* list objects beginning with a single underscore"""
714
714
715 # default namespaces to be searched
715 # default namespaces to be searched
716 def_search = ['user','builtin']
716 def_search = ['user','builtin']
717
717
718 # Process options/args
718 # Process options/args
719 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
719 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
720 opt = opts.get
720 opt = opts.get
721 shell = self.shell
721 shell = self.shell
722 psearch = shell.inspector.psearch
722 psearch = shell.inspector.psearch
723
723
724 # select case options
724 # select case options
725 if opts.has_key('i'):
725 if opts.has_key('i'):
726 ignore_case = True
726 ignore_case = True
727 elif opts.has_key('c'):
727 elif opts.has_key('c'):
728 ignore_case = False
728 ignore_case = False
729 else:
729 else:
730 ignore_case = not shell.rc.wildcards_case_sensitive
730 ignore_case = not shell.rc.wildcards_case_sensitive
731
731
732 # Build list of namespaces to search from user options
732 # Build list of namespaces to search from user options
733 def_search.extend(opt('s',[]))
733 def_search.extend(opt('s',[]))
734 ns_exclude = ns_exclude=opt('e',[])
734 ns_exclude = ns_exclude=opt('e',[])
735 ns_search = [nm for nm in def_search if nm not in ns_exclude]
735 ns_search = [nm for nm in def_search if nm not in ns_exclude]
736
736
737 # Call the actual search
737 # Call the actual search
738 try:
738 try:
739 psearch(args,shell.ns_table,ns_search,
739 psearch(args,shell.ns_table,ns_search,
740 show_all=opt('a'),ignore_case=ignore_case)
740 show_all=opt('a'),ignore_case=ignore_case)
741 except:
741 except:
742 shell.showtraceback()
742 shell.showtraceback()
743
743
744 def magic_who_ls(self, parameter_s=''):
744 def magic_who_ls(self, parameter_s=''):
745 """Return a sorted list of all interactive variables.
745 """Return a sorted list of all interactive variables.
746
746
747 If arguments are given, only variables of types matching these
747 If arguments are given, only variables of types matching these
748 arguments are returned."""
748 arguments are returned."""
749
749
750 user_ns = self.shell.user_ns
750 user_ns = self.shell.user_ns
751 out = []
751 out = []
752 typelist = parameter_s.split()
752 typelist = parameter_s.split()
753 for i in self.shell.user_ns.keys():
753 for i in self.shell.user_ns.keys():
754 if not (i.startswith('_') or i.startswith('_i')) \
754 if not (i.startswith('_') or i.startswith('_i')) \
755 and not (self.shell.internal_ns.has_key(i) or
755 and not (self.shell.internal_ns.has_key(i) or
756 self.shell.user_config_ns.has_key(i)):
756 self.shell.user_config_ns.has_key(i)):
757 if typelist:
757 if typelist:
758 if type(user_ns[i]).__name__ in typelist:
758 if type(user_ns[i]).__name__ in typelist:
759 out.append(i)
759 out.append(i)
760 else:
760 else:
761 out.append(i)
761 out.append(i)
762 out.sort()
762 out.sort()
763 return out
763 return out
764
764
765 def magic_who(self, parameter_s=''):
765 def magic_who(self, parameter_s=''):
766 """Print all interactive variables, with some minimal formatting.
766 """Print all interactive variables, with some minimal formatting.
767
767
768 If any arguments are given, only variables whose type matches one of
768 If any arguments are given, only variables whose type matches one of
769 these are printed. For example:
769 these are printed. For example:
770
770
771 %who function str
771 %who function str
772
772
773 will only list functions and strings, excluding all other types of
773 will only list functions and strings, excluding all other types of
774 variables. To find the proper type names, simply use type(var) at a
774 variables. To find the proper type names, simply use type(var) at a
775 command line to see how python prints type names. For example:
775 command line to see how python prints type names. For example:
776
776
777 In [1]: type('hello')\\
777 In [1]: type('hello')\\
778 Out[1]: <type 'str'>
778 Out[1]: <type 'str'>
779
779
780 indicates that the type name for strings is 'str'.
780 indicates that the type name for strings is 'str'.
781
781
782 %who always excludes executed names loaded through your configuration
782 %who always excludes executed names loaded through your configuration
783 file and things which are internal to IPython.
783 file and things which are internal to IPython.
784
784
785 This is deliberate, as typically you may load many modules and the
785 This is deliberate, as typically you may load many modules and the
786 purpose of %who is to show you only what you've manually defined."""
786 purpose of %who is to show you only what you've manually defined."""
787
787
788 varlist = self.magic_who_ls(parameter_s)
788 varlist = self.magic_who_ls(parameter_s)
789 if not varlist:
789 if not varlist:
790 print 'Interactive namespace is empty.'
790 print 'Interactive namespace is empty.'
791 return
791 return
792
792
793 # if we have variables, move on...
793 # if we have variables, move on...
794
794
795 # stupid flushing problem: when prompts have no separators, stdout is
795 # stupid flushing problem: when prompts have no separators, stdout is
796 # getting lost. I'm starting to think this is a python bug. I'm having
796 # getting lost. I'm starting to think this is a python bug. I'm having
797 # to force a flush with a print because even a sys.stdout.flush
797 # to force a flush with a print because even a sys.stdout.flush
798 # doesn't seem to do anything!
798 # doesn't seem to do anything!
799
799
800 count = 0
800 count = 0
801 for i in varlist:
801 for i in varlist:
802 print i+'\t',
802 print i+'\t',
803 count += 1
803 count += 1
804 if count > 8:
804 if count > 8:
805 count = 0
805 count = 0
806 print
806 print
807 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
807 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
808
808
809 print # well, this does force a flush at the expense of an extra \n
809 print # well, this does force a flush at the expense of an extra \n
810
810
811 def magic_whos(self, parameter_s=''):
811 def magic_whos(self, parameter_s=''):
812 """Like %who, but gives some extra information about each variable.
812 """Like %who, but gives some extra information about each variable.
813
813
814 The same type filtering of %who can be applied here.
814 The same type filtering of %who can be applied here.
815
815
816 For all variables, the type is printed. Additionally it prints:
816 For all variables, the type is printed. Additionally it prints:
817
817
818 - For {},[],(): their length.
818 - For {},[],(): their length.
819
819
820 - For Numeric arrays, a summary with shape, number of elements,
820 - For Numeric arrays, a summary with shape, number of elements,
821 typecode and size in memory.
821 typecode and size in memory.
822
822
823 - Everything else: a string representation, snipping their middle if
823 - Everything else: a string representation, snipping their middle if
824 too long."""
824 too long."""
825
825
826 varnames = self.magic_who_ls(parameter_s)
826 varnames = self.magic_who_ls(parameter_s)
827 if not varnames:
827 if not varnames:
828 print 'Interactive namespace is empty.'
828 print 'Interactive namespace is empty.'
829 return
829 return
830
830
831 # if we have variables, move on...
831 # if we have variables, move on...
832
832
833 # for these types, show len() instead of data:
833 # for these types, show len() instead of data:
834 seq_types = [types.DictType,types.ListType,types.TupleType]
834 seq_types = [types.DictType,types.ListType,types.TupleType]
835
835
836 # for Numeric arrays, display summary info
836 # for Numeric arrays, display summary info
837 try:
837 try:
838 import Numeric
838 import Numeric
839 except ImportError:
839 except ImportError:
840 array_type = None
840 array_type = None
841 else:
841 else:
842 array_type = Numeric.ArrayType.__name__
842 array_type = Numeric.ArrayType.__name__
843
843
844 # Find all variable names and types so we can figure out column sizes
844 # Find all variable names and types so we can figure out column sizes
845 get_vars = lambda i: self.shell.user_ns[i]
845 get_vars = lambda i: self.shell.user_ns[i]
846 type_name = lambda v: type(v).__name__
846 type_name = lambda v: type(v).__name__
847 varlist = map(get_vars,varnames)
847 varlist = map(get_vars,varnames)
848 typelist = map(type_name,varlist)
848 typelist = map(type_name,varlist)
849 # column labels and # of spaces as separator
849 # column labels and # of spaces as separator
850 varlabel = 'Variable'
850 varlabel = 'Variable'
851 typelabel = 'Type'
851 typelabel = 'Type'
852 datalabel = 'Data/Info'
852 datalabel = 'Data/Info'
853 colsep = 3
853 colsep = 3
854 # variable format strings
854 # variable format strings
855 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
855 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
856 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
856 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
857 aformat = "%s: %s elems, type `%s`, %s bytes"
857 aformat = "%s: %s elems, type `%s`, %s bytes"
858 # find the size of the columns to format the output nicely
858 # find the size of the columns to format the output nicely
859 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
859 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
860 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
860 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
861 # table header
861 # table header
862 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
862 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
863 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
863 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
864 # and the table itself
864 # and the table itself
865 kb = 1024
865 kb = 1024
866 Mb = 1048576 # kb**2
866 Mb = 1048576 # kb**2
867 for vname,var,vtype in zip(varnames,varlist,typelist):
867 for vname,var,vtype in zip(varnames,varlist,typelist):
868 print itpl(vformat),
868 print itpl(vformat),
869 if vtype in seq_types:
869 if vtype in seq_types:
870 print len(var)
870 print len(var)
871 elif vtype==array_type:
871 elif vtype==array_type:
872 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
872 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
873 vsize = Numeric.size(var)
873 vsize = Numeric.size(var)
874 vbytes = vsize*var.itemsize()
874 vbytes = vsize*var.itemsize()
875 if vbytes < 100000:
875 if vbytes < 100000:
876 print aformat % (vshape,vsize,var.typecode(),vbytes)
876 print aformat % (vshape,vsize,var.typecode(),vbytes)
877 else:
877 else:
878 print aformat % (vshape,vsize,var.typecode(),vbytes),
878 print aformat % (vshape,vsize,var.typecode(),vbytes),
879 if vbytes < Mb:
879 if vbytes < Mb:
880 print '(%s kb)' % (vbytes/kb,)
880 print '(%s kb)' % (vbytes/kb,)
881 else:
881 else:
882 print '(%s Mb)' % (vbytes/Mb,)
882 print '(%s Mb)' % (vbytes/Mb,)
883 else:
883 else:
884 vstr = str(var)
884 vstr = str(var)
885 if len(vstr) < 50:
885 if len(vstr) < 50:
886 print vstr
886 print vstr
887 else:
887 else:
888 printpl(vfmt_short)
888 printpl(vfmt_short)
889
889
890 def magic_reset(self, parameter_s=''):
890 def magic_reset(self, parameter_s=''):
891 """Resets the namespace by removing all names defined by the user.
891 """Resets the namespace by removing all names defined by the user.
892
892
893 Input/Output history are left around in case you need them."""
893 Input/Output history are left around in case you need them."""
894
894
895 ans = raw_input(
895 ans = raw_input(
896 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
896 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
897 if not ans.lower() == 'y':
897 if not ans.lower() == 'y':
898 print 'Nothing done.'
898 print 'Nothing done.'
899 return
899 return
900 user_ns = self.shell.user_ns
900 user_ns = self.shell.user_ns
901 for i in self.magic_who_ls():
901 for i in self.magic_who_ls():
902 del(user_ns[i])
902 del(user_ns[i])
903
903
904 def magic_config(self,parameter_s=''):
904 def magic_config(self,parameter_s=''):
905 """Show IPython's internal configuration."""
905 """Show IPython's internal configuration."""
906
906
907 page('Current configuration structure:\n'+
907 page('Current configuration structure:\n'+
908 pformat(self.shell.rc.dict()))
908 pformat(self.shell.rc.dict()))
909
909
910 def magic_logstart(self,parameter_s=''):
910 def magic_logstart(self,parameter_s=''):
911 """Start logging anywhere in a session.
911 """Start logging anywhere in a session.
912
912
913 %logstart [-o|-t] [log_name [log_mode]]
913 %logstart [-o|-t] [log_name [log_mode]]
914
914
915 If no name is given, it defaults to a file named 'ipython_log.py' in your
915 If no name is given, it defaults to a file named 'ipython_log.py' in your
916 current directory, in 'rotate' mode (see below).
916 current directory, in 'rotate' mode (see below).
917
917
918 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
918 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
919 history up to that point and then continues logging.
919 history up to that point and then continues logging.
920
920
921 %logstart takes a second optional parameter: logging mode. This can be one
921 %logstart takes a second optional parameter: logging mode. This can be one
922 of (note that the modes are given unquoted):\\
922 of (note that the modes are given unquoted):\\
923 append: well, that says it.\\
923 append: well, that says it.\\
924 backup: rename (if exists) to name~ and start name.\\
924 backup: rename (if exists) to name~ and start name.\\
925 global: single logfile in your home dir, appended to.\\
925 global: single logfile in your home dir, appended to.\\
926 over : overwrite existing log.\\
926 over : overwrite existing log.\\
927 rotate: create rotating logs name.1~, name.2~, etc.
927 rotate: create rotating logs name.1~, name.2~, etc.
928
928
929 Options:
929 Options:
930
930
931 -o: log also IPython's output. In this mode, all commands which
931 -o: log also IPython's output. In this mode, all commands which
932 generate an Out[NN] prompt are recorded to the logfile, right after
932 generate an Out[NN] prompt are recorded to the logfile, right after
933 their corresponding input line. The output lines are always
933 their corresponding input line. The output lines are always
934 prepended with a #[Out]# marker, so that the log remains valid
934 prepended with a '#[Out]# ' marker, so that the log remains valid
935 Python code.
935 Python code.
936
936
937 Since this marker is always the same, filtering only the output from
938 a log is very easy, using for example a simple awk call:
939
940 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
941
937 -t: put timestamps before each input line logged (these are put in
942 -t: put timestamps before each input line logged (these are put in
938 comments)."""
943 comments)."""
939
944
940 opts,par = self.parse_options(parameter_s,'ot')
945 opts,par = self.parse_options(parameter_s,'ot')
941 log_output = 'o' in opts
946 log_output = 'o' in opts
942 timestamp = 't' in opts
947 timestamp = 't' in opts
943
948
944 rc = self.shell.rc
949 rc = self.shell.rc
945 logger = self.shell.logger
950 logger = self.shell.logger
946
951
947 # if no args are given, the defaults set in the logger constructor by
952 # if no args are given, the defaults set in the logger constructor by
948 # ipytohn remain valid
953 # ipytohn remain valid
949 if par:
954 if par:
950 try:
955 try:
951 logfname,logmode = par.split()
956 logfname,logmode = par.split()
952 except:
957 except:
953 logfname = par
958 logfname = par
954 logmode = 'backup'
959 logmode = 'backup'
955 else:
960 else:
956 logfname = logger.logfname
961 logfname = logger.logfname
957 logmode = logger.logmode
962 logmode = logger.logmode
958 # put logfname into rc struct as if it had been called on the command
963 # put logfname into rc struct as if it had been called on the command
959 # line, so it ends up saved in the log header Save it in case we need
964 # line, so it ends up saved in the log header Save it in case we need
960 # to restore it...
965 # to restore it...
961 old_logfile = rc.opts.get('logfile','')
966 old_logfile = rc.opts.get('logfile','')
962 if logfname:
967 if logfname:
963 logfname = os.path.expanduser(logfname)
968 logfname = os.path.expanduser(logfname)
964 rc.opts.logfile = logfname
969 rc.opts.logfile = logfname
965 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
970 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
966 try:
971 try:
967 started = logger.logstart(logfname,loghead,logmode,
972 started = logger.logstart(logfname,loghead,logmode,
968 log_output,timestamp)
973 log_output,timestamp)
969 except:
974 except:
970 rc.opts.logfile = old_logfile
975 rc.opts.logfile = old_logfile
971 warn("Couldn't start log: %s" % sys.exc_info()[1])
976 warn("Couldn't start log: %s" % sys.exc_info()[1])
972 else:
977 else:
973 # log input history up to this point, optionally interleaving
978 # log input history up to this point, optionally interleaving
974 # output if requested
979 # output if requested
975
980
976 if timestamp:
981 if timestamp:
977 # disable timestamping for the previous history, since we've
982 # disable timestamping for the previous history, since we've
978 # lost those already (no time machine here).
983 # lost those already (no time machine here).
979 logger.timestamp = False
984 logger.timestamp = False
980 if log_output:
985 if log_output:
981 log_write = logger.log_write
986 log_write = logger.log_write
982 input_hist = self.shell.input_hist
987 input_hist = self.shell.input_hist
983 output_hist = self.shell.output_hist
988 output_hist = self.shell.output_hist
984 for n in range(1,len(input_hist)-1):
989 for n in range(1,len(input_hist)-1):
985 log_write(input_hist[n].rstrip())
990 log_write(input_hist[n].rstrip())
986 if n in output_hist:
991 if n in output_hist:
987 log_write(repr(output_hist[n]),'output')
992 log_write(repr(output_hist[n]),'output')
988 else:
993 else:
989 logger.log_write(self.shell.input_hist[1:])
994 logger.log_write(self.shell.input_hist[1:])
990 if timestamp:
995 if timestamp:
991 # re-enable timestamping
996 # re-enable timestamping
992 logger.timestamp = True
997 logger.timestamp = True
993
998
994 print ('Activating auto-logging. '
999 print ('Activating auto-logging. '
995 'Current session state plus future input saved.')
1000 'Current session state plus future input saved.')
996 logger.logstate()
1001 logger.logstate()
997
1002
998 def magic_logoff(self,parameter_s=''):
1003 def magic_logoff(self,parameter_s=''):
999 """Temporarily stop logging.
1004 """Temporarily stop logging.
1000
1005
1001 You must have previously started logging."""
1006 You must have previously started logging."""
1002 self.shell.logger.switch_log(0)
1007 self.shell.logger.switch_log(0)
1003
1008
1004 def magic_logon(self,parameter_s=''):
1009 def magic_logon(self,parameter_s=''):
1005 """Restart logging.
1010 """Restart logging.
1006
1011
1007 This function is for restarting logging which you've temporarily
1012 This function is for restarting logging which you've temporarily
1008 stopped with %logoff. For starting logging for the first time, you
1013 stopped with %logoff. For starting logging for the first time, you
1009 must use the %logstart function, which allows you to specify an
1014 must use the %logstart function, which allows you to specify an
1010 optional log filename."""
1015 optional log filename."""
1011
1016
1012 self.shell.logger.switch_log(1)
1017 self.shell.logger.switch_log(1)
1013
1018
1014 def magic_logstate(self,parameter_s=''):
1019 def magic_logstate(self,parameter_s=''):
1015 """Print the status of the logging system."""
1020 """Print the status of the logging system."""
1016
1021
1017 self.shell.logger.logstate()
1022 self.shell.logger.logstate()
1018
1023
1019 def magic_pdb(self, parameter_s=''):
1024 def magic_pdb(self, parameter_s=''):
1020 """Control the calling of the pdb interactive debugger.
1025 """Control the calling of the pdb interactive debugger.
1021
1026
1022 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1027 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1023 argument it works as a toggle.
1028 argument it works as a toggle.
1024
1029
1025 When an exception is triggered, IPython can optionally call the
1030 When an exception is triggered, IPython can optionally call the
1026 interactive pdb debugger after the traceback printout. %pdb toggles
1031 interactive pdb debugger after the traceback printout. %pdb toggles
1027 this feature on and off."""
1032 this feature on and off."""
1028
1033
1029 par = parameter_s.strip().lower()
1034 par = parameter_s.strip().lower()
1030
1035
1031 if par:
1036 if par:
1032 try:
1037 try:
1033 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1038 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1034 except KeyError:
1039 except KeyError:
1035 print ('Incorrect argument. Use on/1, off/0, '
1040 print ('Incorrect argument. Use on/1, off/0, '
1036 'or nothing for a toggle.')
1041 'or nothing for a toggle.')
1037 return
1042 return
1038 else:
1043 else:
1039 # toggle
1044 # toggle
1040 new_pdb = not self.shell.InteractiveTB.call_pdb
1045 new_pdb = not self.shell.InteractiveTB.call_pdb
1041
1046
1042 # set on the shell
1047 # set on the shell
1043 self.shell.call_pdb = new_pdb
1048 self.shell.call_pdb = new_pdb
1044 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1049 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1045
1050
1046 def magic_prun(self, parameter_s ='',user_mode=1,
1051 def magic_prun(self, parameter_s ='',user_mode=1,
1047 opts=None,arg_lst=None,prog_ns=None):
1052 opts=None,arg_lst=None,prog_ns=None):
1048
1053
1049 """Run a statement through the python code profiler.
1054 """Run a statement through the python code profiler.
1050
1055
1051 Usage:\\
1056 Usage:\\
1052 %prun [options] statement
1057 %prun [options] statement
1053
1058
1054 The given statement (which doesn't require quote marks) is run via the
1059 The given statement (which doesn't require quote marks) is run via the
1055 python profiler in a manner similar to the profile.run() function.
1060 python profiler in a manner similar to the profile.run() function.
1056 Namespaces are internally managed to work correctly; profile.run
1061 Namespaces are internally managed to work correctly; profile.run
1057 cannot be used in IPython because it makes certain assumptions about
1062 cannot be used in IPython because it makes certain assumptions about
1058 namespaces which do not hold under IPython.
1063 namespaces which do not hold under IPython.
1059
1064
1060 Options:
1065 Options:
1061
1066
1062 -l <limit>: you can place restrictions on what or how much of the
1067 -l <limit>: you can place restrictions on what or how much of the
1063 profile gets printed. The limit value can be:
1068 profile gets printed. The limit value can be:
1064
1069
1065 * A string: only information for function names containing this string
1070 * A string: only information for function names containing this string
1066 is printed.
1071 is printed.
1067
1072
1068 * An integer: only these many lines are printed.
1073 * An integer: only these many lines are printed.
1069
1074
1070 * A float (between 0 and 1): this fraction of the report is printed
1075 * A float (between 0 and 1): this fraction of the report is printed
1071 (for example, use a limit of 0.4 to see the topmost 40% only).
1076 (for example, use a limit of 0.4 to see the topmost 40% only).
1072
1077
1073 You can combine several limits with repeated use of the option. For
1078 You can combine several limits with repeated use of the option. For
1074 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1079 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1075 information about class constructors.
1080 information about class constructors.
1076
1081
1077 -r: return the pstats.Stats object generated by the profiling. This
1082 -r: return the pstats.Stats object generated by the profiling. This
1078 object has all the information about the profile in it, and you can
1083 object has all the information about the profile in it, and you can
1079 later use it for further analysis or in other functions.
1084 later use it for further analysis or in other functions.
1080
1085
1081 Since magic functions have a particular form of calling which prevents
1086 Since magic functions have a particular form of calling which prevents
1082 you from writing something like:\\
1087 you from writing something like:\\
1083 In [1]: p = %prun -r print 4 # invalid!\\
1088 In [1]: p = %prun -r print 4 # invalid!\\
1084 you must instead use IPython's automatic variables to assign this:\\
1089 you must instead use IPython's automatic variables to assign this:\\
1085 In [1]: %prun -r print 4 \\
1090 In [1]: %prun -r print 4 \\
1086 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1091 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1087 In [2]: stats = _
1092 In [2]: stats = _
1088
1093
1089 If you really need to assign this value via an explicit function call,
1094 If you really need to assign this value via an explicit function call,
1090 you can always tap directly into the true name of the magic function
1095 you can always tap directly into the true name of the magic function
1091 by using the ipmagic function (which IPython automatically adds to the
1096 by using the ipmagic function (which IPython automatically adds to the
1092 builtins):\\
1097 builtins):\\
1093 In [3]: stats = ipmagic('prun','-r print 4')
1098 In [3]: stats = ipmagic('prun','-r print 4')
1094
1099
1095 You can type ipmagic? for more details on ipmagic.
1100 You can type ipmagic? for more details on ipmagic.
1096
1101
1097 -s <key>: sort profile by given key. You can provide more than one key
1102 -s <key>: sort profile by given key. You can provide more than one key
1098 by using the option several times: '-s key1 -s key2 -s key3...'. The
1103 by using the option several times: '-s key1 -s key2 -s key3...'. The
1099 default sorting key is 'time'.
1104 default sorting key is 'time'.
1100
1105
1101 The following is copied verbatim from the profile documentation
1106 The following is copied verbatim from the profile documentation
1102 referenced below:
1107 referenced below:
1103
1108
1104 When more than one key is provided, additional keys are used as
1109 When more than one key is provided, additional keys are used as
1105 secondary criteria when the there is equality in all keys selected
1110 secondary criteria when the there is equality in all keys selected
1106 before them.
1111 before them.
1107
1112
1108 Abbreviations can be used for any key names, as long as the
1113 Abbreviations can be used for any key names, as long as the
1109 abbreviation is unambiguous. The following are the keys currently
1114 abbreviation is unambiguous. The following are the keys currently
1110 defined:
1115 defined:
1111
1116
1112 Valid Arg Meaning\\
1117 Valid Arg Meaning\\
1113 "calls" call count\\
1118 "calls" call count\\
1114 "cumulative" cumulative time\\
1119 "cumulative" cumulative time\\
1115 "file" file name\\
1120 "file" file name\\
1116 "module" file name\\
1121 "module" file name\\
1117 "pcalls" primitive call count\\
1122 "pcalls" primitive call count\\
1118 "line" line number\\
1123 "line" line number\\
1119 "name" function name\\
1124 "name" function name\\
1120 "nfl" name/file/line\\
1125 "nfl" name/file/line\\
1121 "stdname" standard name\\
1126 "stdname" standard name\\
1122 "time" internal time
1127 "time" internal time
1123
1128
1124 Note that all sorts on statistics are in descending order (placing
1129 Note that all sorts on statistics are in descending order (placing
1125 most time consuming items first), where as name, file, and line number
1130 most time consuming items first), where as name, file, and line number
1126 searches are in ascending order (i.e., alphabetical). The subtle
1131 searches are in ascending order (i.e., alphabetical). The subtle
1127 distinction between "nfl" and "stdname" is that the standard name is a
1132 distinction between "nfl" and "stdname" is that the standard name is a
1128 sort of the name as printed, which means that the embedded line
1133 sort of the name as printed, which means that the embedded line
1129 numbers get compared in an odd way. For example, lines 3, 20, and 40
1134 numbers get compared in an odd way. For example, lines 3, 20, and 40
1130 would (if the file names were the same) appear in the string order
1135 would (if the file names were the same) appear in the string order
1131 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1136 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1132 line numbers. In fact, sort_stats("nfl") is the same as
1137 line numbers. In fact, sort_stats("nfl") is the same as
1133 sort_stats("name", "file", "line").
1138 sort_stats("name", "file", "line").
1134
1139
1135 -T <filename>: save profile results as shown on screen to a text
1140 -T <filename>: save profile results as shown on screen to a text
1136 file. The profile is still shown on screen.
1141 file. The profile is still shown on screen.
1137
1142
1138 -D <filename>: save (via dump_stats) profile statistics to given
1143 -D <filename>: save (via dump_stats) profile statistics to given
1139 filename. This data is in a format understod by the pstats module, and
1144 filename. This data is in a format understod by the pstats module, and
1140 is generated by a call to the dump_stats() method of profile
1145 is generated by a call to the dump_stats() method of profile
1141 objects. The profile is still shown on screen.
1146 objects. The profile is still shown on screen.
1142
1147
1143 If you want to run complete programs under the profiler's control, use
1148 If you want to run complete programs under the profiler's control, use
1144 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1149 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1145 contains profiler specific options as described here.
1150 contains profiler specific options as described here.
1146
1151
1147 You can read the complete documentation for the profile module with:\\
1152 You can read the complete documentation for the profile module with:\\
1148 In [1]: import profile; profile.help() """
1153 In [1]: import profile; profile.help() """
1149
1154
1150 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1155 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1151 # protect user quote marks
1156 # protect user quote marks
1152 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1157 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1153
1158
1154 if user_mode: # regular user call
1159 if user_mode: # regular user call
1155 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1160 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1156 list_all=1)
1161 list_all=1)
1157 namespace = self.shell.user_ns
1162 namespace = self.shell.user_ns
1158 else: # called to run a program by %run -p
1163 else: # called to run a program by %run -p
1159 try:
1164 try:
1160 filename = get_py_filename(arg_lst[0])
1165 filename = get_py_filename(arg_lst[0])
1161 except IOError,msg:
1166 except IOError,msg:
1162 error(msg)
1167 error(msg)
1163 return
1168 return
1164
1169
1165 arg_str = 'execfile(filename,prog_ns)'
1170 arg_str = 'execfile(filename,prog_ns)'
1166 namespace = locals()
1171 namespace = locals()
1167
1172
1168 opts.merge(opts_def)
1173 opts.merge(opts_def)
1169
1174
1170 prof = profile.Profile()
1175 prof = profile.Profile()
1171 try:
1176 try:
1172 prof = prof.runctx(arg_str,namespace,namespace)
1177 prof = prof.runctx(arg_str,namespace,namespace)
1173 sys_exit = ''
1178 sys_exit = ''
1174 except SystemExit:
1179 except SystemExit:
1175 sys_exit = """*** SystemExit exception caught in code being profiled."""
1180 sys_exit = """*** SystemExit exception caught in code being profiled."""
1176
1181
1177 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1182 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1178
1183
1179 lims = opts.l
1184 lims = opts.l
1180 if lims:
1185 if lims:
1181 lims = [] # rebuild lims with ints/floats/strings
1186 lims = [] # rebuild lims with ints/floats/strings
1182 for lim in opts.l:
1187 for lim in opts.l:
1183 try:
1188 try:
1184 lims.append(int(lim))
1189 lims.append(int(lim))
1185 except ValueError:
1190 except ValueError:
1186 try:
1191 try:
1187 lims.append(float(lim))
1192 lims.append(float(lim))
1188 except ValueError:
1193 except ValueError:
1189 lims.append(lim)
1194 lims.append(lim)
1190
1195
1191 # trap output
1196 # trap output
1192 sys_stdout = sys.stdout
1197 sys_stdout = sys.stdout
1193 stdout_trap = StringIO()
1198 stdout_trap = StringIO()
1194 try:
1199 try:
1195 sys.stdout = stdout_trap
1200 sys.stdout = stdout_trap
1196 stats.print_stats(*lims)
1201 stats.print_stats(*lims)
1197 finally:
1202 finally:
1198 sys.stdout = sys_stdout
1203 sys.stdout = sys_stdout
1199 output = stdout_trap.getvalue()
1204 output = stdout_trap.getvalue()
1200 output = output.rstrip()
1205 output = output.rstrip()
1201
1206
1202 page(output,screen_lines=self.shell.rc.screen_length)
1207 page(output,screen_lines=self.shell.rc.screen_length)
1203 print sys_exit,
1208 print sys_exit,
1204
1209
1205 dump_file = opts.D[0]
1210 dump_file = opts.D[0]
1206 text_file = opts.T[0]
1211 text_file = opts.T[0]
1207 if dump_file:
1212 if dump_file:
1208 prof.dump_stats(dump_file)
1213 prof.dump_stats(dump_file)
1209 print '\n*** Profile stats marshalled to file',\
1214 print '\n*** Profile stats marshalled to file',\
1210 `dump_file`+'.',sys_exit
1215 `dump_file`+'.',sys_exit
1211 if text_file:
1216 if text_file:
1212 file(text_file,'w').write(output)
1217 file(text_file,'w').write(output)
1213 print '\n*** Profile printout saved to text file',\
1218 print '\n*** Profile printout saved to text file',\
1214 `text_file`+'.',sys_exit
1219 `text_file`+'.',sys_exit
1215
1220
1216 if opts.has_key('r'):
1221 if opts.has_key('r'):
1217 return stats
1222 return stats
1218 else:
1223 else:
1219 return None
1224 return None
1220
1225
1221 def magic_run(self, parameter_s ='',runner=None):
1226 def magic_run(self, parameter_s ='',runner=None):
1222 """Run the named file inside IPython as a program.
1227 """Run the named file inside IPython as a program.
1223
1228
1224 Usage:\\
1229 Usage:\\
1225 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1230 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1226
1231
1227 Parameters after the filename are passed as command-line arguments to
1232 Parameters after the filename are passed as command-line arguments to
1228 the program (put in sys.argv). Then, control returns to IPython's
1233 the program (put in sys.argv). Then, control returns to IPython's
1229 prompt.
1234 prompt.
1230
1235
1231 This is similar to running at a system prompt:\\
1236 This is similar to running at a system prompt:\\
1232 $ python file args\\
1237 $ python file args\\
1233 but with the advantage of giving you IPython's tracebacks, and of
1238 but with the advantage of giving you IPython's tracebacks, and of
1234 loading all variables into your interactive namespace for further use
1239 loading all variables into your interactive namespace for further use
1235 (unless -p is used, see below).
1240 (unless -p is used, see below).
1236
1241
1237 The file is executed in a namespace initially consisting only of
1242 The file is executed in a namespace initially consisting only of
1238 __name__=='__main__' and sys.argv constructed as indicated. It thus
1243 __name__=='__main__' and sys.argv constructed as indicated. It thus
1239 sees its environment as if it were being run as a stand-alone
1244 sees its environment as if it were being run as a stand-alone
1240 program. But after execution, the IPython interactive namespace gets
1245 program. But after execution, the IPython interactive namespace gets
1241 updated with all variables defined in the program (except for __name__
1246 updated with all variables defined in the program (except for __name__
1242 and sys.argv). This allows for very convenient loading of code for
1247 and sys.argv). This allows for very convenient loading of code for
1243 interactive work, while giving each program a 'clean sheet' to run in.
1248 interactive work, while giving each program a 'clean sheet' to run in.
1244
1249
1245 Options:
1250 Options:
1246
1251
1247 -n: __name__ is NOT set to '__main__', but to the running file's name
1252 -n: __name__ is NOT set to '__main__', but to the running file's name
1248 without extension (as python does under import). This allows running
1253 without extension (as python does under import). This allows running
1249 scripts and reloading the definitions in them without calling code
1254 scripts and reloading the definitions in them without calling code
1250 protected by an ' if __name__ == "__main__" ' clause.
1255 protected by an ' if __name__ == "__main__" ' clause.
1251
1256
1252 -i: run the file in IPython's namespace instead of an empty one. This
1257 -i: run the file in IPython's namespace instead of an empty one. This
1253 is useful if you are experimenting with code written in a text editor
1258 is useful if you are experimenting with code written in a text editor
1254 which depends on variables defined interactively.
1259 which depends on variables defined interactively.
1255
1260
1256 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1261 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1257 being run. This is particularly useful if IPython is being used to
1262 being run. This is particularly useful if IPython is being used to
1258 run unittests, which always exit with a sys.exit() call. In such
1263 run unittests, which always exit with a sys.exit() call. In such
1259 cases you are interested in the output of the test results, not in
1264 cases you are interested in the output of the test results, not in
1260 seeing a traceback of the unittest module.
1265 seeing a traceback of the unittest module.
1261
1266
1262 -t: print timing information at the end of the run. IPython will give
1267 -t: print timing information at the end of the run. IPython will give
1263 you an estimated CPU time consumption for your script, which under
1268 you an estimated CPU time consumption for your script, which under
1264 Unix uses the resource module to avoid the wraparound problems of
1269 Unix uses the resource module to avoid the wraparound problems of
1265 time.clock(). Under Unix, an estimate of time spent on system tasks
1270 time.clock(). Under Unix, an estimate of time spent on system tasks
1266 is also given (for Windows platforms this is reported as 0.0).
1271 is also given (for Windows platforms this is reported as 0.0).
1267
1272
1268 If -t is given, an additional -N<N> option can be given, where <N>
1273 If -t is given, an additional -N<N> option can be given, where <N>
1269 must be an integer indicating how many times you want the script to
1274 must be an integer indicating how many times you want the script to
1270 run. The final timing report will include total and per run results.
1275 run. The final timing report will include total and per run results.
1271
1276
1272 For example (testing the script uniq_stable.py):
1277 For example (testing the script uniq_stable.py):
1273
1278
1274 In [1]: run -t uniq_stable
1279 In [1]: run -t uniq_stable
1275
1280
1276 IPython CPU timings (estimated):\\
1281 IPython CPU timings (estimated):\\
1277 User : 0.19597 s.\\
1282 User : 0.19597 s.\\
1278 System: 0.0 s.\\
1283 System: 0.0 s.\\
1279
1284
1280 In [2]: run -t -N5 uniq_stable
1285 In [2]: run -t -N5 uniq_stable
1281
1286
1282 IPython CPU timings (estimated):\\
1287 IPython CPU timings (estimated):\\
1283 Total runs performed: 5\\
1288 Total runs performed: 5\\
1284 Times : Total Per run\\
1289 Times : Total Per run\\
1285 User : 0.910862 s, 0.1821724 s.\\
1290 User : 0.910862 s, 0.1821724 s.\\
1286 System: 0.0 s, 0.0 s.
1291 System: 0.0 s, 0.0 s.
1287
1292
1288 -d: run your program under the control of pdb, the Python debugger.
1293 -d: run your program under the control of pdb, the Python debugger.
1289 This allows you to execute your program step by step, watch variables,
1294 This allows you to execute your program step by step, watch variables,
1290 etc. Internally, what IPython does is similar to calling:
1295 etc. Internally, what IPython does is similar to calling:
1291
1296
1292 pdb.run('execfile("YOURFILENAME")')
1297 pdb.run('execfile("YOURFILENAME")')
1293
1298
1294 with a breakpoint set on line 1 of your file. You can change the line
1299 with a breakpoint set on line 1 of your file. You can change the line
1295 number for this automatic breakpoint to be <N> by using the -bN option
1300 number for this automatic breakpoint to be <N> by using the -bN option
1296 (where N must be an integer). For example:
1301 (where N must be an integer). For example:
1297
1302
1298 %run -d -b40 myscript
1303 %run -d -b40 myscript
1299
1304
1300 will set the first breakpoint at line 40 in myscript.py. Note that
1305 will set the first breakpoint at line 40 in myscript.py. Note that
1301 the first breakpoint must be set on a line which actually does
1306 the first breakpoint must be set on a line which actually does
1302 something (not a comment or docstring) for it to stop execution.
1307 something (not a comment or docstring) for it to stop execution.
1303
1308
1304 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1309 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1305 first enter 'c' (without qoutes) to start execution up to the first
1310 first enter 'c' (without qoutes) to start execution up to the first
1306 breakpoint.
1311 breakpoint.
1307
1312
1308 Entering 'help' gives information about the use of the debugger. You
1313 Entering 'help' gives information about the use of the debugger. You
1309 can easily see pdb's full documentation with "import pdb;pdb.help()"
1314 can easily see pdb's full documentation with "import pdb;pdb.help()"
1310 at a prompt.
1315 at a prompt.
1311
1316
1312 -p: run program under the control of the Python profiler module (which
1317 -p: run program under the control of the Python profiler module (which
1313 prints a detailed report of execution times, function calls, etc).
1318 prints a detailed report of execution times, function calls, etc).
1314
1319
1315 You can pass other options after -p which affect the behavior of the
1320 You can pass other options after -p which affect the behavior of the
1316 profiler itself. See the docs for %prun for details.
1321 profiler itself. See the docs for %prun for details.
1317
1322
1318 In this mode, the program's variables do NOT propagate back to the
1323 In this mode, the program's variables do NOT propagate back to the
1319 IPython interactive namespace (because they remain in the namespace
1324 IPython interactive namespace (because they remain in the namespace
1320 where the profiler executes them).
1325 where the profiler executes them).
1321
1326
1322 Internally this triggers a call to %prun, see its documentation for
1327 Internally this triggers a call to %prun, see its documentation for
1323 details on the options available specifically for profiling."""
1328 details on the options available specifically for profiling."""
1324
1329
1325 # get arguments and set sys.argv for program to be run.
1330 # get arguments and set sys.argv for program to be run.
1326 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1331 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1327 mode='list',list_all=1)
1332 mode='list',list_all=1)
1328
1333
1329 try:
1334 try:
1330 filename = get_py_filename(arg_lst[0])
1335 filename = get_py_filename(arg_lst[0])
1331 except IndexError:
1336 except IndexError:
1332 warn('you must provide at least a filename.')
1337 warn('you must provide at least a filename.')
1333 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1338 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1334 return
1339 return
1335 except IOError,msg:
1340 except IOError,msg:
1336 error(msg)
1341 error(msg)
1337 return
1342 return
1338
1343
1339 # Control the response to exit() calls made by the script being run
1344 # Control the response to exit() calls made by the script being run
1340 exit_ignore = opts.has_key('e')
1345 exit_ignore = opts.has_key('e')
1341
1346
1342 # Make sure that the running script gets a proper sys.argv as if it
1347 # Make sure that the running script gets a proper sys.argv as if it
1343 # were run from a system shell.
1348 # were run from a system shell.
1344 save_argv = sys.argv # save it for later restoring
1349 save_argv = sys.argv # save it for later restoring
1345 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1350 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1346
1351
1347 if opts.has_key('i'):
1352 if opts.has_key('i'):
1348 prog_ns = self.shell.user_ns
1353 prog_ns = self.shell.user_ns
1349 __name__save = self.shell.user_ns['__name__']
1354 __name__save = self.shell.user_ns['__name__']
1350 prog_ns['__name__'] = '__main__'
1355 prog_ns['__name__'] = '__main__'
1351 else:
1356 else:
1352 if opts.has_key('n'):
1357 if opts.has_key('n'):
1353 name = os.path.splitext(os.path.basename(filename))[0]
1358 name = os.path.splitext(os.path.basename(filename))[0]
1354 else:
1359 else:
1355 name = '__main__'
1360 name = '__main__'
1356 prog_ns = {'__name__':name}
1361 prog_ns = {'__name__':name}
1357
1362
1358 # pickle fix. See iplib for an explanation
1363 # pickle fix. See iplib for an explanation
1359 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1364 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1360
1365
1361 stats = None
1366 stats = None
1362 try:
1367 try:
1363 if opts.has_key('p'):
1368 if opts.has_key('p'):
1364 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1369 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1365 else:
1370 else:
1366 if opts.has_key('d'):
1371 if opts.has_key('d'):
1367 deb = Debugger.Pdb(self.shell.rc.colors)
1372 deb = Debugger.Pdb(self.shell.rc.colors)
1368 # reset Breakpoint state, which is moronically kept
1373 # reset Breakpoint state, which is moronically kept
1369 # in a class
1374 # in a class
1370 bdb.Breakpoint.next = 1
1375 bdb.Breakpoint.next = 1
1371 bdb.Breakpoint.bplist = {}
1376 bdb.Breakpoint.bplist = {}
1372 bdb.Breakpoint.bpbynumber = [None]
1377 bdb.Breakpoint.bpbynumber = [None]
1373 # Set an initial breakpoint to stop execution
1378 # Set an initial breakpoint to stop execution
1374 maxtries = 10
1379 maxtries = 10
1375 bp = int(opts.get('b',[1])[0])
1380 bp = int(opts.get('b',[1])[0])
1376 checkline = deb.checkline(filename,bp)
1381 checkline = deb.checkline(filename,bp)
1377 if not checkline:
1382 if not checkline:
1378 for bp in range(bp+1,bp+maxtries+1):
1383 for bp in range(bp+1,bp+maxtries+1):
1379 if deb.checkline(filename,bp):
1384 if deb.checkline(filename,bp):
1380 break
1385 break
1381 else:
1386 else:
1382 msg = ("\nI failed to find a valid line to set "
1387 msg = ("\nI failed to find a valid line to set "
1383 "a breakpoint\n"
1388 "a breakpoint\n"
1384 "after trying up to line: %s.\n"
1389 "after trying up to line: %s.\n"
1385 "Please set a valid breakpoint manually "
1390 "Please set a valid breakpoint manually "
1386 "with the -b option." % bp)
1391 "with the -b option." % bp)
1387 error(msg)
1392 error(msg)
1388 return
1393 return
1389 # if we find a good linenumber, set the breakpoint
1394 # if we find a good linenumber, set the breakpoint
1390 deb.do_break('%s:%s' % (filename,bp))
1395 deb.do_break('%s:%s' % (filename,bp))
1391 # Start file run
1396 # Start file run
1392 print "NOTE: Enter 'c' at the",
1397 print "NOTE: Enter 'c' at the",
1393 print "ipdb> prompt to start your script."
1398 print "ipdb> prompt to start your script."
1394 try:
1399 try:
1395 deb.run('execfile("%s")' % filename,prog_ns)
1400 deb.run('execfile("%s")' % filename,prog_ns)
1396 except:
1401 except:
1397 etype, value, tb = sys.exc_info()
1402 etype, value, tb = sys.exc_info()
1398 # Skip three frames in the traceback: the %run one,
1403 # Skip three frames in the traceback: the %run one,
1399 # one inside bdb.py, and the command-line typed by the
1404 # one inside bdb.py, and the command-line typed by the
1400 # user (run by exec in pdb itself).
1405 # user (run by exec in pdb itself).
1401 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1406 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1402 else:
1407 else:
1403 if runner is None:
1408 if runner is None:
1404 runner = self.shell.safe_execfile
1409 runner = self.shell.safe_execfile
1405 if opts.has_key('t'):
1410 if opts.has_key('t'):
1406 try:
1411 try:
1407 nruns = int(opts['N'][0])
1412 nruns = int(opts['N'][0])
1408 if nruns < 1:
1413 if nruns < 1:
1409 error('Number of runs must be >=1')
1414 error('Number of runs must be >=1')
1410 return
1415 return
1411 except (KeyError):
1416 except (KeyError):
1412 nruns = 1
1417 nruns = 1
1413 if nruns == 1:
1418 if nruns == 1:
1414 t0 = clock2()
1419 t0 = clock2()
1415 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1420 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1416 t1 = clock2()
1421 t1 = clock2()
1417 t_usr = t1[0]-t0[0]
1422 t_usr = t1[0]-t0[0]
1418 t_sys = t1[1]-t1[1]
1423 t_sys = t1[1]-t1[1]
1419 print "\nIPython CPU timings (estimated):"
1424 print "\nIPython CPU timings (estimated):"
1420 print " User : %10s s." % t_usr
1425 print " User : %10s s." % t_usr
1421 print " System: %10s s." % t_sys
1426 print " System: %10s s." % t_sys
1422 else:
1427 else:
1423 runs = range(nruns)
1428 runs = range(nruns)
1424 t0 = clock2()
1429 t0 = clock2()
1425 for nr in runs:
1430 for nr in runs:
1426 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1431 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1427 t1 = clock2()
1432 t1 = clock2()
1428 t_usr = t1[0]-t0[0]
1433 t_usr = t1[0]-t0[0]
1429 t_sys = t1[1]-t1[1]
1434 t_sys = t1[1]-t1[1]
1430 print "\nIPython CPU timings (estimated):"
1435 print "\nIPython CPU timings (estimated):"
1431 print "Total runs performed:",nruns
1436 print "Total runs performed:",nruns
1432 print " Times : %10s %10s" % ('Total','Per run')
1437 print " Times : %10s %10s" % ('Total','Per run')
1433 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1438 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1434 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1439 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1435
1440
1436 else:
1441 else:
1437 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1442 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1438 if opts.has_key('i'):
1443 if opts.has_key('i'):
1439 self.shell.user_ns['__name__'] = __name__save
1444 self.shell.user_ns['__name__'] = __name__save
1440 else:
1445 else:
1441 # update IPython interactive namespace
1446 # update IPython interactive namespace
1442 del prog_ns['__name__']
1447 del prog_ns['__name__']
1443 self.shell.user_ns.update(prog_ns)
1448 self.shell.user_ns.update(prog_ns)
1444 finally:
1449 finally:
1445 sys.argv = save_argv
1450 sys.argv = save_argv
1446 return stats
1451 return stats
1447
1452
1448 def magic_runlog(self, parameter_s =''):
1453 def magic_runlog(self, parameter_s =''):
1449 """Run files as logs.
1454 """Run files as logs.
1450
1455
1451 Usage:\\
1456 Usage:\\
1452 %runlog file1 file2 ...
1457 %runlog file1 file2 ...
1453
1458
1454 Run the named files (treating them as log files) in sequence inside
1459 Run the named files (treating them as log files) in sequence inside
1455 the interpreter, and return to the prompt. This is much slower than
1460 the interpreter, and return to the prompt. This is much slower than
1456 %run because each line is executed in a try/except block, but it
1461 %run because each line is executed in a try/except block, but it
1457 allows running files with syntax errors in them.
1462 allows running files with syntax errors in them.
1458
1463
1459 Normally IPython will guess when a file is one of its own logfiles, so
1464 Normally IPython will guess when a file is one of its own logfiles, so
1460 you can typically use %run even for logs. This shorthand allows you to
1465 you can typically use %run even for logs. This shorthand allows you to
1461 force any file to be treated as a log file."""
1466 force any file to be treated as a log file."""
1462
1467
1463 for f in parameter_s.split():
1468 for f in parameter_s.split():
1464 self.shell.safe_execfile(f,self.shell.user_ns,
1469 self.shell.safe_execfile(f,self.shell.user_ns,
1465 self.shell.user_ns,islog=1)
1470 self.shell.user_ns,islog=1)
1466
1471
1467 def magic_time(self,parameter_s = ''):
1472 def magic_time(self,parameter_s = ''):
1468 """Time execution of a Python statement or expression.
1473 """Time execution of a Python statement or expression.
1469
1474
1470 The CPU and wall clock times are printed, and the value of the
1475 The CPU and wall clock times are printed, and the value of the
1471 expression (if any) is returned. Note that under Win32, system time
1476 expression (if any) is returned. Note that under Win32, system time
1472 is always reported as 0, since it can not be measured.
1477 is always reported as 0, since it can not be measured.
1473
1478
1474 This function provides very basic timing functionality. In Python
1479 This function provides very basic timing functionality. In Python
1475 2.3, the timeit module offers more control and sophistication, but for
1480 2.3, the timeit module offers more control and sophistication, but for
1476 now IPython supports Python 2.2, so we can not rely on timeit being
1481 now IPython supports Python 2.2, so we can not rely on timeit being
1477 present.
1482 present.
1478
1483
1479 Some examples:
1484 Some examples:
1480
1485
1481 In [1]: time 2**128
1486 In [1]: time 2**128
1482 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1487 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1483 Wall time: 0.00
1488 Wall time: 0.00
1484 Out[1]: 340282366920938463463374607431768211456L
1489 Out[1]: 340282366920938463463374607431768211456L
1485
1490
1486 In [2]: n = 1000000
1491 In [2]: n = 1000000
1487
1492
1488 In [3]: time sum(range(n))
1493 In [3]: time sum(range(n))
1489 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1494 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1490 Wall time: 1.37
1495 Wall time: 1.37
1491 Out[3]: 499999500000L
1496 Out[3]: 499999500000L
1492
1497
1493 In [4]: time print 'hello world'
1498 In [4]: time print 'hello world'
1494 hello world
1499 hello world
1495 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1500 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1496 Wall time: 0.00
1501 Wall time: 0.00
1497 """
1502 """
1498
1503
1499 # fail immediately if the given expression can't be compiled
1504 # fail immediately if the given expression can't be compiled
1500 try:
1505 try:
1501 mode = 'eval'
1506 mode = 'eval'
1502 code = compile(parameter_s,'<timed eval>',mode)
1507 code = compile(parameter_s,'<timed eval>',mode)
1503 except SyntaxError:
1508 except SyntaxError:
1504 mode = 'exec'
1509 mode = 'exec'
1505 code = compile(parameter_s,'<timed exec>',mode)
1510 code = compile(parameter_s,'<timed exec>',mode)
1506 # skew measurement as little as possible
1511 # skew measurement as little as possible
1507 glob = self.shell.user_ns
1512 glob = self.shell.user_ns
1508 clk = clock2
1513 clk = clock2
1509 wtime = time.time
1514 wtime = time.time
1510 # time execution
1515 # time execution
1511 wall_st = wtime()
1516 wall_st = wtime()
1512 if mode=='eval':
1517 if mode=='eval':
1513 st = clk()
1518 st = clk()
1514 out = eval(code,glob)
1519 out = eval(code,glob)
1515 end = clk()
1520 end = clk()
1516 else:
1521 else:
1517 st = clk()
1522 st = clk()
1518 exec code in glob
1523 exec code in glob
1519 end = clk()
1524 end = clk()
1520 out = None
1525 out = None
1521 wall_end = wtime()
1526 wall_end = wtime()
1522 # Compute actual times and report
1527 # Compute actual times and report
1523 wall_time = wall_end-wall_st
1528 wall_time = wall_end-wall_st
1524 cpu_user = end[0]-st[0]
1529 cpu_user = end[0]-st[0]
1525 cpu_sys = end[1]-st[1]
1530 cpu_sys = end[1]-st[1]
1526 cpu_tot = cpu_user+cpu_sys
1531 cpu_tot = cpu_user+cpu_sys
1527 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1532 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1528 (cpu_user,cpu_sys,cpu_tot)
1533 (cpu_user,cpu_sys,cpu_tot)
1529 print "Wall time: %.2f" % wall_time
1534 print "Wall time: %.2f" % wall_time
1530 return out
1535 return out
1531
1536
1532 def magic_macro(self,parameter_s = ''):
1537 def magic_macro(self,parameter_s = ''):
1533 """Define a set of input lines as a macro for future re-execution.
1538 """Define a set of input lines as a macro for future re-execution.
1534
1539
1535 Usage:\\
1540 Usage:\\
1536 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1541 %macro name n1:n2 n3:n4 ... n5 .. n6 ...
1537
1542
1538 This will define a global variable called `name` which is a string
1543 This will define a global variable called `name` which is a string
1539 made of joining the slices and lines you specify (n1,n2,... numbers
1544 made of joining the slices and lines you specify (n1,n2,... numbers
1540 above) from your input history into a single string. This variable
1545 above) from your input history into a single string. This variable
1541 acts like an automatic function which re-executes those lines as if
1546 acts like an automatic function which re-executes those lines as if
1542 you had typed them. You just type 'name' at the prompt and the code
1547 you had typed them. You just type 'name' at the prompt and the code
1543 executes.
1548 executes.
1544
1549
1545 Note that the slices use the standard Python slicing notation (5:8
1550 Note that the slices use the standard Python slicing notation (5:8
1546 means include lines numbered 5,6,7).
1551 means include lines numbered 5,6,7).
1547
1552
1548 For example, if your history contains (%hist prints it):
1553 For example, if your history contains (%hist prints it):
1549
1554
1550 44: x=1\\
1555 44: x=1\\
1551 45: y=3\\
1556 45: y=3\\
1552 46: z=x+y\\
1557 46: z=x+y\\
1553 47: print x\\
1558 47: print x\\
1554 48: a=5\\
1559 48: a=5\\
1555 49: print 'x',x,'y',y\\
1560 49: print 'x',x,'y',y\\
1556
1561
1557 you can create a macro with lines 44 through 47 (included) and line 49
1562 you can create a macro with lines 44 through 47 (included) and line 49
1558 called my_macro with:
1563 called my_macro with:
1559
1564
1560 In [51]: %macro my_macro 44:48 49
1565 In [51]: %macro my_macro 44:48 49
1561
1566
1562 Now, typing `my_macro` (without quotes) will re-execute all this code
1567 Now, typing `my_macro` (without quotes) will re-execute all this code
1563 in one pass.
1568 in one pass.
1564
1569
1565 You don't need to give the line-numbers in order, and any given line
1570 You don't need to give the line-numbers in order, and any given line
1566 number can appear multiple times. You can assemble macros with any
1571 number can appear multiple times. You can assemble macros with any
1567 lines from your input history in any order.
1572 lines from your input history in any order.
1568
1573
1569 The macro is a simple object which holds its value in an attribute,
1574 The macro is a simple object which holds its value in an attribute,
1570 but IPython's display system checks for macros and executes them as
1575 but IPython's display system checks for macros and executes them as
1571 code instead of printing them when you type their name.
1576 code instead of printing them when you type their name.
1572
1577
1573 You can view a macro's contents by explicitly printing it with:
1578 You can view a macro's contents by explicitly printing it with:
1574
1579
1575 'print macro_name'.
1580 'print macro_name'.
1576
1581
1577 For one-off cases which DON'T contain magic function calls in them you
1582 For one-off cases which DON'T contain magic function calls in them you
1578 can obtain similar results by explicitly executing slices from your
1583 can obtain similar results by explicitly executing slices from your
1579 input history with:
1584 input history with:
1580
1585
1581 In [60]: exec In[44:48]+In[49]"""
1586 In [60]: exec In[44:48]+In[49]"""
1582
1587
1583 args = parameter_s.split()
1588 args = parameter_s.split()
1584 name,ranges = args[0], args[1:]
1589 name,ranges = args[0], args[1:]
1585 #print 'rng',ranges # dbg
1590 #print 'rng',ranges # dbg
1586 lines = self.extract_input_slices(ranges)
1591 lines = self.extract_input_slices(ranges)
1587 macro = Macro(lines)
1592 macro = Macro(lines)
1588 self.shell.user_ns.update({name:macro})
1593 self.shell.user_ns.update({name:macro})
1589 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1594 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1590 print 'Macro contents:'
1595 print 'Macro contents:'
1591 print macro
1596 print macro
1592
1597
1593 def magic_save(self,parameter_s = ''):
1598 def magic_save(self,parameter_s = ''):
1594 """Save a set of lines to a given filename.
1599 """Save a set of lines to a given filename.
1595
1600
1596 Usage:\\
1601 Usage:\\
1597 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1602 %save filename n1:n2 n3:n4 ... n5 .. n6 ...
1598
1603
1599 This function uses the same syntax as %macro for line extraction, but
1604 This function uses the same syntax as %macro for line extraction, but
1600 instead of creating a macro it saves the resulting string to the
1605 instead of creating a macro it saves the resulting string to the
1601 filename you specify.
1606 filename you specify.
1602
1607
1603 It adds a '.py' extension to the file if you don't do so yourself, and
1608 It adds a '.py' extension to the file if you don't do so yourself, and
1604 it asks for confirmation before overwriting existing files."""
1609 it asks for confirmation before overwriting existing files."""
1605
1610
1606 args = parameter_s.split()
1611 args = parameter_s.split()
1607 fname,ranges = args[0], args[1:]
1612 fname,ranges = args[0], args[1:]
1608 if not fname.endswith('.py'):
1613 if not fname.endswith('.py'):
1609 fname += '.py'
1614 fname += '.py'
1610 if os.path.isfile(fname):
1615 if os.path.isfile(fname):
1611 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1616 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1612 if ans.lower() not in ['y','yes']:
1617 if ans.lower() not in ['y','yes']:
1613 print 'Operation cancelled.'
1618 print 'Operation cancelled.'
1614 return
1619 return
1615 cmds = ''.join(self.extract_input_slices(ranges))
1620 cmds = ''.join(self.extract_input_slices(ranges))
1616 f = file(fname,'w')
1621 f = file(fname,'w')
1617 f.write(cmds)
1622 f.write(cmds)
1618 f.close()
1623 f.close()
1619 print 'The following commands were written to file `%s`:' % fname
1624 print 'The following commands were written to file `%s`:' % fname
1620 print cmds
1625 print cmds
1621
1626
1622 def magic_ed(self,parameter_s = ''):
1627 def magic_ed(self,parameter_s = ''):
1623 """Alias to %edit."""
1628 """Alias to %edit."""
1624 return self.magic_edit(parameter_s)
1629 return self.magic_edit(parameter_s)
1625
1630
1626 def magic_edit(self,parameter_s = '',last_call=['','']):
1631 def magic_edit(self,parameter_s = '',last_call=['','']):
1627 """Bring up an editor and execute the resulting code.
1632 """Bring up an editor and execute the resulting code.
1628
1633
1629 Usage:
1634 Usage:
1630 %edit [options] [args]
1635 %edit [options] [args]
1631
1636
1632 %edit runs IPython's editor hook. The default version of this hook is
1637 %edit runs IPython's editor hook. The default version of this hook is
1633 set to call the __IPYTHON__.rc.editor command. This is read from your
1638 set to call the __IPYTHON__.rc.editor command. This is read from your
1634 environment variable $EDITOR. If this isn't found, it will default to
1639 environment variable $EDITOR. If this isn't found, it will default to
1635 vi under Linux/Unix and to notepad under Windows. See the end of this
1640 vi under Linux/Unix and to notepad under Windows. See the end of this
1636 docstring for how to change the editor hook.
1641 docstring for how to change the editor hook.
1637
1642
1638 You can also set the value of this editor via the command line option
1643 You can also set the value of this editor via the command line option
1639 '-editor' or in your ipythonrc file. This is useful if you wish to use
1644 '-editor' or in your ipythonrc file. This is useful if you wish to use
1640 specifically for IPython an editor different from your typical default
1645 specifically for IPython an editor different from your typical default
1641 (and for Windows users who typically don't set environment variables).
1646 (and for Windows users who typically don't set environment variables).
1642
1647
1643 This command allows you to conveniently edit multi-line code right in
1648 This command allows you to conveniently edit multi-line code right in
1644 your IPython session.
1649 your IPython session.
1645
1650
1646 If called without arguments, %edit opens up an empty editor with a
1651 If called without arguments, %edit opens up an empty editor with a
1647 temporary file and will execute the contents of this file when you
1652 temporary file and will execute the contents of this file when you
1648 close it (don't forget to save it!).
1653 close it (don't forget to save it!).
1649
1654
1650 Options:
1655 Options:
1651
1656
1652 -p: this will call the editor with the same data as the previous time
1657 -p: this will call the editor with the same data as the previous time
1653 it was used, regardless of how long ago (in your current session) it
1658 it was used, regardless of how long ago (in your current session) it
1654 was.
1659 was.
1655
1660
1656 -x: do not execute the edited code immediately upon exit. This is
1661 -x: do not execute the edited code immediately upon exit. This is
1657 mainly useful if you are editing programs which need to be called with
1662 mainly useful if you are editing programs which need to be called with
1658 command line arguments, which you can then do using %run.
1663 command line arguments, which you can then do using %run.
1659
1664
1660 Arguments:
1665 Arguments:
1661
1666
1662 If arguments are given, the following possibilites exist:
1667 If arguments are given, the following possibilites exist:
1663
1668
1664 - The arguments are numbers or pairs of colon-separated numbers (like
1669 - The arguments are numbers or pairs of colon-separated numbers (like
1665 1 4:8 9). These are interpreted as lines of previous input to be
1670 1 4:8 9). These are interpreted as lines of previous input to be
1666 loaded into the editor. The syntax is the same of the %macro command.
1671 loaded into the editor. The syntax is the same of the %macro command.
1667
1672
1668 - If the argument doesn't start with a number, it is evaluated as a
1673 - If the argument doesn't start with a number, it is evaluated as a
1669 variable and its contents loaded into the editor. You can thus edit
1674 variable and its contents loaded into the editor. You can thus edit
1670 any string which contains python code (including the result of
1675 any string which contains python code (including the result of
1671 previous edits).
1676 previous edits).
1672
1677
1673 - If the argument is the name of an object (other than a string),
1678 - If the argument is the name of an object (other than a string),
1674 IPython will try to locate the file where it was defined and open the
1679 IPython will try to locate the file where it was defined and open the
1675 editor at the point where it is defined. You can use `%edit function`
1680 editor at the point where it is defined. You can use `%edit function`
1676 to load an editor exactly at the point where 'function' is defined,
1681 to load an editor exactly at the point where 'function' is defined,
1677 edit it and have the file be executed automatically.
1682 edit it and have the file be executed automatically.
1678
1683
1679 Note: opening at an exact line is only supported under Unix, and some
1684 Note: opening at an exact line is only supported under Unix, and some
1680 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1685 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1681 '+NUMBER' parameter necessary for this feature. Good editors like
1686 '+NUMBER' parameter necessary for this feature. Good editors like
1682 (X)Emacs, vi, jed, pico and joe all do.
1687 (X)Emacs, vi, jed, pico and joe all do.
1683
1688
1684 - If the argument is not found as a variable, IPython will look for a
1689 - If the argument is not found as a variable, IPython will look for a
1685 file with that name (adding .py if necessary) and load it into the
1690 file with that name (adding .py if necessary) and load it into the
1686 editor. It will execute its contents with execfile() when you exit,
1691 editor. It will execute its contents with execfile() when you exit,
1687 loading any code in the file into your interactive namespace.
1692 loading any code in the file into your interactive namespace.
1688
1693
1689 After executing your code, %edit will return as output the code you
1694 After executing your code, %edit will return as output the code you
1690 typed in the editor (except when it was an existing file). This way
1695 typed in the editor (except when it was an existing file). This way
1691 you can reload the code in further invocations of %edit as a variable,
1696 you can reload the code in further invocations of %edit as a variable,
1692 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1697 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1693 the output.
1698 the output.
1694
1699
1695 Note that %edit is also available through the alias %ed.
1700 Note that %edit is also available through the alias %ed.
1696
1701
1697 This is an example of creating a simple function inside the editor and
1702 This is an example of creating a simple function inside the editor and
1698 then modifying it. First, start up the editor:
1703 then modifying it. First, start up the editor:
1699
1704
1700 In [1]: ed\\
1705 In [1]: ed\\
1701 Editing... done. Executing edited code...\\
1706 Editing... done. Executing edited code...\\
1702 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1707 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1703
1708
1704 We can then call the function foo():
1709 We can then call the function foo():
1705
1710
1706 In [2]: foo()\\
1711 In [2]: foo()\\
1707 foo() was defined in an editing session
1712 foo() was defined in an editing session
1708
1713
1709 Now we edit foo. IPython automatically loads the editor with the
1714 Now we edit foo. IPython automatically loads the editor with the
1710 (temporary) file where foo() was previously defined:
1715 (temporary) file where foo() was previously defined:
1711
1716
1712 In [3]: ed foo\\
1717 In [3]: ed foo\\
1713 Editing... done. Executing edited code...
1718 Editing... done. Executing edited code...
1714
1719
1715 And if we call foo() again we get the modified version:
1720 And if we call foo() again we get the modified version:
1716
1721
1717 In [4]: foo()\\
1722 In [4]: foo()\\
1718 foo() has now been changed!
1723 foo() has now been changed!
1719
1724
1720 Here is an example of how to edit a code snippet successive
1725 Here is an example of how to edit a code snippet successive
1721 times. First we call the editor:
1726 times. First we call the editor:
1722
1727
1723 In [8]: ed\\
1728 In [8]: ed\\
1724 Editing... done. Executing edited code...\\
1729 Editing... done. Executing edited code...\\
1725 hello\\
1730 hello\\
1726 Out[8]: "print 'hello'\\n"
1731 Out[8]: "print 'hello'\\n"
1727
1732
1728 Now we call it again with the previous output (stored in _):
1733 Now we call it again with the previous output (stored in _):
1729
1734
1730 In [9]: ed _\\
1735 In [9]: ed _\\
1731 Editing... done. Executing edited code...\\
1736 Editing... done. Executing edited code...\\
1732 hello world\\
1737 hello world\\
1733 Out[9]: "print 'hello world'\\n"
1738 Out[9]: "print 'hello world'\\n"
1734
1739
1735 Now we call it with the output #8 (stored in _8, also as Out[8]):
1740 Now we call it with the output #8 (stored in _8, also as Out[8]):
1736
1741
1737 In [10]: ed _8\\
1742 In [10]: ed _8\\
1738 Editing... done. Executing edited code...\\
1743 Editing... done. Executing edited code...\\
1739 hello again\\
1744 hello again\\
1740 Out[10]: "print 'hello again'\\n"
1745 Out[10]: "print 'hello again'\\n"
1741
1746
1742
1747
1743 Changing the default editor hook:
1748 Changing the default editor hook:
1744
1749
1745 If you wish to write your own editor hook, you can put it in a
1750 If you wish to write your own editor hook, you can put it in a
1746 configuration file which you load at startup time. The default hook
1751 configuration file which you load at startup time. The default hook
1747 is defined in the IPython.hooks module, and you can use that as a
1752 is defined in the IPython.hooks module, and you can use that as a
1748 starting example for further modifications. That file also has
1753 starting example for further modifications. That file also has
1749 general instructions on how to set a new hook for use once you've
1754 general instructions on how to set a new hook for use once you've
1750 defined it."""
1755 defined it."""
1751
1756
1752 # FIXME: This function has become a convoluted mess. It needs a
1757 # FIXME: This function has become a convoluted mess. It needs a
1753 # ground-up rewrite with clean, simple logic.
1758 # ground-up rewrite with clean, simple logic.
1754
1759
1755 def make_filename(arg):
1760 def make_filename(arg):
1756 "Make a filename from the given args"
1761 "Make a filename from the given args"
1757 try:
1762 try:
1758 filename = get_py_filename(arg)
1763 filename = get_py_filename(arg)
1759 except IOError:
1764 except IOError:
1760 if args.endswith('.py'):
1765 if args.endswith('.py'):
1761 filename = arg
1766 filename = arg
1762 else:
1767 else:
1763 filename = None
1768 filename = None
1764 return filename
1769 return filename
1765
1770
1766 # custom exceptions
1771 # custom exceptions
1767 class DataIsObject(Exception): pass
1772 class DataIsObject(Exception): pass
1768
1773
1769 opts,args = self.parse_options(parameter_s,'px')
1774 opts,args = self.parse_options(parameter_s,'px')
1770
1775
1771 # Default line number value
1776 # Default line number value
1772 lineno = None
1777 lineno = None
1773 if opts.has_key('p'):
1778 if opts.has_key('p'):
1774 args = '_%s' % last_call[0]
1779 args = '_%s' % last_call[0]
1775 if not self.shell.user_ns.has_key(args):
1780 if not self.shell.user_ns.has_key(args):
1776 args = last_call[1]
1781 args = last_call[1]
1777
1782
1778 # use last_call to remember the state of the previous call, but don't
1783 # use last_call to remember the state of the previous call, but don't
1779 # let it be clobbered by successive '-p' calls.
1784 # let it be clobbered by successive '-p' calls.
1780 try:
1785 try:
1781 last_call[0] = self.shell.outputcache.prompt_count
1786 last_call[0] = self.shell.outputcache.prompt_count
1782 if not opts.has_key('p'):
1787 if not opts.has_key('p'):
1783 last_call[1] = parameter_s
1788 last_call[1] = parameter_s
1784 except:
1789 except:
1785 pass
1790 pass
1786
1791
1787 # by default this is done with temp files, except when the given
1792 # by default this is done with temp files, except when the given
1788 # arg is a filename
1793 # arg is a filename
1789 use_temp = 1
1794 use_temp = 1
1790
1795
1791 if re.match(r'\d',args):
1796 if re.match(r'\d',args):
1792 # Mode where user specifies ranges of lines, like in %macro.
1797 # Mode where user specifies ranges of lines, like in %macro.
1793 # This means that you can't edit files whose names begin with
1798 # This means that you can't edit files whose names begin with
1794 # numbers this way. Tough.
1799 # numbers this way. Tough.
1795 ranges = args.split()
1800 ranges = args.split()
1796 data = ''.join(self.extract_input_slices(ranges))
1801 data = ''.join(self.extract_input_slices(ranges))
1797 elif args.endswith('.py'):
1802 elif args.endswith('.py'):
1798 filename = make_filename(args)
1803 filename = make_filename(args)
1799 data = ''
1804 data = ''
1800 use_temp = 0
1805 use_temp = 0
1801 elif args:
1806 elif args:
1802 try:
1807 try:
1803 # Load the parameter given as a variable. If not a string,
1808 # Load the parameter given as a variable. If not a string,
1804 # process it as an object instead (below)
1809 # process it as an object instead (below)
1805
1810
1806 #print '*** args',args,'type',type(args) # dbg
1811 #print '*** args',args,'type',type(args) # dbg
1807 data = eval(args,self.shell.user_ns)
1812 data = eval(args,self.shell.user_ns)
1808 if not type(data) in StringTypes:
1813 if not type(data) in StringTypes:
1809 raise DataIsObject
1814 raise DataIsObject
1810 except (NameError,SyntaxError):
1815 except (NameError,SyntaxError):
1811 # given argument is not a variable, try as a filename
1816 # given argument is not a variable, try as a filename
1812 filename = make_filename(args)
1817 filename = make_filename(args)
1813 if filename is None:
1818 if filename is None:
1814 warn("Argument given (%s) can't be found as a variable "
1819 warn("Argument given (%s) can't be found as a variable "
1815 "or as a filename." % args)
1820 "or as a filename." % args)
1816 return
1821 return
1817 data = ''
1822 data = ''
1818 use_temp = 0
1823 use_temp = 0
1819 except DataIsObject:
1824 except DataIsObject:
1820 # For objects, try to edit the file where they are defined
1825 # For objects, try to edit the file where they are defined
1821 try:
1826 try:
1822 filename = inspect.getabsfile(data)
1827 filename = inspect.getabsfile(data)
1823 datafile = 1
1828 datafile = 1
1824 except TypeError:
1829 except TypeError:
1825 filename = make_filename(args)
1830 filename = make_filename(args)
1826 datafile = 1
1831 datafile = 1
1827 warn('Could not find file where `%s` is defined.\n'
1832 warn('Could not find file where `%s` is defined.\n'
1828 'Opening a file named `%s`' % (args,filename))
1833 'Opening a file named `%s`' % (args,filename))
1829 # Now, make sure we can actually read the source (if it was in
1834 # Now, make sure we can actually read the source (if it was in
1830 # a temp file it's gone by now).
1835 # a temp file it's gone by now).
1831 if datafile:
1836 if datafile:
1832 try:
1837 try:
1833 lineno = inspect.getsourcelines(data)[1]
1838 lineno = inspect.getsourcelines(data)[1]
1834 except IOError:
1839 except IOError:
1835 filename = make_filename(args)
1840 filename = make_filename(args)
1836 if filename is None:
1841 if filename is None:
1837 warn('The file `%s` where `%s` was defined cannot '
1842 warn('The file `%s` where `%s` was defined cannot '
1838 'be read.' % (filename,data))
1843 'be read.' % (filename,data))
1839 return
1844 return
1840 use_temp = 0
1845 use_temp = 0
1841 else:
1846 else:
1842 data = ''
1847 data = ''
1843
1848
1844 if use_temp:
1849 if use_temp:
1845 filename = tempfile.mktemp('.py')
1850 filename = tempfile.mktemp('.py')
1846 self.shell.tempfiles.append(filename)
1851 self.shell.tempfiles.append(filename)
1847
1852
1848 if data and use_temp:
1853 if data and use_temp:
1849 tmp_file = open(filename,'w')
1854 tmp_file = open(filename,'w')
1850 tmp_file.write(data)
1855 tmp_file.write(data)
1851 tmp_file.close()
1856 tmp_file.close()
1852
1857
1853 # do actual editing here
1858 # do actual editing here
1854 print 'Editing...',
1859 print 'Editing...',
1855 sys.stdout.flush()
1860 sys.stdout.flush()
1856 self.shell.hooks.editor(filename,lineno)
1861 self.shell.hooks.editor(filename,lineno)
1857 if opts.has_key('x'): # -x prevents actual execution
1862 if opts.has_key('x'): # -x prevents actual execution
1858 print
1863 print
1859 else:
1864 else:
1860 print 'done. Executing edited code...'
1865 print 'done. Executing edited code...'
1861 try:
1866 try:
1862 self.shell.safe_execfile(filename,self.shell.user_ns)
1867 self.shell.safe_execfile(filename,self.shell.user_ns)
1863 except IOError,msg:
1868 except IOError,msg:
1864 if msg.filename == filename:
1869 if msg.filename == filename:
1865 warn('File not found. Did you forget to save?')
1870 warn('File not found. Did you forget to save?')
1866 return
1871 return
1867 else:
1872 else:
1868 self.shell.showtraceback()
1873 self.shell.showtraceback()
1869 except:
1874 except:
1870 self.shell.showtraceback()
1875 self.shell.showtraceback()
1871 if use_temp:
1876 if use_temp:
1872 contents = open(filename).read()
1877 contents = open(filename).read()
1873 return contents
1878 return contents
1874
1879
1875 def magic_xmode(self,parameter_s = ''):
1880 def magic_xmode(self,parameter_s = ''):
1876 """Switch modes for the exception handlers.
1881 """Switch modes for the exception handlers.
1877
1882
1878 Valid modes: Plain, Context and Verbose.
1883 Valid modes: Plain, Context and Verbose.
1879
1884
1880 If called without arguments, acts as a toggle."""
1885 If called without arguments, acts as a toggle."""
1881
1886
1882 def xmode_switch_err(name):
1887 def xmode_switch_err(name):
1883 warn('Error changing %s exception modes.\n%s' %
1888 warn('Error changing %s exception modes.\n%s' %
1884 (name,sys.exc_info()[1]))
1889 (name,sys.exc_info()[1]))
1885
1890
1886 shell = self.shell
1891 shell = self.shell
1887 new_mode = parameter_s.strip().capitalize()
1892 new_mode = parameter_s.strip().capitalize()
1888 try:
1893 try:
1889 shell.InteractiveTB.set_mode(mode=new_mode)
1894 shell.InteractiveTB.set_mode(mode=new_mode)
1890 print 'Exception reporting mode:',shell.InteractiveTB.mode
1895 print 'Exception reporting mode:',shell.InteractiveTB.mode
1891 except:
1896 except:
1892 xmode_switch_err('user')
1897 xmode_switch_err('user')
1893
1898
1894 # threaded shells use a special handler in sys.excepthook
1899 # threaded shells use a special handler in sys.excepthook
1895 if shell.isthreaded:
1900 if shell.isthreaded:
1896 try:
1901 try:
1897 shell.sys_excepthook.set_mode(mode=new_mode)
1902 shell.sys_excepthook.set_mode(mode=new_mode)
1898 except:
1903 except:
1899 xmode_switch_err('threaded')
1904 xmode_switch_err('threaded')
1900
1905
1901 def magic_colors(self,parameter_s = ''):
1906 def magic_colors(self,parameter_s = ''):
1902 """Switch color scheme for prompts, info system and exception handlers.
1907 """Switch color scheme for prompts, info system and exception handlers.
1903
1908
1904 Currently implemented schemes: NoColor, Linux, LightBG.
1909 Currently implemented schemes: NoColor, Linux, LightBG.
1905
1910
1906 Color scheme names are not case-sensitive."""
1911 Color scheme names are not case-sensitive."""
1907
1912
1908 def color_switch_err(name):
1913 def color_switch_err(name):
1909 warn('Error changing %s color schemes.\n%s' %
1914 warn('Error changing %s color schemes.\n%s' %
1910 (name,sys.exc_info()[1]))
1915 (name,sys.exc_info()[1]))
1911
1916
1912
1917
1913 new_scheme = parameter_s.strip()
1918 new_scheme = parameter_s.strip()
1914 if not new_scheme:
1919 if not new_scheme:
1915 print 'You must specify a color scheme.'
1920 print 'You must specify a color scheme.'
1916 return
1921 return
1917 # Under Windows, check for Gary Bishop's readline, which is necessary
1922 # Under Windows, check for Gary Bishop's readline, which is necessary
1918 # for ANSI coloring
1923 # for ANSI coloring
1919 if os.name in ['nt','dos']:
1924 if os.name in ['nt','dos']:
1920 try:
1925 try:
1921 import readline
1926 import readline
1922 except ImportError:
1927 except ImportError:
1923 has_readline = 0
1928 has_readline = 0
1924 else:
1929 else:
1925 try:
1930 try:
1926 readline.GetOutputFile()
1931 readline.GetOutputFile()
1927 except AttributeError:
1932 except AttributeError:
1928 has_readline = 0
1933 has_readline = 0
1929 else:
1934 else:
1930 has_readline = 1
1935 has_readline = 1
1931 if not has_readline:
1936 if not has_readline:
1932 msg = """\
1937 msg = """\
1933 Proper color support under MS Windows requires Gary Bishop's readline library.
1938 Proper color support under MS Windows requires Gary Bishop's readline library.
1934 You can find it at:
1939 You can find it at:
1935 http://sourceforge.net/projects/uncpythontools
1940 http://sourceforge.net/projects/uncpythontools
1936 Gary's readline needs the ctypes module, from:
1941 Gary's readline needs the ctypes module, from:
1937 http://starship.python.net/crew/theller/ctypes
1942 http://starship.python.net/crew/theller/ctypes
1938
1943
1939 Defaulting color scheme to 'NoColor'"""
1944 Defaulting color scheme to 'NoColor'"""
1940 new_scheme = 'NoColor'
1945 new_scheme = 'NoColor'
1941 warn(msg)
1946 warn(msg)
1942 # local shortcut
1947 # local shortcut
1943 shell = self.shell
1948 shell = self.shell
1944
1949
1945 # Set prompt colors
1950 # Set prompt colors
1946 try:
1951 try:
1947 shell.outputcache.set_colors(new_scheme)
1952 shell.outputcache.set_colors(new_scheme)
1948 except:
1953 except:
1949 color_switch_err('prompt')
1954 color_switch_err('prompt')
1950 else:
1955 else:
1951 shell.rc.colors = \
1956 shell.rc.colors = \
1952 shell.outputcache.color_table.active_scheme_name
1957 shell.outputcache.color_table.active_scheme_name
1953 # Set exception colors
1958 # Set exception colors
1954 try:
1959 try:
1955 shell.InteractiveTB.set_colors(scheme = new_scheme)
1960 shell.InteractiveTB.set_colors(scheme = new_scheme)
1956 shell.SyntaxTB.set_colors(scheme = new_scheme)
1961 shell.SyntaxTB.set_colors(scheme = new_scheme)
1957 except:
1962 except:
1958 color_switch_err('exception')
1963 color_switch_err('exception')
1959
1964
1960 # threaded shells use a verbose traceback in sys.excepthook
1965 # threaded shells use a verbose traceback in sys.excepthook
1961 if shell.isthreaded:
1966 if shell.isthreaded:
1962 try:
1967 try:
1963 shell.sys_excepthook.set_colors(scheme=new_scheme)
1968 shell.sys_excepthook.set_colors(scheme=new_scheme)
1964 except:
1969 except:
1965 color_switch_err('system exception handler')
1970 color_switch_err('system exception handler')
1966
1971
1967 # Set info (for 'object?') colors
1972 # Set info (for 'object?') colors
1968 if shell.rc.color_info:
1973 if shell.rc.color_info:
1969 try:
1974 try:
1970 shell.inspector.set_active_scheme(new_scheme)
1975 shell.inspector.set_active_scheme(new_scheme)
1971 except:
1976 except:
1972 color_switch_err('object inspector')
1977 color_switch_err('object inspector')
1973 else:
1978 else:
1974 shell.inspector.set_active_scheme('NoColor')
1979 shell.inspector.set_active_scheme('NoColor')
1975
1980
1976 def magic_color_info(self,parameter_s = ''):
1981 def magic_color_info(self,parameter_s = ''):
1977 """Toggle color_info.
1982 """Toggle color_info.
1978
1983
1979 The color_info configuration parameter controls whether colors are
1984 The color_info configuration parameter controls whether colors are
1980 used for displaying object details (by things like %psource, %pfile or
1985 used for displaying object details (by things like %psource, %pfile or
1981 the '?' system). This function toggles this value with each call.
1986 the '?' system). This function toggles this value with each call.
1982
1987
1983 Note that unless you have a fairly recent pager (less works better
1988 Note that unless you have a fairly recent pager (less works better
1984 than more) in your system, using colored object information displays
1989 than more) in your system, using colored object information displays
1985 will not work properly. Test it and see."""
1990 will not work properly. Test it and see."""
1986
1991
1987 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1992 self.shell.rc.color_info = 1 - self.shell.rc.color_info
1988 self.magic_colors(self.shell.rc.colors)
1993 self.magic_colors(self.shell.rc.colors)
1989 print 'Object introspection functions have now coloring:',
1994 print 'Object introspection functions have now coloring:',
1990 print ['OFF','ON'][self.shell.rc.color_info]
1995 print ['OFF','ON'][self.shell.rc.color_info]
1991
1996
1992 def magic_Pprint(self, parameter_s=''):
1997 def magic_Pprint(self, parameter_s=''):
1993 """Toggle pretty printing on/off."""
1998 """Toggle pretty printing on/off."""
1994
1999
1995 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2000 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
1996 print 'Pretty printing has been turned', \
2001 print 'Pretty printing has been turned', \
1997 ['OFF','ON'][self.shell.outputcache.Pprint]
2002 ['OFF','ON'][self.shell.outputcache.Pprint]
1998
2003
1999 def magic_exit(self, parameter_s=''):
2004 def magic_exit(self, parameter_s=''):
2000 """Exit IPython, confirming if configured to do so.
2005 """Exit IPython, confirming if configured to do so.
2001
2006
2002 You can configure whether IPython asks for confirmation upon exit by
2007 You can configure whether IPython asks for confirmation upon exit by
2003 setting the confirm_exit flag in the ipythonrc file."""
2008 setting the confirm_exit flag in the ipythonrc file."""
2004
2009
2005 self.shell.exit()
2010 self.shell.exit()
2006
2011
2007 def magic_quit(self, parameter_s=''):
2012 def magic_quit(self, parameter_s=''):
2008 """Exit IPython, confirming if configured to do so (like %exit)"""
2013 """Exit IPython, confirming if configured to do so (like %exit)"""
2009
2014
2010 self.shell.exit()
2015 self.shell.exit()
2011
2016
2012 def magic_Exit(self, parameter_s=''):
2017 def magic_Exit(self, parameter_s=''):
2013 """Exit IPython without confirmation."""
2018 """Exit IPython without confirmation."""
2014
2019
2015 self.shell.exit_now = True
2020 self.shell.exit_now = True
2016
2021
2017 def magic_Quit(self, parameter_s=''):
2022 def magic_Quit(self, parameter_s=''):
2018 """Exit IPython without confirmation (like %Exit)."""
2023 """Exit IPython without confirmation (like %Exit)."""
2019
2024
2020 self.shell.exit_now = True
2025 self.shell.exit_now = True
2021
2026
2022 #......................................................................
2027 #......................................................................
2023 # Functions to implement unix shell-type things
2028 # Functions to implement unix shell-type things
2024
2029
2025 def magic_alias(self, parameter_s = ''):
2030 def magic_alias(self, parameter_s = ''):
2026 """Define an alias for a system command.
2031 """Define an alias for a system command.
2027
2032
2028 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2033 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2029
2034
2030 Then, typing 'alias_name params' will execute the system command 'cmd
2035 Then, typing 'alias_name params' will execute the system command 'cmd
2031 params' (from your underlying operating system).
2036 params' (from your underlying operating system).
2032
2037
2033 Aliases have lower precedence than magic functions and Python normal
2038 Aliases have lower precedence than magic functions and Python normal
2034 variables, so if 'foo' is both a Python variable and an alias, the
2039 variables, so if 'foo' is both a Python variable and an alias, the
2035 alias can not be executed until 'del foo' removes the Python variable.
2040 alias can not be executed until 'del foo' removes the Python variable.
2036
2041
2037 You can use the %l specifier in an alias definition to represent the
2042 You can use the %l specifier in an alias definition to represent the
2038 whole line when the alias is called. For example:
2043 whole line when the alias is called. For example:
2039
2044
2040 In [2]: alias all echo "Input in brackets: <%l>"\\
2045 In [2]: alias all echo "Input in brackets: <%l>"\\
2041 In [3]: all hello world\\
2046 In [3]: all hello world\\
2042 Input in brackets: <hello world>
2047 Input in brackets: <hello world>
2043
2048
2044 You can also define aliases with parameters using %s specifiers (one
2049 You can also define aliases with parameters using %s specifiers (one
2045 per parameter):
2050 per parameter):
2046
2051
2047 In [1]: alias parts echo first %s second %s\\
2052 In [1]: alias parts echo first %s second %s\\
2048 In [2]: %parts A B\\
2053 In [2]: %parts A B\\
2049 first A second B\\
2054 first A second B\\
2050 In [3]: %parts A\\
2055 In [3]: %parts A\\
2051 Incorrect number of arguments: 2 expected.\\
2056 Incorrect number of arguments: 2 expected.\\
2052 parts is an alias to: 'echo first %s second %s'
2057 parts is an alias to: 'echo first %s second %s'
2053
2058
2054 Note that %l and %s are mutually exclusive. You can only use one or
2059 Note that %l and %s are mutually exclusive. You can only use one or
2055 the other in your aliases.
2060 the other in your aliases.
2056
2061
2057 Aliases expand Python variables just like system calls using ! or !!
2062 Aliases expand Python variables just like system calls using ! or !!
2058 do: all expressions prefixed with '$' get expanded. For details of
2063 do: all expressions prefixed with '$' get expanded. For details of
2059 the semantic rules, see PEP-215:
2064 the semantic rules, see PEP-215:
2060 http://www.python.org/peps/pep-0215.html. This is the library used by
2065 http://www.python.org/peps/pep-0215.html. This is the library used by
2061 IPython for variable expansion. If you want to access a true shell
2066 IPython for variable expansion. If you want to access a true shell
2062 variable, an extra $ is necessary to prevent its expansion by IPython:
2067 variable, an extra $ is necessary to prevent its expansion by IPython:
2063
2068
2064 In [6]: alias show echo\\
2069 In [6]: alias show echo\\
2065 In [7]: PATH='A Python string'\\
2070 In [7]: PATH='A Python string'\\
2066 In [8]: show $PATH\\
2071 In [8]: show $PATH\\
2067 A Python string\\
2072 A Python string\\
2068 In [9]: show $$PATH\\
2073 In [9]: show $$PATH\\
2069 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2074 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2070
2075
2071 You can use the alias facility to acess all of $PATH. See the %rehash
2076 You can use the alias facility to acess all of $PATH. See the %rehash
2072 and %rehashx functions, which automatically create aliases for the
2077 and %rehashx functions, which automatically create aliases for the
2073 contents of your $PATH.
2078 contents of your $PATH.
2074
2079
2075 If called with no parameters, %alias prints the current alias table."""
2080 If called with no parameters, %alias prints the current alias table."""
2076
2081
2077 par = parameter_s.strip()
2082 par = parameter_s.strip()
2078 if not par:
2083 if not par:
2079 if self.shell.rc.automagic:
2084 if self.shell.rc.automagic:
2080 prechar = ''
2085 prechar = ''
2081 else:
2086 else:
2082 prechar = self.shell.ESC_MAGIC
2087 prechar = self.shell.ESC_MAGIC
2083 print 'Alias\t\tSystem Command\n'+'-'*30
2088 print 'Alias\t\tSystem Command\n'+'-'*30
2084 atab = self.shell.alias_table
2089 atab = self.shell.alias_table
2085 aliases = atab.keys()
2090 aliases = atab.keys()
2086 aliases.sort()
2091 aliases.sort()
2087 for alias in aliases:
2092 for alias in aliases:
2088 print prechar+alias+'\t\t'+atab[alias][1]
2093 print prechar+alias+'\t\t'+atab[alias][1]
2089 print '-'*30+'\nTotal number of aliases:',len(aliases)
2094 print '-'*30+'\nTotal number of aliases:',len(aliases)
2090 return
2095 return
2091 try:
2096 try:
2092 alias,cmd = par.split(None,1)
2097 alias,cmd = par.split(None,1)
2093 except:
2098 except:
2094 print OInspect.getdoc(self.magic_alias)
2099 print OInspect.getdoc(self.magic_alias)
2095 else:
2100 else:
2096 nargs = cmd.count('%s')
2101 nargs = cmd.count('%s')
2097 if nargs>0 and cmd.find('%l')>=0:
2102 if nargs>0 and cmd.find('%l')>=0:
2098 error('The %s and %l specifiers are mutually exclusive '
2103 error('The %s and %l specifiers are mutually exclusive '
2099 'in alias definitions.')
2104 'in alias definitions.')
2100 else: # all looks OK
2105 else: # all looks OK
2101 self.shell.alias_table[alias] = (nargs,cmd)
2106 self.shell.alias_table[alias] = (nargs,cmd)
2102 self.shell.alias_table_validate(verbose=1)
2107 self.shell.alias_table_validate(verbose=1)
2103 # end magic_alias
2108 # end magic_alias
2104
2109
2105 def magic_unalias(self, parameter_s = ''):
2110 def magic_unalias(self, parameter_s = ''):
2106 """Remove an alias"""
2111 """Remove an alias"""
2107
2112
2108 aname = parameter_s.strip()
2113 aname = parameter_s.strip()
2109 if aname in self.shell.alias_table:
2114 if aname in self.shell.alias_table:
2110 del self.shell.alias_table[aname]
2115 del self.shell.alias_table[aname]
2111
2116
2112 def magic_rehash(self, parameter_s = ''):
2117 def magic_rehash(self, parameter_s = ''):
2113 """Update the alias table with all entries in $PATH.
2118 """Update the alias table with all entries in $PATH.
2114
2119
2115 This version does no checks on execute permissions or whether the
2120 This version does no checks on execute permissions or whether the
2116 contents of $PATH are truly files (instead of directories or something
2121 contents of $PATH are truly files (instead of directories or something
2117 else). For such a safer (but slower) version, use %rehashx."""
2122 else). For such a safer (but slower) version, use %rehashx."""
2118
2123
2119 # This function (and rehashx) manipulate the alias_table directly
2124 # This function (and rehashx) manipulate the alias_table directly
2120 # rather than calling magic_alias, for speed reasons. A rehash on a
2125 # rather than calling magic_alias, for speed reasons. A rehash on a
2121 # typical Linux box involves several thousand entries, so efficiency
2126 # typical Linux box involves several thousand entries, so efficiency
2122 # here is a top concern.
2127 # here is a top concern.
2123
2128
2124 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2129 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2125 alias_table = self.shell.alias_table
2130 alias_table = self.shell.alias_table
2126 for pdir in path:
2131 for pdir in path:
2127 for ff in os.listdir(pdir):
2132 for ff in os.listdir(pdir):
2128 # each entry in the alias table must be (N,name), where
2133 # each entry in the alias table must be (N,name), where
2129 # N is the number of positional arguments of the alias.
2134 # N is the number of positional arguments of the alias.
2130 alias_table[ff] = (0,ff)
2135 alias_table[ff] = (0,ff)
2131 # Make sure the alias table doesn't contain keywords or builtins
2136 # Make sure the alias table doesn't contain keywords or builtins
2132 self.shell.alias_table_validate()
2137 self.shell.alias_table_validate()
2133 # Call again init_auto_alias() so we get 'rm -i' and other modified
2138 # Call again init_auto_alias() so we get 'rm -i' and other modified
2134 # aliases since %rehash will probably clobber them
2139 # aliases since %rehash will probably clobber them
2135 self.shell.init_auto_alias()
2140 self.shell.init_auto_alias()
2136
2141
2137 def magic_rehashx(self, parameter_s = ''):
2142 def magic_rehashx(self, parameter_s = ''):
2138 """Update the alias table with all executable files in $PATH.
2143 """Update the alias table with all executable files in $PATH.
2139
2144
2140 This version explicitly checks that every entry in $PATH is a file
2145 This version explicitly checks that every entry in $PATH is a file
2141 with execute access (os.X_OK), so it is much slower than %rehash.
2146 with execute access (os.X_OK), so it is much slower than %rehash.
2142
2147
2143 Under Windows, it checks executability as a match agains a
2148 Under Windows, it checks executability as a match agains a
2144 '|'-separated string of extensions, stored in the IPython config
2149 '|'-separated string of extensions, stored in the IPython config
2145 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2150 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2146
2151
2147 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2152 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2148 alias_table = self.shell.alias_table
2153 alias_table = self.shell.alias_table
2149
2154
2150 if os.name == 'posix':
2155 if os.name == 'posix':
2151 isexec = lambda fname:os.path.isfile(fname) and \
2156 isexec = lambda fname:os.path.isfile(fname) and \
2152 os.access(fname,os.X_OK)
2157 os.access(fname,os.X_OK)
2153 else:
2158 else:
2154
2159
2155 try:
2160 try:
2156 winext = os.environ['pathext'].replace(';','|').replace('.','')
2161 winext = os.environ['pathext'].replace(';','|').replace('.','')
2157 except KeyError:
2162 except KeyError:
2158 winext = 'exe|com|bat'
2163 winext = 'exe|com|bat'
2159
2164
2160 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2165 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2161 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2166 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2162 savedir = os.getcwd()
2167 savedir = os.getcwd()
2163 try:
2168 try:
2164 # write the whole loop for posix/Windows so we don't have an if in
2169 # write the whole loop for posix/Windows so we don't have an if in
2165 # the innermost part
2170 # the innermost part
2166 if os.name == 'posix':
2171 if os.name == 'posix':
2167 for pdir in path:
2172 for pdir in path:
2168 os.chdir(pdir)
2173 os.chdir(pdir)
2169 for ff in os.listdir(pdir):
2174 for ff in os.listdir(pdir):
2170 if isexec(ff):
2175 if isexec(ff):
2171 # each entry in the alias table must be (N,name),
2176 # each entry in the alias table must be (N,name),
2172 # where N is the number of positional arguments of the
2177 # where N is the number of positional arguments of the
2173 # alias.
2178 # alias.
2174 alias_table[ff] = (0,ff)
2179 alias_table[ff] = (0,ff)
2175 else:
2180 else:
2176 for pdir in path:
2181 for pdir in path:
2177 os.chdir(pdir)
2182 os.chdir(pdir)
2178 for ff in os.listdir(pdir):
2183 for ff in os.listdir(pdir):
2179 if isexec(ff):
2184 if isexec(ff):
2180 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2185 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2181 # Make sure the alias table doesn't contain keywords or builtins
2186 # Make sure the alias table doesn't contain keywords or builtins
2182 self.shell.alias_table_validate()
2187 self.shell.alias_table_validate()
2183 # Call again init_auto_alias() so we get 'rm -i' and other
2188 # Call again init_auto_alias() so we get 'rm -i' and other
2184 # modified aliases since %rehashx will probably clobber them
2189 # modified aliases since %rehashx will probably clobber them
2185 self.shell.init_auto_alias()
2190 self.shell.init_auto_alias()
2186 finally:
2191 finally:
2187 os.chdir(savedir)
2192 os.chdir(savedir)
2188
2193
2189 def magic_pwd(self, parameter_s = ''):
2194 def magic_pwd(self, parameter_s = ''):
2190 """Return the current working directory path."""
2195 """Return the current working directory path."""
2191 return os.getcwd()
2196 return os.getcwd()
2192
2197
2193 def magic_cd(self, parameter_s=''):
2198 def magic_cd(self, parameter_s=''):
2194 """Change the current working directory.
2199 """Change the current working directory.
2195
2200
2196 This command automatically maintains an internal list of directories
2201 This command automatically maintains an internal list of directories
2197 you visit during your IPython session, in the variable _dh. The
2202 you visit during your IPython session, in the variable _dh. The
2198 command %dhist shows this history nicely formatted.
2203 command %dhist shows this history nicely formatted.
2199
2204
2200 Usage:
2205 Usage:
2201
2206
2202 cd 'dir': changes to directory 'dir'.
2207 cd 'dir': changes to directory 'dir'.
2203
2208
2204 cd -: changes to the last visited directory.
2209 cd -: changes to the last visited directory.
2205
2210
2206 cd -<n>: changes to the n-th directory in the directory history.
2211 cd -<n>: changes to the n-th directory in the directory history.
2207
2212
2208 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2213 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2209 (note: cd <bookmark_name> is enough if there is no
2214 (note: cd <bookmark_name> is enough if there is no
2210 directory <bookmark_name>, but a bookmark with the name exists.)
2215 directory <bookmark_name>, but a bookmark with the name exists.)
2211
2216
2212 Options:
2217 Options:
2213
2218
2214 -q: quiet. Do not print the working directory after the cd command is
2219 -q: quiet. Do not print the working directory after the cd command is
2215 executed. By default IPython's cd command does print this directory,
2220 executed. By default IPython's cd command does print this directory,
2216 since the default prompts do not display path information.
2221 since the default prompts do not display path information.
2217
2222
2218 Note that !cd doesn't work for this purpose because the shell where
2223 Note that !cd doesn't work for this purpose because the shell where
2219 !command runs is immediately discarded after executing 'command'."""
2224 !command runs is immediately discarded after executing 'command'."""
2220
2225
2221 parameter_s = parameter_s.strip()
2226 parameter_s = parameter_s.strip()
2222 bkms = self.shell.persist.get("bookmarks",{})
2227 bkms = self.shell.persist.get("bookmarks",{})
2223
2228
2224 numcd = re.match(r'(-)(\d+)$',parameter_s)
2229 numcd = re.match(r'(-)(\d+)$',parameter_s)
2225 # jump in directory history by number
2230 # jump in directory history by number
2226 if numcd:
2231 if numcd:
2227 nn = int(numcd.group(2))
2232 nn = int(numcd.group(2))
2228 try:
2233 try:
2229 ps = self.shell.user_ns['_dh'][nn]
2234 ps = self.shell.user_ns['_dh'][nn]
2230 except IndexError:
2235 except IndexError:
2231 print 'The requested directory does not exist in history.'
2236 print 'The requested directory does not exist in history.'
2232 return
2237 return
2233 else:
2238 else:
2234 opts = {}
2239 opts = {}
2235 else:
2240 else:
2236 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2241 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2237 # jump to previous
2242 # jump to previous
2238 if ps == '-':
2243 if ps == '-':
2239 try:
2244 try:
2240 ps = self.shell.user_ns['_dh'][-2]
2245 ps = self.shell.user_ns['_dh'][-2]
2241 except IndexError:
2246 except IndexError:
2242 print 'No previous directory to change to.'
2247 print 'No previous directory to change to.'
2243 return
2248 return
2244 # jump to bookmark
2249 # jump to bookmark
2245 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2250 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2246 if bkms.has_key(ps):
2251 if bkms.has_key(ps):
2247 target = bkms[ps]
2252 target = bkms[ps]
2248 print '(bookmark:%s) -> %s' % (ps,target)
2253 print '(bookmark:%s) -> %s' % (ps,target)
2249 ps = target
2254 ps = target
2250 else:
2255 else:
2251 if bkms:
2256 if bkms:
2252 error("Bookmark '%s' not found. "
2257 error("Bookmark '%s' not found. "
2253 "Use '%bookmark -l' to see your bookmarks." % ps)
2258 "Use '%bookmark -l' to see your bookmarks." % ps)
2254 else:
2259 else:
2255 print "Bookmarks not set - use %bookmark <bookmarkname>"
2260 print "Bookmarks not set - use %bookmark <bookmarkname>"
2256 return
2261 return
2257
2262
2258 # at this point ps should point to the target dir
2263 # at this point ps should point to the target dir
2259 if ps:
2264 if ps:
2260 try:
2265 try:
2261 os.chdir(os.path.expanduser(ps))
2266 os.chdir(os.path.expanduser(ps))
2262 except OSError:
2267 except OSError:
2263 print sys.exc_info()[1]
2268 print sys.exc_info()[1]
2264 else:
2269 else:
2265 self.shell.user_ns['_dh'].append(os.getcwd())
2270 self.shell.user_ns['_dh'].append(os.getcwd())
2266 else:
2271 else:
2267 os.chdir(self.shell.home_dir)
2272 os.chdir(self.shell.home_dir)
2268 self.shell.user_ns['_dh'].append(os.getcwd())
2273 self.shell.user_ns['_dh'].append(os.getcwd())
2269 if not 'q' in opts:
2274 if not 'q' in opts:
2270 print self.shell.user_ns['_dh'][-1]
2275 print self.shell.user_ns['_dh'][-1]
2271
2276
2272 def magic_dhist(self, parameter_s=''):
2277 def magic_dhist(self, parameter_s=''):
2273 """Print your history of visited directories.
2278 """Print your history of visited directories.
2274
2279
2275 %dhist -> print full history\\
2280 %dhist -> print full history\\
2276 %dhist n -> print last n entries only\\
2281 %dhist n -> print last n entries only\\
2277 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2282 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2278
2283
2279 This history is automatically maintained by the %cd command, and
2284 This history is automatically maintained by the %cd command, and
2280 always available as the global list variable _dh. You can use %cd -<n>
2285 always available as the global list variable _dh. You can use %cd -<n>
2281 to go to directory number <n>."""
2286 to go to directory number <n>."""
2282
2287
2283 dh = self.shell.user_ns['_dh']
2288 dh = self.shell.user_ns['_dh']
2284 if parameter_s:
2289 if parameter_s:
2285 try:
2290 try:
2286 args = map(int,parameter_s.split())
2291 args = map(int,parameter_s.split())
2287 except:
2292 except:
2288 self.arg_err(Magic.magic_dhist)
2293 self.arg_err(Magic.magic_dhist)
2289 return
2294 return
2290 if len(args) == 1:
2295 if len(args) == 1:
2291 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2296 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2292 elif len(args) == 2:
2297 elif len(args) == 2:
2293 ini,fin = args
2298 ini,fin = args
2294 else:
2299 else:
2295 self.arg_err(Magic.magic_dhist)
2300 self.arg_err(Magic.magic_dhist)
2296 return
2301 return
2297 else:
2302 else:
2298 ini,fin = 0,len(dh)
2303 ini,fin = 0,len(dh)
2299 nlprint(dh,
2304 nlprint(dh,
2300 header = 'Directory history (kept in _dh)',
2305 header = 'Directory history (kept in _dh)',
2301 start=ini,stop=fin)
2306 start=ini,stop=fin)
2302
2307
2303 def magic_env(self, parameter_s=''):
2308 def magic_env(self, parameter_s=''):
2304 """List environment variables."""
2309 """List environment variables."""
2305
2310
2306 return os.environ.data
2311 return os.environ.data
2307
2312
2308 def magic_pushd(self, parameter_s=''):
2313 def magic_pushd(self, parameter_s=''):
2309 """Place the current dir on stack and change directory.
2314 """Place the current dir on stack and change directory.
2310
2315
2311 Usage:\\
2316 Usage:\\
2312 %pushd ['dirname']
2317 %pushd ['dirname']
2313
2318
2314 %pushd with no arguments does a %pushd to your home directory.
2319 %pushd with no arguments does a %pushd to your home directory.
2315 """
2320 """
2316 if parameter_s == '': parameter_s = '~'
2321 if parameter_s == '': parameter_s = '~'
2317 dir_s = self.shell.dir_stack
2322 dir_s = self.shell.dir_stack
2318 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2323 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2319 os.path.expanduser(self.shell.dir_stack[0]):
2324 os.path.expanduser(self.shell.dir_stack[0]):
2320 try:
2325 try:
2321 self.magic_cd(parameter_s)
2326 self.magic_cd(parameter_s)
2322 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2327 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2323 self.magic_dirs()
2328 self.magic_dirs()
2324 except:
2329 except:
2325 print 'Invalid directory'
2330 print 'Invalid directory'
2326 else:
2331 else:
2327 print 'You are already there!'
2332 print 'You are already there!'
2328
2333
2329 def magic_popd(self, parameter_s=''):
2334 def magic_popd(self, parameter_s=''):
2330 """Change to directory popped off the top of the stack.
2335 """Change to directory popped off the top of the stack.
2331 """
2336 """
2332 if len (self.shell.dir_stack) > 1:
2337 if len (self.shell.dir_stack) > 1:
2333 self.shell.dir_stack.pop(0)
2338 self.shell.dir_stack.pop(0)
2334 self.magic_cd(self.shell.dir_stack[0])
2339 self.magic_cd(self.shell.dir_stack[0])
2335 print self.shell.dir_stack[0]
2340 print self.shell.dir_stack[0]
2336 else:
2341 else:
2337 print "You can't remove the starting directory from the stack:",\
2342 print "You can't remove the starting directory from the stack:",\
2338 self.shell.dir_stack
2343 self.shell.dir_stack
2339
2344
2340 def magic_dirs(self, parameter_s=''):
2345 def magic_dirs(self, parameter_s=''):
2341 """Return the current directory stack."""
2346 """Return the current directory stack."""
2342
2347
2343 return self.shell.dir_stack[:]
2348 return self.shell.dir_stack[:]
2344
2349
2345 def magic_sc(self, parameter_s=''):
2350 def magic_sc(self, parameter_s=''):
2346 """Shell capture - execute a shell command and capture its output.
2351 """Shell capture - execute a shell command and capture its output.
2347
2352
2348 %sc [options] varname=command
2353 %sc [options] varname=command
2349
2354
2350 IPython will run the given command using commands.getoutput(), and
2355 IPython will run the given command using commands.getoutput(), and
2351 will then update the user's interactive namespace with a variable
2356 will then update the user's interactive namespace with a variable
2352 called varname, containing the value of the call. Your command can
2357 called varname, containing the value of the call. Your command can
2353 contain shell wildcards, pipes, etc.
2358 contain shell wildcards, pipes, etc.
2354
2359
2355 The '=' sign in the syntax is mandatory, and the variable name you
2360 The '=' sign in the syntax is mandatory, and the variable name you
2356 supply must follow Python's standard conventions for valid names.
2361 supply must follow Python's standard conventions for valid names.
2357
2362
2358 Options:
2363 Options:
2359
2364
2360 -l: list output. Split the output on newlines into a list before
2365 -l: list output. Split the output on newlines into a list before
2361 assigning it to the given variable. By default the output is stored
2366 assigning it to the given variable. By default the output is stored
2362 as a single string.
2367 as a single string.
2363
2368
2364 -v: verbose. Print the contents of the variable.
2369 -v: verbose. Print the contents of the variable.
2365
2370
2366 In most cases you should not need to split as a list, because the
2371 In most cases you should not need to split as a list, because the
2367 returned value is a special type of string which can automatically
2372 returned value is a special type of string which can automatically
2368 provide its contents either as a list (split on newlines) or as a
2373 provide its contents either as a list (split on newlines) or as a
2369 space-separated string. These are convenient, respectively, either
2374 space-separated string. These are convenient, respectively, either
2370 for sequential processing or to be passed to a shell command.
2375 for sequential processing or to be passed to a shell command.
2371
2376
2372 For example:
2377 For example:
2373
2378
2374 # Capture into variable a
2379 # Capture into variable a
2375 In [9]: sc a=ls *py
2380 In [9]: sc a=ls *py
2376
2381
2377 # a is a string with embedded newlines
2382 # a is a string with embedded newlines
2378 In [10]: a
2383 In [10]: a
2379 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2384 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2380
2385
2381 # which can be seen as a list:
2386 # which can be seen as a list:
2382 In [11]: a.l
2387 In [11]: a.l
2383 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2388 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2384
2389
2385 # or as a whitespace-separated string:
2390 # or as a whitespace-separated string:
2386 In [12]: a.s
2391 In [12]: a.s
2387 Out[12]: 'setup.py win32_manual_post_install.py'
2392 Out[12]: 'setup.py win32_manual_post_install.py'
2388
2393
2389 # a.s is useful to pass as a single command line:
2394 # a.s is useful to pass as a single command line:
2390 In [13]: !wc -l $a.s
2395 In [13]: !wc -l $a.s
2391 146 setup.py
2396 146 setup.py
2392 130 win32_manual_post_install.py
2397 130 win32_manual_post_install.py
2393 276 total
2398 276 total
2394
2399
2395 # while the list form is useful to loop over:
2400 # while the list form is useful to loop over:
2396 In [14]: for f in a.l:
2401 In [14]: for f in a.l:
2397 ....: !wc -l $f
2402 ....: !wc -l $f
2398 ....:
2403 ....:
2399 146 setup.py
2404 146 setup.py
2400 130 win32_manual_post_install.py
2405 130 win32_manual_post_install.py
2401
2406
2402 Similiarly, the lists returned by the -l option are also special, in
2407 Similiarly, the lists returned by the -l option are also special, in
2403 the sense that you can equally invoke the .s attribute on them to
2408 the sense that you can equally invoke the .s attribute on them to
2404 automatically get a whitespace-separated string from their contents:
2409 automatically get a whitespace-separated string from their contents:
2405
2410
2406 In [1]: sc -l b=ls *py
2411 In [1]: sc -l b=ls *py
2407
2412
2408 In [2]: b
2413 In [2]: b
2409 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2414 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2410
2415
2411 In [3]: b.s
2416 In [3]: b.s
2412 Out[3]: 'setup.py win32_manual_post_install.py'
2417 Out[3]: 'setup.py win32_manual_post_install.py'
2413
2418
2414 In summary, both the lists and strings used for ouptut capture have
2419 In summary, both the lists and strings used for ouptut capture have
2415 the following special attributes:
2420 the following special attributes:
2416
2421
2417 .l (or .list) : value as list.
2422 .l (or .list) : value as list.
2418 .n (or .nlstr): value as newline-separated string.
2423 .n (or .nlstr): value as newline-separated string.
2419 .s (or .spstr): value as space-separated string.
2424 .s (or .spstr): value as space-separated string.
2420 """
2425 """
2421
2426
2422 opts,args = self.parse_options(parameter_s,'lv')
2427 opts,args = self.parse_options(parameter_s,'lv')
2423 # Try to get a variable name and command to run
2428 # Try to get a variable name and command to run
2424 try:
2429 try:
2425 # the variable name must be obtained from the parse_options
2430 # the variable name must be obtained from the parse_options
2426 # output, which uses shlex.split to strip options out.
2431 # output, which uses shlex.split to strip options out.
2427 var,_ = args.split('=',1)
2432 var,_ = args.split('=',1)
2428 var = var.strip()
2433 var = var.strip()
2429 # But the the command has to be extracted from the original input
2434 # But the the command has to be extracted from the original input
2430 # parameter_s, not on what parse_options returns, to avoid the
2435 # parameter_s, not on what parse_options returns, to avoid the
2431 # quote stripping which shlex.split performs on it.
2436 # quote stripping which shlex.split performs on it.
2432 _,cmd = parameter_s.split('=',1)
2437 _,cmd = parameter_s.split('=',1)
2433 except ValueError:
2438 except ValueError:
2434 var,cmd = '',''
2439 var,cmd = '',''
2435 if not var:
2440 if not var:
2436 error('you must specify a variable to assign the command to.')
2441 error('you must specify a variable to assign the command to.')
2437 return
2442 return
2438 # If all looks ok, proceed
2443 # If all looks ok, proceed
2439 out,err = self.shell.getoutputerror(cmd)
2444 out,err = self.shell.getoutputerror(cmd)
2440 if err:
2445 if err:
2441 print >> Term.cerr,err
2446 print >> Term.cerr,err
2442 if opts.has_key('l'):
2447 if opts.has_key('l'):
2443 out = SList(out.split('\n'))
2448 out = SList(out.split('\n'))
2444 else:
2449 else:
2445 out = LSString(out)
2450 out = LSString(out)
2446 if opts.has_key('v'):
2451 if opts.has_key('v'):
2447 print '%s ==\n%s' % (var,pformat(out))
2452 print '%s ==\n%s' % (var,pformat(out))
2448 self.shell.user_ns.update({var:out})
2453 self.shell.user_ns.update({var:out})
2449
2454
2450 def magic_sx(self, parameter_s=''):
2455 def magic_sx(self, parameter_s=''):
2451 """Shell execute - run a shell command and capture its output.
2456 """Shell execute - run a shell command and capture its output.
2452
2457
2453 %sx command
2458 %sx command
2454
2459
2455 IPython will run the given command using commands.getoutput(), and
2460 IPython will run the given command using commands.getoutput(), and
2456 return the result formatted as a list (split on '\\n'). Since the
2461 return the result formatted as a list (split on '\\n'). Since the
2457 output is _returned_, it will be stored in ipython's regular output
2462 output is _returned_, it will be stored in ipython's regular output
2458 cache Out[N] and in the '_N' automatic variables.
2463 cache Out[N] and in the '_N' automatic variables.
2459
2464
2460 Notes:
2465 Notes:
2461
2466
2462 1) If an input line begins with '!!', then %sx is automatically
2467 1) If an input line begins with '!!', then %sx is automatically
2463 invoked. That is, while:
2468 invoked. That is, while:
2464 !ls
2469 !ls
2465 causes ipython to simply issue system('ls'), typing
2470 causes ipython to simply issue system('ls'), typing
2466 !!ls
2471 !!ls
2467 is a shorthand equivalent to:
2472 is a shorthand equivalent to:
2468 %sx ls
2473 %sx ls
2469
2474
2470 2) %sx differs from %sc in that %sx automatically splits into a list,
2475 2) %sx differs from %sc in that %sx automatically splits into a list,
2471 like '%sc -l'. The reason for this is to make it as easy as possible
2476 like '%sc -l'. The reason for this is to make it as easy as possible
2472 to process line-oriented shell output via further python commands.
2477 to process line-oriented shell output via further python commands.
2473 %sc is meant to provide much finer control, but requires more
2478 %sc is meant to provide much finer control, but requires more
2474 typing.
2479 typing.
2475
2480
2476 3) Just like %sc -l, this is a list with special attributes:
2481 3) Just like %sc -l, this is a list with special attributes:
2477
2482
2478 .l (or .list) : value as list.
2483 .l (or .list) : value as list.
2479 .n (or .nlstr): value as newline-separated string.
2484 .n (or .nlstr): value as newline-separated string.
2480 .s (or .spstr): value as whitespace-separated string.
2485 .s (or .spstr): value as whitespace-separated string.
2481
2486
2482 This is very useful when trying to use such lists as arguments to
2487 This is very useful when trying to use such lists as arguments to
2483 system commands."""
2488 system commands."""
2484
2489
2485 if parameter_s:
2490 if parameter_s:
2486 out,err = self.shell.getoutputerror(parameter_s)
2491 out,err = self.shell.getoutputerror(parameter_s)
2487 if err:
2492 if err:
2488 print >> Term.cerr,err
2493 print >> Term.cerr,err
2489 return SList(out.split('\n'))
2494 return SList(out.split('\n'))
2490
2495
2491 def magic_bg(self, parameter_s=''):
2496 def magic_bg(self, parameter_s=''):
2492 """Run a job in the background, in a separate thread.
2497 """Run a job in the background, in a separate thread.
2493
2498
2494 For example,
2499 For example,
2495
2500
2496 %bg myfunc(x,y,z=1)
2501 %bg myfunc(x,y,z=1)
2497
2502
2498 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2503 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2499 execution starts, a message will be printed indicating the job
2504 execution starts, a message will be printed indicating the job
2500 number. If your job number is 5, you can use
2505 number. If your job number is 5, you can use
2501
2506
2502 myvar = jobs.result(5) or myvar = jobs[5].result
2507 myvar = jobs.result(5) or myvar = jobs[5].result
2503
2508
2504 to assign this result to variable 'myvar'.
2509 to assign this result to variable 'myvar'.
2505
2510
2506 IPython has a job manager, accessible via the 'jobs' object. You can
2511 IPython has a job manager, accessible via the 'jobs' object. You can
2507 type jobs? to get more information about it, and use jobs.<TAB> to see
2512 type jobs? to get more information about it, and use jobs.<TAB> to see
2508 its attributes. All attributes not starting with an underscore are
2513 its attributes. All attributes not starting with an underscore are
2509 meant for public use.
2514 meant for public use.
2510
2515
2511 In particular, look at the jobs.new() method, which is used to create
2516 In particular, look at the jobs.new() method, which is used to create
2512 new jobs. This magic %bg function is just a convenience wrapper
2517 new jobs. This magic %bg function is just a convenience wrapper
2513 around jobs.new(), for expression-based jobs. If you want to create a
2518 around jobs.new(), for expression-based jobs. If you want to create a
2514 new job with an explicit function object and arguments, you must call
2519 new job with an explicit function object and arguments, you must call
2515 jobs.new() directly.
2520 jobs.new() directly.
2516
2521
2517 The jobs.new docstring also describes in detail several important
2522 The jobs.new docstring also describes in detail several important
2518 caveats associated with a thread-based model for background job
2523 caveats associated with a thread-based model for background job
2519 execution. Type jobs.new? for details.
2524 execution. Type jobs.new? for details.
2520
2525
2521 You can check the status of all jobs with jobs.status().
2526 You can check the status of all jobs with jobs.status().
2522
2527
2523 The jobs variable is set by IPython into the Python builtin namespace.
2528 The jobs variable is set by IPython into the Python builtin namespace.
2524 If you ever declare a variable named 'jobs', you will shadow this
2529 If you ever declare a variable named 'jobs', you will shadow this
2525 name. You can either delete your global jobs variable to regain
2530 name. You can either delete your global jobs variable to regain
2526 access to the job manager, or make a new name and assign it manually
2531 access to the job manager, or make a new name and assign it manually
2527 to the manager (stored in IPython's namespace). For example, to
2532 to the manager (stored in IPython's namespace). For example, to
2528 assign the job manager to the Jobs name, use:
2533 assign the job manager to the Jobs name, use:
2529
2534
2530 Jobs = __builtins__.jobs"""
2535 Jobs = __builtins__.jobs"""
2531
2536
2532 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2537 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2533
2538
2534 def magic_store(self, parameter_s=''):
2539 def magic_store(self, parameter_s=''):
2535 """Lightweight persistence for python variables.
2540 """Lightweight persistence for python variables.
2536
2541
2537 Example:
2542 Example:
2538
2543
2539 ville@badger[~]|1> A = ['hello',10,'world']\\
2544 ville@badger[~]|1> A = ['hello',10,'world']\\
2540 ville@badger[~]|2> %store A\\
2545 ville@badger[~]|2> %store A\\
2541 ville@badger[~]|3> Exit
2546 ville@badger[~]|3> Exit
2542
2547
2543 (IPython session is closed and started again...)
2548 (IPython session is closed and started again...)
2544
2549
2545 ville@badger:~$ ipython -p pysh\\
2550 ville@badger:~$ ipython -p pysh\\
2546 ville@badger[~]|1> print A
2551 ville@badger[~]|1> print A
2547
2552
2548 ['hello', 10, 'world']
2553 ['hello', 10, 'world']
2549
2554
2550 Usage:
2555 Usage:
2551
2556
2552 %store - Show list of all variables and their current values\\
2557 %store - Show list of all variables and their current values\\
2553 %store <var> - Store the *current* value of the variable to disk\\
2558 %store <var> - Store the *current* value of the variable to disk\\
2554 %store -d - Remove the variable and its value from storage\\
2559 %store -d - Remove the variable and its value from storage\\
2555 %store -r - Remove all variables from storage
2560 %store -r - Remove all variables from storage
2556
2561
2557 It should be noted that if you change the value of a variable, you
2562 It should be noted that if you change the value of a variable, you
2558 need to %store it again if you want to persist the new value.
2563 need to %store it again if you want to persist the new value.
2559
2564
2560 Note also that the variables will need to be pickleable; most basic
2565 Note also that the variables will need to be pickleable; most basic
2561 python types can be safely %stored.
2566 python types can be safely %stored.
2562 """
2567 """
2563
2568
2564 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2569 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2565 # delete
2570 # delete
2566 if opts.has_key('d'):
2571 if opts.has_key('d'):
2567 try:
2572 try:
2568 todel = args[0]
2573 todel = args[0]
2569 except IndexError:
2574 except IndexError:
2570 error('You must provide the variable to forget')
2575 error('You must provide the variable to forget')
2571 else:
2576 else:
2572 try:
2577 try:
2573 del self.shell.persist['S:' + todel]
2578 del self.shell.persist['S:' + todel]
2574 except:
2579 except:
2575 error("Can't delete variable '%s'" % todel)
2580 error("Can't delete variable '%s'" % todel)
2576 # reset
2581 # reset
2577 elif opts.has_key('r'):
2582 elif opts.has_key('r'):
2578 for k in self.shell.persist.keys():
2583 for k in self.shell.persist.keys():
2579 if k.startswith('S:'):
2584 if k.startswith('S:'):
2580 del self.shell.persist[k]
2585 del self.shell.persist[k]
2581
2586
2582 # run without arguments -> list variables & values
2587 # run without arguments -> list variables & values
2583 elif not args:
2588 elif not args:
2584 vars = [v[2:] for v in self.shell.persist.keys()
2589 vars = [v[2:] for v in self.shell.persist.keys()
2585 if v.startswith('S:')]
2590 if v.startswith('S:')]
2586 vars.sort()
2591 vars.sort()
2587 if vars:
2592 if vars:
2588 size = max(map(len,vars))
2593 size = max(map(len,vars))
2589 else:
2594 else:
2590 size = 0
2595 size = 0
2591
2596
2592 print 'Stored variables and their in-memory values:'
2597 print 'Stored variables and their in-memory values:'
2593 fmt = '%-'+str(size)+'s -> %s'
2598 fmt = '%-'+str(size)+'s -> %s'
2594 get = self.shell.user_ns.get
2599 get = self.shell.user_ns.get
2595 for var in vars:
2600 for var in vars:
2596 # print 30 first characters from every var
2601 # print 30 first characters from every var
2597 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2602 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2598
2603
2599 # default action - store the variable
2604 # default action - store the variable
2600 else:
2605 else:
2601 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2606 pickled = pickle.dumps(self.shell.user_ns[args[0] ])
2602 self.shell.persist[ 'S:' + args[0] ] = pickled
2607 self.shell.persist[ 'S:' + args[0] ] = pickled
2603 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2608 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2604
2609
2605 def magic_bookmark(self, parameter_s=''):
2610 def magic_bookmark(self, parameter_s=''):
2606 """Manage IPython's bookmark system.
2611 """Manage IPython's bookmark system.
2607
2612
2608 %bookmark <name> - set bookmark to current dir
2613 %bookmark <name> - set bookmark to current dir
2609 %bookmark <name> <dir> - set bookmark to <dir>
2614 %bookmark <name> <dir> - set bookmark to <dir>
2610 %bookmark -l - list all bookmarks
2615 %bookmark -l - list all bookmarks
2611 %bookmark -d <name> - remove bookmark
2616 %bookmark -d <name> - remove bookmark
2612 %bookmark -r - remove all bookmarks
2617 %bookmark -r - remove all bookmarks
2613
2618
2614 You can later on access a bookmarked folder with:
2619 You can later on access a bookmarked folder with:
2615 %cd -b <name>
2620 %cd -b <name>
2616 or simply '%cd <name>' if there is no directory called <name> AND
2621 or simply '%cd <name>' if there is no directory called <name> AND
2617 there is such a bookmark defined.
2622 there is such a bookmark defined.
2618
2623
2619 Your bookmarks persist through IPython sessions, but they are
2624 Your bookmarks persist through IPython sessions, but they are
2620 associated with each profile."""
2625 associated with each profile."""
2621
2626
2622 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2627 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2623 if len(args) > 2:
2628 if len(args) > 2:
2624 error('You can only give at most two arguments')
2629 error('You can only give at most two arguments')
2625 return
2630 return
2626
2631
2627 bkms = self.shell.persist.get('bookmarks',{})
2632 bkms = self.shell.persist.get('bookmarks',{})
2628
2633
2629 if opts.has_key('d'):
2634 if opts.has_key('d'):
2630 try:
2635 try:
2631 todel = args[0]
2636 todel = args[0]
2632 except IndexError:
2637 except IndexError:
2633 error('You must provide a bookmark to delete')
2638 error('You must provide a bookmark to delete')
2634 else:
2639 else:
2635 try:
2640 try:
2636 del bkms[todel]
2641 del bkms[todel]
2637 except:
2642 except:
2638 error("Can't delete bookmark '%s'" % todel)
2643 error("Can't delete bookmark '%s'" % todel)
2639 elif opts.has_key('r'):
2644 elif opts.has_key('r'):
2640 bkms = {}
2645 bkms = {}
2641 elif opts.has_key('l'):
2646 elif opts.has_key('l'):
2642 bks = bkms.keys()
2647 bks = bkms.keys()
2643 bks.sort()
2648 bks.sort()
2644 if bks:
2649 if bks:
2645 size = max(map(len,bks))
2650 size = max(map(len,bks))
2646 else:
2651 else:
2647 size = 0
2652 size = 0
2648 fmt = '%-'+str(size)+'s -> %s'
2653 fmt = '%-'+str(size)+'s -> %s'
2649 print 'Current bookmarks:'
2654 print 'Current bookmarks:'
2650 for bk in bks:
2655 for bk in bks:
2651 print fmt % (bk,bkms[bk])
2656 print fmt % (bk,bkms[bk])
2652 else:
2657 else:
2653 if not args:
2658 if not args:
2654 error("You must specify the bookmark name")
2659 error("You must specify the bookmark name")
2655 elif len(args)==1:
2660 elif len(args)==1:
2656 bkms[args[0]] = os.getcwd()
2661 bkms[args[0]] = os.getcwd()
2657 elif len(args)==2:
2662 elif len(args)==2:
2658 bkms[args[0]] = args[1]
2663 bkms[args[0]] = args[1]
2659 self.shell.persist['bookmarks'] = bkms
2664 self.shell.persist['bookmarks'] = bkms
2660
2665
2661 def magic_pycat(self, parameter_s=''):
2666 def magic_pycat(self, parameter_s=''):
2662 """Show a syntax-highlighted file through a pager.
2667 """Show a syntax-highlighted file through a pager.
2663
2668
2664 This magic is similar to the cat utility, but it will assume the file
2669 This magic is similar to the cat utility, but it will assume the file
2665 to be Python source and will show it with syntax highlighting. """
2670 to be Python source and will show it with syntax highlighting. """
2666
2671
2667 filename = get_py_filename(parameter_s)
2672 filename = get_py_filename(parameter_s)
2668 page(self.shell.colorize(file_read(filename)),
2673 page(self.shell.colorize(file_read(filename)),
2669 screen_lines=self.shell.rc.screen_length)
2674 screen_lines=self.shell.rc.screen_length)
2670
2675
2671 # end Magic
2676 # end Magic
General Comments 0
You need to be logged in to leave comments. Login now