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