##// END OF EJS Templates
Work on startup related things....
Brian Granger -
Show More
@@ -0,0 +1,67
1 #!/usr/bin/env python
2 # encoding: utf-8
3 """
4 Context managers for adding things to sys.path temporarily.
5
6 Authors:
7
8 * Brian Granger
9 """
10
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2009 The IPython Development Team
13 #
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
17
18 #-----------------------------------------------------------------------------
19 # Imports
20 #-----------------------------------------------------------------------------
21
22
23 import sys
24
25 class appended_to_syspath(object):
26 """A context for appending a directory to sys.path for a second."""
27
28 def __init__(self, dir):
29 self.dir = dir
30
31 def __enter__(self):
32 if self.dir not in sys.path:
33 sys.path.append(self.dir)
34 self.added = True
35 else:
36 self.added = False
37
38 def __exit__(self, type, value, traceback):
39 if self.added:
40 try:
41 sys.path.remove(self.dir)
42 except ValueError:
43 pass
44 # Returning False causes any exceptions to be re-raised.
45 return False
46
47 class prepended_to_syspath(object):
48 """A context for prepending a directory to sys.path for a second."""
49
50 def __init__(self, dir):
51 self.dir = dir
52
53 def __enter__(self):
54 if self.dir not in sys.path:
55 sys.path.insert(0,self.dir)
56 self.added = True
57 else:
58 self.added = False
59
60 def __exit__(self, type, value, traceback):
61 if self.added:
62 try:
63 sys.path.remove(self.dir)
64 except ValueError:
65 pass
66 # Returning False causes any exceptions to be re-raised.
67 return False
@@ -1,9 +1,8
1 1 from ipython_config import *
2 2
3 EXECUTE.extend([
3 Global.exec_lines.extend([
4 4 'import cmath',
5 5 'from math import *',
6 6 'print "*** math functions available globally, cmath as a module"'
7
8 7 ])
9 8
@@ -1,8 +1,8
1 1 from ipython_config import *
2 2
3 EXECUTE.extend([
3 Global.exec_lines.extend([
4 4 'import numpy',
5 5 'import scipy',
6 6 'import numpy as np',
7 7 'import scipy as sp',
8 8 ]) No newline at end of file
@@ -1,7 +1,8
1 1 from ipython_config_numeric import *
2 2
3 EXECUTE.extend([
4
5
3 Global.exec_lines.extend([
4 'import matplotlib',
5 'from matplotlib import pyplot as plt',
6 'from matplotlib.pyplot import *'
6 7 ])
7 8
@@ -1,15 +1,13
1 1 from ipython_config import *
2 2
3 EXECUTE.insert(0, 'from IPython.extensions.InterpreterExec import *')
3 InteractiveShell.prompt_in2 = '\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
4 InteractiveShell.prompt_in2 = '\C_Green|\C_LightGreen\D\C_Green> '
5 InteractiveShell.prompt_out = '<\#> '
4 6
5 PROMPT_IN1 = '\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
6 PROMPT_IN2 = '\C_Green|\C_LightGreen\D\C_Green> '
7 PROMPT_OUT = '<\#> '
7 InteractiveShell.prompts_pad_left = True
8 8
9 PROMPTS_PAD_LEFT = True
9 InteractiveShell.separate_in = ''
10 InteractiveShell.separate_out = ''
11 InteractiveShell.separate_out2 = ''
10 12
11 SEPARATE_IN = 0
12 SEPARATE_OUT = 0
13 SEPARATE_OUT2 = 0
14
15 MULTI_LINE_SPECIALS = True No newline at end of file
13 PrefilterManager.multi_line_specials = True No newline at end of file
@@ -1,9 +1,9
1 1 from ipython_config import *
2 2
3 EXECUTE.extend([
4 'from __future__ import division'
5 'from sympy import *'
6 'x, y, z = symbols('xyz')'
7 'k, m, n = symbols('kmn', integer=True)'
8 'f, g, h = map(Function, 'fgh')'
3 Global.exec_lines.extend([
4 "from __future__ import division"
5 "from sympy import *"
6 "x, y, z = symbols('xyz')"
7 "k, m, n = symbols('kmn', integer=True)"
8 "f, g, h = map(Function, 'fgh')"
9 9 ])
@@ -1,264 +1,262
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 IPython's alias component
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2008-2009 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 import __builtin__
23 23 import keyword
24 24 import os
25 25 import re
26 26 import sys
27 27
28 28 from IPython.core.component import Component
29 29 from IPython.core.splitinput import split_user_input
30 30
31 31 from IPython.utils.traitlets import CBool, List, Instance
32 32 from IPython.utils.genutils import error
33 33 from IPython.utils.autoattr import auto_attr
34 34
35 35 #-----------------------------------------------------------------------------
36 36 # Utilities
37 37 #-----------------------------------------------------------------------------
38 38
39 39 # This is used as the pattern for calls to split_user_input.
40 40 shell_line_split = re.compile(r'^(\s*)(\S*\s*)(.*$)')
41 41
42 42 def default_aliases():
43 43 # Make some aliases automatically
44 44 # Prepare list of shell aliases to auto-define
45 45 if os.name == 'posix':
46 46 default_aliases = ('mkdir mkdir', 'rmdir rmdir',
47 47 'mv mv -i','rm rm -i','cp cp -i',
48 48 'cat cat','less less','clear clear',
49 49 # a better ls
50 50 'ls ls -F',
51 51 # long ls
52 52 'll ls -lF')
53 53 # Extra ls aliases with color, which need special treatment on BSD
54 54 # variants
55 55 ls_extra = ( # color ls
56 56 'lc ls -F -o --color',
57 57 # ls normal files only
58 58 'lf ls -F -o --color %l | grep ^-',
59 59 # ls symbolic links
60 60 'lk ls -F -o --color %l | grep ^l',
61 61 # directories or links to directories,
62 62 'ldir ls -F -o --color %l | grep /$',
63 63 # things which are executable
64 64 'lx ls -F -o --color %l | grep ^-..x',
65 65 )
66 66 # The BSDs don't ship GNU ls, so they don't understand the
67 67 # --color switch out of the box
68 68 if 'bsd' in sys.platform:
69 69 ls_extra = ( # ls normal files only
70 70 'lf ls -lF | grep ^-',
71 71 # ls symbolic links
72 72 'lk ls -lF | grep ^l',
73 73 # directories or links to directories,
74 74 'ldir ls -lF | grep /$',
75 75 # things which are executable
76 76 'lx ls -lF | grep ^-..x',
77 77 )
78 78 default_aliases = default_aliases + ls_extra
79 79 elif os.name in ['nt','dos']:
80 80 default_aliases = ('ls dir /on',
81 81 'ddir dir /ad /on', 'ldir dir /ad /on',
82 82 'mkdir mkdir','rmdir rmdir','echo echo',
83 83 'ren ren','cls cls','copy copy')
84 84 else:
85 85 default_aliases = ()
86 86 return [s.split(None,1) for s in default_aliases]
87 87
88 88
89 89 class AliasError(Exception):
90 90 pass
91 91
92 92
93 93 class InvalidAliasError(AliasError):
94 94 pass
95 95
96 96
97 97 #-----------------------------------------------------------------------------
98 98 # Main AliasManager class
99 99 #-----------------------------------------------------------------------------
100 100
101 101
102 102 class AliasManager(Component):
103 103
104 104 default_aliases = List(default_aliases(), config=True)
105 105 user_aliases = List(default_value=[], config=True)
106 106
107 107 def __init__(self, parent, config=None):
108 108 super(AliasManager, self).__init__(parent, config=config)
109 109 self.alias_table = {}
110 110 self.exclude_aliases()
111 111 self.init_aliases()
112 112
113 113 @auto_attr
114 114 def shell(self):
115 shell = Component.get_instances(
115 return Component.get_instances(
116 116 root=self.root,
117 klass='IPython.core.iplib.InteractiveShell'
118 )[0]
119 return shell
117 klass='IPython.core.iplib.InteractiveShell')[0]
120 118
121 119 def __contains__(self, name):
122 120 if name in self.alias_table:
123 121 return True
124 122 else:
125 123 return False
126 124
127 125 @property
128 126 def aliases(self):
129 127 return [(item[0], item[1][1]) for item in self.alias_table.iteritems()]
130 128
131 129 def exclude_aliases(self):
132 130 # set of things NOT to alias (keywords, builtins and some magics)
133 131 no_alias = set(['cd','popd','pushd','dhist','alias','unalias'])
134 132 no_alias.update(set(keyword.kwlist))
135 133 no_alias.update(set(__builtin__.__dict__.keys()))
136 134 self.no_alias = no_alias
137 135
138 136 def init_aliases(self):
139 137 # Load default aliases
140 138 for name, cmd in self.default_aliases:
141 139 self.soft_define_alias(name, cmd)
142 140
143 141 # Load user aliases
144 142 for name, cmd in self.user_aliases:
145 143 self.soft_define_alias(name, cmd)
146 144
147 145 def clear_aliases(self):
148 146 self.alias_table.clear()
149 147
150 148 def soft_define_alias(self, name, cmd):
151 149 """Define an alias, but don't raise on an AliasError."""
152 150 try:
153 151 self.define_alias(name, cmd)
154 152 except AliasError, e:
155 153 error("Invalid alias: %s" % e)
156 154
157 155 def define_alias(self, name, cmd):
158 156 """Define a new alias after validating it.
159 157
160 158 This will raise an :exc:`AliasError` if there are validation
161 159 problems.
162 160 """
163 161 nargs = self.validate_alias(name, cmd)
164 162 self.alias_table[name] = (nargs, cmd)
165 163
166 164 def undefine_alias(self, name):
167 165 if self.alias_table.has_key(name):
168 166 del self.alias_table[name]
169 167
170 168 def validate_alias(self, name, cmd):
171 169 """Validate an alias and return the its number of arguments."""
172 170 if name in self.no_alias:
173 171 raise InvalidAliasError("The name %s can't be aliased "
174 172 "because it is a keyword or builtin." % name)
175 173 if not (isinstance(cmd, basestring)):
176 174 raise InvalidAliasError("An alias command must be a string, "
177 175 "got: %r" % name)
178 176 nargs = cmd.count('%s')
179 177 if nargs>0 and cmd.find('%l')>=0:
180 178 raise InvalidAliasError('The %s and %l specifiers are mutually '
181 179 'exclusive in alias definitions.')
182 180 return nargs
183 181
184 182 def call_alias(self, alias, rest=''):
185 183 """Call an alias given its name and the rest of the line."""
186 184 cmd = self.transform_alias(alias, rest)
187 185 try:
188 186 self.shell.system(cmd)
189 187 except:
190 188 self.shell.showtraceback()
191 189
192 190 def transform_alias(self, alias,rest=''):
193 191 """Transform alias to system command string."""
194 192 nargs, cmd = self.alias_table[alias]
195 193
196 194 if ' ' in cmd and os.path.isfile(cmd):
197 195 cmd = '"%s"' % cmd
198 196
199 197 # Expand the %l special to be the user's input line
200 198 if cmd.find('%l') >= 0:
201 199 cmd = cmd.replace('%l', rest)
202 200 rest = ''
203 201 if nargs==0:
204 202 # Simple, argument-less aliases
205 203 cmd = '%s %s' % (cmd, rest)
206 204 else:
207 205 # Handle aliases with positional arguments
208 206 args = rest.split(None, nargs)
209 207 if len(args) < nargs:
210 208 raise AliasError('Alias <%s> requires %s arguments, %s given.' %
211 209 (alias, nargs, len(args)))
212 210 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
213 211 return cmd
214 212
215 213 def expand_alias(self, line):
216 214 """ Expand an alias in the command line
217 215
218 216 Returns the provided command line, possibly with the first word
219 217 (command) translated according to alias expansion rules.
220 218
221 219 [ipython]|16> _ip.expand_aliases("np myfile.txt")
222 220 <16> 'q:/opt/np/notepad++.exe myfile.txt'
223 221 """
224 222
225 223 pre,fn,rest = split_user_input(line)
226 224 res = pre + self.expand_aliases(fn, rest)
227 225 return res
228 226
229 227 def expand_aliases(self, fn, rest):
230 228 """Expand multiple levels of aliases:
231 229
232 230 if:
233 231
234 232 alias foo bar /tmp
235 233 alias baz foo
236 234
237 235 then:
238 236
239 237 baz huhhahhei -> bar /tmp huhhahhei
240 238
241 239 """
242 240 line = fn + " " + rest
243 241
244 242 done = set()
245 243 while 1:
246 244 pre,fn,rest = split_user_input(line, shell_line_split)
247 245 if fn in self.alias_table:
248 246 if fn in done:
249 247 warn("Cyclic alias definition, repeated '%s'" % fn)
250 248 return ""
251 249 done.add(fn)
252 250
253 251 l2 = self.transform_alias(fn, rest)
254 252 if l2 == line:
255 253 break
256 254 # ls -> ls -F should not recurse forever
257 255 if l2.split(None,1)[0] == line.split(None,1)[0]:
258 256 line = l2
259 257 break
260 258 line=l2
261 259 else:
262 260 break
263 261
264 262 return line
@@ -1,265 +1,287
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 An application for IPython
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10
11 11 Notes
12 12 -----
13 13 """
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2008-2009 The IPython Development Team
17 17 #
18 18 # Distributed under the terms of the BSD License. The full license is in
19 19 # the file COPYING, distributed as part of this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 import logging
26 27 import os
27 28 import sys
28 29 import traceback
29 30 from copy import deepcopy
30 31
31 32 from IPython.utils.genutils import get_ipython_dir, filefind
32 33 from IPython.config.loader import (
33 34 PyFileConfigLoader,
34 35 ArgParseConfigLoader,
35 36 Config,
36 37 NoConfigDefault
37 38 )
38 39
39 40 #-----------------------------------------------------------------------------
40 41 # Classes and functions
41 42 #-----------------------------------------------------------------------------
42 43
43 44
44 45 class IPythonArgParseConfigLoader(ArgParseConfigLoader):
45 46 """Default command line options for IPython based applications."""
46 47
47 48 def _add_other_arguments(self):
48 49 self.parser.add_argument('-ipythondir',dest='Global.ipythondir',type=str,
49 50 help='Set to override default location of Global.ipythondir.',
50 51 default=NoConfigDefault,
51 52 metavar='Global.ipythondir')
52 53 self.parser.add_argument('-p','-profile',dest='Global.profile',type=str,
53 54 help='The string name of the ipython profile to be used.',
54 55 default=NoConfigDefault,
55 56 metavar='Global.profile')
56 self.parser.add_argument('-debug',dest="Global.debug",action='store_true',
57 help='Debug the application startup process.',
57 self.parser.add_argument('-log_level',dest="Global.log_level",type=int,
58 help='Set the log level (0,10,20,30,40,50). Default is 30.',
58 59 default=NoConfigDefault)
59 60 self.parser.add_argument('-config_file',dest='Global.config_file',type=str,
60 61 help='Set the config file name to override default.',
61 62 default=NoConfigDefault,
62 63 metavar='Global.config_file')
63 64
64 65
65 66 class ApplicationError(Exception):
66 67 pass
67 68
68 69
69 70 class Application(object):
70 71 """Load a config, construct an app and run it.
71 72 """
72 73
73 74 config_file_name = 'ipython_config.py'
74 75 name = 'ipython'
75 debug = False
76 76
77 77 def __init__(self):
78 pass
78 self.init_logger()
79
80 def init_logger(self):
81 self.log = logging.getLogger(self.__class__.__name__)
82 # This is used as the default until the command line arguments are read.
83 self.log.setLevel(logging.WARN)
84 self._log_handler = logging.StreamHandler()
85 self._log_formatter = logging.Formatter("[%(name)s] %(message)s")
86 self._log_handler.setFormatter(self._log_formatter)
87 self.log.addHandler(self._log_handler)
88
89 def _set_log_level(self, level):
90 self.log.setLevel(level)
91
92 def _get_log_level(self):
93 return self.log.level
94
95 log_level = property(_get_log_level, _set_log_level)
79 96
80 97 def start(self):
81 98 """Start the application."""
82 99 self.attempt(self.create_default_config)
83 100 self.attempt(self.pre_load_command_line_config)
84 101 self.attempt(self.load_command_line_config, action='abort')
85 102 self.attempt(self.post_load_command_line_config)
86 103 self.attempt(self.find_ipythondir)
87 104 self.attempt(self.find_config_file_name)
88 105 self.attempt(self.find_config_file_paths)
89 106 self.attempt(self.pre_load_file_config)
90 107 self.attempt(self.load_file_config)
91 108 self.attempt(self.post_load_file_config)
92 109 self.attempt(self.merge_configs)
93 110 self.attempt(self.pre_construct)
94 111 self.attempt(self.construct)
95 112 self.attempt(self.post_construct)
96 113 self.attempt(self.start_app)
97 114
98 115 #-------------------------------------------------------------------------
99 116 # Various stages of Application creation
100 117 #-------------------------------------------------------------------------
101 118
102 119 def create_default_config(self):
103 120 """Create defaults that can't be set elsewhere."""
104 121 self.default_config = Config()
105 122 self.default_config.Global.ipythondir = get_ipython_dir()
123 self.log.debug('Default config loaded:')
124 self.log.debug(repr(self.default_config))
106 125
107 126 def create_command_line_config(self):
108 127 """Create and return a command line config loader."""
109 128 return IPythonArgParseConfigLoader(description=self.name)
110 129
111 130 def pre_load_command_line_config(self):
112 131 """Do actions just before loading the command line config."""
113 132 pass
114 133
115 134 def load_command_line_config(self):
116 135 """Load the command line config.
117 136
118 137 This method also sets ``self.debug``.
119 138 """
120 139
121 140 loader = self.create_command_line_config()
122 141 self.command_line_config = loader.load_config()
142
123 143 try:
124 self.debug = self.command_line_config.Global.debug
144 self.log_level = self.command_line_config.Global.log_level
125 145 except AttributeError:
126 pass # use class default
127 self.log("Default config loaded:", self.default_config)
128 self.log("Command line config loaded:", self.command_line_config)
146 pass # Use existing value which is set in Application.init_logger.
147
148 self.log.debug("Command line config loaded:")
149 self.log.debug(repr(self.command_line_config))
129 150
130 151 def post_load_command_line_config(self):
131 152 """Do actions just after loading the command line config."""
132 153 pass
133 154
134 155 def find_ipythondir(self):
135 156 """Set the IPython directory.
136 157
137 158 This sets ``self.ipythondir``, but the actual value that is passed
138 159 to the application is kept in either ``self.default_config`` or
139 160 ``self.command_line_config``. This also added ``self.ipythondir`` to
140 161 ``sys.path`` so config files there can be references by other config
141 162 files.
142 163 """
143 164
144 165 try:
145 166 self.ipythondir = self.command_line_config.Global.ipythondir
146 167 except AttributeError:
147 168 self.ipythondir = self.default_config.Global.ipythondir
148 169 sys.path.append(os.path.abspath(self.ipythondir))
149 170 if not os.path.isdir(self.ipythondir):
150 171 os.makedirs(self.ipythondir, mode = 0777)
151 self.log("IPYTHONDIR set to: %s" % self.ipythondir)
172 self.log.debug("IPYTHONDIR set to: %s" % self.ipythondir)
152 173
153 174 def find_config_file_name(self):
154 175 """Find the config file name for this application.
155 176
156 177 If a profile has been set at the command line, this will resolve
157 178 it. The search paths for the config file are set in
158 179 :meth:`find_config_file_paths` and then passed to the config file
159 180 loader where they are resolved to an absolute path.
160 181 """
161 182
162 183 try:
163 184 self.config_file_name = self.command_line_config.Global.config_file
164 185 except AttributeError:
165 186 pass
166 187
167 188 try:
168 189 self.profile_name = self.command_line_config.Global.profile
169 190 name_parts = self.config_file_name.split('.')
170 191 name_parts.insert(1, '_' + self.profile_name + '.')
171 192 self.config_file_name = ''.join(name_parts)
172 193 except AttributeError:
173 194 pass
174 195
175 196 def find_config_file_paths(self):
176 197 """Set the search paths for resolving the config file."""
177 198 self.config_file_paths = (os.getcwd(), self.ipythondir)
178 199
179 200 def pre_load_file_config(self):
180 201 """Do actions before the config file is loaded."""
181 202 pass
182 203
183 204 def load_file_config(self):
184 205 """Load the config file.
185 206
186 207 This tries to load the config file from disk. If successful, the
187 208 ``CONFIG_FILE`` config variable is set to the resolved config file
188 209 location. If not successful, an empty config is used.
189 210 """
211 self.log.debug("Attempting to load config file: <%s>" % self.config_file_name)
190 212 loader = PyFileConfigLoader(self.config_file_name,
191 213 path=self.config_file_paths)
192 214 try:
193 215 self.file_config = loader.load_config()
194 216 self.file_config.Global.config_file = loader.full_filename
195 217 except IOError:
196 self.log("Config file not found, skipping: %s" % \
197 self.config_file_name)
218 self.log.warn("Config file not found, skipping: <%s>" % \
219 self.config_file_name, exc_info=True)
220 self.file_config = Config()
221 except:
222 self.log.warn("Error loading config file: <%s>" % \
223 self.config_file_name, exc_info=True)
198 224 self.file_config = Config()
199 225 else:
200 self.log("Config file loaded: %s" % loader.full_filename,
201 self.file_config)
226 self.log.debug("Config file loaded: <%s>" % loader.full_filename)
227 self.log.debug(repr(self.file_config))
228 # We need to keeep self.log_level updated.
229 try:
230 self.log_level = self.file_config.Global.log_level
231 except AttributeError:
232 pass # Use existing value
202 233
203 234 def post_load_file_config(self):
204 235 """Do actions after the config file is loaded."""
205 236 pass
206 237
207 238 def merge_configs(self):
208 239 """Merge the default, command line and file config objects."""
209 240 config = Config()
210 241 config._merge(self.default_config)
211 242 config._merge(self.file_config)
212 243 config._merge(self.command_line_config)
213 244 self.master_config = config
214 self.log("Master config created:", self.master_config)
245 self.log.debug("Master config created:")
246 self.log.debug(repr(self.master_config))
215 247
216 248 def pre_construct(self):
217 249 """Do actions after the config has been built, but before construct."""
218 250 pass
219 251
220 252 def construct(self):
221 253 """Construct the main components that make up this app."""
222 self.log("Constructing components for application...")
254 self.log.debug("Constructing components for application")
223 255
224 256 def post_construct(self):
225 257 """Do actions after construct, but before starting the app."""
226 258 pass
227 259
228 260 def start_app(self):
229 261 """Actually start the app."""
230 self.log("Starting application...")
262 self.log.debug("Starting application")
231 263
232 264 #-------------------------------------------------------------------------
233 265 # Utility methods
234 266 #-------------------------------------------------------------------------
235 267
236 268 def abort(self):
237 269 """Abort the starting of the application."""
238 print "Aborting application: ", self.name
270 self.log.critical("Aborting application: %s" % self.name, exc_info=True)
239 271 sys.exit(1)
240 272
241 273 def exit(self):
242 print "Exiting application: ", self.name
274 self.log.critical("Aborting application: %s" % self.name)
243 275 sys.exit(1)
244 276
245 277 def attempt(self, func, action='abort'):
246 278 try:
247 279 func()
248 280 except SystemExit:
249 281 self.exit()
250 282 except:
251 283 if action == 'abort':
252 self.print_traceback()
253 284 self.abort()
254 285 elif action == 'exit':
255 286 self.exit()
256
257 def print_traceback(self):
258 print "Error in appliction startup: ", self.name
259 print
260 traceback.print_exc()
261
262 def log(self, *args):
263 if self.debug:
264 for arg in args:
265 print "[%s] %s" % (self.name, arg) No newline at end of file
287 No newline at end of file
@@ -1,118 +1,116
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 A context manager for managing things injected into :mod:`__builtin__`.
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Copyright (C) 2008-2009 The IPython Development Team
13 13 #
14 14 # Distributed under the terms of the BSD License. The full license is in
15 15 # the file COPYING, distributed as part of this software.
16 16 #-----------------------------------------------------------------------------
17 17
18 18 #-----------------------------------------------------------------------------
19 19 # Imports
20 20 #-----------------------------------------------------------------------------
21 21
22 22 import __builtin__
23 23
24 24 from IPython.core.component import Component
25 25 from IPython.core.quitter import Quitter
26 26
27 27 from IPython.utils.autoattr import auto_attr
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Classes and functions
31 31 #-----------------------------------------------------------------------------
32 32
33 33
34 34 class BuiltinUndefined(object): pass
35 35 BuiltinUndefined = BuiltinUndefined()
36 36
37 37
38 38 class BuiltinTrap(Component):
39 39
40 40 def __init__(self, parent):
41 41 super(BuiltinTrap, self).__init__(parent, None, None)
42 42 self._orig_builtins = {}
43 43 # We define this to track if a single BuiltinTrap is nested.
44 44 # Only turn off the trap when the outermost call to __exit__ is made.
45 45 self._nested_level = 0
46 46
47 47 @auto_attr
48 48 def shell(self):
49 shell = Component.get_instances(
49 return Component.get_instances(
50 50 root=self.root,
51 klass='IPython.core.iplib.InteractiveShell'
52 )[0]
53 return shell
51 klass='IPython.core.iplib.InteractiveShell')[0]
54 52
55 53 def __enter__(self):
56 54 if self._nested_level == 0:
57 55 self.set()
58 56 self._nested_level += 1
59 57 # I return self, so callers can use add_builtin in a with clause.
60 58 return self
61 59
62 60 def __exit__(self, type, value, traceback):
63 61 if self._nested_level == 1:
64 62 self.unset()
65 63 self._nested_level -= 1
66 64 return True
67 65
68 66 def add_builtin(self, key, value):
69 67 """Add a builtin and save the original."""
70 68 orig = __builtin__.__dict__.get(key, BuiltinUndefined)
71 69 self._orig_builtins[key] = orig
72 70 __builtin__.__dict__[key] = value
73 71
74 72 def remove_builtin(self, key):
75 73 """Remove an added builtin and re-set the original."""
76 74 try:
77 75 orig = self._orig_builtins.pop(key)
78 76 except KeyError:
79 77 pass
80 78 else:
81 79 if orig is BuiltinUndefined:
82 80 del __builtin__.__dict__[key]
83 81 else:
84 82 __builtin__.__dict__[key] = orig
85 83
86 84 def set(self):
87 85 """Store ipython references in the __builtin__ namespace."""
88 86 self.add_builtin('exit', Quitter(self.shell, 'exit'))
89 87 self.add_builtin('quit', Quitter(self.shell, 'quit'))
90 88
91 89 # Recursive reload function
92 90 try:
93 91 from IPython.lib import deepreload
94 92 if self.shell.deep_reload:
95 93 self.add_builtin('reload', deepreload.reload)
96 94 else:
97 95 self.add_builtin('dreload', deepreload.reload)
98 96 del deepreload
99 97 except ImportError:
100 98 pass
101 99
102 100 # Keep in the builtins a flag for when IPython is active. We set it
103 101 # with setdefault so that multiple nested IPythons don't clobber one
104 102 # another. Each will increase its value by one upon being activated,
105 103 # which also gives us a way to determine the nesting level.
106 104 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
107 105
108 106 def unset(self):
109 107 """Remove any builtins which might have been added by add_builtins, or
110 108 restore overwritten ones to their previous values."""
111 109 for key in self._orig_builtins.keys():
112 110 self.remove_builtin(key)
113 111 self._orig_builtins.clear()
114 112 self._builtins_added = False
115 113 try:
116 114 del __builtin__.__dict__['__IPYTHON__active']
117 115 except KeyError:
118 116 pass
@@ -1,78 +1,76
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 A context manager for handling sys.displayhook.
5 5
6 6 Authors:
7 7
8 8 * Robert Kern
9 9 * Brian Granger
10 10 """
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Copyright (C) 2008-2009 The IPython Development Team
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #-----------------------------------------------------------------------------
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Imports
21 21 #-----------------------------------------------------------------------------
22 22
23 23 import sys
24 24
25 25 from IPython.core.component import Component
26 26
27 27 from IPython.utils.autoattr import auto_attr
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Classes and functions
31 31 #-----------------------------------------------------------------------------
32 32
33 33
34 34 class DisplayTrap(Component):
35 35 """Object to manage sys.displayhook.
36 36
37 37 This came from IPython.core.kernel.display_hook, but is simplified
38 38 (no callbacks or formatters) until more of the core is refactored.
39 39 """
40 40
41 41 def __init__(self, parent, hook):
42 42 super(DisplayTrap, self).__init__(parent, None, None)
43 43 self.hook = hook
44 44 self.old_hook = None
45 45 # We define this to track if a single BuiltinTrap is nested.
46 46 # Only turn off the trap when the outermost call to __exit__ is made.
47 47 self._nested_level = 0
48 48
49 49 @auto_attr
50 50 def shell(self):
51 shell = Component.get_instances(
51 return Component.get_instances(
52 52 root=self.root,
53 klass='IPython.core.iplib.InteractiveShell'
54 )[0]
55 return shell
53 klass='IPython.core.iplib.InteractiveShell')[0]
56 54
57 55 def __enter__(self):
58 56 if self._nested_level == 0:
59 57 self.set()
60 58 self._nested_level += 1
61 59 return self
62 60
63 61 def __exit__(self, type, value, traceback):
64 62 if self._nested_level == 1:
65 63 self.unset()
66 64 self._nested_level -= 1
67 65 return True
68 66
69 67 def set(self):
70 68 """Set the hook."""
71 69 if sys.displayhook is not self.hook:
72 70 self.old_hook = sys.displayhook
73 71 sys.displayhook = self.hook
74 72
75 73 def unset(self):
76 74 """Unset the hook."""
77 75 sys.displayhook = self.old_hook
78 76
@@ -1,272 +1,280
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 An embedded IPython shell.
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10
11 11 Notes
12 12 -----
13 13 """
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2008-2009 The IPython Development Team
17 17 #
18 18 # Distributed under the terms of the BSD License. The full license is in
19 19 # the file COPYING, distributed as part of this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 26 from __future__ import with_statement
27 27
28 28 import sys
29 29 from contextlib import nested
30 30
31 31 from IPython.core import ultratb
32 32 from IPython.core.iplib import InteractiveShell
33 33 from IPython.core.ipapp import load_default_config
34 34
35 35 from IPython.utils.traitlets import Bool, Str, CBool
36 36 from IPython.utils.genutils import ask_yes_no
37 37
38 38
39 39 #-----------------------------------------------------------------------------
40 40 # Classes and functions
41 41 #-----------------------------------------------------------------------------
42 42
43 43 # This is an additional magic that is exposed in embedded shells.
44 44 def kill_embedded(self,parameter_s=''):
45 45 """%kill_embedded : deactivate for good the current embedded IPython.
46 46
47 47 This function (after asking for confirmation) sets an internal flag so that
48 48 an embedded IPython will never activate again. This is useful to
49 49 permanently disable a shell that is being called inside a loop: once you've
50 50 figured out what you needed from it, you may then kill it and the program
51 51 will then continue to run without the interactive shell interfering again.
52 52 """
53 53
54 54 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
55 55 "(y/n)? [y/N] ",'n')
56 56 if kill:
57 57 self.embedded_active = False
58 58 print "This embedded IPython will not reactivate anymore once you exit."
59 59
60 60
61 61 class InteractiveShellEmbed(InteractiveShell):
62 62
63 63 dummy_mode = Bool(False)
64 64 exit_msg = Str('')
65 65 embedded = CBool(True)
66 66 embedded_active = CBool(True)
67 # Like the base class display_banner is not configurable, but here it
68 # is True by default.
69 display_banner = CBool(True)
67 70
68 71 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
69 72 user_ns=None, user_global_ns=None,
70 banner1=None, banner2=None,
73 banner1=None, banner2=None, display_banner=None,
71 74 custom_exceptions=((),None), exit_msg=''):
72 75
73 76 self.save_sys_ipcompleter()
74 77
75 78 super(InteractiveShellEmbed,self).__init__(
76 79 parent=parent, config=config, ipythondir=ipythondir, usage=usage,
77 80 user_ns=user_ns, user_global_ns=user_global_ns,
78 banner1=banner1, banner2=banner2,
81 banner1=banner1, banner2=banner2, display_banner=display_banner,
79 82 custom_exceptions=custom_exceptions)
80 83
81 84 self.exit_msg = exit_msg
82 85 self.define_magic("kill_embedded", kill_embedded)
83 86
84 87 # don't use the ipython crash handler so that user exceptions aren't
85 88 # trapped
86 89 sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
87 90 mode=self.xmode,
88 91 call_pdb=self.pdb)
89 92
90 93 self.restore_sys_ipcompleter()
91 94
92 95 def init_sys_modules(self):
93 96 pass
94 97
95 98 def save_sys_ipcompleter(self):
96 99 """Save readline completer status."""
97 100 try:
98 101 #print 'Save completer',sys.ipcompleter # dbg
99 102 self.sys_ipcompleter_orig = sys.ipcompleter
100 103 except:
101 104 pass # not nested with IPython
102 105
103 106 def restore_sys_ipcompleter(self):
104 107 """Restores the readline completer which was in place.
105 108
106 109 This allows embedded IPython within IPython not to disrupt the
107 110 parent's completion.
108 111 """
109 112 try:
110 113 self.readline.set_completer(self.sys_ipcompleter_orig)
111 114 sys.ipcompleter = self.sys_ipcompleter_orig
112 115 except:
113 116 pass
114 117
115 118 def __call__(self, header='', local_ns=None, global_ns=None, dummy=None,
116 119 stack_depth=1):
117 120 """Activate the interactive interpreter.
118 121
119 122 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
120 123 the interpreter shell with the given local and global namespaces, and
121 124 optionally print a header string at startup.
122 125
123 126 The shell can be globally activated/deactivated using the
124 127 set/get_dummy_mode methods. This allows you to turn off a shell used
125 128 for debugging globally.
126 129
127 130 However, *each* time you call the shell you can override the current
128 131 state of dummy_mode with the optional keyword parameter 'dummy'. For
129 132 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
130 133 can still have a specific call work by making it as IPShell(dummy=0).
131 134
132 135 The optional keyword parameter dummy controls whether the call
133 136 actually does anything.
134 137 """
135 138
136 139 # If the user has turned it off, go away
137 140 if not self.embedded_active:
138 141 return
139 142
140 143 # Normal exits from interactive mode set this flag, so the shell can't
141 144 # re-enter (it checks this variable at the start of interactive mode).
142 145 self.exit_now = False
143 146
144 147 # Allow the dummy parameter to override the global __dummy_mode
145 148 if dummy or (dummy != 0 and self.dummy_mode):
146 149 return
147 150
148 151 if self.has_readline:
149 152 self.set_completer()
150 153
151 if self.banner and header:
152 format = '%s\n%s\n'
153 else:
154 format = '%s%s\n'
155 banner = format % (self.banner,header)
154 # self.banner is auto computed
155 if header:
156 self.old_banner2 = self.banner2
157 self.banner2 = self.banner2 + '\n' + header + '\n'
156 158
157 159 # Call the embedding code with a stack depth of 1 so it can skip over
158 160 # our call and get the original caller's namespaces.
159 self.mainloop(banner, local_ns, global_ns,
160 stack_depth=stack_depth)
161 self.mainloop(local_ns, global_ns, stack_depth=stack_depth)
162
163 self.banner2 = self.old_banner2
161 164
162 165 if self.exit_msg is not None:
163 166 print self.exit_msg
164 167
165 168 self.restore_sys_ipcompleter()
166 169
167 def mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
170 def mainloop(self, local_ns=None, global_ns=None, stack_depth=0,
171 display_banner=None):
168 172 """Embeds IPython into a running python program.
169 173
170 174 Input:
171 175
172 176 - header: An optional header message can be specified.
173 177
174 178 - local_ns, global_ns: working namespaces. If given as None, the
175 179 IPython-initialized one is updated with __main__.__dict__, so that
176 180 program variables become visible but user-specific configuration
177 181 remains possible.
178 182
179 183 - stack_depth: specifies how many levels in the stack to go to
180 184 looking for namespaces (when local_ns and global_ns are None). This
181 185 allows an intermediate caller to make sure that this function gets
182 186 the namespace from the intended level in the stack. By default (0)
183 187 it will get its locals and globals from the immediate caller.
184 188
185 189 Warning: it's possible to use this in a program which is being run by
186 190 IPython itself (via %run), but some funny things will happen (a few
187 191 globals get overwritten). In the future this will be cleaned up, as
188 192 there is no fundamental reason why it can't work perfectly."""
189 193
190 194 # Get locals and globals from caller
191 195 if local_ns is None or global_ns is None:
192 196 call_frame = sys._getframe(stack_depth).f_back
193 197
194 198 if local_ns is None:
195 199 local_ns = call_frame.f_locals
196 200 if global_ns is None:
197 201 global_ns = call_frame.f_globals
198 202
199 203 # Update namespaces and fire up interpreter
200 204
201 205 # The global one is easy, we can just throw it in
202 206 self.user_global_ns = global_ns
203 207
204 208 # but the user/local one is tricky: ipython needs it to store internal
205 209 # data, but we also need the locals. We'll copy locals in the user
206 210 # one, but will track what got copied so we can delete them at exit.
207 211 # This is so that a later embedded call doesn't see locals from a
208 212 # previous call (which most likely existed in a separate scope).
209 213 local_varnames = local_ns.keys()
210 214 self.user_ns.update(local_ns)
211 215 #self.user_ns['local_ns'] = local_ns # dbg
212 216
213 217 # Patch for global embedding to make sure that things don't overwrite
214 218 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
215 219 # FIXME. Test this a bit more carefully (the if.. is new)
216 220 if local_ns is None and global_ns is None:
217 221 self.user_global_ns.update(__main__.__dict__)
218 222
219 223 # make sure the tab-completer has the correct frame information, so it
220 224 # actually completes using the frame's locals/globals
221 225 self.set_completer_frame()
222 226
223 227 with nested(self.builtin_trap, self.display_trap):
224 self.interact(header)
228 self.interact(display_banner=display_banner)
225 229
226 230 # now, purge out the user namespace from anything we might have added
227 231 # from the caller's local namespace
228 232 delvar = self.user_ns.pop
229 233 for var in local_varnames:
230 234 delvar(var,None)
231 235
232 236 def set_completer_frame(self, frame=None):
233 237 if frame:
234 238 self.Completer.namespace = frame.f_locals
235 239 self.Completer.global_namespace = frame.f_globals
236 240 else:
237 241 self.Completer.namespace = self.user_ns
238 242 self.Completer.global_namespace = self.user_global_ns
239 243
240 244
241 245 _embedded_shell = None
242 246
243 247
244 248 def embed(header='', config=None, usage=None, banner1=None, banner2=None,
245 exit_msg=''):
249 display_banner=True, exit_msg=''):
246 250 """Call this to embed IPython at the current point in your program.
247 251
248 252 The first invocation of this will create an :class:`InteractiveShellEmbed`
249 253 instance and then call it. Consecutive calls just call the already
250 254 created instance.
251 255
252 256 Here is a simple example::
253 257
254 258 from IPython import embed
255 259 a = 10
256 260 b = 20
257 261 embed('First time')
258 262 c = 30
259 263 d = 40
260 264 embed
261 265
262 266 Full customization can be done by passing a :class:`Struct` in as the
263 267 config argument.
264 268 """
265 269 if config is None:
266 270 config = load_default_config()
271 config.InteractiveShellEmbed = config.InteractiveShell
267 272 global _embedded_shell
268 273 if _embedded_shell is None:
269 _embedded_shell = InteractiveShellEmbed(config=config,
270 usage=usage, banner1=banner1, banner2=banner2, exit_msg=exit_msg)
274 _embedded_shell = InteractiveShellEmbed(
275 config=config, usage=usage,
276 banner1=banner1, banner2=banner2,
277 display_banner=display_banner, exit_msg=exit_msg
278 )
271 279 _embedded_shell(header=header, stack_depth=2)
272 280
@@ -1,349 +1,442
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 The main IPython application object
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10
11 11 Notes
12 12 -----
13 13 """
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Copyright (C) 2008-2009 The IPython Development Team
17 17 #
18 18 # Distributed under the terms of the BSD License. The full license is in
19 19 # the file COPYING, distributed as part of this software.
20 20 #-----------------------------------------------------------------------------
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Imports
24 24 #-----------------------------------------------------------------------------
25 25
26 import logging
26 27 import os
27 28 import sys
28 29 import warnings
29 30
30 31 from IPython.core.application import Application, IPythonArgParseConfigLoader
31 32 from IPython.core import release
32 33 from IPython.core.iplib import InteractiveShell
33 34 from IPython.config.loader import (
34 35 NoConfigDefault,
35 36 Config,
37 ConfigError,
36 38 PyFileConfigLoader
37 39 )
38 40
39 41 from IPython.utils.ipstruct import Struct
40 from IPython.utils.genutils import get_ipython_dir
42 from IPython.utils.genutils import filefind, get_ipython_dir
41 43
42 44 #-----------------------------------------------------------------------------
43 45 # Utilities and helpers
44 46 #-----------------------------------------------------------------------------
45 47
46 48
47 49 ipython_desc = """
48 50 A Python shell with automatic history (input and output), dynamic object
49 51 introspection, easier configuration, command completion, access to the system
50 52 shell and more.
51 53 """
52 54
53 55 def threaded_shell_warning():
54 56 msg = """
55 57
56 58 The IPython threaded shells and their associated command line
57 59 arguments (pylab/wthread/gthread/qthread/q4thread) have been
58 60 deprecated. See the %gui magic for information on the new interface.
59 61 """
60 62 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
61 63
62 64
63 65 #-----------------------------------------------------------------------------
64 66 # Main classes and functions
65 67 #-----------------------------------------------------------------------------
66 68
67 69 cl_args = (
68 70 (('-autocall',), dict(
69 71 type=int, dest='InteractiveShell.autocall', default=NoConfigDefault,
70 72 help='Set the autocall value (0,1,2).',
71 73 metavar='InteractiveShell.autocall')
72 74 ),
73 75 (('-autoindent',), dict(
74 76 action='store_true', dest='InteractiveShell.autoindent', default=NoConfigDefault,
75 77 help='Turn on autoindenting.')
76 78 ),
77 79 (('-noautoindent',), dict(
78 80 action='store_false', dest='InteractiveShell.autoindent', default=NoConfigDefault,
79 81 help='Turn off autoindenting.')
80 82 ),
81 83 (('-automagic',), dict(
82 84 action='store_true', dest='InteractiveShell.automagic', default=NoConfigDefault,
83 85 help='Turn on the auto calling of magic commands.')
84 86 ),
85 87 (('-noautomagic',), dict(
86 88 action='store_false', dest='InteractiveShell.automagic', default=NoConfigDefault,
87 89 help='Turn off the auto calling of magic commands.')
88 90 ),
89 91 (('-autoedit_syntax',), dict(
90 92 action='store_true', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
91 93 help='Turn on auto editing of files with syntax errors.')
92 94 ),
93 95 (('-noautoedit_syntax',), dict(
94 96 action='store_false', dest='InteractiveShell.autoedit_syntax', default=NoConfigDefault,
95 97 help='Turn off auto editing of files with syntax errors.')
96 98 ),
97 99 (('-banner',), dict(
98 action='store_true', dest='InteractiveShell.display_banner', default=NoConfigDefault,
100 action='store_true', dest='Global.display_banner', default=NoConfigDefault,
99 101 help='Display a banner upon starting IPython.')
100 102 ),
101 103 (('-nobanner',), dict(
102 action='store_false', dest='InteractiveShell.display_banner', default=NoConfigDefault,
104 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
103 105 help="Don't display a banner upon starting IPython.")
104 106 ),
105 107 (('-c',), dict(
106 108 type=str, dest='InteractiveShell.c', default=NoConfigDefault,
107 109 help="Execute the given command string.",
108 110 metavar='InteractiveShell.c')
109 111 ),
110 112 (('-cache_size',), dict(
111 113 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
112 114 help="Set the size of the output cache.",
113 115 metavar='InteractiveShell.cache_size')
114 116 ),
115 117 (('-classic',), dict(
116 118 action='store_true', dest='Global.classic', default=NoConfigDefault,
117 119 help="Gives IPython a similar feel to the classic Python prompt.")
118 120 ),
119 121 (('-colors',), dict(
120 122 type=str, dest='InteractiveShell.colors', default=NoConfigDefault,
121 123 help="Set the color scheme (NoColor, Linux, and LightBG).",
122 124 metavar='InteractiveShell.colors')
123 125 ),
124 126 (('-color_info',), dict(
125 127 action='store_true', dest='InteractiveShell.color_info', default=NoConfigDefault,
126 128 help="Enable using colors for info related things.")
127 129 ),
128 130 (('-nocolor_info',), dict(
129 131 action='store_false', dest='InteractiveShell.color_info', default=NoConfigDefault,
130 132 help="Disable using colors for info related things.")
131 133 ),
132 134 (('-confirm_exit',), dict(
133 135 action='store_true', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
134 136 help="Prompt the user when existing.")
135 137 ),
136 138 (('-noconfirm_exit',), dict(
137 139 action='store_false', dest='InteractiveShell.confirm_exit', default=NoConfigDefault,
138 140 help="Don't prompt the user when existing.")
139 141 ),
140 142 (('-deep_reload',), dict(
141 143 action='store_true', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
142 144 help="Enable deep (recursive) reloading by default.")
143 145 ),
144 146 (('-nodeep_reload',), dict(
145 147 action='store_false', dest='InteractiveShell.deep_reload', default=NoConfigDefault,
146 148 help="Disable deep (recursive) reloading by default.")
147 149 ),
148 150 (('-editor',), dict(
149 151 type=str, dest='InteractiveShell.editor', default=NoConfigDefault,
150 152 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).",
151 153 metavar='InteractiveShell.editor')
152 154 ),
153 155 (('-log','-l'), dict(
154 156 action='store_true', dest='InteractiveShell.logstart', default=NoConfigDefault,
155 157 help="Start logging to the default file (./ipython_log.py).")
156 158 ),
157 159 (('-logfile','-lf'), dict(
158 160 type=str, dest='InteractiveShell.logfile', default=NoConfigDefault,
159 161 help="Specify the name of your logfile.",
160 162 metavar='InteractiveShell.logfile')
161 163 ),
162 164 (('-logplay','-lp'), dict(
163 165 type=str, dest='InteractiveShell.logplay', default=NoConfigDefault,
164 166 help="Re-play a log file and then append to it.",
165 167 metavar='InteractiveShell.logplay')
166 168 ),
167 169 (('-pdb',), dict(
168 170 action='store_true', dest='InteractiveShell.pdb', default=NoConfigDefault,
169 171 help="Enable auto calling the pdb debugger after every exception.")
170 172 ),
171 173 (('-nopdb',), dict(
172 174 action='store_false', dest='InteractiveShell.pdb', default=NoConfigDefault,
173 175 help="Disable auto calling the pdb debugger after every exception.")
174 176 ),
175 177 (('-pprint',), dict(
176 178 action='store_true', dest='InteractiveShell.pprint', default=NoConfigDefault,
177 179 help="Enable auto pretty printing of results.")
178 180 ),
179 181 (('-nopprint',), dict(
180 182 action='store_false', dest='InteractiveShell.pprint', default=NoConfigDefault,
181 183 help="Disable auto auto pretty printing of results.")
182 184 ),
183 185 (('-prompt_in1','-pi1'), dict(
184 186 type=str, dest='InteractiveShell.prompt_in1', default=NoConfigDefault,
185 187 help="Set the main input prompt ('In [\#]: ')",
186 188 metavar='InteractiveShell.prompt_in1')
187 189 ),
188 190 (('-prompt_in2','-pi2'), dict(
189 191 type=str, dest='InteractiveShell.prompt_in2', default=NoConfigDefault,
190 192 help="Set the secondary input prompt (' .\D.: ')",
191 193 metavar='InteractiveShell.prompt_in2')
192 194 ),
193 195 (('-prompt_out','-po'), dict(
194 196 type=str, dest='InteractiveShell.prompt_out', default=NoConfigDefault,
195 197 help="Set the output prompt ('Out[\#]:')",
196 198 metavar='InteractiveShell.prompt_out')
197 199 ),
198 200 (('-quick',), dict(
199 201 action='store_true', dest='Global.quick', default=NoConfigDefault,
200 202 help="Enable quick startup with no config files.")
201 203 ),
202 204 (('-readline',), dict(
203 205 action='store_true', dest='InteractiveShell.readline_use', default=NoConfigDefault,
204 206 help="Enable readline for command line usage.")
205 207 ),
206 208 (('-noreadline',), dict(
207 209 action='store_false', dest='InteractiveShell.readline_use', default=NoConfigDefault,
208 210 help="Disable readline for command line usage.")
209 211 ),
210 212 (('-screen_length','-sl'), dict(
211 213 type=int, dest='InteractiveShell.screen_length', default=NoConfigDefault,
212 214 help='Number of lines on screen, used to control printing of long strings.',
213 215 metavar='InteractiveShell.screen_length')
214 216 ),
215 217 (('-separate_in','-si'), dict(
216 218 type=str, dest='InteractiveShell.separate_in', default=NoConfigDefault,
217 219 help="Separator before input prompts. Default '\n'.",
218 220 metavar='InteractiveShell.separate_in')
219 221 ),
220 222 (('-separate_out','-so'), dict(
221 223 type=str, dest='InteractiveShell.separate_out', default=NoConfigDefault,
222 224 help="Separator before output prompts. Default 0 (nothing).",
223 225 metavar='InteractiveShell.separate_out')
224 226 ),
225 227 (('-separate_out2','-so2'), dict(
226 228 type=str, dest='InteractiveShell.separate_out2', default=NoConfigDefault,
227 229 help="Separator after output prompts. Default 0 (nonight).",
228 230 metavar='InteractiveShell.separate_out2')
229 231 ),
230 232 (('-nosep',), dict(
231 233 action='store_true', dest='Global.nosep', default=NoConfigDefault,
232 234 help="Eliminate all spacing between prompts.")
233 235 ),
234 236 (('-term_title',), dict(
235 237 action='store_true', dest='InteractiveShell.term_title', default=NoConfigDefault,
236 238 help="Enable auto setting the terminal title.")
237 239 ),
238 240 (('-noterm_title',), dict(
239 241 action='store_false', dest='InteractiveShell.term_title', default=NoConfigDefault,
240 242 help="Disable auto setting the terminal title.")
241 243 ),
242 244 (('-xmode',), dict(
243 245 type=str, dest='InteractiveShell.xmode', default=NoConfigDefault,
244 246 help="Exception mode ('Plain','Context','Verbose')",
245 247 metavar='InteractiveShell.xmode')
246 248 ),
249 (('-ext',), dict(
250 type=str, dest='Global.extra_extension', default=NoConfigDefault,
251 help="The dotted module name of an IPython extension to load.",
252 metavar='Global.extra_extension')
253 ),
247 254 # These are only here to get the proper deprecation warnings
248 255 (('-pylab','-wthread','-qthread','-q4thread','-gthread'), dict(
249 256 action='store_true', dest='Global.threaded_shell', default=NoConfigDefault,
250 257 help="These command line flags are deprecated, see the 'gui' magic.")
251 258 ),
252 259 )
253 260
254 261
255 262 class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader):
256 263
257 264 arguments = cl_args
258 265
259 266
260 267 _default_config_file_name = 'ipython_config.py'
261 268
262 269 class IPythonApp(Application):
263 270 name = 'ipython'
264 271 config_file_name = _default_config_file_name
265 272
273 def create_default_config(self):
274 super(IPythonApp, self).create_default_config()
275 self.default_config.Global.display_banner=True
276 # Let the parent class set the default, but each time log_level
277 # changes from config, we need to update self.log_level as that is
278 # what updates the actual log level in self.log.
279 self.default_config.Global.log_level = self.log_level
280
266 281 def create_command_line_config(self):
267 282 """Create and return a command line config loader."""
268 283 return IPythonAppCLConfigLoader(
269 284 description=ipython_desc,
270 285 version=release.version)
271 286
272 287 def post_load_command_line_config(self):
273 288 """Do actions after loading cl config."""
274 289 clc = self.command_line_config
275 290
276 291 # Display the deprecation warnings about threaded shells
277 292 if hasattr(clc.Global, 'threaded_shell'):
278 293 threaded_shell_warning()
279 294 del clc.Global['threaded_shell']
280 295
281 296 def load_file_config(self):
282 297 if hasattr(self.command_line_config.Global, 'quick'):
283 298 if self.command_line_config.Global.quick:
284 299 self.file_config = Config()
285 300 return
286 301 super(IPythonApp, self).load_file_config()
287 302
288 303 def post_load_file_config(self):
289 """Logic goes here."""
304 if hasattr(self.command_line_config.Global, 'extra_extension'):
305 if not hasattr(self.file_config.Global, 'extensions'):
306 self.file_config.Global.extensions = []
307 self.file_config.Global.extensions.append(
308 self.command_line_config.Global.extra_extension)
309 del self.command_line_config.Global.extra_extension
290 310
291 311 def pre_construct(self):
292 312 config = self.master_config
293 313
294 314 if hasattr(config.Global, 'classic'):
295 315 if config.Global.classic:
296 316 config.InteractiveShell.cache_size = 0
297 317 config.InteractiveShell.pprint = 0
298 318 config.InteractiveShell.prompt_in1 = '>>> '
299 319 config.InteractiveShell.prompt_in2 = '... '
300 320 config.InteractiveShell.prompt_out = ''
301 321 config.InteractiveShell.separate_in = \
302 322 config.InteractiveShell.separate_out = \
303 323 config.InteractiveShell.separate_out2 = ''
304 324 config.InteractiveShell.colors = 'NoColor'
305 325 config.InteractiveShell.xmode = 'Plain'
306 326
307 327 # All this should be moved to traitlet handlers in InteractiveShell
308 328 # But, currently InteractiveShell doesn't have support for changing
309 329 # these values at runtime. Once we support that, this should
310 330 # be moved there!!!
311 331 if hasattr(config.Global, 'nosep'):
312 332 if config.Global.nosep:
313 333 config.InteractiveShell.separate_in = \
314 334 config.InteractiveShell.separate_out = \
315 335 config.InteractiveShell.separate_out2 = '0'
316 336
317 337 def construct(self):
318 338 # I am a little hesitant to put these into InteractiveShell itself.
319 339 # But that might be the place for them
320 340 sys.path.insert(0, '')
321 # add personal ipythondir to sys.path so that users can put things in
322 # there for customization
323 sys.path.append(os.path.abspath(self.ipythondir))
324
341
325 342 # Create an InteractiveShell instance
326 343 self.shell = InteractiveShell(
327 344 parent=None,
328 345 config=self.master_config
329 346 )
330
347
348 def post_construct(self):
349 """Do actions after construct, but before starting the app."""
350 # shell.display_banner should always be False for the terminal
351 # based app, because we call shell.show_banner() by hand below
352 # so the banner shows *before* all extension loading stuff.
353 self.shell.display_banner = False
354
355 if self.master_config.Global.display_banner:
356 self.shell.show_banner()
357
358 # Make sure there is a space below the banner.
359 if self.log_level <= logging.INFO: print
360
361 self._load_extensions()
362 self._run_exec_lines()
363 self._run_exec_files()
364
365 def _load_extensions(self):
366 """Load all IPython extensions in Global.extensions.
367
368 This uses the :meth:`InteractiveShell.load_extensions` to load all
369 the extensions listed in ``self.master_config.Global.extensions``.
370 """
371 try:
372 if hasattr(self.master_config.Global, 'extensions'):
373 self.log.debug("Loading IPython extensions...")
374 extensions = self.master_config.Global.extensions
375 for ext in extensions:
376 try:
377 self.log.info("Loading IPython extension: %s" % ext)
378 self.shell.load_extension(ext)
379 except:
380 self.log.warn("Error in loading extension: %s" % ext)
381 self.shell.showtraceback()
382 except:
383 self.log.warn("Unknown error in loading extensions:")
384 self.shell.showtraceback()
385
386 def _run_exec_lines(self):
387 """Run lines of code in Global.exec_lines in the user's namespace."""
388 try:
389 if hasattr(self.master_config.Global, 'exec_lines'):
390 self.log.debug("Running code from Global.exec_lines...")
391 exec_lines = self.master_config.Global.exec_lines
392 for line in exec_lines:
393 try:
394 self.log.info("Running code in user namespace: %s" % line)
395 self.shell.runlines(line)
396 except:
397 self.log.warn("Error in executing line in user namespace: %s" % line)
398 self.shell.showtraceback()
399 except:
400 self.log.warn("Unknown error in handling Global.exec_lines:")
401 self.shell.showtraceback()
402
403 def _run_exec_files(self):
404 try:
405 if hasattr(self.master_config.Global, 'exec_files'):
406 self.log.debug("Running files in Global.exec_files...")
407 exec_files = self.master_config.Global.exec_files
408 for fname in exec_files:
409 full_filename = filefind(fname, ['.', self.ipythondir])
410 if os.path.isfile(full_filename):
411 if full_filename.endswith('.py'):
412 self.log.info("Running file in user namespace: %s" % full_filename)
413 self.shell.safe_execfile(full_filename, self.shell.user_ns)
414 elif full_filename.endswith('.ipy'):
415 self.log.info("Running file in user namespace: %s" % full_filename)
416 self.shell.safe_execfile_ipy(full_filename)
417 else:
418 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
419 except:
420 self.log.warn("Unknown error in handling Global.exec_files:")
421 self.shell.showtraceback()
422
331 423 def start_app(self):
424 self.log.debug("Starting IPython's mainloop...")
332 425 self.shell.mainloop()
333 426
334 427
335 428 def load_default_config(ipythondir=None):
336 429 """Load the default config file from the default ipythondir.
337 430
338 431 This is useful for embedded shells.
339 432 """
340 433 if ipythondir is None:
341 434 ipythondir = get_ipython_dir()
342 435 cl = PyFileConfigLoader(_default_config_file_name, ipythondir)
343 436 config = cl.load_config()
344 437 return config
345 438
346 439
347 440 if __name__ == '__main__':
348 441 app = IPythonApp()
349 442 app.start() No newline at end of file
@@ -1,2495 +1,2480
1 1 # -*- coding: utf-8 -*-
2 2 """
3 3 Main IPython Component
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 9 # Copyright (C) 2008-2009 The IPython Development Team
10 10 #
11 11 # Distributed under the terms of the BSD License. The full license is in
12 12 # the file COPYING, distributed as part of this software.
13 13 #-----------------------------------------------------------------------------
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Imports
17 17 #-----------------------------------------------------------------------------
18 18
19 19 from __future__ import with_statement
20 20
21 21 import __builtin__
22 22 import StringIO
23 23 import bdb
24 24 import codeop
25 25 import exceptions
26 26 import new
27 27 import os
28 28 import re
29 29 import string
30 30 import sys
31 31 import tempfile
32 32 from contextlib import nested
33 33
34 34 from IPython.core import ultratb
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import shadowns
37 37 from IPython.core import history as ipcorehist
38 38 from IPython.core import prefilter
39 39 from IPython.core.alias import AliasManager
40 40 from IPython.core.builtin_trap import BuiltinTrap
41 41 from IPython.core.display_trap import DisplayTrap
42 42 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
43 43 from IPython.core.logger import Logger
44 44 from IPython.core.magic import Magic
45 45 from IPython.core.prompts import CachedOutput
46 46 from IPython.core.prefilter import PrefilterManager
47 47 from IPython.core.component import Component
48 48 from IPython.core.usage import interactive_usage, default_banner
49 49 from IPython.core.error import TryNext, UsageError
50 50
51 51 from IPython.extensions import pickleshare
52 52 from IPython.external.Itpl import ItplNS
53 53 from IPython.lib.backgroundjobs import BackgroundJobManager
54 54 from IPython.utils.ipstruct import Struct
55 55 from IPython.utils import PyColorize
56 56 from IPython.utils.genutils import *
57 57 from IPython.utils.genutils import get_ipython_dir
58 from IPython.utils.strdispatch import StrDispatch
59 58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
59 from IPython.utils.strdispatch import StrDispatch
60 from IPython.utils.syspathcontext import prepended_to_syspath
60 61
61 62 # from IPython.utils import growl
62 63 # growl.start("IPython")
63 64
64 65 from IPython.utils.traitlets import (
65 66 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
66 67 )
67 68
68 69 #-----------------------------------------------------------------------------
69 70 # Globals
70 71 #-----------------------------------------------------------------------------
71 72
72 73
73 74 # store the builtin raw_input globally, and use this always, in case user code
74 75 # overwrites it (like wx.py.PyShell does)
75 76 raw_input_original = raw_input
76 77
77 78 # compiled regexps for autoindent management
78 79 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
79 80
80 81
81 82 #-----------------------------------------------------------------------------
82 83 # Utilities
83 84 #-----------------------------------------------------------------------------
84 85
85 86
86 87 ini_spaces_re = re.compile(r'^(\s+)')
87 88
88 89
89 90 def num_ini_spaces(strng):
90 91 """Return the number of initial spaces in a string"""
91 92
92 93 ini_spaces = ini_spaces_re.match(strng)
93 94 if ini_spaces:
94 95 return ini_spaces.end()
95 96 else:
96 97 return 0
97 98
98 99
99 100 def softspace(file, newvalue):
100 101 """Copied from code.py, to remove the dependency"""
101 102
102 103 oldvalue = 0
103 104 try:
104 105 oldvalue = file.softspace
105 106 except AttributeError:
106 107 pass
107 108 try:
108 109 file.softspace = newvalue
109 110 except (AttributeError, TypeError):
110 111 # "attribute-less object" or "read-only attributes"
111 112 pass
112 113 return oldvalue
113 114
114 115
115 116 class SpaceInInput(exceptions.Exception): pass
116 117
117 118 class Bunch: pass
118 119
119 120 class InputList(list):
120 121 """Class to store user input.
121 122
122 123 It's basically a list, but slices return a string instead of a list, thus
123 124 allowing things like (assuming 'In' is an instance):
124 125
125 126 exec In[4:7]
126 127
127 128 or
128 129
129 130 exec In[5:9] + In[14] + In[21:25]"""
130 131
131 132 def __getslice__(self,i,j):
132 133 return ''.join(list.__getslice__(self,i,j))
133 134
134 135
135 136 class SyntaxTB(ultratb.ListTB):
136 137 """Extension which holds some state: the last exception value"""
137 138
138 139 def __init__(self,color_scheme = 'NoColor'):
139 140 ultratb.ListTB.__init__(self,color_scheme)
140 141 self.last_syntax_error = None
141 142
142 143 def __call__(self, etype, value, elist):
143 144 self.last_syntax_error = value
144 145 ultratb.ListTB.__call__(self,etype,value,elist)
145 146
146 147 def clear_err_state(self):
147 148 """Return the current error state and clear it"""
148 149 e = self.last_syntax_error
149 150 self.last_syntax_error = None
150 151 return e
151 152
152 153
153 154 def get_default_editor():
154 155 try:
155 156 ed = os.environ['EDITOR']
156 157 except KeyError:
157 158 if os.name == 'posix':
158 159 ed = 'vi' # the only one guaranteed to be there!
159 160 else:
160 161 ed = 'notepad' # same in Windows!
161 162 return ed
162 163
163 164
164 165 class SeparateStr(Str):
165 166 """A Str subclass to validate separate_in, separate_out, etc.
166 167
167 168 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
168 169 """
169 170
170 171 def validate(self, obj, value):
171 172 if value == '0': value = ''
172 173 value = value.replace('\\n','\n')
173 174 return super(SeparateStr, self).validate(obj, value)
174 175
175 176
176 177 #-----------------------------------------------------------------------------
177 178 # Main IPython class
178 179 #-----------------------------------------------------------------------------
179 180
180 181
181 182 class InteractiveShell(Component, Magic):
182 183 """An enhanced, interactive shell for Python."""
183 184
184 185 autocall = Enum((0,1,2), config=True)
185 186 autoedit_syntax = CBool(False, config=True)
186 187 autoindent = CBool(True, config=True)
187 188 automagic = CBool(True, config=True)
188 display_banner = CBool(True, config=True)
189 189 banner = Str('')
190 190 banner1 = Str(default_banner, config=True)
191 191 banner2 = Str('', config=True)
192 192 c = Str('', config=True)
193 193 cache_size = Int(1000, config=True)
194 194 color_info = CBool(True, config=True)
195 195 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
196 196 default_value='LightBG', config=True)
197 197 confirm_exit = CBool(True, config=True)
198 198 debug = CBool(False, config=True)
199 199 deep_reload = CBool(False, config=True)
200 # This display_banner only controls whether or not self.show_banner()
201 # is called when mainloop/interact are called. The default is False
202 # because for the terminal based application, the banner behavior
203 # is controlled by Global.display_banner, which IPythonApp looks at
204 # to determine if *it* should call show_banner() by hand or not.
205 display_banner = CBool(False) # This isn't configurable!
200 206 embedded = CBool(False)
201 207 embedded_active = CBool(False)
202 208 editor = Str(get_default_editor(), config=True)
203 209 filename = Str("<ipython console>")
204 210 interactive = CBool(False, config=True)
205 211 ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
206 212 logstart = CBool(False, config=True)
207 213 logfile = Str('', config=True)
208 214 logplay = Str('', config=True)
209 215 object_info_string_level = Enum((0,1,2), default_value=0,
210 216 config=True)
211 217 pager = Str('less', config=True)
212 218 pdb = CBool(False, config=True)
213 219 pprint = CBool(True, config=True)
214 220 profile = Str('', config=True)
215 221 prompt_in1 = Str('In [\\#]: ', config=True)
216 222 prompt_in2 = Str(' .\\D.: ', config=True)
217 223 prompt_out = Str('Out[\\#]: ', config=True)
218 224 prompts_pad_left = CBool(True, config=True)
219 225 quiet = CBool(False, config=True)
220 226
221 227 readline_use = CBool(True, config=True)
222 228 readline_merge_completions = CBool(True, config=True)
223 229 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
224 230 readline_remove_delims = Str('-/~', config=True)
225 231 readline_parse_and_bind = List([
226 232 'tab: complete',
227 233 '"\C-l": possible-completions',
228 234 'set show-all-if-ambiguous on',
229 235 '"\C-o": tab-insert',
230 236 '"\M-i": " "',
231 237 '"\M-o": "\d\d\d\d"',
232 238 '"\M-I": "\d\d\d\d"',
233 239 '"\C-r": reverse-search-history',
234 240 '"\C-s": forward-search-history',
235 241 '"\C-p": history-search-backward',
236 242 '"\C-n": history-search-forward',
237 243 '"\e[A": history-search-backward',
238 244 '"\e[B": history-search-forward',
239 245 '"\C-k": kill-line',
240 246 '"\C-u": unix-line-discard',
241 247 ], allow_none=False, config=True)
242 248
243 249 screen_length = Int(0, config=True)
244 250
245 251 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
246 252 separate_in = SeparateStr('\n', config=True)
247 253 separate_out = SeparateStr('', config=True)
248 254 separate_out2 = SeparateStr('', config=True)
249 255
250 256 system_header = Str('IPython system call: ', config=True)
251 257 system_verbose = CBool(False, config=True)
252 258 term_title = CBool(False, config=True)
253 259 wildcards_case_sensitive = CBool(True, config=True)
254 260 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
255 261 default_value='Context', config=True)
256 262
257 263 autoexec = List(allow_none=False)
258 264
259 265 # class attribute to indicate whether the class supports threads or not.
260 266 # Subclasses with thread support should override this as needed.
261 267 isthreaded = False
262 268
263 269 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
264 270 user_ns=None, user_global_ns=None,
265 banner1=None, banner2=None,
271 banner1=None, banner2=None, display_banner=None,
266 272 custom_exceptions=((),None)):
267 273
268 274 # This is where traitlets with a config_key argument are updated
269 275 # from the values on config.
270 276 super(InteractiveShell, self).__init__(parent, config=config)
271 277
272 278 # These are relatively independent and stateless
273 279 self.init_ipythondir(ipythondir)
274 280 self.init_instance_attrs()
275 281 self.init_term_title()
276 282 self.init_usage(usage)
277 self.init_banner(banner1, banner2)
283 self.init_banner(banner1, banner2, display_banner)
278 284
279 285 # Create namespaces (user_ns, user_global_ns, etc.)
280 286 self.init_create_namespaces(user_ns, user_global_ns)
281 287 # This has to be done after init_create_namespaces because it uses
282 288 # something in self.user_ns, but before init_sys_modules, which
283 289 # is the first thing to modify sys.
284 290 self.save_sys_module_state()
285 291 self.init_sys_modules()
286 292
287 293 self.init_history()
288 294 self.init_encoding()
289 295 self.init_prefilter()
290 296
291 297 Magic.__init__(self, self)
292 298
293 299 self.init_syntax_highlighting()
294 300 self.init_hooks()
295 301 self.init_pushd_popd_magic()
296 302 self.init_traceback_handlers(custom_exceptions)
297 303 self.init_user_ns()
298 304 self.init_logger()
299 305 self.init_alias()
300 306 self.init_builtins()
301 307
302 308 # pre_config_initialization
303 309 self.init_shadow_hist()
304 310
305 311 # The next section should contain averything that was in ipmaker.
306 312 self.init_logstart()
307 313
308 314 # The following was in post_config_initialization
309 315 self.init_inspector()
310 316 self.init_readline()
311 317 self.init_prompts()
312 318 self.init_displayhook()
313 319 self.init_reload_doctest()
314 320 self.init_magics()
315 321 self.init_pdb()
316 322 self.hooks.late_startup_hook()
317 323
318 324 def get_ipython(self):
319 325 return self
320 326
321 327 #-------------------------------------------------------------------------
322 328 # Traitlet changed handlers
323 329 #-------------------------------------------------------------------------
324 330
325 331 def _banner1_changed(self):
326 332 self.compute_banner()
327 333
328 334 def _banner2_changed(self):
329 335 self.compute_banner()
330 336
331 337 def _ipythondir_changed(self, name, new):
332 338 if not os.path.isdir(new):
333 339 os.makedirs(new, mode = 0777)
340 if not os.path.isdir(self.ipython_extension_dir):
341 os.makedirs(self.ipython_extension_dir, mode = 0777)
342
343 @property
344 def ipython_extension_dir(self):
345 return os.path.join(self.ipythondir, 'extensions')
334 346
335 347 @property
336 348 def usable_screen_length(self):
337 349 if self.screen_length == 0:
338 350 return 0
339 351 else:
340 352 num_lines_bot = self.separate_in.count('\n')+1
341 353 return self.screen_length - num_lines_bot
342 354
343 355 def _term_title_changed(self, name, new_value):
344 356 self.init_term_title()
345 357
346 358 def set_autoindent(self,value=None):
347 359 """Set the autoindent flag, checking for readline support.
348 360
349 361 If called with no arguments, it acts as a toggle."""
350 362
351 363 if not self.has_readline:
352 364 if os.name == 'posix':
353 365 warn("The auto-indent feature requires the readline library")
354 366 self.autoindent = 0
355 367 return
356 368 if value is None:
357 369 self.autoindent = not self.autoindent
358 370 else:
359 371 self.autoindent = value
360 372
361 373 #-------------------------------------------------------------------------
362 374 # init_* methods called by __init__
363 375 #-------------------------------------------------------------------------
364 376
365 377 def init_ipythondir(self, ipythondir):
366 378 if ipythondir is not None:
367 379 self.ipythondir = ipythondir
368 380 self.config.Global.ipythondir = self.ipythondir
369 381 return
370 382
371 383 if hasattr(self.config.Global, 'ipythondir'):
372 384 self.ipythondir = self.config.Global.ipythondir
373 385 else:
374 386 self.ipythondir = get_ipython_dir()
375 387
376 388 # All children can just read this
377 389 self.config.Global.ipythondir = self.ipythondir
378 390
379 391 def init_instance_attrs(self):
380 392 self.jobs = BackgroundJobManager()
381 393 self.more = False
382 394
383 395 # command compiler
384 396 self.compile = codeop.CommandCompiler()
385 397
386 398 # User input buffer
387 399 self.buffer = []
388 400
389 401 # Make an empty namespace, which extension writers can rely on both
390 402 # existing and NEVER being used by ipython itself. This gives them a
391 403 # convenient location for storing additional information and state
392 404 # their extensions may require, without fear of collisions with other
393 405 # ipython names that may develop later.
394 406 self.meta = Struct()
395 407
396 408 # Object variable to store code object waiting execution. This is
397 409 # used mainly by the multithreaded shells, but it can come in handy in
398 410 # other situations. No need to use a Queue here, since it's a single
399 411 # item which gets cleared once run.
400 412 self.code_to_run = None
401 413
402 414 # Flag to mark unconditional exit
403 415 self.exit_now = False
404 416
405 417 # Temporary files used for various purposes. Deleted at exit.
406 418 self.tempfiles = []
407 419
408 420 # Keep track of readline usage (later set by init_readline)
409 421 self.has_readline = False
410 422
411 423 # keep track of where we started running (mainly for crash post-mortem)
412 424 # This is not being used anywhere currently.
413 425 self.starting_dir = os.getcwd()
414 426
415 427 # Indentation management
416 428 self.indent_current_nsp = 0
417 429
418 430 def init_term_title(self):
419 431 # Enable or disable the terminal title.
420 432 if self.term_title:
421 433 toggle_set_term_title(True)
422 434 set_term_title('IPython: ' + abbrev_cwd())
423 435 else:
424 436 toggle_set_term_title(False)
425 437
426 438 def init_usage(self, usage=None):
427 439 if usage is None:
428 440 self.usage = interactive_usage
429 441 else:
430 442 self.usage = usage
431 443
432 def init_banner(self, banner1, banner2):
433 if self.c: # regular python doesn't print the banner with -c
434 self.display_banner = False
435 if banner1 is not None:
436 self.banner1 = banner1
437 if banner2 is not None:
438 self.banner2 = banner2
439 self.compute_banner()
440
441 def compute_banner(self):
442 self.banner = self.banner1 + '\n'
443 if self.profile:
444 self.banner += '\nIPython profile: %s\n' % self.profile
445 if self.banner2:
446 self.banner += '\n' + self.banner2 + '\n'
447
448 444 def init_encoding(self):
449 445 # Get system encoding at startup time. Certain terminals (like Emacs
450 446 # under Win32 have it set to None, and we need to have a known valid
451 447 # encoding to use in the raw_input() method
452 448 try:
453 449 self.stdin_encoding = sys.stdin.encoding or 'ascii'
454 450 except AttributeError:
455 451 self.stdin_encoding = 'ascii'
456 452
457 453 def init_syntax_highlighting(self):
458 454 # Python source parser/formatter for syntax highlighting
459 455 pyformat = PyColorize.Parser().format
460 456 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
461 457
462 458 def init_pushd_popd_magic(self):
463 459 # for pushd/popd management
464 460 try:
465 461 self.home_dir = get_home_dir()
466 462 except HomeDirError, msg:
467 463 fatal(msg)
468 464
469 465 self.dir_stack = []
470 466
471 467 def init_logger(self):
472 468 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
473 469 # local shortcut, this is used a LOT
474 470 self.log = self.logger.log
475 471 # template for logfile headers. It gets resolved at runtime by the
476 472 # logstart method.
477 473 self.loghead_tpl = \
478 474 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
479 475 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
480 476 #log# opts = %s
481 477 #log# args = %s
482 478 #log# It is safe to make manual edits below here.
483 479 #log#-----------------------------------------------------------------------
484 480 """
485 481
486 482 def init_logstart(self):
487 483 if self.logplay:
488 484 self.magic_logstart(self.logplay + ' append')
489 elif self.logfile:
485 elif self.logfile:
490 486 self.magic_logstart(self.logfile)
491 487 elif self.logstart:
492 488 self.magic_logstart()
493 489
494 490 def init_builtins(self):
495 491 self.builtin_trap = BuiltinTrap(self)
496 492
497 493 def init_inspector(self):
498 494 # Object inspector
499 495 self.inspector = oinspect.Inspector(oinspect.InspectColors,
500 496 PyColorize.ANSICodeColors,
501 497 'NoColor',
502 498 self.object_info_string_level)
503 499
504 500 def init_prompts(self):
505 501 # Initialize cache, set in/out prompts and printing system
506 502 self.outputcache = CachedOutput(self,
507 503 self.cache_size,
508 504 self.pprint,
509 505 input_sep = self.separate_in,
510 506 output_sep = self.separate_out,
511 507 output_sep2 = self.separate_out2,
512 508 ps1 = self.prompt_in1,
513 509 ps2 = self.prompt_in2,
514 510 ps_out = self.prompt_out,
515 511 pad_left = self.prompts_pad_left)
516 512
517 513 # user may have over-ridden the default print hook:
518 514 try:
519 515 self.outputcache.__class__.display = self.hooks.display
520 516 except AttributeError:
521 517 pass
522 518
523 519 def init_displayhook(self):
524 520 self.display_trap = DisplayTrap(self, self.outputcache)
525 521
526 522 def init_reload_doctest(self):
527 523 # Do a proper resetting of doctest, including the necessary displayhook
528 524 # monkeypatching
529 525 try:
530 526 doctest_reload()
531 527 except ImportError:
532 528 warn("doctest module does not exist.")
533 529
534 530 #-------------------------------------------------------------------------
531 # Things related to the banner
532 #-------------------------------------------------------------------------
533
534 def init_banner(self, banner1, banner2, display_banner):
535 if banner1 is not None:
536 self.banner1 = banner1
537 if banner2 is not None:
538 self.banner2 = banner2
539 if display_banner is not None:
540 self.display_banner = display_banner
541 self.compute_banner()
542
543 def show_banner(self, banner=None):
544 if banner is None:
545 banner = self.banner
546 self.write(banner)
547
548 def compute_banner(self):
549 self.banner = self.banner1 + '\n'
550 if self.profile:
551 self.banner += '\nIPython profile: %s\n' % self.profile
552 if self.banner2:
553 self.banner += '\n' + self.banner2 + '\n'
554
555 #-------------------------------------------------------------------------
535 556 # Things related to injections into the sys module
536 557 #-------------------------------------------------------------------------
537 558
538 559 def save_sys_module_state(self):
539 560 """Save the state of hooks in the sys module.
540 561
541 562 This has to be called after self.user_ns is created.
542 563 """
543 564 self._orig_sys_module_state = {}
544 565 self._orig_sys_module_state['stdin'] = sys.stdin
545 566 self._orig_sys_module_state['stdout'] = sys.stdout
546 567 self._orig_sys_module_state['stderr'] = sys.stderr
547 568 self._orig_sys_module_state['excepthook'] = sys.excepthook
548 569 try:
549 570 self._orig_sys_modules_main_name = self.user_ns['__name__']
550 571 except KeyError:
551 572 pass
552 573
553 574 def restore_sys_module_state(self):
554 575 """Restore the state of the sys module."""
555 576 try:
556 577 for k, v in self._orig_sys_module_state.items():
557 578 setattr(sys, k, v)
558 579 except AttributeError:
559 580 pass
560 581 try:
561 582 delattr(sys, 'ipcompleter')
562 583 except AttributeError:
563 584 pass
564 585 # Reset what what done in self.init_sys_modules
565 586 try:
566 587 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
567 588 except (AttributeError, KeyError):
568 589 pass
569 590
570 591 #-------------------------------------------------------------------------
571 592 # Things related to hooks
572 593 #-------------------------------------------------------------------------
573 594
574 595 def init_hooks(self):
575 596 # hooks holds pointers used for user-side customizations
576 597 self.hooks = Struct()
577 598
578 599 self.strdispatchers = {}
579 600
580 601 # Set all default hooks, defined in the IPython.hooks module.
581 602 import IPython.core.hooks
582 603 hooks = IPython.core.hooks
583 604 for hook_name in hooks.__all__:
584 605 # default hooks have priority 100, i.e. low; user hooks should have
585 606 # 0-100 priority
586 607 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
587 608
588 609 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
589 610 """set_hook(name,hook) -> sets an internal IPython hook.
590 611
591 612 IPython exposes some of its internal API as user-modifiable hooks. By
592 613 adding your function to one of these hooks, you can modify IPython's
593 614 behavior to call at runtime your own routines."""
594 615
595 616 # At some point in the future, this should validate the hook before it
596 617 # accepts it. Probably at least check that the hook takes the number
597 618 # of args it's supposed to.
598 619
599 620 f = new.instancemethod(hook,self,self.__class__)
600 621
601 622 # check if the hook is for strdispatcher first
602 623 if str_key is not None:
603 624 sdp = self.strdispatchers.get(name, StrDispatch())
604 625 sdp.add_s(str_key, f, priority )
605 626 self.strdispatchers[name] = sdp
606 627 return
607 628 if re_key is not None:
608 629 sdp = self.strdispatchers.get(name, StrDispatch())
609 630 sdp.add_re(re.compile(re_key), f, priority )
610 631 self.strdispatchers[name] = sdp
611 632 return
612 633
613 634 dp = getattr(self.hooks, name, None)
614 635 if name not in IPython.core.hooks.__all__:
615 636 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
616 637 if not dp:
617 638 dp = IPython.core.hooks.CommandChainDispatcher()
618 639
619 640 try:
620 641 dp.add(f,priority)
621 642 except AttributeError:
622 643 # it was not commandchain, plain old func - replace
623 644 dp = f
624 645
625 646 setattr(self.hooks,name, dp)
626 647
627 648 #-------------------------------------------------------------------------
628 649 # Things related to the "main" module
629 650 #-------------------------------------------------------------------------
630 651
631 652 def new_main_mod(self,ns=None):
632 653 """Return a new 'main' module object for user code execution.
633 654 """
634 655 main_mod = self._user_main_module
635 656 init_fakemod_dict(main_mod,ns)
636 657 return main_mod
637 658
638 659 def cache_main_mod(self,ns,fname):
639 660 """Cache a main module's namespace.
640 661
641 662 When scripts are executed via %run, we must keep a reference to the
642 663 namespace of their __main__ module (a FakeModule instance) around so
643 664 that Python doesn't clear it, rendering objects defined therein
644 665 useless.
645 666
646 667 This method keeps said reference in a private dict, keyed by the
647 668 absolute path of the module object (which corresponds to the script
648 669 path). This way, for multiple executions of the same script we only
649 670 keep one copy of the namespace (the last one), thus preventing memory
650 671 leaks from old references while allowing the objects from the last
651 672 execution to be accessible.
652 673
653 674 Note: we can not allow the actual FakeModule instances to be deleted,
654 675 because of how Python tears down modules (it hard-sets all their
655 676 references to None without regard for reference counts). This method
656 677 must therefore make a *copy* of the given namespace, to allow the
657 678 original module's __dict__ to be cleared and reused.
658 679
659 680
660 681 Parameters
661 682 ----------
662 683 ns : a namespace (a dict, typically)
663 684
664 685 fname : str
665 686 Filename associated with the namespace.
666 687
667 688 Examples
668 689 --------
669 690
670 691 In [10]: import IPython
671 692
672 693 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
673 694
674 695 In [12]: IPython.__file__ in _ip._main_ns_cache
675 696 Out[12]: True
676 697 """
677 698 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
678 699
679 700 def clear_main_mod_cache(self):
680 701 """Clear the cache of main modules.
681 702
682 703 Mainly for use by utilities like %reset.
683 704
684 705 Examples
685 706 --------
686 707
687 708 In [15]: import IPython
688 709
689 710 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
690 711
691 712 In [17]: len(_ip._main_ns_cache) > 0
692 713 Out[17]: True
693 714
694 715 In [18]: _ip.clear_main_mod_cache()
695 716
696 717 In [19]: len(_ip._main_ns_cache) == 0
697 718 Out[19]: True
698 719 """
699 720 self._main_ns_cache.clear()
700 721
701 722 #-------------------------------------------------------------------------
702 723 # Things related to debugging
703 724 #-------------------------------------------------------------------------
704 725
705 726 def init_pdb(self):
706 727 # Set calling of pdb on exceptions
707 728 # self.call_pdb is a property
708 729 self.call_pdb = self.pdb
709 730
710 731 def _get_call_pdb(self):
711 732 return self._call_pdb
712 733
713 734 def _set_call_pdb(self,val):
714 735
715 736 if val not in (0,1,False,True):
716 737 raise ValueError,'new call_pdb value must be boolean'
717 738
718 739 # store value in instance
719 740 self._call_pdb = val
720 741
721 742 # notify the actual exception handlers
722 743 self.InteractiveTB.call_pdb = val
723 744 if self.isthreaded:
724 745 try:
725 746 self.sys_excepthook.call_pdb = val
726 747 except:
727 748 warn('Failed to activate pdb for threaded exception handler')
728 749
729 750 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
730 751 'Control auto-activation of pdb at exceptions')
731 752
732 753 def debugger(self,force=False):
733 754 """Call the pydb/pdb debugger.
734 755
735 756 Keywords:
736 757
737 758 - force(False): by default, this routine checks the instance call_pdb
738 759 flag and does not actually invoke the debugger if the flag is false.
739 760 The 'force' option forces the debugger to activate even if the flag
740 761 is false.
741 762 """
742 763
743 764 if not (force or self.call_pdb):
744 765 return
745 766
746 767 if not hasattr(sys,'last_traceback'):
747 768 error('No traceback has been produced, nothing to debug.')
748 769 return
749 770
750 771 # use pydb if available
751 772 if debugger.has_pydb:
752 773 from pydb import pm
753 774 else:
754 775 # fallback to our internal debugger
755 776 pm = lambda : self.InteractiveTB.debugger(force=True)
756 777 self.history_saving_wrapper(pm)()
757 778
758 779 #-------------------------------------------------------------------------
759 780 # Things related to IPython's various namespaces
760 781 #-------------------------------------------------------------------------
761 782
762 783 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
763 784 # Create the namespace where the user will operate. user_ns is
764 785 # normally the only one used, and it is passed to the exec calls as
765 786 # the locals argument. But we do carry a user_global_ns namespace
766 787 # given as the exec 'globals' argument, This is useful in embedding
767 788 # situations where the ipython shell opens in a context where the
768 789 # distinction between locals and globals is meaningful. For
769 790 # non-embedded contexts, it is just the same object as the user_ns dict.
770 791
771 792 # FIXME. For some strange reason, __builtins__ is showing up at user
772 793 # level as a dict instead of a module. This is a manual fix, but I
773 794 # should really track down where the problem is coming from. Alex
774 795 # Schmolck reported this problem first.
775 796
776 797 # A useful post by Alex Martelli on this topic:
777 798 # Re: inconsistent value from __builtins__
778 799 # Von: Alex Martelli <aleaxit@yahoo.com>
779 800 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
780 801 # Gruppen: comp.lang.python
781 802
782 803 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
783 804 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
784 805 # > <type 'dict'>
785 806 # > >>> print type(__builtins__)
786 807 # > <type 'module'>
787 808 # > Is this difference in return value intentional?
788 809
789 810 # Well, it's documented that '__builtins__' can be either a dictionary
790 811 # or a module, and it's been that way for a long time. Whether it's
791 812 # intentional (or sensible), I don't know. In any case, the idea is
792 813 # that if you need to access the built-in namespace directly, you
793 814 # should start with "import __builtin__" (note, no 's') which will
794 815 # definitely give you a module. Yeah, it's somewhat confusing:-(.
795 816
796 817 # These routines return properly built dicts as needed by the rest of
797 818 # the code, and can also be used by extension writers to generate
798 819 # properly initialized namespaces.
799 820 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
800 821 user_global_ns)
801 822
802 823 # Assign namespaces
803 824 # This is the namespace where all normal user variables live
804 825 self.user_ns = user_ns
805 826 self.user_global_ns = user_global_ns
806 827
807 828 # An auxiliary namespace that checks what parts of the user_ns were
808 829 # loaded at startup, so we can list later only variables defined in
809 830 # actual interactive use. Since it is always a subset of user_ns, it
810 831 # doesn't need to be seaparately tracked in the ns_table
811 832 self.user_config_ns = {}
812 833
813 834 # A namespace to keep track of internal data structures to prevent
814 835 # them from cluttering user-visible stuff. Will be updated later
815 836 self.internal_ns = {}
816 837
817 838 # Now that FakeModule produces a real module, we've run into a nasty
818 839 # problem: after script execution (via %run), the module where the user
819 840 # code ran is deleted. Now that this object is a true module (needed
820 841 # so docetst and other tools work correctly), the Python module
821 842 # teardown mechanism runs over it, and sets to None every variable
822 843 # present in that module. Top-level references to objects from the
823 844 # script survive, because the user_ns is updated with them. However,
824 845 # calling functions defined in the script that use other things from
825 846 # the script will fail, because the function's closure had references
826 847 # to the original objects, which are now all None. So we must protect
827 848 # these modules from deletion by keeping a cache.
828 849 #
829 850 # To avoid keeping stale modules around (we only need the one from the
830 851 # last run), we use a dict keyed with the full path to the script, so
831 852 # only the last version of the module is held in the cache. Note,
832 853 # however, that we must cache the module *namespace contents* (their
833 854 # __dict__). Because if we try to cache the actual modules, old ones
834 855 # (uncached) could be destroyed while still holding references (such as
835 856 # those held by GUI objects that tend to be long-lived)>
836 857 #
837 858 # The %reset command will flush this cache. See the cache_main_mod()
838 859 # and clear_main_mod_cache() methods for details on use.
839 860
840 861 # This is the cache used for 'main' namespaces
841 862 self._main_ns_cache = {}
842 863 # And this is the single instance of FakeModule whose __dict__ we keep
843 864 # copying and clearing for reuse on each %run
844 865 self._user_main_module = FakeModule()
845 866
846 867 # A table holding all the namespaces IPython deals with, so that
847 868 # introspection facilities can search easily.
848 869 self.ns_table = {'user':user_ns,
849 870 'user_global':user_global_ns,
850 871 'internal':self.internal_ns,
851 872 'builtin':__builtin__.__dict__
852 873 }
853 874
854 875 # Similarly, track all namespaces where references can be held and that
855 876 # we can safely clear (so it can NOT include builtin). This one can be
856 877 # a simple list.
857 878 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
858 879 self.internal_ns, self._main_ns_cache ]
859 880
860 881 def init_sys_modules(self):
861 882 # We need to insert into sys.modules something that looks like a
862 883 # module but which accesses the IPython namespace, for shelve and
863 884 # pickle to work interactively. Normally they rely on getting
864 885 # everything out of __main__, but for embedding purposes each IPython
865 886 # instance has its own private namespace, so we can't go shoving
866 887 # everything into __main__.
867 888
868 889 # note, however, that we should only do this for non-embedded
869 890 # ipythons, which really mimic the __main__.__dict__ with their own
870 891 # namespace. Embedded instances, on the other hand, should not do
871 892 # this because they need to manage the user local/global namespaces
872 893 # only, but they live within a 'normal' __main__ (meaning, they
873 894 # shouldn't overtake the execution environment of the script they're
874 895 # embedded in).
875 896
876 897 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
877 898
878 899 try:
879 900 main_name = self.user_ns['__name__']
880 901 except KeyError:
881 902 raise KeyError('user_ns dictionary MUST have a "__name__" key')
882 903 else:
883 904 sys.modules[main_name] = FakeModule(self.user_ns)
884 905
885 906 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
886 907 """Return a valid local and global user interactive namespaces.
887 908
888 909 This builds a dict with the minimal information needed to operate as a
889 910 valid IPython user namespace, which you can pass to the various
890 911 embedding classes in ipython. The default implementation returns the
891 912 same dict for both the locals and the globals to allow functions to
892 913 refer to variables in the namespace. Customized implementations can
893 914 return different dicts. The locals dictionary can actually be anything
894 915 following the basic mapping protocol of a dict, but the globals dict
895 916 must be a true dict, not even a subclass. It is recommended that any
896 917 custom object for the locals namespace synchronize with the globals
897 918 dict somehow.
898 919
899 920 Raises TypeError if the provided globals namespace is not a true dict.
900 921
901 922 :Parameters:
902 923 user_ns : dict-like, optional
903 924 The current user namespace. The items in this namespace should
904 925 be included in the output. If None, an appropriate blank
905 926 namespace should be created.
906 927 user_global_ns : dict, optional
907 928 The current user global namespace. The items in this namespace
908 929 should be included in the output. If None, an appropriate
909 930 blank namespace should be created.
910 931
911 932 :Returns:
912 933 A tuple pair of dictionary-like object to be used as the local namespace
913 934 of the interpreter and a dict to be used as the global namespace.
914 935 """
915 936
916 937 if user_ns is None:
917 938 # Set __name__ to __main__ to better match the behavior of the
918 939 # normal interpreter.
919 940 user_ns = {'__name__' :'__main__',
920 941 '__builtins__' : __builtin__,
921 942 }
922 943 else:
923 944 user_ns.setdefault('__name__','__main__')
924 945 user_ns.setdefault('__builtins__',__builtin__)
925 946
926 947 if user_global_ns is None:
927 948 user_global_ns = user_ns
928 949 if type(user_global_ns) is not dict:
929 950 raise TypeError("user_global_ns must be a true dict; got %r"
930 951 % type(user_global_ns))
931 952
932 953 return user_ns, user_global_ns
933 954
934 955 def init_user_ns(self):
935 956 """Initialize all user-visible namespaces to their minimum defaults.
936 957
937 958 Certain history lists are also initialized here, as they effectively
938 959 act as user namespaces.
939 960
940 961 Notes
941 962 -----
942 963 All data structures here are only filled in, they are NOT reset by this
943 964 method. If they were not empty before, data will simply be added to
944 965 therm.
945 966 """
946 967 # Store myself as the public api!!!
947 968 self.user_ns['get_ipython'] = self.get_ipython
948 969
949 970 # make global variables for user access to the histories
950 971 self.user_ns['_ih'] = self.input_hist
951 972 self.user_ns['_oh'] = self.output_hist
952 973 self.user_ns['_dh'] = self.dir_hist
953 974
954 975 # user aliases to input and output histories
955 976 self.user_ns['In'] = self.input_hist
956 977 self.user_ns['Out'] = self.output_hist
957 978
958 979 self.user_ns['_sh'] = shadowns
959 980
960 981 # Put 'help' in the user namespace
961 982 try:
962 983 from site import _Helper
963 984 self.user_ns['help'] = _Helper()
964 985 except ImportError:
965 986 warn('help() not available - check site.py')
966 987
967 988 def reset(self):
968 989 """Clear all internal namespaces.
969 990
970 991 Note that this is much more aggressive than %reset, since it clears
971 992 fully all namespaces, as well as all input/output lists.
972 993 """
973 994 for ns in self.ns_refs_table:
974 995 ns.clear()
975 996
976 997 self.alias_manager.clear_aliases()
977 998
978 999 # Clear input and output histories
979 1000 self.input_hist[:] = []
980 1001 self.input_hist_raw[:] = []
981 1002 self.output_hist.clear()
982 1003
983 1004 # Restore the user namespaces to minimal usability
984 1005 self.init_user_ns()
985 1006
986 1007 # Restore the default and user aliases
987 1008 self.alias_manager.init_aliases()
988 1009
989 1010 def push(self, variables, interactive=True):
990 1011 """Inject a group of variables into the IPython user namespace.
991 1012
992 1013 Parameters
993 1014 ----------
994 1015 variables : dict, str or list/tuple of str
995 1016 The variables to inject into the user's namespace. If a dict,
996 1017 a simple update is done. If a str, the string is assumed to
997 1018 have variable names separated by spaces. A list/tuple of str
998 1019 can also be used to give the variable names. If just the variable
999 1020 names are give (list/tuple/str) then the variable values looked
1000 1021 up in the callers frame.
1001 1022 interactive : bool
1002 1023 If True (default), the variables will be listed with the ``who``
1003 1024 magic.
1004 1025 """
1005 1026 vdict = None
1006 1027
1007 1028 # We need a dict of name/value pairs to do namespace updates.
1008 1029 if isinstance(variables, dict):
1009 1030 vdict = variables
1010 1031 elif isinstance(variables, (basestring, list, tuple)):
1011 1032 if isinstance(variables, basestring):
1012 1033 vlist = variables.split()
1013 1034 else:
1014 1035 vlist = variables
1015 1036 vdict = {}
1016 1037 cf = sys._getframe(1)
1017 1038 for name in vlist:
1018 1039 try:
1019 1040 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1020 1041 except:
1021 1042 print ('Could not get variable %s from %s' %
1022 1043 (name,cf.f_code.co_name))
1023 1044 else:
1024 1045 raise ValueError('variables must be a dict/str/list/tuple')
1025 1046
1026 1047 # Propagate variables to user namespace
1027 1048 self.user_ns.update(vdict)
1028 1049
1029 1050 # And configure interactive visibility
1030 1051 config_ns = self.user_config_ns
1031 1052 if interactive:
1032 1053 for name, val in vdict.iteritems():
1033 1054 config_ns.pop(name, None)
1034 1055 else:
1035 1056 for name,val in vdict.iteritems():
1036 1057 config_ns[name] = val
1037 1058
1038 1059 #-------------------------------------------------------------------------
1039 1060 # Things related to history management
1040 1061 #-------------------------------------------------------------------------
1041 1062
1042 1063 def init_history(self):
1043 1064 # List of input with multi-line handling.
1044 1065 self.input_hist = InputList()
1045 1066 # This one will hold the 'raw' input history, without any
1046 1067 # pre-processing. This will allow users to retrieve the input just as
1047 1068 # it was exactly typed in by the user, with %hist -r.
1048 1069 self.input_hist_raw = InputList()
1049 1070
1050 1071 # list of visited directories
1051 1072 try:
1052 1073 self.dir_hist = [os.getcwd()]
1053 1074 except OSError:
1054 1075 self.dir_hist = []
1055 1076
1056 1077 # dict of output history
1057 1078 self.output_hist = {}
1058 1079
1059 1080 # Now the history file
1060 1081 if self.profile:
1061 1082 histfname = 'history-%s' % self.profile
1062 1083 else:
1063 1084 histfname = 'history'
1064 1085 self.histfile = os.path.join(self.ipythondir, histfname)
1065 1086
1066 1087 # Fill the history zero entry, user counter starts at 1
1067 1088 self.input_hist.append('\n')
1068 1089 self.input_hist_raw.append('\n')
1069 1090
1070 1091 def init_shadow_hist(self):
1071 1092 try:
1072 1093 self.db = pickleshare.PickleShareDB(self.ipythondir + "/db")
1073 1094 except exceptions.UnicodeDecodeError:
1074 1095 print "Your ipythondir can't be decoded to unicode!"
1075 1096 print "Please set HOME environment variable to something that"
1076 1097 print r"only has ASCII characters, e.g. c:\home"
1077 1098 print "Now it is", self.ipythondir
1078 1099 sys.exit()
1079 1100 self.shadowhist = ipcorehist.ShadowHist(self.db)
1080 1101
1081 1102 def savehist(self):
1082 1103 """Save input history to a file (via readline library)."""
1083 1104
1084 1105 if not self.has_readline:
1085 1106 return
1086 1107
1087 1108 try:
1088 1109 self.readline.write_history_file(self.histfile)
1089 1110 except:
1090 1111 print 'Unable to save IPython command history to file: ' + \
1091 1112 `self.histfile`
1092 1113
1093 1114 def reloadhist(self):
1094 1115 """Reload the input history from disk file."""
1095 1116
1096 1117 if self.has_readline:
1097 1118 try:
1098 1119 self.readline.clear_history()
1099 1120 self.readline.read_history_file(self.shell.histfile)
1100 1121 except AttributeError:
1101 1122 pass
1102 1123
1103 1124 def history_saving_wrapper(self, func):
1104 1125 """ Wrap func for readline history saving
1105 1126
1106 1127 Convert func into callable that saves & restores
1107 1128 history around the call """
1108 1129
1109 1130 if not self.has_readline:
1110 1131 return func
1111 1132
1112 1133 def wrapper():
1113 1134 self.savehist()
1114 1135 try:
1115 1136 func()
1116 1137 finally:
1117 1138 readline.read_history_file(self.histfile)
1118 1139 return wrapper
1119 1140
1120 1141 #-------------------------------------------------------------------------
1121 1142 # Things related to exception handling and tracebacks (not debugging)
1122 1143 #-------------------------------------------------------------------------
1123 1144
1124 1145 def init_traceback_handlers(self, custom_exceptions):
1125 1146 # Syntax error handler.
1126 1147 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1127 1148
1128 1149 # The interactive one is initialized with an offset, meaning we always
1129 1150 # want to remove the topmost item in the traceback, which is our own
1130 1151 # internal code. Valid modes: ['Plain','Context','Verbose']
1131 1152 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1132 1153 color_scheme='NoColor',
1133 1154 tb_offset = 1)
1134 1155
1135 1156 # IPython itself shouldn't crash. This will produce a detailed
1136 1157 # post-mortem if it does. But we only install the crash handler for
1137 1158 # non-threaded shells, the threaded ones use a normal verbose reporter
1138 1159 # and lose the crash handler. This is because exceptions in the main
1139 1160 # thread (such as in GUI code) propagate directly to sys.excepthook,
1140 1161 # and there's no point in printing crash dumps for every user exception.
1141 1162 if self.isthreaded:
1142 1163 ipCrashHandler = ultratb.FormattedTB()
1143 1164 else:
1144 1165 from IPython.core import crashhandler
1145 1166 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1146 1167 self.set_crash_handler(ipCrashHandler)
1147 1168
1148 1169 # and add any custom exception handlers the user may have specified
1149 1170 self.set_custom_exc(*custom_exceptions)
1150 1171
1151 1172 def set_crash_handler(self, crashHandler):
1152 1173 """Set the IPython crash handler.
1153 1174
1154 1175 This must be a callable with a signature suitable for use as
1155 1176 sys.excepthook."""
1156 1177
1157 1178 # Install the given crash handler as the Python exception hook
1158 1179 sys.excepthook = crashHandler
1159 1180
1160 1181 # The instance will store a pointer to this, so that runtime code
1161 1182 # (such as magics) can access it. This is because during the
1162 1183 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1163 1184 # frameworks).
1164 1185 self.sys_excepthook = sys.excepthook
1165 1186
1166 1187 def set_custom_exc(self,exc_tuple,handler):
1167 1188 """set_custom_exc(exc_tuple,handler)
1168 1189
1169 1190 Set a custom exception handler, which will be called if any of the
1170 1191 exceptions in exc_tuple occur in the mainloop (specifically, in the
1171 1192 runcode() method.
1172 1193
1173 1194 Inputs:
1174 1195
1175 1196 - exc_tuple: a *tuple* of valid exceptions to call the defined
1176 1197 handler for. It is very important that you use a tuple, and NOT A
1177 1198 LIST here, because of the way Python's except statement works. If
1178 1199 you only want to trap a single exception, use a singleton tuple:
1179 1200
1180 1201 exc_tuple == (MyCustomException,)
1181 1202
1182 1203 - handler: this must be defined as a function with the following
1183 1204 basic interface: def my_handler(self,etype,value,tb).
1184 1205
1185 1206 This will be made into an instance method (via new.instancemethod)
1186 1207 of IPython itself, and it will be called if any of the exceptions
1187 1208 listed in the exc_tuple are caught. If the handler is None, an
1188 1209 internal basic one is used, which just prints basic info.
1189 1210
1190 1211 WARNING: by putting in your own exception handler into IPython's main
1191 1212 execution loop, you run a very good chance of nasty crashes. This
1192 1213 facility should only be used if you really know what you are doing."""
1193 1214
1194 1215 assert type(exc_tuple)==type(()) , \
1195 1216 "The custom exceptions must be given AS A TUPLE."
1196 1217
1197 1218 def dummy_handler(self,etype,value,tb):
1198 1219 print '*** Simple custom exception handler ***'
1199 1220 print 'Exception type :',etype
1200 1221 print 'Exception value:',value
1201 1222 print 'Traceback :',tb
1202 1223 print 'Source code :','\n'.join(self.buffer)
1203 1224
1204 1225 if handler is None: handler = dummy_handler
1205 1226
1206 1227 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1207 1228 self.custom_exceptions = exc_tuple
1208 1229
1209 1230 def excepthook(self, etype, value, tb):
1210 1231 """One more defense for GUI apps that call sys.excepthook.
1211 1232
1212 1233 GUI frameworks like wxPython trap exceptions and call
1213 1234 sys.excepthook themselves. I guess this is a feature that
1214 1235 enables them to keep running after exceptions that would
1215 1236 otherwise kill their mainloop. This is a bother for IPython
1216 1237 which excepts to catch all of the program exceptions with a try:
1217 1238 except: statement.
1218 1239
1219 1240 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1220 1241 any app directly invokes sys.excepthook, it will look to the user like
1221 1242 IPython crashed. In order to work around this, we can disable the
1222 1243 CrashHandler and replace it with this excepthook instead, which prints a
1223 1244 regular traceback using our InteractiveTB. In this fashion, apps which
1224 1245 call sys.excepthook will generate a regular-looking exception from
1225 1246 IPython, and the CrashHandler will only be triggered by real IPython
1226 1247 crashes.
1227 1248
1228 1249 This hook should be used sparingly, only in places which are not likely
1229 1250 to be true IPython errors.
1230 1251 """
1231 1252 self.showtraceback((etype,value,tb),tb_offset=0)
1232 1253
1233 1254 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1234 1255 """Display the exception that just occurred.
1235 1256
1236 1257 If nothing is known about the exception, this is the method which
1237 1258 should be used throughout the code for presenting user tracebacks,
1238 1259 rather than directly invoking the InteractiveTB object.
1239 1260
1240 1261 A specific showsyntaxerror() also exists, but this method can take
1241 1262 care of calling it if needed, so unless you are explicitly catching a
1242 1263 SyntaxError exception, don't try to analyze the stack manually and
1243 1264 simply call this method."""
1244 1265
1245 1266
1246 1267 # Though this won't be called by syntax errors in the input line,
1247 1268 # there may be SyntaxError cases whith imported code.
1248 1269
1249 1270 try:
1250 1271 if exc_tuple is None:
1251 1272 etype, value, tb = sys.exc_info()
1252 1273 else:
1253 1274 etype, value, tb = exc_tuple
1254 1275
1255 1276 if etype is SyntaxError:
1256 1277 self.showsyntaxerror(filename)
1257 1278 elif etype is UsageError:
1258 1279 print "UsageError:", value
1259 1280 else:
1260 1281 # WARNING: these variables are somewhat deprecated and not
1261 1282 # necessarily safe to use in a threaded environment, but tools
1262 1283 # like pdb depend on their existence, so let's set them. If we
1263 1284 # find problems in the field, we'll need to revisit their use.
1264 1285 sys.last_type = etype
1265 1286 sys.last_value = value
1266 1287 sys.last_traceback = tb
1267 1288
1268 1289 if etype in self.custom_exceptions:
1269 1290 self.CustomTB(etype,value,tb)
1270 1291 else:
1271 1292 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1272 1293 if self.InteractiveTB.call_pdb and self.has_readline:
1273 1294 # pdb mucks up readline, fix it back
1274 1295 self.set_completer()
1275 1296 except KeyboardInterrupt:
1276 1297 self.write("\nKeyboardInterrupt\n")
1277 1298
1278 1299 def showsyntaxerror(self, filename=None):
1279 1300 """Display the syntax error that just occurred.
1280 1301
1281 1302 This doesn't display a stack trace because there isn't one.
1282 1303
1283 1304 If a filename is given, it is stuffed in the exception instead
1284 1305 of what was there before (because Python's parser always uses
1285 1306 "<string>" when reading from a string).
1286 1307 """
1287 1308 etype, value, last_traceback = sys.exc_info()
1288 1309
1289 1310 # See note about these variables in showtraceback() below
1290 1311 sys.last_type = etype
1291 1312 sys.last_value = value
1292 1313 sys.last_traceback = last_traceback
1293 1314
1294 1315 if filename and etype is SyntaxError:
1295 1316 # Work hard to stuff the correct filename in the exception
1296 1317 try:
1297 1318 msg, (dummy_filename, lineno, offset, line) = value
1298 1319 except:
1299 1320 # Not the format we expect; leave it alone
1300 1321 pass
1301 1322 else:
1302 1323 # Stuff in the right filename
1303 1324 try:
1304 1325 # Assume SyntaxError is a class exception
1305 1326 value = SyntaxError(msg, (filename, lineno, offset, line))
1306 1327 except:
1307 1328 # If that failed, assume SyntaxError is a string
1308 1329 value = msg, (filename, lineno, offset, line)
1309 1330 self.SyntaxTB(etype,value,[])
1310 1331
1311 1332 def edit_syntax_error(self):
1312 1333 """The bottom half of the syntax error handler called in the main loop.
1313 1334
1314 1335 Loop until syntax error is fixed or user cancels.
1315 1336 """
1316 1337
1317 1338 while self.SyntaxTB.last_syntax_error:
1318 1339 # copy and clear last_syntax_error
1319 1340 err = self.SyntaxTB.clear_err_state()
1320 1341 if not self._should_recompile(err):
1321 1342 return
1322 1343 try:
1323 1344 # may set last_syntax_error again if a SyntaxError is raised
1324 1345 self.safe_execfile(err.filename,self.user_ns)
1325 1346 except:
1326 1347 self.showtraceback()
1327 1348 else:
1328 1349 try:
1329 1350 f = file(err.filename)
1330 1351 try:
1331 1352 # This should be inside a display_trap block and I
1332 1353 # think it is.
1333 1354 sys.displayhook(f.read())
1334 1355 finally:
1335 1356 f.close()
1336 1357 except:
1337 1358 self.showtraceback()
1338 1359
1339 1360 def _should_recompile(self,e):
1340 1361 """Utility routine for edit_syntax_error"""
1341 1362
1342 1363 if e.filename in ('<ipython console>','<input>','<string>',
1343 1364 '<console>','<BackgroundJob compilation>',
1344 1365 None):
1345 1366
1346 1367 return False
1347 1368 try:
1348 1369 if (self.autoedit_syntax and
1349 1370 not self.ask_yes_no('Return to editor to correct syntax error? '
1350 1371 '[Y/n] ','y')):
1351 1372 return False
1352 1373 except EOFError:
1353 1374 return False
1354 1375
1355 1376 def int0(x):
1356 1377 try:
1357 1378 return int(x)
1358 1379 except TypeError:
1359 1380 return 0
1360 1381 # always pass integer line and offset values to editor hook
1361 1382 try:
1362 1383 self.hooks.fix_error_editor(e.filename,
1363 1384 int0(e.lineno),int0(e.offset),e.msg)
1364 1385 except TryNext:
1365 1386 warn('Could not open editor')
1366 1387 return False
1367 1388 return True
1368 1389
1369 1390 #-------------------------------------------------------------------------
1370 1391 # Things related to tab completion
1371 1392 #-------------------------------------------------------------------------
1372 1393
1373 1394 def complete(self, text):
1374 1395 """Return a sorted list of all possible completions on text.
1375 1396
1376 1397 Inputs:
1377 1398
1378 1399 - text: a string of text to be completed on.
1379 1400
1380 1401 This is a wrapper around the completion mechanism, similar to what
1381 1402 readline does at the command line when the TAB key is hit. By
1382 1403 exposing it as a method, it can be used by other non-readline
1383 1404 environments (such as GUIs) for text completion.
1384 1405
1385 1406 Simple usage example:
1386 1407
1387 1408 In [7]: x = 'hello'
1388 1409
1389 1410 In [8]: x
1390 1411 Out[8]: 'hello'
1391 1412
1392 1413 In [9]: print x
1393 1414 hello
1394 1415
1395 1416 In [10]: _ip.complete('x.l')
1396 1417 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1397 1418 """
1398 1419
1399 1420 # Inject names into __builtin__ so we can complete on the added names.
1400 1421 with self.builtin_trap:
1401 1422 complete = self.Completer.complete
1402 1423 state = 0
1403 1424 # use a dict so we get unique keys, since ipyhton's multiple
1404 1425 # completers can return duplicates. When we make 2.4 a requirement,
1405 1426 # start using sets instead, which are faster.
1406 1427 comps = {}
1407 1428 while True:
1408 1429 newcomp = complete(text,state,line_buffer=text)
1409 1430 if newcomp is None:
1410 1431 break
1411 1432 comps[newcomp] = 1
1412 1433 state += 1
1413 1434 outcomps = comps.keys()
1414 1435 outcomps.sort()
1415 1436 #print "T:",text,"OC:",outcomps # dbg
1416 1437 #print "vars:",self.user_ns.keys()
1417 1438 return outcomps
1418 1439
1419 1440 def set_custom_completer(self,completer,pos=0):
1420 1441 """set_custom_completer(completer,pos=0)
1421 1442
1422 1443 Adds a new custom completer function.
1423 1444
1424 1445 The position argument (defaults to 0) is the index in the completers
1425 1446 list where you want the completer to be inserted."""
1426 1447
1427 1448 newcomp = new.instancemethod(completer,self.Completer,
1428 1449 self.Completer.__class__)
1429 1450 self.Completer.matchers.insert(pos,newcomp)
1430 1451
1431 1452 def set_completer(self):
1432 1453 """reset readline's completer to be our own."""
1433 1454 self.readline.set_completer(self.Completer.complete)
1434 1455
1435 1456 #-------------------------------------------------------------------------
1436 1457 # Things related to readline
1437 1458 #-------------------------------------------------------------------------
1438 1459
1439 1460 def init_readline(self):
1440 1461 """Command history completion/saving/reloading."""
1441 1462
1442 1463 self.rl_next_input = None
1443 1464 self.rl_do_indent = False
1444 1465
1445 1466 if not self.readline_use:
1446 1467 return
1447 1468
1448 1469 import IPython.utils.rlineimpl as readline
1449 1470
1450 1471 if not readline.have_readline:
1451 1472 self.has_readline = 0
1452 1473 self.readline = None
1453 1474 # no point in bugging windows users with this every time:
1454 1475 warn('Readline services not available on this platform.')
1455 1476 else:
1456 1477 sys.modules['readline'] = readline
1457 1478 import atexit
1458 1479 from IPython.core.completer import IPCompleter
1459 1480 self.Completer = IPCompleter(self,
1460 1481 self.user_ns,
1461 1482 self.user_global_ns,
1462 1483 self.readline_omit__names,
1463 1484 self.alias_manager.alias_table)
1464 1485 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1465 1486 self.strdispatchers['complete_command'] = sdisp
1466 1487 self.Completer.custom_completers = sdisp
1467 1488 # Platform-specific configuration
1468 1489 if os.name == 'nt':
1469 1490 self.readline_startup_hook = readline.set_pre_input_hook
1470 1491 else:
1471 1492 self.readline_startup_hook = readline.set_startup_hook
1472 1493
1473 1494 # Load user's initrc file (readline config)
1474 1495 # Or if libedit is used, load editrc.
1475 1496 inputrc_name = os.environ.get('INPUTRC')
1476 1497 if inputrc_name is None:
1477 1498 home_dir = get_home_dir()
1478 1499 if home_dir is not None:
1479 1500 inputrc_name = '.inputrc'
1480 1501 if readline.uses_libedit:
1481 1502 inputrc_name = '.editrc'
1482 1503 inputrc_name = os.path.join(home_dir, inputrc_name)
1483 1504 if os.path.isfile(inputrc_name):
1484 1505 try:
1485 1506 readline.read_init_file(inputrc_name)
1486 1507 except:
1487 1508 warn('Problems reading readline initialization file <%s>'
1488 1509 % inputrc_name)
1489 1510
1490 1511 self.has_readline = 1
1491 1512 self.readline = readline
1492 1513 # save this in sys so embedded copies can restore it properly
1493 1514 sys.ipcompleter = self.Completer.complete
1494 1515 self.set_completer()
1495 1516
1496 1517 # Configure readline according to user's prefs
1497 1518 # This is only done if GNU readline is being used. If libedit
1498 1519 # is being used (as on Leopard) the readline config is
1499 1520 # not run as the syntax for libedit is different.
1500 1521 if not readline.uses_libedit:
1501 1522 for rlcommand in self.readline_parse_and_bind:
1502 1523 #print "loading rl:",rlcommand # dbg
1503 1524 readline.parse_and_bind(rlcommand)
1504 1525
1505 1526 # Remove some chars from the delimiters list. If we encounter
1506 1527 # unicode chars, discard them.
1507 1528 delims = readline.get_completer_delims().encode("ascii", "ignore")
1508 1529 delims = delims.translate(string._idmap,
1509 1530 self.readline_remove_delims)
1510 1531 readline.set_completer_delims(delims)
1511 1532 # otherwise we end up with a monster history after a while:
1512 1533 readline.set_history_length(1000)
1513 1534 try:
1514 1535 #print '*** Reading readline history' # dbg
1515 1536 readline.read_history_file(self.histfile)
1516 1537 except IOError:
1517 1538 pass # It doesn't exist yet.
1518 1539
1519 1540 atexit.register(self.atexit_operations)
1520 1541 del atexit
1521 1542
1522 1543 # Configure auto-indent for all platforms
1523 1544 self.set_autoindent(self.autoindent)
1524 1545
1525 1546 def set_next_input(self, s):
1526 1547 """ Sets the 'default' input string for the next command line.
1527 1548
1528 1549 Requires readline.
1529 1550
1530 1551 Example:
1531 1552
1532 1553 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1533 1554 [D:\ipython]|2> Hello Word_ # cursor is here
1534 1555 """
1535 1556
1536 1557 self.rl_next_input = s
1537 1558
1538 1559 def pre_readline(self):
1539 1560 """readline hook to be used at the start of each line.
1540 1561
1541 1562 Currently it handles auto-indent only."""
1542 1563
1543 1564 #debugx('self.indent_current_nsp','pre_readline:')
1544 1565
1545 1566 if self.rl_do_indent:
1546 1567 self.readline.insert_text(self._indent_current_str())
1547 1568 if self.rl_next_input is not None:
1548 1569 self.readline.insert_text(self.rl_next_input)
1549 1570 self.rl_next_input = None
1550 1571
1551 1572 def _indent_current_str(self):
1552 1573 """return the current level of indentation as a string"""
1553 1574 return self.indent_current_nsp * ' '
1554 1575
1555 1576 #-------------------------------------------------------------------------
1556 1577 # Things related to magics
1557 1578 #-------------------------------------------------------------------------
1558 1579
1559 1580 def init_magics(self):
1560 1581 # Set user colors (don't do it in the constructor above so that it
1561 1582 # doesn't crash if colors option is invalid)
1562 1583 self.magic_colors(self.colors)
1563 1584
1564 1585 def magic(self,arg_s):
1565 1586 """Call a magic function by name.
1566 1587
1567 1588 Input: a string containing the name of the magic function to call and any
1568 1589 additional arguments to be passed to the magic.
1569 1590
1570 1591 magic('name -opt foo bar') is equivalent to typing at the ipython
1571 1592 prompt:
1572 1593
1573 1594 In[1]: %name -opt foo bar
1574 1595
1575 1596 To call a magic without arguments, simply use magic('name').
1576 1597
1577 1598 This provides a proper Python function to call IPython's magics in any
1578 1599 valid Python code you can type at the interpreter, including loops and
1579 1600 compound statements.
1580 1601 """
1581 1602
1582 1603 args = arg_s.split(' ',1)
1583 1604 magic_name = args[0]
1584 1605 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1585 1606
1586 1607 try:
1587 1608 magic_args = args[1]
1588 1609 except IndexError:
1589 1610 magic_args = ''
1590 1611 fn = getattr(self,'magic_'+magic_name,None)
1591 1612 if fn is None:
1592 1613 error("Magic function `%s` not found." % magic_name)
1593 1614 else:
1594 1615 magic_args = self.var_expand(magic_args,1)
1595 1616 with nested(self.builtin_trap,):
1596 1617 result = fn(magic_args)
1597 1618 # Unfortunately, the return statement is what will trigger
1598 1619 # the displayhook, but it is no longer set!
1599 1620 return result
1600 1621
1601 1622 def define_magic(self, magicname, func):
1602 1623 """Expose own function as magic function for ipython
1603 1624
1604 1625 def foo_impl(self,parameter_s=''):
1605 1626 'My very own magic!. (Use docstrings, IPython reads them).'
1606 1627 print 'Magic function. Passed parameter is between < >:'
1607 1628 print '<%s>' % parameter_s
1608 1629 print 'The self object is:',self
1609 1630
1610 1631 self.define_magic('foo',foo_impl)
1611 1632 """
1612 1633
1613 1634 import new
1614 1635 im = new.instancemethod(func,self, self.__class__)
1615 1636 old = getattr(self, "magic_" + magicname, None)
1616 1637 setattr(self, "magic_" + magicname, im)
1617 1638 return old
1618 1639
1619 1640 #-------------------------------------------------------------------------
1620 1641 # Things related to macros
1621 1642 #-------------------------------------------------------------------------
1622 1643
1623 1644 def define_macro(self, name, themacro):
1624 1645 """Define a new macro
1625 1646
1626 1647 Parameters
1627 1648 ----------
1628 1649 name : str
1629 1650 The name of the macro.
1630 1651 themacro : str or Macro
1631 1652 The action to do upon invoking the macro. If a string, a new
1632 1653 Macro object is created by passing the string to it.
1633 1654 """
1634 1655
1635 1656 from IPython.core import macro
1636 1657
1637 1658 if isinstance(themacro, basestring):
1638 1659 themacro = macro.Macro(themacro)
1639 1660 if not isinstance(themacro, macro.Macro):
1640 1661 raise ValueError('A macro must be a string or a Macro instance.')
1641 1662 self.user_ns[name] = themacro
1642 1663
1643 1664 #-------------------------------------------------------------------------
1644 1665 # Things related to the running of system commands
1645 1666 #-------------------------------------------------------------------------
1646 1667
1647 1668 def system(self, cmd):
1648 1669 """Make a system call, using IPython."""
1649 1670 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1650 1671
1651 1672 #-------------------------------------------------------------------------
1652 1673 # Things related to aliases
1653 1674 #-------------------------------------------------------------------------
1654 1675
1655 1676 def init_alias(self):
1656 1677 self.alias_manager = AliasManager(self, config=self.config)
1657 1678 self.ns_table['alias'] = self.alias_manager.alias_table,
1658 1679
1659 1680 #-------------------------------------------------------------------------
1660 1681 # Things related to the running of code
1661 1682 #-------------------------------------------------------------------------
1662 1683
1663 1684 def ex(self, cmd):
1664 1685 """Execute a normal python statement in user namespace."""
1665 1686 with nested(self.builtin_trap,):
1666 1687 exec cmd in self.user_global_ns, self.user_ns
1667 1688
1668 1689 def ev(self, expr):
1669 1690 """Evaluate python expression expr in user namespace.
1670 1691
1671 1692 Returns the result of evaluation
1672 1693 """
1673 1694 with nested(self.builtin_trap,):
1674 1695 return eval(expr, self.user_global_ns, self.user_ns)
1675 1696
1676 def mainloop(self, banner=None):
1697 def mainloop(self, display_banner=None):
1677 1698 """Start the mainloop.
1678 1699
1679 1700 If an optional banner argument is given, it will override the
1680 1701 internally created default banner.
1681 1702 """
1682 1703
1683 1704 with nested(self.builtin_trap, self.display_trap):
1684 1705 if self.c: # Emulate Python's -c option
1685 1706 self.exec_init_cmd()
1686 1707
1687 if self.display_banner:
1688 if banner is None:
1689 banner = self.banner
1690
1691 1708 # if you run stuff with -c <cmd>, raw hist is not updated
1692 1709 # ensure that it's in sync
1693 1710 if len(self.input_hist) != len (self.input_hist_raw):
1694 1711 self.input_hist_raw = InputList(self.input_hist)
1695 1712
1696 1713 while 1:
1697 1714 try:
1698 self.interact()
1715 self.interact(display_banner=display_banner)
1699 1716 #self.interact_with_readline()
1700 1717 # XXX for testing of a readline-decoupled repl loop, call
1701 1718 # interact_with_readline above
1702 1719 break
1703 1720 except KeyboardInterrupt:
1704 1721 # this should not be necessary, but KeyboardInterrupt
1705 1722 # handling seems rather unpredictable...
1706 1723 self.write("\nKeyboardInterrupt in interact()\n")
1707 1724
1708 1725 def exec_init_cmd(self):
1709 1726 """Execute a command given at the command line.
1710 1727
1711 1728 This emulates Python's -c option."""
1712 1729
1713 1730 #sys.argv = ['-c']
1714 1731 self.push_line(self.prefilter_manager.prefilter_lines(self.c, False))
1715 1732 if not self.interactive:
1716 1733 self.ask_exit()
1717 1734
1718 1735 def interact_prompt(self):
1719 1736 """ Print the prompt (in read-eval-print loop)
1720 1737
1721 1738 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1722 1739 used in standard IPython flow.
1723 1740 """
1724 1741 if self.more:
1725 1742 try:
1726 1743 prompt = self.hooks.generate_prompt(True)
1727 1744 except:
1728 1745 self.showtraceback()
1729 1746 if self.autoindent:
1730 1747 self.rl_do_indent = True
1731 1748
1732 1749 else:
1733 1750 try:
1734 1751 prompt = self.hooks.generate_prompt(False)
1735 1752 except:
1736 1753 self.showtraceback()
1737 1754 self.write(prompt)
1738 1755
1739 1756 def interact_handle_input(self,line):
1740 1757 """ Handle the input line (in read-eval-print loop)
1741 1758
1742 1759 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1743 1760 used in standard IPython flow.
1744 1761 """
1745 1762 if line.lstrip() == line:
1746 1763 self.shadowhist.add(line.strip())
1747 1764 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1748 1765
1749 1766 if line.strip():
1750 1767 if self.more:
1751 1768 self.input_hist_raw[-1] += '%s\n' % line
1752 1769 else:
1753 1770 self.input_hist_raw.append('%s\n' % line)
1754 1771
1755 1772
1756 1773 self.more = self.push_line(lineout)
1757 1774 if (self.SyntaxTB.last_syntax_error and
1758 1775 self.autoedit_syntax):
1759 1776 self.edit_syntax_error()
1760 1777
1761 1778 def interact_with_readline(self):
1762 1779 """ Demo of using interact_handle_input, interact_prompt
1763 1780
1764 1781 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1765 1782 it should work like this.
1766 1783 """
1767 1784 self.readline_startup_hook(self.pre_readline)
1768 1785 while not self.exit_now:
1769 1786 self.interact_prompt()
1770 1787 if self.more:
1771 1788 self.rl_do_indent = True
1772 1789 else:
1773 1790 self.rl_do_indent = False
1774 1791 line = raw_input_original().decode(self.stdin_encoding)
1775 1792 self.interact_handle_input(line)
1776 1793
1777 def interact(self, banner=None):
1794 def interact(self, display_banner=None):
1778 1795 """Closely emulate the interactive Python console."""
1779 1796
1780 1797 # batch run -> do not interact
1781 1798 if self.exit_now:
1782 1799 return
1783 1800
1784 if self.display_banner:
1785 if banner is None:
1786 banner = self.banner
1787 self.write(banner)
1801 if display_banner is None:
1802 display_banner = self.display_banner
1803 if display_banner:
1804 self.show_banner()
1788 1805
1789 1806 more = 0
1790 1807
1791 1808 # Mark activity in the builtins
1792 1809 __builtin__.__dict__['__IPYTHON__active'] += 1
1793 1810
1794 1811 if self.has_readline:
1795 1812 self.readline_startup_hook(self.pre_readline)
1796 1813 # exit_now is set by a call to %Exit or %Quit, through the
1797 1814 # ask_exit callback.
1798 1815
1799 1816 while not self.exit_now:
1800 1817 self.hooks.pre_prompt_hook()
1801 1818 if more:
1802 1819 try:
1803 1820 prompt = self.hooks.generate_prompt(True)
1804 1821 except:
1805 1822 self.showtraceback()
1806 1823 if self.autoindent:
1807 1824 self.rl_do_indent = True
1808 1825
1809 1826 else:
1810 1827 try:
1811 1828 prompt = self.hooks.generate_prompt(False)
1812 1829 except:
1813 1830 self.showtraceback()
1814 1831 try:
1815 1832 line = self.raw_input(prompt, more)
1816 1833 if self.exit_now:
1817 1834 # quick exit on sys.std[in|out] close
1818 1835 break
1819 1836 if self.autoindent:
1820 1837 self.rl_do_indent = False
1821 1838
1822 1839 except KeyboardInterrupt:
1823 1840 #double-guard against keyboardinterrupts during kbdint handling
1824 1841 try:
1825 1842 self.write('\nKeyboardInterrupt\n')
1826 1843 self.resetbuffer()
1827 1844 # keep cache in sync with the prompt counter:
1828 1845 self.outputcache.prompt_count -= 1
1829 1846
1830 1847 if self.autoindent:
1831 1848 self.indent_current_nsp = 0
1832 1849 more = 0
1833 1850 except KeyboardInterrupt:
1834 1851 pass
1835 1852 except EOFError:
1836 1853 if self.autoindent:
1837 1854 self.rl_do_indent = False
1838 1855 self.readline_startup_hook(None)
1839 1856 self.write('\n')
1840 1857 self.exit()
1841 1858 except bdb.BdbQuit:
1842 1859 warn('The Python debugger has exited with a BdbQuit exception.\n'
1843 1860 'Because of how pdb handles the stack, it is impossible\n'
1844 1861 'for IPython to properly format this particular exception.\n'
1845 1862 'IPython will resume normal operation.')
1846 1863 except:
1847 1864 # exceptions here are VERY RARE, but they can be triggered
1848 1865 # asynchronously by signal handlers, for example.
1849 1866 self.showtraceback()
1850 1867 else:
1851 1868 more = self.push_line(line)
1852 1869 if (self.SyntaxTB.last_syntax_error and
1853 1870 self.autoedit_syntax):
1854 1871 self.edit_syntax_error()
1855 1872
1856 1873 # We are off again...
1857 1874 __builtin__.__dict__['__IPYTHON__active'] -= 1
1858 1875
1859 def safe_execfile(self,fname,*where,**kw):
1876 def safe_execfile(self, fname, *where, **kw):
1860 1877 """A safe version of the builtin execfile().
1861 1878
1862 This version will never throw an exception, and knows how to handle
1863 ipython logs as well.
1879 This version will never throw an exception, but instead print
1880 helpful error messages to the screen. This only works on pure
1881 Python files with the .py extension.
1864 1882
1865 :Parameters:
1866 fname : string
1867 Name of the file to be executed.
1868
1869 where : tuple
1883 Parameters
1884 ----------
1885 fname : string
1886 The name of the file to be executed.
1887 where : tuple
1870 1888 One or two namespaces, passed to execfile() as (globals,locals).
1871 1889 If only one is given, it is passed as both.
1890 exit_ignore : bool (False)
1891 If True, then don't print errors for non-zero exit statuses.
1892 """
1893 kw.setdefault('exit_ignore', False)
1872 1894
1873 :Keywords:
1874 islog : boolean (False)
1875
1876 quiet : boolean (True)
1895 fname = os.path.abspath(os.path.expanduser(fname))
1877 1896
1878 exit_ignore : boolean (False)
1879 """
1897 # Make sure we have a .py file
1898 if not fname.endswith('.py'):
1899 warn('File must end with .py to be run using execfile: <%s>' % fname)
1880 1900
1881 def syspath_cleanup():
1882 """Internal cleanup routine for sys.path."""
1883 if add_dname:
1884 try:
1885 sys.path.remove(dname)
1886 except ValueError:
1887 # For some reason the user has already removed it, ignore.
1888 pass
1889
1890 fname = os.path.expanduser(fname)
1901 # Make sure we can open the file
1902 try:
1903 with open(fname) as thefile:
1904 pass
1905 except:
1906 warn('Could not open file <%s> for safe execution.' % fname)
1907 return
1891 1908
1892 1909 # Find things also in current directory. This is needed to mimic the
1893 1910 # behavior of running a script from the system command line, where
1894 1911 # Python inserts the script's directory into sys.path
1895 dname = os.path.dirname(os.path.abspath(fname))
1896 add_dname = False
1897 if dname not in sys.path:
1898 sys.path.insert(0,dname)
1899 add_dname = True
1900
1901 try:
1902 xfile = open(fname)
1903 except:
1904 print >> Term.cerr, \
1905 'Could not open file <%s> for safe execution.' % fname
1906 syspath_cleanup()
1907 return None
1912 dname = os.path.dirname(fname)
1908 1913
1909 kw.setdefault('islog',0)
1910 kw.setdefault('quiet',1)
1911 kw.setdefault('exit_ignore',0)
1912
1913 first = xfile.readline()
1914 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
1915 xfile.close()
1916 # line by line execution
1917 if first.startswith(loghead) or kw['islog']:
1918 print 'Loading log file <%s> one line at a time...' % fname
1919 if kw['quiet']:
1920 stdout_save = sys.stdout
1921 sys.stdout = StringIO.StringIO()
1922 try:
1923 globs,locs = where[0:2]
1924 except:
1925 try:
1926 globs = locs = where[0]
1927 except:
1928 globs = locs = globals()
1929 badblocks = []
1930
1931 # we also need to identify indented blocks of code when replaying
1932 # logs and put them together before passing them to an exec
1933 # statement. This takes a bit of regexp and look-ahead work in the
1934 # file. It's easiest if we swallow the whole thing in memory
1935 # first, and manually walk through the lines list moving the
1936 # counter ourselves.
1937 indent_re = re.compile('\s+\S')
1938 xfile = open(fname)
1939 filelines = xfile.readlines()
1940 xfile.close()
1941 nlines = len(filelines)
1942 lnum = 0
1943 while lnum < nlines:
1944 line = filelines[lnum]
1945 lnum += 1
1946 # don't re-insert logger status info into cache
1947 if line.startswith('#log#'):
1948 continue
1949 else:
1950 # build a block of code (maybe a single line) for execution
1951 block = line
1952 try:
1953 next = filelines[lnum] # lnum has already incremented
1954 except:
1955 next = None
1956 while next and indent_re.match(next):
1957 block += next
1958 lnum += 1
1959 try:
1960 next = filelines[lnum]
1961 except:
1962 next = None
1963 # now execute the block of one or more lines
1964 try:
1965 exec block in globs,locs
1966 except SystemExit:
1967 pass
1968 except:
1969 badblocks.append(block.rstrip())
1970 if kw['quiet']: # restore stdout
1971 sys.stdout.close()
1972 sys.stdout = stdout_save
1973 print 'Finished replaying log file <%s>' % fname
1974 if badblocks:
1975 print >> sys.stderr, ('\nThe following lines/blocks in file '
1976 '<%s> reported errors:' % fname)
1977
1978 for badline in badblocks:
1979 print >> sys.stderr, badline
1980 else: # regular file execution
1914 with prepended_to_syspath(dname):
1981 1915 try:
1982 1916 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1983 1917 # Work around a bug in Python for Windows. The bug was
1984 1918 # fixed in in Python 2.5 r54159 and 54158, but that's still
1985 1919 # SVN Python as of March/07. For details, see:
1986 1920 # http://projects.scipy.org/ipython/ipython/ticket/123
1987 1921 try:
1988 1922 globs,locs = where[0:2]
1989 1923 except:
1990 1924 try:
1991 1925 globs = locs = where[0]
1992 1926 except:
1993 1927 globs = locs = globals()
1994 1928 exec file(fname) in globs,locs
1995 1929 else:
1996 1930 execfile(fname,*where)
1997 1931 except SyntaxError:
1998 1932 self.showsyntaxerror()
1999 1933 warn('Failure executing file: <%s>' % fname)
2000 except SystemExit,status:
1934 except SystemExit, status:
2001 1935 # Code that correctly sets the exit status flag to success (0)
2002 1936 # shouldn't be bothered with a traceback. Note that a plain
2003 1937 # sys.exit() does NOT set the message to 0 (it's empty) so that
2004 1938 # will still get a traceback. Note that the structure of the
2005 1939 # SystemExit exception changed between Python 2.4 and 2.5, so
2006 1940 # the checks must be done in a version-dependent way.
2007 1941 show = False
2008
2009 if sys.version_info[:2] > (2,5):
2010 if status.message!=0 and not kw['exit_ignore']:
2011 show = True
2012 else:
2013 if status.code and not kw['exit_ignore']:
2014 show = True
1942 if status.message!=0 and not kw['exit_ignore']:
1943 show = True
2015 1944 if show:
2016 1945 self.showtraceback()
2017 1946 warn('Failure executing file: <%s>' % fname)
2018 1947 except:
2019 1948 self.showtraceback()
2020 1949 warn('Failure executing file: <%s>' % fname)
2021 1950
2022 syspath_cleanup()
1951 def safe_execfile_ipy(self, fname):
1952 """Like safe_execfile, but for .ipy files with IPython syntax.
1953
1954 Parameters
1955 ----------
1956 fname : str
1957 The name of the file to execute. The filename must have a
1958 .ipy extension.
1959 """
1960 fname = os.path.abspath(os.path.expanduser(fname))
1961
1962 # Make sure we have a .py file
1963 if not fname.endswith('.ipy'):
1964 warn('File must end with .py to be run using execfile: <%s>' % fname)
1965
1966 # Make sure we can open the file
1967 try:
1968 with open(fname) as thefile:
1969 pass
1970 except:
1971 warn('Could not open file <%s> for safe execution.' % fname)
1972 return
1973
1974 # Find things also in current directory. This is needed to mimic the
1975 # behavior of running a script from the system command line, where
1976 # Python inserts the script's directory into sys.path
1977 dname = os.path.dirname(fname)
1978
1979 with prepended_to_syspath(dname):
1980 try:
1981 with open(fname) as thefile:
1982 script = thefile.read()
1983 # self.runlines currently captures all exceptions
1984 # raise in user code. It would be nice if there were
1985 # versions of runlines, execfile that did raise, so
1986 # we could catch the errors.
1987 self.runlines(script, clean=True)
1988 except:
1989 self.showtraceback()
1990 warn('Unknown failure executing file: <%s>' % fname)
1991
1992 def _is_secondary_block_start(self, s):
1993 if not s.endswith(':'):
1994 return False
1995 if (s.startswith('elif') or
1996 s.startswith('else') or
1997 s.startswith('except') or
1998 s.startswith('finally')):
1999 return True
2023 2000
2024 2001 def cleanup_ipy_script(self, script):
2025 2002 """Make a script safe for self.runlines()
2026 2003
2027 Notes
2028 -----
2029 This was copied over from the old ipapi and probably can be done
2030 away with once we move to block based interpreter.
2031
2032 - Removes empty lines Suffixes all indented blocks that end with
2033 - unindented lines with empty lines
2004 Currently, IPython is lines based, with blocks being detected by
2005 empty lines. This is a problem for block based scripts that may
2006 not have empty lines after blocks. This script adds those empty
2007 lines to make scripts safe for running in the current line based
2008 IPython.
2034 2009 """
2035
2036 2010 res = []
2037 2011 lines = script.splitlines()
2038
2039 2012 level = 0
2013
2040 2014 for l in lines:
2041 2015 lstripped = l.lstrip()
2042 2016 stripped = l.strip()
2043 2017 if not stripped:
2044 2018 continue
2045 newlevel = len(l) - len(lstripped)
2046 def is_secondary_block_start(s):
2047 if not s.endswith(':'):
2048 return False
2049 if (s.startswith('elif') or
2050 s.startswith('else') or
2051 s.startswith('except') or
2052 s.startswith('finally')):
2053 return True
2054
2019 newlevel = len(l) - len(lstripped)
2055 2020 if level > 0 and newlevel == 0 and \
2056 not is_secondary_block_start(stripped):
2021 not self._is_secondary_block_start(stripped):
2057 2022 # add empty line
2058 2023 res.append('')
2059
2060 2024 res.append(l)
2061 2025 level = newlevel
2026
2062 2027 return '\n'.join(res) + '\n'
2063 2028
2064 2029 def runlines(self, lines, clean=False):
2065 2030 """Run a string of one or more lines of source.
2066 2031
2067 2032 This method is capable of running a string containing multiple source
2068 2033 lines, as if they had been entered at the IPython prompt. Since it
2069 2034 exposes IPython's processing machinery, the given strings can contain
2070 2035 magic calls (%magic), special shell access (!cmd), etc.
2071 2036 """
2072 2037
2073 2038 if isinstance(lines, (list, tuple)):
2074 2039 lines = '\n'.join(lines)
2075 2040
2076 2041 if clean:
2077 2042 lines = self.cleanup_ipy_script(lines)
2078 2043
2079 2044 # We must start with a clean buffer, in case this is run from an
2080 2045 # interactive IPython session (via a magic, for example).
2081 2046 self.resetbuffer()
2082 2047 lines = lines.splitlines()
2083 2048 more = 0
2084 2049
2085 2050 with nested(self.builtin_trap, self.display_trap):
2086 2051 for line in lines:
2087 2052 # skip blank lines so we don't mess up the prompt counter, but do
2088 2053 # NOT skip even a blank line if we are in a code block (more is
2089 2054 # true)
2090 2055
2091 2056 if line or more:
2092 2057 # push to raw history, so hist line numbers stay in sync
2093 2058 self.input_hist_raw.append("# " + line + "\n")
2094 more = self.push_line(self.prefilter_manager.prefilter_lines(line,more))
2059 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2060 more = self.push_line(prefiltered)
2095 2061 # IPython's runsource returns None if there was an error
2096 2062 # compiling the code. This allows us to stop processing right
2097 2063 # away, so the user gets the error message at the right place.
2098 2064 if more is None:
2099 2065 break
2100 2066 else:
2101 2067 self.input_hist_raw.append("\n")
2102 2068 # final newline in case the input didn't have it, so that the code
2103 2069 # actually does get executed
2104 2070 if more:
2105 2071 self.push_line('\n')
2106 2072
2107 2073 def runsource(self, source, filename='<input>', symbol='single'):
2108 2074 """Compile and run some source in the interpreter.
2109 2075
2110 2076 Arguments are as for compile_command().
2111 2077
2112 2078 One several things can happen:
2113 2079
2114 2080 1) The input is incorrect; compile_command() raised an
2115 2081 exception (SyntaxError or OverflowError). A syntax traceback
2116 2082 will be printed by calling the showsyntaxerror() method.
2117 2083
2118 2084 2) The input is incomplete, and more input is required;
2119 2085 compile_command() returned None. Nothing happens.
2120 2086
2121 2087 3) The input is complete; compile_command() returned a code
2122 2088 object. The code is executed by calling self.runcode() (which
2123 2089 also handles run-time exceptions, except for SystemExit).
2124 2090
2125 2091 The return value is:
2126 2092
2127 2093 - True in case 2
2128 2094
2129 2095 - False in the other cases, unless an exception is raised, where
2130 2096 None is returned instead. This can be used by external callers to
2131 2097 know whether to continue feeding input or not.
2132 2098
2133 2099 The return value can be used to decide whether to use sys.ps1 or
2134 2100 sys.ps2 to prompt the next line."""
2135 2101
2136 2102 # if the source code has leading blanks, add 'if 1:\n' to it
2137 2103 # this allows execution of indented pasted code. It is tempting
2138 2104 # to add '\n' at the end of source to run commands like ' a=1'
2139 2105 # directly, but this fails for more complicated scenarios
2140 2106 source=source.encode(self.stdin_encoding)
2141 2107 if source[:1] in [' ', '\t']:
2142 2108 source = 'if 1:\n%s' % source
2143 2109
2144 2110 try:
2145 2111 code = self.compile(source,filename,symbol)
2146 2112 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2147 2113 # Case 1
2148 2114 self.showsyntaxerror(filename)
2149 2115 return None
2150 2116
2151 2117 if code is None:
2152 2118 # Case 2
2153 2119 return True
2154 2120
2155 2121 # Case 3
2156 2122 # We store the code object so that threaded shells and
2157 2123 # custom exception handlers can access all this info if needed.
2158 2124 # The source corresponding to this can be obtained from the
2159 2125 # buffer attribute as '\n'.join(self.buffer).
2160 2126 self.code_to_run = code
2161 2127 # now actually execute the code object
2162 2128 if self.runcode(code) == 0:
2163 2129 return False
2164 2130 else:
2165 2131 return None
2166 2132
2167 2133 def runcode(self,code_obj):
2168 2134 """Execute a code object.
2169 2135
2170 2136 When an exception occurs, self.showtraceback() is called to display a
2171 2137 traceback.
2172 2138
2173 2139 Return value: a flag indicating whether the code to be run completed
2174 2140 successfully:
2175 2141
2176 2142 - 0: successful execution.
2177 2143 - 1: an error occurred.
2178 2144 """
2179 2145
2180 2146 # Set our own excepthook in case the user code tries to call it
2181 2147 # directly, so that the IPython crash handler doesn't get triggered
2182 2148 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2183 2149
2184 2150 # we save the original sys.excepthook in the instance, in case config
2185 2151 # code (such as magics) needs access to it.
2186 2152 self.sys_excepthook = old_excepthook
2187 2153 outflag = 1 # happens in more places, so it's easier as default
2188 2154 try:
2189 2155 try:
2190 2156 self.hooks.pre_runcode_hook()
2191 2157 exec code_obj in self.user_global_ns, self.user_ns
2192 2158 finally:
2193 2159 # Reset our crash handler in place
2194 2160 sys.excepthook = old_excepthook
2195 2161 except SystemExit:
2196 2162 self.resetbuffer()
2197 2163 self.showtraceback()
2198 2164 warn("Type %exit or %quit to exit IPython "
2199 2165 "(%Exit or %Quit do so unconditionally).",level=1)
2200 2166 except self.custom_exceptions:
2201 2167 etype,value,tb = sys.exc_info()
2202 2168 self.CustomTB(etype,value,tb)
2203 2169 except:
2204 2170 self.showtraceback()
2205 2171 else:
2206 2172 outflag = 0
2207 2173 if softspace(sys.stdout, 0):
2208 2174 print
2209 2175 # Flush out code object which has been run (and source)
2210 2176 self.code_to_run = None
2211 2177 return outflag
2212 2178
2213 2179 def push_line(self, line):
2214 2180 """Push a line to the interpreter.
2215 2181
2216 2182 The line should not have a trailing newline; it may have
2217 2183 internal newlines. The line is appended to a buffer and the
2218 2184 interpreter's runsource() method is called with the
2219 2185 concatenated contents of the buffer as source. If this
2220 2186 indicates that the command was executed or invalid, the buffer
2221 2187 is reset; otherwise, the command is incomplete, and the buffer
2222 2188 is left as it was after the line was appended. The return
2223 2189 value is 1 if more input is required, 0 if the line was dealt
2224 2190 with in some way (this is the same as runsource()).
2225 2191 """
2226 2192
2227 2193 # autoindent management should be done here, and not in the
2228 2194 # interactive loop, since that one is only seen by keyboard input. We
2229 2195 # need this done correctly even for code run via runlines (which uses
2230 2196 # push).
2231 2197
2232 2198 #print 'push line: <%s>' % line # dbg
2233 2199 for subline in line.splitlines():
2234 2200 self._autoindent_update(subline)
2235 2201 self.buffer.append(line)
2236 2202 more = self.runsource('\n'.join(self.buffer), self.filename)
2237 2203 if not more:
2238 2204 self.resetbuffer()
2239 2205 return more
2240 2206
2241 2207 def _autoindent_update(self,line):
2242 2208 """Keep track of the indent level."""
2243 2209
2244 2210 #debugx('line')
2245 2211 #debugx('self.indent_current_nsp')
2246 2212 if self.autoindent:
2247 2213 if line:
2248 2214 inisp = num_ini_spaces(line)
2249 2215 if inisp < self.indent_current_nsp:
2250 2216 self.indent_current_nsp = inisp
2251 2217
2252 2218 if line[-1] == ':':
2253 2219 self.indent_current_nsp += 4
2254 2220 elif dedent_re.match(line):
2255 2221 self.indent_current_nsp -= 4
2256 2222 else:
2257 2223 self.indent_current_nsp = 0
2258 2224
2259 2225 def resetbuffer(self):
2260 2226 """Reset the input buffer."""
2261 2227 self.buffer[:] = []
2262 2228
2263 2229 def raw_input(self,prompt='',continue_prompt=False):
2264 2230 """Write a prompt and read a line.
2265 2231
2266 2232 The returned line does not include the trailing newline.
2267 2233 When the user enters the EOF key sequence, EOFError is raised.
2268 2234
2269 2235 Optional inputs:
2270 2236
2271 2237 - prompt(''): a string to be printed to prompt the user.
2272 2238
2273 2239 - continue_prompt(False): whether this line is the first one or a
2274 2240 continuation in a sequence of inputs.
2275 2241 """
2276 2242 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2277 2243
2278 2244 # Code run by the user may have modified the readline completer state.
2279 2245 # We must ensure that our completer is back in place.
2280 2246
2281 2247 if self.has_readline:
2282 2248 self.set_completer()
2283 2249
2284 2250 try:
2285 2251 line = raw_input_original(prompt).decode(self.stdin_encoding)
2286 2252 except ValueError:
2287 2253 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2288 2254 " or sys.stdout.close()!\nExiting IPython!")
2289 2255 self.ask_exit()
2290 2256 return ""
2291 2257
2292 2258 # Try to be reasonably smart about not re-indenting pasted input more
2293 2259 # than necessary. We do this by trimming out the auto-indent initial
2294 2260 # spaces, if the user's actual input started itself with whitespace.
2295 2261 #debugx('self.buffer[-1]')
2296 2262
2297 2263 if self.autoindent:
2298 2264 if num_ini_spaces(line) > self.indent_current_nsp:
2299 2265 line = line[self.indent_current_nsp:]
2300 2266 self.indent_current_nsp = 0
2301 2267
2302 2268 # store the unfiltered input before the user has any chance to modify
2303 2269 # it.
2304 2270 if line.strip():
2305 2271 if continue_prompt:
2306 2272 self.input_hist_raw[-1] += '%s\n' % line
2307 if self.has_readline: # and some config option is set?
2273 if self.has_readline and self.readline_use:
2308 2274 try:
2309 2275 histlen = self.readline.get_current_history_length()
2310 2276 if histlen > 1:
2311 2277 newhist = self.input_hist_raw[-1].rstrip()
2312 2278 self.readline.remove_history_item(histlen-1)
2313 2279 self.readline.replace_history_item(histlen-2,
2314 2280 newhist.encode(self.stdin_encoding))
2315 2281 except AttributeError:
2316 2282 pass # re{move,place}_history_item are new in 2.4.
2317 2283 else:
2318 2284 self.input_hist_raw.append('%s\n' % line)
2319 2285 # only entries starting at first column go to shadow history
2320 2286 if line.lstrip() == line:
2321 2287 self.shadowhist.add(line.strip())
2322 2288 elif not continue_prompt:
2323 2289 self.input_hist_raw.append('\n')
2324 2290 try:
2325 2291 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2326 2292 except:
2327 2293 # blanket except, in case a user-defined prefilter crashes, so it
2328 2294 # can't take all of ipython with it.
2329 2295 self.showtraceback()
2330 2296 return ''
2331 2297 else:
2332 2298 return lineout
2333 2299
2334 2300 # def init_exec_commands(self):
2335 2301 # for cmd in self.config.EXECUTE:
2336 2302 # print "execute:", cmd
2337 2303 # self.api.runlines(cmd)
2338 2304 #
2339 2305 # batchrun = False
2340 2306 # if self.config.has_key('EXECFILE'):
2341 2307 # for batchfile in [path(arg) for arg in self.config.EXECFILE
2342 2308 # if arg.lower().endswith('.ipy')]:
2343 2309 # if not batchfile.isfile():
2344 2310 # print "No such batch file:", batchfile
2345 2311 # continue
2346 2312 # self.api.runlines(batchfile.text())
2347 2313 # batchrun = True
2348 2314 # # without -i option, exit after running the batch file
2349 2315 # if batchrun and not self.interactive:
2350 2316 # self.ask_exit()
2351 2317
2352 # def load(self, mod):
2353 # """ Load an extension.
2354 #
2355 # Some modules should (or must) be 'load()':ed, rather than just imported.
2356 #
2357 # Loading will do:
2358 #
2359 # - run init_ipython(ip)
2360 # - run ipython_firstrun(ip)
2361 # """
2362 #
2363 # if mod in self.extensions:
2364 # # just to make sure we don't init it twice
2365 # # note that if you 'load' a module that has already been
2366 # # imported, init_ipython gets run anyway
2367 #
2368 # return self.extensions[mod]
2369 # __import__(mod)
2370 # m = sys.modules[mod]
2371 # if hasattr(m,'init_ipython'):
2372 # m.init_ipython(self)
2373 #
2374 # if hasattr(m,'ipython_firstrun'):
2375 # already_loaded = self.db.get('firstrun_done', set())
2376 # if mod not in already_loaded:
2377 # m.ipython_firstrun(self)
2378 # already_loaded.add(mod)
2379 # self.db['firstrun_done'] = already_loaded
2380 #
2381 # self.extensions[mod] = m
2382 # return m
2318 #-------------------------------------------------------------------------
2319 # IPython extensions
2320 #-------------------------------------------------------------------------
2321
2322 def load_extension(self, module_str):
2323 """Load an IPython extension.
2324
2325 An IPython extension is an importable Python module that has
2326 a function with the signature::
2327
2328 def load_in_ipython(ipython):
2329 # Do things with ipython
2330
2331 This function is called after your extension is imported and the
2332 currently active :class:`InteractiveShell` instance is passed as
2333 the only argument. You can do anything you want with IPython at
2334 that point, including defining new magic and aliases, adding new
2335 components, etc.
2336
2337 You can put your extension modules anywhere you want, as long as
2338 they can be imported by Python's standard import mechanism. However,
2339 to make it easy to write extensions, you can also put your extensions
2340 in ``os.path.join(self.ipythondir, 'extensions')``. This directory
2341 is added to ``sys.path`` automatically.
2342 """
2343 from IPython.utils.syspathcontext import prepended_to_syspath
2344
2345 if module_str in sys.modules:
2346 return
2347
2348 with prepended_to_syspath(self.ipython_extension_dir):
2349 __import__(module_str)
2350 mod = sys.modules[module_str]
2351 self._call_load_in_ipython(mod)
2352
2353 def reload_extension(self, module_str):
2354 """Reload an IPython extension by doing reload."""
2355 from IPython.utils.syspathcontext import prepended_to_syspath
2356
2357 with prepended_to_syspath(self.ipython_extension_dir):
2358 if module_str in sys.modules:
2359 mod = sys.modules[module_str]
2360 reload(mod)
2361 self._call_load_in_ipython(mod)
2362 else:
2363 self.load_extension(self, module_str)
2364
2365 def _call_load_in_ipython(self, mod):
2366 if hasattr(mod, 'load_in_ipython'):
2367 mod.load_in_ipython(self)
2383 2368
2384 2369 #-------------------------------------------------------------------------
2385 2370 # Things related to the prefilter
2386 2371 #-------------------------------------------------------------------------
2387 2372
2388 2373 def init_prefilter(self):
2389 2374 self.prefilter_manager = PrefilterManager(self, config=self.config)
2390 2375
2391 2376 #-------------------------------------------------------------------------
2392 2377 # Utilities
2393 2378 #-------------------------------------------------------------------------
2394 2379
2395 2380 def getoutput(self, cmd):
2396 2381 return getoutput(self.var_expand(cmd,depth=2),
2397 2382 header=self.system_header,
2398 2383 verbose=self.system_verbose)
2399 2384
2400 2385 def getoutputerror(self, cmd):
2401 2386 return getoutputerror(self.var_expand(cmd,depth=2),
2402 2387 header=self.system_header,
2403 2388 verbose=self.system_verbose)
2404 2389
2405 2390 def var_expand(self,cmd,depth=0):
2406 2391 """Expand python variables in a string.
2407 2392
2408 2393 The depth argument indicates how many frames above the caller should
2409 2394 be walked to look for the local namespace where to expand variables.
2410 2395
2411 2396 The global namespace for expansion is always the user's interactive
2412 2397 namespace.
2413 2398 """
2414 2399
2415 2400 return str(ItplNS(cmd,
2416 2401 self.user_ns, # globals
2417 2402 # Skip our own frame in searching for locals:
2418 2403 sys._getframe(depth+1).f_locals # locals
2419 2404 ))
2420 2405
2421 2406 def mktempfile(self,data=None):
2422 2407 """Make a new tempfile and return its filename.
2423 2408
2424 2409 This makes a call to tempfile.mktemp, but it registers the created
2425 2410 filename internally so ipython cleans it up at exit time.
2426 2411
2427 2412 Optional inputs:
2428 2413
2429 2414 - data(None): if data is given, it gets written out to the temp file
2430 2415 immediately, and the file is closed again."""
2431 2416
2432 2417 filename = tempfile.mktemp('.py','ipython_edit_')
2433 2418 self.tempfiles.append(filename)
2434 2419
2435 2420 if data:
2436 2421 tmp_file = open(filename,'w')
2437 2422 tmp_file.write(data)
2438 2423 tmp_file.close()
2439 2424 return filename
2440 2425
2441 2426 def write(self,data):
2442 2427 """Write a string to the default output"""
2443 2428 Term.cout.write(data)
2444 2429
2445 2430 def write_err(self,data):
2446 2431 """Write a string to the default error output"""
2447 2432 Term.cerr.write(data)
2448 2433
2449 2434 def ask_yes_no(self,prompt,default=True):
2450 2435 if self.quiet:
2451 2436 return True
2452 2437 return ask_yes_no(prompt,default)
2453 2438
2454 2439 #-------------------------------------------------------------------------
2455 2440 # Things related to IPython exiting
2456 2441 #-------------------------------------------------------------------------
2457 2442
2458 2443 def ask_exit(self):
2459 2444 """ Call for exiting. Can be overiden and used as a callback. """
2460 2445 self.exit_now = True
2461 2446
2462 2447 def exit(self):
2463 2448 """Handle interactive exit.
2464 2449
2465 2450 This method calls the ask_exit callback."""
2466 2451 if self.confirm_exit:
2467 2452 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2468 2453 self.ask_exit()
2469 2454 else:
2470 2455 self.ask_exit()
2471 2456
2472 2457 def atexit_operations(self):
2473 2458 """This will be executed at the time of exit.
2474 2459
2475 2460 Saving of persistent data should be performed here.
2476 2461 """
2477 2462 self.savehist()
2478 2463
2479 2464 # Cleanup all tempfiles left around
2480 2465 for tfile in self.tempfiles:
2481 2466 try:
2482 2467 os.unlink(tfile)
2483 2468 except OSError:
2484 2469 pass
2485 2470
2486 2471 # Clear all user namespaces to release all references cleanly.
2487 2472 self.reset()
2488 2473
2489 2474 # Run user hooks
2490 2475 self.hooks.shutdown_hook()
2491 2476
2492 2477 def cleanup(self):
2493 2478 self.restore_sys_module_state()
2494 2479
2495 2480
@@ -1,3563 +1,3544
1 1 # -*- coding: utf-8 -*-
2 2 """Magic functions for InteractiveShell.
3 3 """
4 4
5 5 #*****************************************************************************
6 6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 7 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #*****************************************************************************
12 12
13 13 #****************************************************************************
14 14 # Modules and globals
15 15
16 16 # Python standard modules
17 17 import __builtin__
18 18 import bdb
19 19 import inspect
20 20 import os
21 21 import pdb
22 22 import pydoc
23 23 import sys
24 24 import re
25 25 import tempfile
26 26 import time
27 27 import cPickle as pickle
28 28 import textwrap
29 29 from cStringIO import StringIO
30 30 from getopt import getopt,GetoptError
31 31 from pprint import pprint, pformat
32 32
33 33 # cProfile was added in Python2.5
34 34 try:
35 35 import cProfile as profile
36 36 import pstats
37 37 except ImportError:
38 38 # profile isn't bundled by default in Debian for license reasons
39 39 try:
40 40 import profile,pstats
41 41 except ImportError:
42 42 profile = pstats = None
43 43
44 44 # Homebrewed
45 45 import IPython
46 46 from IPython.utils import wildcard
47 47 from IPython.core import debugger, oinspect
48 48 from IPython.core.error import TryNext
49 49 from IPython.core.fakemodule import FakeModule
50 50 from IPython.core.prefilter import ESC_MAGIC
51 51 from IPython.external.Itpl import Itpl, itpl, printpl,itplns
52 52 from IPython.utils.PyColorize import Parser
53 53 from IPython.utils.ipstruct import Struct
54 54 from IPython.core.macro import Macro
55 55 from IPython.utils.genutils import *
56 56 from IPython.core.page import page
57 57 from IPython.utils import platutils
58 58 import IPython.utils.generics
59 59 from IPython.core.error import UsageError
60 60 from IPython.testing import decorators as testdec
61 61
62 62 #***************************************************************************
63 63 # Utility functions
64 64 def on_off(tag):
65 65 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
66 66 return ['OFF','ON'][tag]
67 67
68 68 class Bunch: pass
69 69
70 70 def compress_dhist(dh):
71 71 head, tail = dh[:-10], dh[-10:]
72 72
73 73 newhead = []
74 74 done = set()
75 75 for h in head:
76 76 if h in done:
77 77 continue
78 78 newhead.append(h)
79 79 done.add(h)
80 80
81 81 return newhead + tail
82 82
83 83
84 84 #***************************************************************************
85 85 # Main class implementing Magic functionality
86 86 class Magic:
87 87 """Magic functions for InteractiveShell.
88 88
89 89 Shell functions which can be reached as %function_name. All magic
90 90 functions should accept a string, which they can parse for their own
91 91 needs. This can make some functions easier to type, eg `%cd ../`
92 92 vs. `%cd("../")`
93 93
94 94 ALL definitions MUST begin with the prefix magic_. The user won't need it
95 95 at the command line, but it is is needed in the definition. """
96 96
97 97 # class globals
98 98 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
99 99 'Automagic is ON, % prefix NOT needed for magic functions.']
100 100
101 101 #......................................................................
102 102 # some utility functions
103 103
104 104 def __init__(self,shell):
105 105
106 106 self.options_table = {}
107 107 if profile is None:
108 108 self.magic_prun = self.profile_missing_notice
109 109 self.shell = shell
110 110
111 111 # namespace for holding state we may need
112 112 self._magic_state = Bunch()
113 113
114 114 def profile_missing_notice(self, *args, **kwargs):
115 115 error("""\
116 116 The profile module could not be found. It has been removed from the standard
117 117 python packages because of its non-free license. To use profiling, install the
118 118 python-profiler package from non-free.""")
119 119
120 120 def default_option(self,fn,optstr):
121 121 """Make an entry in the options_table for fn, with value optstr"""
122 122
123 123 if fn not in self.lsmagic():
124 124 error("%s is not a magic function" % fn)
125 125 self.options_table[fn] = optstr
126 126
127 127 def lsmagic(self):
128 128 """Return a list of currently available magic functions.
129 129
130 130 Gives a list of the bare names after mangling (['ls','cd', ...], not
131 131 ['magic_ls','magic_cd',...]"""
132 132
133 133 # FIXME. This needs a cleanup, in the way the magics list is built.
134 134
135 135 # magics in class definition
136 136 class_magic = lambda fn: fn.startswith('magic_') and \
137 137 callable(Magic.__dict__[fn])
138 138 # in instance namespace (run-time user additions)
139 139 inst_magic = lambda fn: fn.startswith('magic_') and \
140 140 callable(self.__dict__[fn])
141 141 # and bound magics by user (so they can access self):
142 142 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
143 143 callable(self.__class__.__dict__[fn])
144 144 magics = filter(class_magic,Magic.__dict__.keys()) + \
145 145 filter(inst_magic,self.__dict__.keys()) + \
146 146 filter(inst_bound_magic,self.__class__.__dict__.keys())
147 147 out = []
148 148 for fn in set(magics):
149 149 out.append(fn.replace('magic_','',1))
150 150 out.sort()
151 151 return out
152 152
153 153 def extract_input_slices(self,slices,raw=False):
154 154 """Return as a string a set of input history slices.
155 155
156 156 Inputs:
157 157
158 158 - slices: the set of slices is given as a list of strings (like
159 159 ['1','4:8','9'], since this function is for use by magic functions
160 160 which get their arguments as strings.
161 161
162 162 Optional inputs:
163 163
164 164 - raw(False): by default, the processed input is used. If this is
165 165 true, the raw input history is used instead.
166 166
167 167 Note that slices can be called with two notations:
168 168
169 169 N:M -> standard python form, means including items N...(M-1).
170 170
171 171 N-M -> include items N..M (closed endpoint)."""
172 172
173 173 if raw:
174 174 hist = self.shell.input_hist_raw
175 175 else:
176 176 hist = self.shell.input_hist
177 177
178 178 cmds = []
179 179 for chunk in slices:
180 180 if ':' in chunk:
181 181 ini,fin = map(int,chunk.split(':'))
182 182 elif '-' in chunk:
183 183 ini,fin = map(int,chunk.split('-'))
184 184 fin += 1
185 185 else:
186 186 ini = int(chunk)
187 187 fin = ini+1
188 188 cmds.append(hist[ini:fin])
189 189 return cmds
190 190
191 191 def _ofind(self, oname, namespaces=None):
192 192 """Find an object in the available namespaces.
193 193
194 194 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
195 195
196 196 Has special code to detect magic functions.
197 197 """
198 198
199 199 oname = oname.strip()
200 200
201 201 alias_ns = None
202 202 if namespaces is None:
203 203 # Namespaces to search in:
204 204 # Put them in a list. The order is important so that we
205 205 # find things in the same order that Python finds them.
206 206 namespaces = [ ('Interactive', self.shell.user_ns),
207 207 ('IPython internal', self.shell.internal_ns),
208 208 ('Python builtin', __builtin__.__dict__),
209 209 ('Alias', self.shell.alias_manager.alias_table),
210 210 ]
211 211 alias_ns = self.shell.alias_manager.alias_table
212 212
213 213 # initialize results to 'null'
214 214 found = 0; obj = None; ospace = None; ds = None;
215 215 ismagic = 0; isalias = 0; parent = None
216 216
217 217 # Look for the given name by splitting it in parts. If the head is
218 218 # found, then we look for all the remaining parts as members, and only
219 219 # declare success if we can find them all.
220 220 oname_parts = oname.split('.')
221 221 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
222 222 for nsname,ns in namespaces:
223 223 try:
224 224 obj = ns[oname_head]
225 225 except KeyError:
226 226 continue
227 227 else:
228 228 #print 'oname_rest:', oname_rest # dbg
229 229 for part in oname_rest:
230 230 try:
231 231 parent = obj
232 232 obj = getattr(obj,part)
233 233 except:
234 234 # Blanket except b/c some badly implemented objects
235 235 # allow __getattr__ to raise exceptions other than
236 236 # AttributeError, which then crashes IPython.
237 237 break
238 238 else:
239 239 # If we finish the for loop (no break), we got all members
240 240 found = 1
241 241 ospace = nsname
242 242 if ns == alias_ns:
243 243 isalias = 1
244 244 break # namespace loop
245 245
246 246 # Try to see if it's magic
247 247 if not found:
248 248 if oname.startswith(ESC_MAGIC):
249 249 oname = oname[1:]
250 250 obj = getattr(self,'magic_'+oname,None)
251 251 if obj is not None:
252 252 found = 1
253 253 ospace = 'IPython internal'
254 254 ismagic = 1
255 255
256 256 # Last try: special-case some literals like '', [], {}, etc:
257 257 if not found and oname_head in ["''",'""','[]','{}','()']:
258 258 obj = eval(oname_head)
259 259 found = 1
260 260 ospace = 'Interactive'
261 261
262 262 return {'found':found, 'obj':obj, 'namespace':ospace,
263 263 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
264 264
265 265 def arg_err(self,func):
266 266 """Print docstring if incorrect arguments were passed"""
267 267 print 'Error in arguments:'
268 268 print OInspect.getdoc(func)
269 269
270 270 def format_latex(self,strng):
271 271 """Format a string for latex inclusion."""
272 272
273 273 # Characters that need to be escaped for latex:
274 274 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
275 275 # Magic command names as headers:
276 276 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
277 277 re.MULTILINE)
278 278 # Magic commands
279 279 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
280 280 re.MULTILINE)
281 281 # Paragraph continue
282 282 par_re = re.compile(r'\\$',re.MULTILINE)
283 283
284 284 # The "\n" symbol
285 285 newline_re = re.compile(r'\\n')
286 286
287 287 # Now build the string for output:
288 288 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
289 289 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
290 290 strng)
291 291 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
292 292 strng = par_re.sub(r'\\\\',strng)
293 293 strng = escape_re.sub(r'\\\1',strng)
294 294 strng = newline_re.sub(r'\\textbackslash{}n',strng)
295 295 return strng
296 296
297 297 def format_screen(self,strng):
298 298 """Format a string for screen printing.
299 299
300 300 This removes some latex-type format codes."""
301 301 # Paragraph continue
302 302 par_re = re.compile(r'\\$',re.MULTILINE)
303 303 strng = par_re.sub('',strng)
304 304 return strng
305 305
306 306 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
307 307 """Parse options passed to an argument string.
308 308
309 309 The interface is similar to that of getopt(), but it returns back a
310 310 Struct with the options as keys and the stripped argument string still
311 311 as a string.
312 312
313 313 arg_str is quoted as a true sys.argv vector by using shlex.split.
314 314 This allows us to easily expand variables, glob files, quote
315 315 arguments, etc.
316 316
317 317 Options:
318 318 -mode: default 'string'. If given as 'list', the argument string is
319 319 returned as a list (split on whitespace) instead of a string.
320 320
321 321 -list_all: put all option values in lists. Normally only options
322 322 appearing more than once are put in a list.
323 323
324 324 -posix (True): whether to split the input line in POSIX mode or not,
325 325 as per the conventions outlined in the shlex module from the
326 326 standard library."""
327 327
328 328 # inject default options at the beginning of the input line
329 329 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
330 330 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
331 331
332 332 mode = kw.get('mode','string')
333 333 if mode not in ['string','list']:
334 334 raise ValueError,'incorrect mode given: %s' % mode
335 335 # Get options
336 336 list_all = kw.get('list_all',0)
337 337 posix = kw.get('posix',True)
338 338
339 339 # Check if we have more than one argument to warrant extra processing:
340 340 odict = {} # Dictionary with options
341 341 args = arg_str.split()
342 342 if len(args) >= 1:
343 343 # If the list of inputs only has 0 or 1 thing in it, there's no
344 344 # need to look for options
345 345 argv = arg_split(arg_str,posix)
346 346 # Do regular option processing
347 347 try:
348 348 opts,args = getopt(argv,opt_str,*long_opts)
349 349 except GetoptError,e:
350 350 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
351 351 " ".join(long_opts)))
352 352 for o,a in opts:
353 353 if o.startswith('--'):
354 354 o = o[2:]
355 355 else:
356 356 o = o[1:]
357 357 try:
358 358 odict[o].append(a)
359 359 except AttributeError:
360 360 odict[o] = [odict[o],a]
361 361 except KeyError:
362 362 if list_all:
363 363 odict[o] = [a]
364 364 else:
365 365 odict[o] = a
366 366
367 367 # Prepare opts,args for return
368 368 opts = Struct(odict)
369 369 if mode == 'string':
370 370 args = ' '.join(args)
371 371
372 372 return opts,args
373 373
374 374 #......................................................................
375 375 # And now the actual magic functions
376 376
377 377 # Functions for IPython shell work (vars,funcs, config, etc)
378 378 def magic_lsmagic(self, parameter_s = ''):
379 379 """List currently available magic functions."""
380 380 mesc = ESC_MAGIC
381 381 print 'Available magic functions:\n'+mesc+\
382 382 (' '+mesc).join(self.lsmagic())
383 383 print '\n' + Magic.auto_status[self.shell.automagic]
384 384 return None
385 385
386 386 def magic_magic(self, parameter_s = ''):
387 387 """Print information about the magic function system.
388 388
389 389 Supported formats: -latex, -brief, -rest
390 390 """
391 391
392 392 mode = ''
393 393 try:
394 394 if parameter_s.split()[0] == '-latex':
395 395 mode = 'latex'
396 396 if parameter_s.split()[0] == '-brief':
397 397 mode = 'brief'
398 398 if parameter_s.split()[0] == '-rest':
399 399 mode = 'rest'
400 400 rest_docs = []
401 401 except:
402 402 pass
403 403
404 404 magic_docs = []
405 405 for fname in self.lsmagic():
406 406 mname = 'magic_' + fname
407 407 for space in (Magic,self,self.__class__):
408 408 try:
409 409 fn = space.__dict__[mname]
410 410 except KeyError:
411 411 pass
412 412 else:
413 413 break
414 414 if mode == 'brief':
415 415 # only first line
416 416 if fn.__doc__:
417 417 fndoc = fn.__doc__.split('\n',1)[0]
418 418 else:
419 419 fndoc = 'No documentation'
420 420 else:
421 421 if fn.__doc__:
422 422 fndoc = fn.__doc__.rstrip()
423 423 else:
424 424 fndoc = 'No documentation'
425 425
426 426
427 427 if mode == 'rest':
428 428 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
429 429 fname,fndoc))
430 430
431 431 else:
432 432 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
433 433 fname,fndoc))
434 434
435 435 magic_docs = ''.join(magic_docs)
436 436
437 437 if mode == 'rest':
438 438 return "".join(rest_docs)
439 439
440 440 if mode == 'latex':
441 441 print self.format_latex(magic_docs)
442 442 return
443 443 else:
444 444 magic_docs = self.format_screen(magic_docs)
445 445 if mode == 'brief':
446 446 return magic_docs
447 447
448 448 outmsg = """
449 449 IPython's 'magic' functions
450 450 ===========================
451 451
452 452 The magic function system provides a series of functions which allow you to
453 453 control the behavior of IPython itself, plus a lot of system-type
454 454 features. All these functions are prefixed with a % character, but parameters
455 455 are given without parentheses or quotes.
456 456
457 457 NOTE: If you have 'automagic' enabled (via the command line option or with the
458 458 %automagic function), you don't need to type in the % explicitly. By default,
459 459 IPython ships with automagic on, so you should only rarely need the % escape.
460 460
461 461 Example: typing '%cd mydir' (without the quotes) changes you working directory
462 462 to 'mydir', if it exists.
463 463
464 464 You can define your own magic functions to extend the system. See the supplied
465 465 ipythonrc and example-magic.py files for details (in your ipython
466 466 configuration directory, typically $HOME/.ipython/).
467 467
468 468 You can also define your own aliased names for magic functions. In your
469 469 ipythonrc file, placing a line like:
470 470
471 471 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
472 472
473 473 will define %pf as a new name for %profile.
474 474
475 475 You can also call magics in code using the magic() function, which IPython
476 476 automatically adds to the builtin namespace. Type 'magic?' for details.
477 477
478 478 For a list of the available magic functions, use %lsmagic. For a description
479 479 of any of them, type %magic_name?, e.g. '%cd?'.
480 480
481 481 Currently the magic system has the following functions:\n"""
482 482
483 483 mesc = ESC_MAGIC
484 484 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
485 485 "\n\n%s%s\n\n%s" % (outmsg,
486 486 magic_docs,mesc,mesc,
487 487 (' '+mesc).join(self.lsmagic()),
488 488 Magic.auto_status[self.shell.automagic] ) )
489 489
490 490 page(outmsg,screen_lines=self.shell.usable_screen_length)
491 491
492 492
493 493 def magic_autoindent(self, parameter_s = ''):
494 494 """Toggle autoindent on/off (if available)."""
495 495
496 496 self.shell.set_autoindent()
497 497 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
498 498
499 499
500 500 def magic_automagic(self, parameter_s = ''):
501 501 """Make magic functions callable without having to type the initial %.
502 502
503 503 Without argumentsl toggles on/off (when off, you must call it as
504 504 %automagic, of course). With arguments it sets the value, and you can
505 505 use any of (case insensitive):
506 506
507 507 - on,1,True: to activate
508 508
509 509 - off,0,False: to deactivate.
510 510
511 511 Note that magic functions have lowest priority, so if there's a
512 512 variable whose name collides with that of a magic fn, automagic won't
513 513 work for that function (you get the variable instead). However, if you
514 514 delete the variable (del var), the previously shadowed magic function
515 515 becomes visible to automagic again."""
516 516
517 517 arg = parameter_s.lower()
518 518 if parameter_s in ('on','1','true'):
519 519 self.shell.automagic = True
520 520 elif parameter_s in ('off','0','false'):
521 521 self.shell.automagic = False
522 522 else:
523 523 self.shell.automagic = not self.shell.automagic
524 524 print '\n' + Magic.auto_status[self.shell.automagic]
525 525
526 526 @testdec.skip_doctest
527 527 def magic_autocall(self, parameter_s = ''):
528 528 """Make functions callable without having to type parentheses.
529 529
530 530 Usage:
531 531
532 532 %autocall [mode]
533 533
534 534 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
535 535 value is toggled on and off (remembering the previous state).
536 536
537 537 In more detail, these values mean:
538 538
539 539 0 -> fully disabled
540 540
541 541 1 -> active, but do not apply if there are no arguments on the line.
542 542
543 543 In this mode, you get:
544 544
545 545 In [1]: callable
546 546 Out[1]: <built-in function callable>
547 547
548 548 In [2]: callable 'hello'
549 549 ------> callable('hello')
550 550 Out[2]: False
551 551
552 552 2 -> Active always. Even if no arguments are present, the callable
553 553 object is called:
554 554
555 555 In [2]: float
556 556 ------> float()
557 557 Out[2]: 0.0
558 558
559 559 Note that even with autocall off, you can still use '/' at the start of
560 560 a line to treat the first argument on the command line as a function
561 561 and add parentheses to it:
562 562
563 563 In [8]: /str 43
564 564 ------> str(43)
565 565 Out[8]: '43'
566 566
567 567 # all-random (note for auto-testing)
568 568 """
569 569
570 570 if parameter_s:
571 571 arg = int(parameter_s)
572 572 else:
573 573 arg = 'toggle'
574 574
575 575 if not arg in (0,1,2,'toggle'):
576 576 error('Valid modes: (0->Off, 1->Smart, 2->Full')
577 577 return
578 578
579 579 if arg in (0,1,2):
580 580 self.shell.autocall = arg
581 581 else: # toggle
582 582 if self.shell.autocall:
583 583 self._magic_state.autocall_save = self.shell.autocall
584 584 self.shell.autocall = 0
585 585 else:
586 586 try:
587 587 self.shell.autocall = self._magic_state.autocall_save
588 588 except AttributeError:
589 589 self.shell.autocall = self._magic_state.autocall_save = 1
590 590
591 591 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
592 592
593 593 def magic_system_verbose(self, parameter_s = ''):
594 594 """Set verbose printing of system calls.
595 595
596 596 If called without an argument, act as a toggle"""
597 597
598 598 if parameter_s:
599 599 val = bool(eval(parameter_s))
600 600 else:
601 601 val = None
602 602
603 603 if self.shell.system_verbose:
604 604 self.shell.system_verbose = False
605 605 else:
606 606 self.shell.system_verbose = True
607 607 print "System verbose printing is:",\
608 608 ['OFF','ON'][self.shell.system_verbose]
609 609
610 610
611 611 def magic_page(self, parameter_s=''):
612 612 """Pretty print the object and display it through a pager.
613 613
614 614 %page [options] OBJECT
615 615
616 616 If no object is given, use _ (last output).
617 617
618 618 Options:
619 619
620 620 -r: page str(object), don't pretty-print it."""
621 621
622 622 # After a function contributed by Olivier Aubert, slightly modified.
623 623
624 624 # Process options/args
625 625 opts,args = self.parse_options(parameter_s,'r')
626 626 raw = 'r' in opts
627 627
628 628 oname = args and args or '_'
629 629 info = self._ofind(oname)
630 630 if info['found']:
631 631 txt = (raw and str or pformat)( info['obj'] )
632 632 page(txt)
633 633 else:
634 634 print 'Object `%s` not found' % oname
635 635
636 636 def magic_profile(self, parameter_s=''):
637 637 """Print your currently active IPyhton profile."""
638 638 if self.shell.profile:
639 639 printpl('Current IPython profile: $self.shell.profile.')
640 640 else:
641 641 print 'No profile active.'
642 642
643 643 def magic_pinfo(self, parameter_s='', namespaces=None):
644 644 """Provide detailed information about an object.
645 645
646 646 '%pinfo object' is just a synonym for object? or ?object."""
647 647
648 648 #print 'pinfo par: <%s>' % parameter_s # dbg
649 649
650 650
651 651 # detail_level: 0 -> obj? , 1 -> obj??
652 652 detail_level = 0
653 653 # We need to detect if we got called as 'pinfo pinfo foo', which can
654 654 # happen if the user types 'pinfo foo?' at the cmd line.
655 655 pinfo,qmark1,oname,qmark2 = \
656 656 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
657 657 if pinfo or qmark1 or qmark2:
658 658 detail_level = 1
659 659 if "*" in oname:
660 660 self.magic_psearch(oname)
661 661 else:
662 662 self._inspect('pinfo', oname, detail_level=detail_level,
663 663 namespaces=namespaces)
664 664
665 665 def magic_pdef(self, parameter_s='', namespaces=None):
666 666 """Print the definition header for any callable object.
667 667
668 668 If the object is a class, print the constructor information."""
669 669 self._inspect('pdef',parameter_s, namespaces)
670 670
671 671 def magic_pdoc(self, parameter_s='', namespaces=None):
672 672 """Print the docstring for an object.
673 673
674 674 If the given object is a class, it will print both the class and the
675 675 constructor docstrings."""
676 676 self._inspect('pdoc',parameter_s, namespaces)
677 677
678 678 def magic_psource(self, parameter_s='', namespaces=None):
679 679 """Print (or run through pager) the source code for an object."""
680 680 self._inspect('psource',parameter_s, namespaces)
681 681
682 682 def magic_pfile(self, parameter_s=''):
683 683 """Print (or run through pager) the file where an object is defined.
684 684
685 685 The file opens at the line where the object definition begins. IPython
686 686 will honor the environment variable PAGER if set, and otherwise will
687 687 do its best to print the file in a convenient form.
688 688
689 689 If the given argument is not an object currently defined, IPython will
690 690 try to interpret it as a filename (automatically adding a .py extension
691 691 if needed). You can thus use %pfile as a syntax highlighting code
692 692 viewer."""
693 693
694 694 # first interpret argument as an object name
695 695 out = self._inspect('pfile',parameter_s)
696 696 # if not, try the input as a filename
697 697 if out == 'not found':
698 698 try:
699 699 filename = get_py_filename(parameter_s)
700 700 except IOError,msg:
701 701 print msg
702 702 return
703 703 page(self.shell.inspector.format(file(filename).read()))
704 704
705 705 def _inspect(self,meth,oname,namespaces=None,**kw):
706 706 """Generic interface to the inspector system.
707 707
708 708 This function is meant to be called by pdef, pdoc & friends."""
709 709
710 710 #oname = oname.strip()
711 711 #print '1- oname: <%r>' % oname # dbg
712 712 try:
713 713 oname = oname.strip().encode('ascii')
714 714 #print '2- oname: <%r>' % oname # dbg
715 715 except UnicodeEncodeError:
716 716 print 'Python identifiers can only contain ascii characters.'
717 717 return 'not found'
718 718
719 719 info = Struct(self._ofind(oname, namespaces))
720 720
721 721 if info.found:
722 722 try:
723 723 IPython.utils.generics.inspect_object(info.obj)
724 724 return
725 725 except TryNext:
726 726 pass
727 727 # Get the docstring of the class property if it exists.
728 728 path = oname.split('.')
729 729 root = '.'.join(path[:-1])
730 730 if info.parent is not None:
731 731 try:
732 732 target = getattr(info.parent, '__class__')
733 733 # The object belongs to a class instance.
734 734 try:
735 735 target = getattr(target, path[-1])
736 736 # The class defines the object.
737 737 if isinstance(target, property):
738 738 oname = root + '.__class__.' + path[-1]
739 739 info = Struct(self._ofind(oname))
740 740 except AttributeError: pass
741 741 except AttributeError: pass
742 742
743 743 pmethod = getattr(self.shell.inspector,meth)
744 744 formatter = info.ismagic and self.format_screen or None
745 745 if meth == 'pdoc':
746 746 pmethod(info.obj,oname,formatter)
747 747 elif meth == 'pinfo':
748 748 pmethod(info.obj,oname,formatter,info,**kw)
749 749 else:
750 750 pmethod(info.obj,oname)
751 751 else:
752 752 print 'Object `%s` not found.' % oname
753 753 return 'not found' # so callers can take other action
754 754
755 755 def magic_psearch(self, parameter_s=''):
756 756 """Search for object in namespaces by wildcard.
757 757
758 758 %psearch [options] PATTERN [OBJECT TYPE]
759 759
760 760 Note: ? can be used as a synonym for %psearch, at the beginning or at
761 761 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
762 762 rest of the command line must be unchanged (options come first), so
763 763 for example the following forms are equivalent
764 764
765 765 %psearch -i a* function
766 766 -i a* function?
767 767 ?-i a* function
768 768
769 769 Arguments:
770 770
771 771 PATTERN
772 772
773 773 where PATTERN is a string containing * as a wildcard similar to its
774 774 use in a shell. The pattern is matched in all namespaces on the
775 775 search path. By default objects starting with a single _ are not
776 776 matched, many IPython generated objects have a single
777 777 underscore. The default is case insensitive matching. Matching is
778 778 also done on the attributes of objects and not only on the objects
779 779 in a module.
780 780
781 781 [OBJECT TYPE]
782 782
783 783 Is the name of a python type from the types module. The name is
784 784 given in lowercase without the ending type, ex. StringType is
785 785 written string. By adding a type here only objects matching the
786 786 given type are matched. Using all here makes the pattern match all
787 787 types (this is the default).
788 788
789 789 Options:
790 790
791 791 -a: makes the pattern match even objects whose names start with a
792 792 single underscore. These names are normally ommitted from the
793 793 search.
794 794
795 795 -i/-c: make the pattern case insensitive/sensitive. If neither of
796 796 these options is given, the default is read from your ipythonrc
797 797 file. The option name which sets this value is
798 798 'wildcards_case_sensitive'. If this option is not specified in your
799 799 ipythonrc file, IPython's internal default is to do a case sensitive
800 800 search.
801 801
802 802 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
803 803 specifiy can be searched in any of the following namespaces:
804 804 'builtin', 'user', 'user_global','internal', 'alias', where
805 805 'builtin' and 'user' are the search defaults. Note that you should
806 806 not use quotes when specifying namespaces.
807 807
808 808 'Builtin' contains the python module builtin, 'user' contains all
809 809 user data, 'alias' only contain the shell aliases and no python
810 810 objects, 'internal' contains objects used by IPython. The
811 811 'user_global' namespace is only used by embedded IPython instances,
812 812 and it contains module-level globals. You can add namespaces to the
813 813 search with -s or exclude them with -e (these options can be given
814 814 more than once).
815 815
816 816 Examples:
817 817
818 818 %psearch a* -> objects beginning with an a
819 819 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
820 820 %psearch a* function -> all functions beginning with an a
821 821 %psearch re.e* -> objects beginning with an e in module re
822 822 %psearch r*.e* -> objects that start with e in modules starting in r
823 823 %psearch r*.* string -> all strings in modules beginning with r
824 824
825 825 Case sensitve search:
826 826
827 827 %psearch -c a* list all object beginning with lower case a
828 828
829 829 Show objects beginning with a single _:
830 830
831 831 %psearch -a _* list objects beginning with a single underscore"""
832 832 try:
833 833 parameter_s = parameter_s.encode('ascii')
834 834 except UnicodeEncodeError:
835 835 print 'Python identifiers can only contain ascii characters.'
836 836 return
837 837
838 838 # default namespaces to be searched
839 839 def_search = ['user','builtin']
840 840
841 841 # Process options/args
842 842 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
843 843 opt = opts.get
844 844 shell = self.shell
845 845 psearch = shell.inspector.psearch
846 846
847 847 # select case options
848 848 if opts.has_key('i'):
849 849 ignore_case = True
850 850 elif opts.has_key('c'):
851 851 ignore_case = False
852 852 else:
853 853 ignore_case = not shell.wildcards_case_sensitive
854 854
855 855 # Build list of namespaces to search from user options
856 856 def_search.extend(opt('s',[]))
857 857 ns_exclude = ns_exclude=opt('e',[])
858 858 ns_search = [nm for nm in def_search if nm not in ns_exclude]
859 859
860 860 # Call the actual search
861 861 try:
862 862 psearch(args,shell.ns_table,ns_search,
863 863 show_all=opt('a'),ignore_case=ignore_case)
864 864 except:
865 865 shell.showtraceback()
866 866
867 867 def magic_who_ls(self, parameter_s=''):
868 868 """Return a sorted list of all interactive variables.
869 869
870 870 If arguments are given, only variables of types matching these
871 871 arguments are returned."""
872 872
873 873 user_ns = self.shell.user_ns
874 874 internal_ns = self.shell.internal_ns
875 875 user_config_ns = self.shell.user_config_ns
876 876 out = []
877 877 typelist = parameter_s.split()
878 878
879 879 for i in user_ns:
880 880 if not (i.startswith('_') or i.startswith('_i')) \
881 881 and not (i in internal_ns or i in user_config_ns):
882 882 if typelist:
883 883 if type(user_ns[i]).__name__ in typelist:
884 884 out.append(i)
885 885 else:
886 886 out.append(i)
887 887 out.sort()
888 888 return out
889 889
890 890 def magic_who(self, parameter_s=''):
891 891 """Print all interactive variables, with some minimal formatting.
892 892
893 893 If any arguments are given, only variables whose type matches one of
894 894 these are printed. For example:
895 895
896 896 %who function str
897 897
898 898 will only list functions and strings, excluding all other types of
899 899 variables. To find the proper type names, simply use type(var) at a
900 900 command line to see how python prints type names. For example:
901 901
902 902 In [1]: type('hello')\\
903 903 Out[1]: <type 'str'>
904 904
905 905 indicates that the type name for strings is 'str'.
906 906
907 907 %who always excludes executed names loaded through your configuration
908 908 file and things which are internal to IPython.
909 909
910 910 This is deliberate, as typically you may load many modules and the
911 911 purpose of %who is to show you only what you've manually defined."""
912 912
913 913 varlist = self.magic_who_ls(parameter_s)
914 914 if not varlist:
915 915 if parameter_s:
916 916 print 'No variables match your requested type.'
917 917 else:
918 918 print 'Interactive namespace is empty.'
919 919 return
920 920
921 921 # if we have variables, move on...
922 922 count = 0
923 923 for i in varlist:
924 924 print i+'\t',
925 925 count += 1
926 926 if count > 8:
927 927 count = 0
928 928 print
929 929 print
930 930
931 931 def magic_whos(self, parameter_s=''):
932 932 """Like %who, but gives some extra information about each variable.
933 933
934 934 The same type filtering of %who can be applied here.
935 935
936 936 For all variables, the type is printed. Additionally it prints:
937 937
938 938 - For {},[],(): their length.
939 939
940 940 - For numpy and Numeric arrays, a summary with shape, number of
941 941 elements, typecode and size in memory.
942 942
943 943 - Everything else: a string representation, snipping their middle if
944 944 too long."""
945 945
946 946 varnames = self.magic_who_ls(parameter_s)
947 947 if not varnames:
948 948 if parameter_s:
949 949 print 'No variables match your requested type.'
950 950 else:
951 951 print 'Interactive namespace is empty.'
952 952 return
953 953
954 954 # if we have variables, move on...
955 955
956 956 # for these types, show len() instead of data:
957 957 seq_types = [types.DictType,types.ListType,types.TupleType]
958 958
959 959 # for numpy/Numeric arrays, display summary info
960 960 try:
961 961 import numpy
962 962 except ImportError:
963 963 ndarray_type = None
964 964 else:
965 965 ndarray_type = numpy.ndarray.__name__
966 966 try:
967 967 import Numeric
968 968 except ImportError:
969 969 array_type = None
970 970 else:
971 971 array_type = Numeric.ArrayType.__name__
972 972
973 973 # Find all variable names and types so we can figure out column sizes
974 974 def get_vars(i):
975 975 return self.shell.user_ns[i]
976 976
977 977 # some types are well known and can be shorter
978 978 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
979 979 def type_name(v):
980 980 tn = type(v).__name__
981 981 return abbrevs.get(tn,tn)
982 982
983 983 varlist = map(get_vars,varnames)
984 984
985 985 typelist = []
986 986 for vv in varlist:
987 987 tt = type_name(vv)
988 988
989 989 if tt=='instance':
990 990 typelist.append( abbrevs.get(str(vv.__class__),
991 991 str(vv.__class__)))
992 992 else:
993 993 typelist.append(tt)
994 994
995 995 # column labels and # of spaces as separator
996 996 varlabel = 'Variable'
997 997 typelabel = 'Type'
998 998 datalabel = 'Data/Info'
999 999 colsep = 3
1000 1000 # variable format strings
1001 1001 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1002 1002 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1003 1003 aformat = "%s: %s elems, type `%s`, %s bytes"
1004 1004 # find the size of the columns to format the output nicely
1005 1005 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1006 1006 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1007 1007 # table header
1008 1008 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1009 1009 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1010 1010 # and the table itself
1011 1011 kb = 1024
1012 1012 Mb = 1048576 # kb**2
1013 1013 for vname,var,vtype in zip(varnames,varlist,typelist):
1014 1014 print itpl(vformat),
1015 1015 if vtype in seq_types:
1016 1016 print len(var)
1017 1017 elif vtype in [array_type,ndarray_type]:
1018 1018 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1019 1019 if vtype==ndarray_type:
1020 1020 # numpy
1021 1021 vsize = var.size
1022 1022 vbytes = vsize*var.itemsize
1023 1023 vdtype = var.dtype
1024 1024 else:
1025 1025 # Numeric
1026 1026 vsize = Numeric.size(var)
1027 1027 vbytes = vsize*var.itemsize()
1028 1028 vdtype = var.typecode()
1029 1029
1030 1030 if vbytes < 100000:
1031 1031 print aformat % (vshape,vsize,vdtype,vbytes)
1032 1032 else:
1033 1033 print aformat % (vshape,vsize,vdtype,vbytes),
1034 1034 if vbytes < Mb:
1035 1035 print '(%s kb)' % (vbytes/kb,)
1036 1036 else:
1037 1037 print '(%s Mb)' % (vbytes/Mb,)
1038 1038 else:
1039 1039 try:
1040 1040 vstr = str(var)
1041 1041 except UnicodeEncodeError:
1042 1042 vstr = unicode(var).encode(sys.getdefaultencoding(),
1043 1043 'backslashreplace')
1044 1044 vstr = vstr.replace('\n','\\n')
1045 1045 if len(vstr) < 50:
1046 1046 print vstr
1047 1047 else:
1048 1048 printpl(vfmt_short)
1049 1049
1050 1050 def magic_reset(self, parameter_s=''):
1051 1051 """Resets the namespace by removing all names defined by the user.
1052 1052
1053 1053 Input/Output history are left around in case you need them.
1054 1054
1055 1055 Parameters
1056 1056 ----------
1057 1057 -y : force reset without asking for confirmation.
1058 1058
1059 1059 Examples
1060 1060 --------
1061 1061 In [6]: a = 1
1062 1062
1063 1063 In [7]: a
1064 1064 Out[7]: 1
1065 1065
1066 1066 In [8]: 'a' in _ip.user_ns
1067 1067 Out[8]: True
1068 1068
1069 1069 In [9]: %reset -f
1070 1070
1071 1071 In [10]: 'a' in _ip.user_ns
1072 1072 Out[10]: False
1073 1073 """
1074 1074
1075 1075 if parameter_s == '-f':
1076 1076 ans = True
1077 1077 else:
1078 1078 ans = self.shell.ask_yes_no(
1079 1079 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1080 1080 if not ans:
1081 1081 print 'Nothing done.'
1082 1082 return
1083 1083 user_ns = self.shell.user_ns
1084 1084 for i in self.magic_who_ls():
1085 1085 del(user_ns[i])
1086 1086
1087 1087 # Also flush the private list of module references kept for script
1088 1088 # execution protection
1089 1089 self.shell.clear_main_mod_cache()
1090 1090
1091 1091 def magic_logstart(self,parameter_s=''):
1092 1092 """Start logging anywhere in a session.
1093 1093
1094 1094 %logstart [-o|-r|-t] [log_name [log_mode]]
1095 1095
1096 1096 If no name is given, it defaults to a file named 'ipython_log.py' in your
1097 1097 current directory, in 'rotate' mode (see below).
1098 1098
1099 1099 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1100 1100 history up to that point and then continues logging.
1101 1101
1102 1102 %logstart takes a second optional parameter: logging mode. This can be one
1103 1103 of (note that the modes are given unquoted):\\
1104 1104 append: well, that says it.\\
1105 1105 backup: rename (if exists) to name~ and start name.\\
1106 1106 global: single logfile in your home dir, appended to.\\
1107 1107 over : overwrite existing log.\\
1108 1108 rotate: create rotating logs name.1~, name.2~, etc.
1109 1109
1110 1110 Options:
1111 1111
1112 1112 -o: log also IPython's output. In this mode, all commands which
1113 1113 generate an Out[NN] prompt are recorded to the logfile, right after
1114 1114 their corresponding input line. The output lines are always
1115 1115 prepended with a '#[Out]# ' marker, so that the log remains valid
1116 1116 Python code.
1117 1117
1118 1118 Since this marker is always the same, filtering only the output from
1119 1119 a log is very easy, using for example a simple awk call:
1120 1120
1121 1121 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1122 1122
1123 1123 -r: log 'raw' input. Normally, IPython's logs contain the processed
1124 1124 input, so that user lines are logged in their final form, converted
1125 1125 into valid Python. For example, %Exit is logged as
1126 1126 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1127 1127 exactly as typed, with no transformations applied.
1128 1128
1129 1129 -t: put timestamps before each input line logged (these are put in
1130 1130 comments)."""
1131 1131
1132 1132 opts,par = self.parse_options(parameter_s,'ort')
1133 1133 log_output = 'o' in opts
1134 1134 log_raw_input = 'r' in opts
1135 1135 timestamp = 't' in opts
1136 1136
1137 1137 logger = self.shell.logger
1138 1138
1139 1139 # if no args are given, the defaults set in the logger constructor by
1140 1140 # ipytohn remain valid
1141 1141 if par:
1142 1142 try:
1143 1143 logfname,logmode = par.split()
1144 1144 except:
1145 1145 logfname = par
1146 1146 logmode = 'backup'
1147 1147 else:
1148 1148 logfname = logger.logfname
1149 1149 logmode = logger.logmode
1150 1150 # put logfname into rc struct as if it had been called on the command
1151 1151 # line, so it ends up saved in the log header Save it in case we need
1152 1152 # to restore it...
1153 1153 old_logfile = self.shell.logfile
1154 1154 if logfname:
1155 1155 logfname = os.path.expanduser(logfname)
1156 1156 self.shell.logfile = logfname
1157 1157 # TODO: we need to re-think how logs with args/opts are replayed
1158 1158 # and tracked.
1159 1159 # loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1160 1160 loghead = self.shell.loghead_tpl % ('','')
1161 1161 try:
1162 1162 started = logger.logstart(logfname,loghead,logmode,
1163 1163 log_output,timestamp,log_raw_input)
1164 1164 except:
1165 1165 rc.opts.logfile = old_logfile
1166 1166 warn("Couldn't start log: %s" % sys.exc_info()[1])
1167 1167 else:
1168 1168 # log input history up to this point, optionally interleaving
1169 1169 # output if requested
1170 1170
1171 1171 if timestamp:
1172 1172 # disable timestamping for the previous history, since we've
1173 1173 # lost those already (no time machine here).
1174 1174 logger.timestamp = False
1175 1175
1176 1176 if log_raw_input:
1177 1177 input_hist = self.shell.input_hist_raw
1178 1178 else:
1179 1179 input_hist = self.shell.input_hist
1180 1180
1181 1181 if log_output:
1182 1182 log_write = logger.log_write
1183 1183 output_hist = self.shell.output_hist
1184 1184 for n in range(1,len(input_hist)-1):
1185 1185 log_write(input_hist[n].rstrip())
1186 1186 if n in output_hist:
1187 1187 log_write(repr(output_hist[n]),'output')
1188 1188 else:
1189 1189 logger.log_write(input_hist[1:])
1190 1190 if timestamp:
1191 1191 # re-enable timestamping
1192 1192 logger.timestamp = True
1193 1193
1194 1194 print ('Activating auto-logging. '
1195 1195 'Current session state plus future input saved.')
1196 1196 logger.logstate()
1197 1197
1198 1198 def magic_logstop(self,parameter_s=''):
1199 1199 """Fully stop logging and close log file.
1200 1200
1201 1201 In order to start logging again, a new %logstart call needs to be made,
1202 1202 possibly (though not necessarily) with a new filename, mode and other
1203 1203 options."""
1204 1204 self.logger.logstop()
1205 1205
1206 1206 def magic_logoff(self,parameter_s=''):
1207 1207 """Temporarily stop logging.
1208 1208
1209 1209 You must have previously started logging."""
1210 1210 self.shell.logger.switch_log(0)
1211 1211
1212 1212 def magic_logon(self,parameter_s=''):
1213 1213 """Restart logging.
1214 1214
1215 1215 This function is for restarting logging which you've temporarily
1216 1216 stopped with %logoff. For starting logging for the first time, you
1217 1217 must use the %logstart function, which allows you to specify an
1218 1218 optional log filename."""
1219 1219
1220 1220 self.shell.logger.switch_log(1)
1221 1221
1222 1222 def magic_logstate(self,parameter_s=''):
1223 1223 """Print the status of the logging system."""
1224 1224
1225 1225 self.shell.logger.logstate()
1226 1226
1227 1227 def magic_pdb(self, parameter_s=''):
1228 1228 """Control the automatic calling of the pdb interactive debugger.
1229 1229
1230 1230 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1231 1231 argument it works as a toggle.
1232 1232
1233 1233 When an exception is triggered, IPython can optionally call the
1234 1234 interactive pdb debugger after the traceback printout. %pdb toggles
1235 1235 this feature on and off.
1236 1236
1237 1237 The initial state of this feature is set in your ipythonrc
1238 1238 configuration file (the variable is called 'pdb').
1239 1239
1240 1240 If you want to just activate the debugger AFTER an exception has fired,
1241 1241 without having to type '%pdb on' and rerunning your code, you can use
1242 1242 the %debug magic."""
1243 1243
1244 1244 par = parameter_s.strip().lower()
1245 1245
1246 1246 if par:
1247 1247 try:
1248 1248 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1249 1249 except KeyError:
1250 1250 print ('Incorrect argument. Use on/1, off/0, '
1251 1251 'or nothing for a toggle.')
1252 1252 return
1253 1253 else:
1254 1254 # toggle
1255 1255 new_pdb = not self.shell.call_pdb
1256 1256
1257 1257 # set on the shell
1258 1258 self.shell.call_pdb = new_pdb
1259 1259 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1260 1260
1261 1261 def magic_debug(self, parameter_s=''):
1262 1262 """Activate the interactive debugger in post-mortem mode.
1263 1263
1264 1264 If an exception has just occurred, this lets you inspect its stack
1265 1265 frames interactively. Note that this will always work only on the last
1266 1266 traceback that occurred, so you must call this quickly after an
1267 1267 exception that you wish to inspect has fired, because if another one
1268 1268 occurs, it clobbers the previous one.
1269 1269
1270 1270 If you want IPython to automatically do this on every exception, see
1271 1271 the %pdb magic for more details.
1272 1272 """
1273 1273
1274 1274 self.shell.debugger(force=True)
1275 1275
1276 1276 @testdec.skip_doctest
1277 1277 def magic_prun(self, parameter_s ='',user_mode=1,
1278 1278 opts=None,arg_lst=None,prog_ns=None):
1279 1279
1280 1280 """Run a statement through the python code profiler.
1281 1281
1282 1282 Usage:
1283 1283 %prun [options] statement
1284 1284
1285 1285 The given statement (which doesn't require quote marks) is run via the
1286 1286 python profiler in a manner similar to the profile.run() function.
1287 1287 Namespaces are internally managed to work correctly; profile.run
1288 1288 cannot be used in IPython because it makes certain assumptions about
1289 1289 namespaces which do not hold under IPython.
1290 1290
1291 1291 Options:
1292 1292
1293 1293 -l <limit>: you can place restrictions on what or how much of the
1294 1294 profile gets printed. The limit value can be:
1295 1295
1296 1296 * A string: only information for function names containing this string
1297 1297 is printed.
1298 1298
1299 1299 * An integer: only these many lines are printed.
1300 1300
1301 1301 * A float (between 0 and 1): this fraction of the report is printed
1302 1302 (for example, use a limit of 0.4 to see the topmost 40% only).
1303 1303
1304 1304 You can combine several limits with repeated use of the option. For
1305 1305 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1306 1306 information about class constructors.
1307 1307
1308 1308 -r: return the pstats.Stats object generated by the profiling. This
1309 1309 object has all the information about the profile in it, and you can
1310 1310 later use it for further analysis or in other functions.
1311 1311
1312 1312 -s <key>: sort profile by given key. You can provide more than one key
1313 1313 by using the option several times: '-s key1 -s key2 -s key3...'. The
1314 1314 default sorting key is 'time'.
1315 1315
1316 1316 The following is copied verbatim from the profile documentation
1317 1317 referenced below:
1318 1318
1319 1319 When more than one key is provided, additional keys are used as
1320 1320 secondary criteria when the there is equality in all keys selected
1321 1321 before them.
1322 1322
1323 1323 Abbreviations can be used for any key names, as long as the
1324 1324 abbreviation is unambiguous. The following are the keys currently
1325 1325 defined:
1326 1326
1327 1327 Valid Arg Meaning
1328 1328 "calls" call count
1329 1329 "cumulative" cumulative time
1330 1330 "file" file name
1331 1331 "module" file name
1332 1332 "pcalls" primitive call count
1333 1333 "line" line number
1334 1334 "name" function name
1335 1335 "nfl" name/file/line
1336 1336 "stdname" standard name
1337 1337 "time" internal time
1338 1338
1339 1339 Note that all sorts on statistics are in descending order (placing
1340 1340 most time consuming items first), where as name, file, and line number
1341 1341 searches are in ascending order (i.e., alphabetical). The subtle
1342 1342 distinction between "nfl" and "stdname" is that the standard name is a
1343 1343 sort of the name as printed, which means that the embedded line
1344 1344 numbers get compared in an odd way. For example, lines 3, 20, and 40
1345 1345 would (if the file names were the same) appear in the string order
1346 1346 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1347 1347 line numbers. In fact, sort_stats("nfl") is the same as
1348 1348 sort_stats("name", "file", "line").
1349 1349
1350 1350 -T <filename>: save profile results as shown on screen to a text
1351 1351 file. The profile is still shown on screen.
1352 1352
1353 1353 -D <filename>: save (via dump_stats) profile statistics to given
1354 1354 filename. This data is in a format understod by the pstats module, and
1355 1355 is generated by a call to the dump_stats() method of profile
1356 1356 objects. The profile is still shown on screen.
1357 1357
1358 1358 If you want to run complete programs under the profiler's control, use
1359 1359 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1360 1360 contains profiler specific options as described here.
1361 1361
1362 1362 You can read the complete documentation for the profile module with::
1363 1363
1364 1364 In [1]: import profile; profile.help()
1365 1365 """
1366 1366
1367 1367 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1368 1368 # protect user quote marks
1369 1369 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1370 1370
1371 1371 if user_mode: # regular user call
1372 1372 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1373 1373 list_all=1)
1374 1374 namespace = self.shell.user_ns
1375 1375 else: # called to run a program by %run -p
1376 1376 try:
1377 1377 filename = get_py_filename(arg_lst[0])
1378 1378 except IOError,msg:
1379 1379 error(msg)
1380 1380 return
1381 1381
1382 1382 arg_str = 'execfile(filename,prog_ns)'
1383 1383 namespace = locals()
1384 1384
1385 1385 opts.merge(opts_def)
1386 1386
1387 1387 prof = profile.Profile()
1388 1388 try:
1389 1389 prof = prof.runctx(arg_str,namespace,namespace)
1390 1390 sys_exit = ''
1391 1391 except SystemExit:
1392 1392 sys_exit = """*** SystemExit exception caught in code being profiled."""
1393 1393
1394 1394 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1395 1395
1396 1396 lims = opts.l
1397 1397 if lims:
1398 1398 lims = [] # rebuild lims with ints/floats/strings
1399 1399 for lim in opts.l:
1400 1400 try:
1401 1401 lims.append(int(lim))
1402 1402 except ValueError:
1403 1403 try:
1404 1404 lims.append(float(lim))
1405 1405 except ValueError:
1406 1406 lims.append(lim)
1407 1407
1408 1408 # Trap output.
1409 1409 stdout_trap = StringIO()
1410 1410
1411 1411 if hasattr(stats,'stream'):
1412 1412 # In newer versions of python, the stats object has a 'stream'
1413 1413 # attribute to write into.
1414 1414 stats.stream = stdout_trap
1415 1415 stats.print_stats(*lims)
1416 1416 else:
1417 1417 # For older versions, we manually redirect stdout during printing
1418 1418 sys_stdout = sys.stdout
1419 1419 try:
1420 1420 sys.stdout = stdout_trap
1421 1421 stats.print_stats(*lims)
1422 1422 finally:
1423 1423 sys.stdout = sys_stdout
1424 1424
1425 1425 output = stdout_trap.getvalue()
1426 1426 output = output.rstrip()
1427 1427
1428 1428 page(output,screen_lines=self.shell.usable_screen_length)
1429 1429 print sys_exit,
1430 1430
1431 1431 dump_file = opts.D[0]
1432 1432 text_file = opts.T[0]
1433 1433 if dump_file:
1434 1434 prof.dump_stats(dump_file)
1435 1435 print '\n*** Profile stats marshalled to file',\
1436 1436 `dump_file`+'.',sys_exit
1437 1437 if text_file:
1438 1438 pfile = file(text_file,'w')
1439 1439 pfile.write(output)
1440 1440 pfile.close()
1441 1441 print '\n*** Profile printout saved to text file',\
1442 1442 `text_file`+'.',sys_exit
1443 1443
1444 1444 if opts.has_key('r'):
1445 1445 return stats
1446 1446 else:
1447 1447 return None
1448 1448
1449 1449 @testdec.skip_doctest
1450 1450 def magic_run(self, parameter_s ='',runner=None,
1451 1451 file_finder=get_py_filename):
1452 1452 """Run the named file inside IPython as a program.
1453 1453
1454 1454 Usage:\\
1455 1455 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1456 1456
1457 1457 Parameters after the filename are passed as command-line arguments to
1458 1458 the program (put in sys.argv). Then, control returns to IPython's
1459 1459 prompt.
1460 1460
1461 1461 This is similar to running at a system prompt:\\
1462 1462 $ python file args\\
1463 1463 but with the advantage of giving you IPython's tracebacks, and of
1464 1464 loading all variables into your interactive namespace for further use
1465 1465 (unless -p is used, see below).
1466 1466
1467 1467 The file is executed in a namespace initially consisting only of
1468 1468 __name__=='__main__' and sys.argv constructed as indicated. It thus
1469 1469 sees its environment as if it were being run as a stand-alone program
1470 1470 (except for sharing global objects such as previously imported
1471 1471 modules). But after execution, the IPython interactive namespace gets
1472 1472 updated with all variables defined in the program (except for __name__
1473 1473 and sys.argv). This allows for very convenient loading of code for
1474 1474 interactive work, while giving each program a 'clean sheet' to run in.
1475 1475
1476 1476 Options:
1477 1477
1478 1478 -n: __name__ is NOT set to '__main__', but to the running file's name
1479 1479 without extension (as python does under import). This allows running
1480 1480 scripts and reloading the definitions in them without calling code
1481 1481 protected by an ' if __name__ == "__main__" ' clause.
1482 1482
1483 1483 -i: run the file in IPython's namespace instead of an empty one. This
1484 1484 is useful if you are experimenting with code written in a text editor
1485 1485 which depends on variables defined interactively.
1486 1486
1487 1487 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1488 1488 being run. This is particularly useful if IPython is being used to
1489 1489 run unittests, which always exit with a sys.exit() call. In such
1490 1490 cases you are interested in the output of the test results, not in
1491 1491 seeing a traceback of the unittest module.
1492 1492
1493 1493 -t: print timing information at the end of the run. IPython will give
1494 1494 you an estimated CPU time consumption for your script, which under
1495 1495 Unix uses the resource module to avoid the wraparound problems of
1496 1496 time.clock(). Under Unix, an estimate of time spent on system tasks
1497 1497 is also given (for Windows platforms this is reported as 0.0).
1498 1498
1499 1499 If -t is given, an additional -N<N> option can be given, where <N>
1500 1500 must be an integer indicating how many times you want the script to
1501 1501 run. The final timing report will include total and per run results.
1502 1502
1503 1503 For example (testing the script uniq_stable.py):
1504 1504
1505 1505 In [1]: run -t uniq_stable
1506 1506
1507 1507 IPython CPU timings (estimated):\\
1508 1508 User : 0.19597 s.\\
1509 1509 System: 0.0 s.\\
1510 1510
1511 1511 In [2]: run -t -N5 uniq_stable
1512 1512
1513 1513 IPython CPU timings (estimated):\\
1514 1514 Total runs performed: 5\\
1515 1515 Times : Total Per run\\
1516 1516 User : 0.910862 s, 0.1821724 s.\\
1517 1517 System: 0.0 s, 0.0 s.
1518 1518
1519 1519 -d: run your program under the control of pdb, the Python debugger.
1520 1520 This allows you to execute your program step by step, watch variables,
1521 1521 etc. Internally, what IPython does is similar to calling:
1522 1522
1523 1523 pdb.run('execfile("YOURFILENAME")')
1524 1524
1525 1525 with a breakpoint set on line 1 of your file. You can change the line
1526 1526 number for this automatic breakpoint to be <N> by using the -bN option
1527 1527 (where N must be an integer). For example:
1528 1528
1529 1529 %run -d -b40 myscript
1530 1530
1531 1531 will set the first breakpoint at line 40 in myscript.py. Note that
1532 1532 the first breakpoint must be set on a line which actually does
1533 1533 something (not a comment or docstring) for it to stop execution.
1534 1534
1535 1535 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1536 1536 first enter 'c' (without qoutes) to start execution up to the first
1537 1537 breakpoint.
1538 1538
1539 1539 Entering 'help' gives information about the use of the debugger. You
1540 1540 can easily see pdb's full documentation with "import pdb;pdb.help()"
1541 1541 at a prompt.
1542 1542
1543 1543 -p: run program under the control of the Python profiler module (which
1544 1544 prints a detailed report of execution times, function calls, etc).
1545 1545
1546 1546 You can pass other options after -p which affect the behavior of the
1547 1547 profiler itself. See the docs for %prun for details.
1548 1548
1549 1549 In this mode, the program's variables do NOT propagate back to the
1550 1550 IPython interactive namespace (because they remain in the namespace
1551 1551 where the profiler executes them).
1552 1552
1553 1553 Internally this triggers a call to %prun, see its documentation for
1554 1554 details on the options available specifically for profiling.
1555 1555
1556 1556 There is one special usage for which the text above doesn't apply:
1557 1557 if the filename ends with .ipy, the file is run as ipython script,
1558 1558 just as if the commands were written on IPython prompt.
1559 1559 """
1560 1560
1561 1561 # get arguments and set sys.argv for program to be run.
1562 1562 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1563 1563 mode='list',list_all=1)
1564 1564
1565 1565 try:
1566 1566 filename = file_finder(arg_lst[0])
1567 1567 except IndexError:
1568 1568 warn('you must provide at least a filename.')
1569 1569 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1570 1570 return
1571 1571 except IOError,msg:
1572 1572 error(msg)
1573 1573 return
1574 1574
1575 1575 if filename.lower().endswith('.ipy'):
1576 self.runlines(open(filename).read(), clean=True)
1576 self.safe_execfile_ipy(filename)
1577 1577 return
1578 1578
1579 1579 # Control the response to exit() calls made by the script being run
1580 1580 exit_ignore = opts.has_key('e')
1581 1581
1582 1582 # Make sure that the running script gets a proper sys.argv as if it
1583 1583 # were run from a system shell.
1584 1584 save_argv = sys.argv # save it for later restoring
1585 1585 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1586 1586
1587 1587 if opts.has_key('i'):
1588 1588 # Run in user's interactive namespace
1589 1589 prog_ns = self.shell.user_ns
1590 1590 __name__save = self.shell.user_ns['__name__']
1591 1591 prog_ns['__name__'] = '__main__'
1592 1592 main_mod = self.shell.new_main_mod(prog_ns)
1593 1593 else:
1594 1594 # Run in a fresh, empty namespace
1595 1595 if opts.has_key('n'):
1596 1596 name = os.path.splitext(os.path.basename(filename))[0]
1597 1597 else:
1598 1598 name = '__main__'
1599 1599
1600 1600 main_mod = self.shell.new_main_mod()
1601 1601 prog_ns = main_mod.__dict__
1602 1602 prog_ns['__name__'] = name
1603 1603
1604 1604 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1605 1605 # set the __file__ global in the script's namespace
1606 1606 prog_ns['__file__'] = filename
1607 1607
1608 1608 # pickle fix. See iplib for an explanation. But we need to make sure
1609 1609 # that, if we overwrite __main__, we replace it at the end
1610 1610 main_mod_name = prog_ns['__name__']
1611 1611
1612 1612 if main_mod_name == '__main__':
1613 1613 restore_main = sys.modules['__main__']
1614 1614 else:
1615 1615 restore_main = False
1616 1616
1617 1617 # This needs to be undone at the end to prevent holding references to
1618 1618 # every single object ever created.
1619 1619 sys.modules[main_mod_name] = main_mod
1620 1620
1621 1621 stats = None
1622 1622 try:
1623 1623 self.shell.savehist()
1624 1624
1625 1625 if opts.has_key('p'):
1626 1626 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1627 1627 else:
1628 1628 if opts.has_key('d'):
1629 1629 deb = debugger.Pdb(self.shell.colors)
1630 1630 # reset Breakpoint state, which is moronically kept
1631 1631 # in a class
1632 1632 bdb.Breakpoint.next = 1
1633 1633 bdb.Breakpoint.bplist = {}
1634 1634 bdb.Breakpoint.bpbynumber = [None]
1635 1635 # Set an initial breakpoint to stop execution
1636 1636 maxtries = 10
1637 1637 bp = int(opts.get('b',[1])[0])
1638 1638 checkline = deb.checkline(filename,bp)
1639 1639 if not checkline:
1640 1640 for bp in range(bp+1,bp+maxtries+1):
1641 1641 if deb.checkline(filename,bp):
1642 1642 break
1643 1643 else:
1644 1644 msg = ("\nI failed to find a valid line to set "
1645 1645 "a breakpoint\n"
1646 1646 "after trying up to line: %s.\n"
1647 1647 "Please set a valid breakpoint manually "
1648 1648 "with the -b option." % bp)
1649 1649 error(msg)
1650 1650 return
1651 1651 # if we find a good linenumber, set the breakpoint
1652 1652 deb.do_break('%s:%s' % (filename,bp))
1653 1653 # Start file run
1654 1654 print "NOTE: Enter 'c' at the",
1655 1655 print "%s prompt to start your script." % deb.prompt
1656 1656 try:
1657 1657 deb.run('execfile("%s")' % filename,prog_ns)
1658 1658
1659 1659 except:
1660 1660 etype, value, tb = sys.exc_info()
1661 1661 # Skip three frames in the traceback: the %run one,
1662 1662 # one inside bdb.py, and the command-line typed by the
1663 1663 # user (run by exec in pdb itself).
1664 1664 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1665 1665 else:
1666 1666 if runner is None:
1667 1667 runner = self.shell.safe_execfile
1668 1668 if opts.has_key('t'):
1669 1669 # timed execution
1670 1670 try:
1671 1671 nruns = int(opts['N'][0])
1672 1672 if nruns < 1:
1673 1673 error('Number of runs must be >=1')
1674 1674 return
1675 1675 except (KeyError):
1676 1676 nruns = 1
1677 1677 if nruns == 1:
1678 1678 t0 = clock2()
1679 1679 runner(filename,prog_ns,prog_ns,
1680 1680 exit_ignore=exit_ignore)
1681 1681 t1 = clock2()
1682 1682 t_usr = t1[0]-t0[0]
1683 1683 t_sys = t1[1]-t0[1]
1684 1684 print "\nIPython CPU timings (estimated):"
1685 1685 print " User : %10s s." % t_usr
1686 1686 print " System: %10s s." % t_sys
1687 1687 else:
1688 1688 runs = range(nruns)
1689 1689 t0 = clock2()
1690 1690 for nr in runs:
1691 1691 runner(filename,prog_ns,prog_ns,
1692 1692 exit_ignore=exit_ignore)
1693 1693 t1 = clock2()
1694 1694 t_usr = t1[0]-t0[0]
1695 1695 t_sys = t1[1]-t0[1]
1696 1696 print "\nIPython CPU timings (estimated):"
1697 1697 print "Total runs performed:",nruns
1698 1698 print " Times : %10s %10s" % ('Total','Per run')
1699 1699 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1700 1700 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1701 1701
1702 1702 else:
1703 1703 # regular execution
1704 1704 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1705 1705
1706 1706 if opts.has_key('i'):
1707 1707 self.shell.user_ns['__name__'] = __name__save
1708 1708 else:
1709 1709 # The shell MUST hold a reference to prog_ns so after %run
1710 1710 # exits, the python deletion mechanism doesn't zero it out
1711 1711 # (leaving dangling references).
1712 1712 self.shell.cache_main_mod(prog_ns,filename)
1713 1713 # update IPython interactive namespace
1714 1714
1715 1715 # Some forms of read errors on the file may mean the
1716 1716 # __name__ key was never set; using pop we don't have to
1717 1717 # worry about a possible KeyError.
1718 1718 prog_ns.pop('__name__', None)
1719 1719
1720 1720 self.shell.user_ns.update(prog_ns)
1721 1721 finally:
1722 1722 # It's a bit of a mystery why, but __builtins__ can change from
1723 1723 # being a module to becoming a dict missing some key data after
1724 1724 # %run. As best I can see, this is NOT something IPython is doing
1725 1725 # at all, and similar problems have been reported before:
1726 1726 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1727 1727 # Since this seems to be done by the interpreter itself, the best
1728 1728 # we can do is to at least restore __builtins__ for the user on
1729 1729 # exit.
1730 1730 self.shell.user_ns['__builtins__'] = __builtin__
1731 1731
1732 1732 # Ensure key global structures are restored
1733 1733 sys.argv = save_argv
1734 1734 if restore_main:
1735 1735 sys.modules['__main__'] = restore_main
1736 1736 else:
1737 1737 # Remove from sys.modules the reference to main_mod we'd
1738 1738 # added. Otherwise it will trap references to objects
1739 1739 # contained therein.
1740 1740 del sys.modules[main_mod_name]
1741 1741
1742 1742 self.shell.reloadhist()
1743 1743
1744 1744 return stats
1745 1745
1746 def magic_runlog(self, parameter_s =''):
1747 """Run files as logs.
1748
1749 Usage:\\
1750 %runlog file1 file2 ...
1751
1752 Run the named files (treating them as log files) in sequence inside
1753 the interpreter, and return to the prompt. This is much slower than
1754 %run because each line is executed in a try/except block, but it
1755 allows running files with syntax errors in them.
1756
1757 Normally IPython will guess when a file is one of its own logfiles, so
1758 you can typically use %run even for logs. This shorthand allows you to
1759 force any file to be treated as a log file."""
1760
1761 for f in parameter_s.split():
1762 self.shell.safe_execfile(f,self.shell.user_ns,
1763 self.shell.user_ns,islog=1)
1764
1765 1746 @testdec.skip_doctest
1766 1747 def magic_timeit(self, parameter_s =''):
1767 1748 """Time execution of a Python statement or expression
1768 1749
1769 1750 Usage:\\
1770 1751 %timeit [-n<N> -r<R> [-t|-c]] statement
1771 1752
1772 1753 Time execution of a Python statement or expression using the timeit
1773 1754 module.
1774 1755
1775 1756 Options:
1776 1757 -n<N>: execute the given statement <N> times in a loop. If this value
1777 1758 is not given, a fitting value is chosen.
1778 1759
1779 1760 -r<R>: repeat the loop iteration <R> times and take the best result.
1780 1761 Default: 3
1781 1762
1782 1763 -t: use time.time to measure the time, which is the default on Unix.
1783 1764 This function measures wall time.
1784 1765
1785 1766 -c: use time.clock to measure the time, which is the default on
1786 1767 Windows and measures wall time. On Unix, resource.getrusage is used
1787 1768 instead and returns the CPU user time.
1788 1769
1789 1770 -p<P>: use a precision of <P> digits to display the timing result.
1790 1771 Default: 3
1791 1772
1792 1773
1793 1774 Examples:
1794 1775
1795 1776 In [1]: %timeit pass
1796 1777 10000000 loops, best of 3: 53.3 ns per loop
1797 1778
1798 1779 In [2]: u = None
1799 1780
1800 1781 In [3]: %timeit u is None
1801 1782 10000000 loops, best of 3: 184 ns per loop
1802 1783
1803 1784 In [4]: %timeit -r 4 u == None
1804 1785 1000000 loops, best of 4: 242 ns per loop
1805 1786
1806 1787 In [5]: import time
1807 1788
1808 1789 In [6]: %timeit -n1 time.sleep(2)
1809 1790 1 loops, best of 3: 2 s per loop
1810 1791
1811 1792
1812 1793 The times reported by %timeit will be slightly higher than those
1813 1794 reported by the timeit.py script when variables are accessed. This is
1814 1795 due to the fact that %timeit executes the statement in the namespace
1815 1796 of the shell, compared with timeit.py, which uses a single setup
1816 1797 statement to import function or create variables. Generally, the bias
1817 1798 does not matter as long as results from timeit.py are not mixed with
1818 1799 those from %timeit."""
1819 1800
1820 1801 import timeit
1821 1802 import math
1822 1803
1823 1804 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1824 1805 # certain terminals. Until we figure out a robust way of
1825 1806 # auto-detecting if the terminal can deal with it, use plain 'us' for
1826 1807 # microseconds. I am really NOT happy about disabling the proper
1827 1808 # 'micro' prefix, but crashing is worse... If anyone knows what the
1828 1809 # right solution for this is, I'm all ears...
1829 1810 #
1830 1811 # Note: using
1831 1812 #
1832 1813 # s = u'\xb5'
1833 1814 # s.encode(sys.getdefaultencoding())
1834 1815 #
1835 1816 # is not sufficient, as I've seen terminals where that fails but
1836 1817 # print s
1837 1818 #
1838 1819 # succeeds
1839 1820 #
1840 1821 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1841 1822
1842 1823 #units = [u"s", u"ms",u'\xb5',"ns"]
1843 1824 units = [u"s", u"ms",u'us',"ns"]
1844 1825
1845 1826 scaling = [1, 1e3, 1e6, 1e9]
1846 1827
1847 1828 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1848 1829 posix=False)
1849 1830 if stmt == "":
1850 1831 return
1851 1832 timefunc = timeit.default_timer
1852 1833 number = int(getattr(opts, "n", 0))
1853 1834 repeat = int(getattr(opts, "r", timeit.default_repeat))
1854 1835 precision = int(getattr(opts, "p", 3))
1855 1836 if hasattr(opts, "t"):
1856 1837 timefunc = time.time
1857 1838 if hasattr(opts, "c"):
1858 1839 timefunc = clock
1859 1840
1860 1841 timer = timeit.Timer(timer=timefunc)
1861 1842 # this code has tight coupling to the inner workings of timeit.Timer,
1862 1843 # but is there a better way to achieve that the code stmt has access
1863 1844 # to the shell namespace?
1864 1845
1865 1846 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1866 1847 'setup': "pass"}
1867 1848 # Track compilation time so it can be reported if too long
1868 1849 # Minimum time above which compilation time will be reported
1869 1850 tc_min = 0.1
1870 1851
1871 1852 t0 = clock()
1872 1853 code = compile(src, "<magic-timeit>", "exec")
1873 1854 tc = clock()-t0
1874 1855
1875 1856 ns = {}
1876 1857 exec code in self.shell.user_ns, ns
1877 1858 timer.inner = ns["inner"]
1878 1859
1879 1860 if number == 0:
1880 1861 # determine number so that 0.2 <= total time < 2.0
1881 1862 number = 1
1882 1863 for i in range(1, 10):
1883 1864 if timer.timeit(number) >= 0.2:
1884 1865 break
1885 1866 number *= 10
1886 1867
1887 1868 best = min(timer.repeat(repeat, number)) / number
1888 1869
1889 1870 if best > 0.0:
1890 1871 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1891 1872 else:
1892 1873 order = 3
1893 1874 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1894 1875 precision,
1895 1876 best * scaling[order],
1896 1877 units[order])
1897 1878 if tc > tc_min:
1898 1879 print "Compiler time: %.2f s" % tc
1899 1880
1900 1881 @testdec.skip_doctest
1901 1882 def magic_time(self,parameter_s = ''):
1902 1883 """Time execution of a Python statement or expression.
1903 1884
1904 1885 The CPU and wall clock times are printed, and the value of the
1905 1886 expression (if any) is returned. Note that under Win32, system time
1906 1887 is always reported as 0, since it can not be measured.
1907 1888
1908 1889 This function provides very basic timing functionality. In Python
1909 1890 2.3, the timeit module offers more control and sophistication, so this
1910 1891 could be rewritten to use it (patches welcome).
1911 1892
1912 1893 Some examples:
1913 1894
1914 1895 In [1]: time 2**128
1915 1896 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1916 1897 Wall time: 0.00
1917 1898 Out[1]: 340282366920938463463374607431768211456L
1918 1899
1919 1900 In [2]: n = 1000000
1920 1901
1921 1902 In [3]: time sum(range(n))
1922 1903 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1923 1904 Wall time: 1.37
1924 1905 Out[3]: 499999500000L
1925 1906
1926 1907 In [4]: time print 'hello world'
1927 1908 hello world
1928 1909 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1929 1910 Wall time: 0.00
1930 1911
1931 1912 Note that the time needed by Python to compile the given expression
1932 1913 will be reported if it is more than 0.1s. In this example, the
1933 1914 actual exponentiation is done by Python at compilation time, so while
1934 1915 the expression can take a noticeable amount of time to compute, that
1935 1916 time is purely due to the compilation:
1936 1917
1937 1918 In [5]: time 3**9999;
1938 1919 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1939 1920 Wall time: 0.00 s
1940 1921
1941 1922 In [6]: time 3**999999;
1942 1923 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1943 1924 Wall time: 0.00 s
1944 1925 Compiler : 0.78 s
1945 1926 """
1946 1927
1947 1928 # fail immediately if the given expression can't be compiled
1948 1929
1949 1930 expr = self.shell.prefilter(parameter_s,False)
1950 1931
1951 1932 # Minimum time above which compilation time will be reported
1952 1933 tc_min = 0.1
1953 1934
1954 1935 try:
1955 1936 mode = 'eval'
1956 1937 t0 = clock()
1957 1938 code = compile(expr,'<timed eval>',mode)
1958 1939 tc = clock()-t0
1959 1940 except SyntaxError:
1960 1941 mode = 'exec'
1961 1942 t0 = clock()
1962 1943 code = compile(expr,'<timed exec>',mode)
1963 1944 tc = clock()-t0
1964 1945 # skew measurement as little as possible
1965 1946 glob = self.shell.user_ns
1966 1947 clk = clock2
1967 1948 wtime = time.time
1968 1949 # time execution
1969 1950 wall_st = wtime()
1970 1951 if mode=='eval':
1971 1952 st = clk()
1972 1953 out = eval(code,glob)
1973 1954 end = clk()
1974 1955 else:
1975 1956 st = clk()
1976 1957 exec code in glob
1977 1958 end = clk()
1978 1959 out = None
1979 1960 wall_end = wtime()
1980 1961 # Compute actual times and report
1981 1962 wall_time = wall_end-wall_st
1982 1963 cpu_user = end[0]-st[0]
1983 1964 cpu_sys = end[1]-st[1]
1984 1965 cpu_tot = cpu_user+cpu_sys
1985 1966 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1986 1967 (cpu_user,cpu_sys,cpu_tot)
1987 1968 print "Wall time: %.2f s" % wall_time
1988 1969 if tc > tc_min:
1989 1970 print "Compiler : %.2f s" % tc
1990 1971 return out
1991 1972
1992 1973 @testdec.skip_doctest
1993 1974 def magic_macro(self,parameter_s = ''):
1994 1975 """Define a set of input lines as a macro for future re-execution.
1995 1976
1996 1977 Usage:\\
1997 1978 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1998 1979
1999 1980 Options:
2000 1981
2001 1982 -r: use 'raw' input. By default, the 'processed' history is used,
2002 1983 so that magics are loaded in their transformed version to valid
2003 1984 Python. If this option is given, the raw input as typed as the
2004 1985 command line is used instead.
2005 1986
2006 1987 This will define a global variable called `name` which is a string
2007 1988 made of joining the slices and lines you specify (n1,n2,... numbers
2008 1989 above) from your input history into a single string. This variable
2009 1990 acts like an automatic function which re-executes those lines as if
2010 1991 you had typed them. You just type 'name' at the prompt and the code
2011 1992 executes.
2012 1993
2013 1994 The notation for indicating number ranges is: n1-n2 means 'use line
2014 1995 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2015 1996 using the lines numbered 5,6 and 7.
2016 1997
2017 1998 Note: as a 'hidden' feature, you can also use traditional python slice
2018 1999 notation, where N:M means numbers N through M-1.
2019 2000
2020 2001 For example, if your history contains (%hist prints it):
2021 2002
2022 2003 44: x=1
2023 2004 45: y=3
2024 2005 46: z=x+y
2025 2006 47: print x
2026 2007 48: a=5
2027 2008 49: print 'x',x,'y',y
2028 2009
2029 2010 you can create a macro with lines 44 through 47 (included) and line 49
2030 2011 called my_macro with:
2031 2012
2032 2013 In [55]: %macro my_macro 44-47 49
2033 2014
2034 2015 Now, typing `my_macro` (without quotes) will re-execute all this code
2035 2016 in one pass.
2036 2017
2037 2018 You don't need to give the line-numbers in order, and any given line
2038 2019 number can appear multiple times. You can assemble macros with any
2039 2020 lines from your input history in any order.
2040 2021
2041 2022 The macro is a simple object which holds its value in an attribute,
2042 2023 but IPython's display system checks for macros and executes them as
2043 2024 code instead of printing them when you type their name.
2044 2025
2045 2026 You can view a macro's contents by explicitly printing it with:
2046 2027
2047 2028 'print macro_name'.
2048 2029
2049 2030 For one-off cases which DON'T contain magic function calls in them you
2050 2031 can obtain similar results by explicitly executing slices from your
2051 2032 input history with:
2052 2033
2053 2034 In [60]: exec In[44:48]+In[49]"""
2054 2035
2055 2036 opts,args = self.parse_options(parameter_s,'r',mode='list')
2056 2037 if not args:
2057 2038 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2058 2039 macs.sort()
2059 2040 return macs
2060 2041 if len(args) == 1:
2061 2042 raise UsageError(
2062 2043 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2063 2044 name,ranges = args[0], args[1:]
2064 2045
2065 2046 #print 'rng',ranges # dbg
2066 2047 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2067 2048 macro = Macro(lines)
2068 2049 self.shell.define_macro(name, macro)
2069 2050 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2070 2051 print 'Macro contents:'
2071 2052 print macro,
2072 2053
2073 2054 def magic_save(self,parameter_s = ''):
2074 2055 """Save a set of lines to a given filename.
2075 2056
2076 2057 Usage:\\
2077 2058 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2078 2059
2079 2060 Options:
2080 2061
2081 2062 -r: use 'raw' input. By default, the 'processed' history is used,
2082 2063 so that magics are loaded in their transformed version to valid
2083 2064 Python. If this option is given, the raw input as typed as the
2084 2065 command line is used instead.
2085 2066
2086 2067 This function uses the same syntax as %macro for line extraction, but
2087 2068 instead of creating a macro it saves the resulting string to the
2088 2069 filename you specify.
2089 2070
2090 2071 It adds a '.py' extension to the file if you don't do so yourself, and
2091 2072 it asks for confirmation before overwriting existing files."""
2092 2073
2093 2074 opts,args = self.parse_options(parameter_s,'r',mode='list')
2094 2075 fname,ranges = args[0], args[1:]
2095 2076 if not fname.endswith('.py'):
2096 2077 fname += '.py'
2097 2078 if os.path.isfile(fname):
2098 2079 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2099 2080 if ans.lower() not in ['y','yes']:
2100 2081 print 'Operation cancelled.'
2101 2082 return
2102 2083 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2103 2084 f = file(fname,'w')
2104 2085 f.write(cmds)
2105 2086 f.close()
2106 2087 print 'The following commands were written to file `%s`:' % fname
2107 2088 print cmds
2108 2089
2109 2090 def _edit_macro(self,mname,macro):
2110 2091 """open an editor with the macro data in a file"""
2111 2092 filename = self.shell.mktempfile(macro.value)
2112 2093 self.shell.hooks.editor(filename)
2113 2094
2114 2095 # and make a new macro object, to replace the old one
2115 2096 mfile = open(filename)
2116 2097 mvalue = mfile.read()
2117 2098 mfile.close()
2118 2099 self.shell.user_ns[mname] = Macro(mvalue)
2119 2100
2120 2101 def magic_ed(self,parameter_s=''):
2121 2102 """Alias to %edit."""
2122 2103 return self.magic_edit(parameter_s)
2123 2104
2124 2105 @testdec.skip_doctest
2125 2106 def magic_edit(self,parameter_s='',last_call=['','']):
2126 2107 """Bring up an editor and execute the resulting code.
2127 2108
2128 2109 Usage:
2129 2110 %edit [options] [args]
2130 2111
2131 2112 %edit runs IPython's editor hook. The default version of this hook is
2132 2113 set to call the __IPYTHON__.rc.editor command. This is read from your
2133 2114 environment variable $EDITOR. If this isn't found, it will default to
2134 2115 vi under Linux/Unix and to notepad under Windows. See the end of this
2135 2116 docstring for how to change the editor hook.
2136 2117
2137 2118 You can also set the value of this editor via the command line option
2138 2119 '-editor' or in your ipythonrc file. This is useful if you wish to use
2139 2120 specifically for IPython an editor different from your typical default
2140 2121 (and for Windows users who typically don't set environment variables).
2141 2122
2142 2123 This command allows you to conveniently edit multi-line code right in
2143 2124 your IPython session.
2144 2125
2145 2126 If called without arguments, %edit opens up an empty editor with a
2146 2127 temporary file and will execute the contents of this file when you
2147 2128 close it (don't forget to save it!).
2148 2129
2149 2130
2150 2131 Options:
2151 2132
2152 2133 -n <number>: open the editor at a specified line number. By default,
2153 2134 the IPython editor hook uses the unix syntax 'editor +N filename', but
2154 2135 you can configure this by providing your own modified hook if your
2155 2136 favorite editor supports line-number specifications with a different
2156 2137 syntax.
2157 2138
2158 2139 -p: this will call the editor with the same data as the previous time
2159 2140 it was used, regardless of how long ago (in your current session) it
2160 2141 was.
2161 2142
2162 2143 -r: use 'raw' input. This option only applies to input taken from the
2163 2144 user's history. By default, the 'processed' history is used, so that
2164 2145 magics are loaded in their transformed version to valid Python. If
2165 2146 this option is given, the raw input as typed as the command line is
2166 2147 used instead. When you exit the editor, it will be executed by
2167 2148 IPython's own processor.
2168 2149
2169 2150 -x: do not execute the edited code immediately upon exit. This is
2170 2151 mainly useful if you are editing programs which need to be called with
2171 2152 command line arguments, which you can then do using %run.
2172 2153
2173 2154
2174 2155 Arguments:
2175 2156
2176 2157 If arguments are given, the following possibilites exist:
2177 2158
2178 2159 - The arguments are numbers or pairs of colon-separated numbers (like
2179 2160 1 4:8 9). These are interpreted as lines of previous input to be
2180 2161 loaded into the editor. The syntax is the same of the %macro command.
2181 2162
2182 2163 - If the argument doesn't start with a number, it is evaluated as a
2183 2164 variable and its contents loaded into the editor. You can thus edit
2184 2165 any string which contains python code (including the result of
2185 2166 previous edits).
2186 2167
2187 2168 - If the argument is the name of an object (other than a string),
2188 2169 IPython will try to locate the file where it was defined and open the
2189 2170 editor at the point where it is defined. You can use `%edit function`
2190 2171 to load an editor exactly at the point where 'function' is defined,
2191 2172 edit it and have the file be executed automatically.
2192 2173
2193 2174 If the object is a macro (see %macro for details), this opens up your
2194 2175 specified editor with a temporary file containing the macro's data.
2195 2176 Upon exit, the macro is reloaded with the contents of the file.
2196 2177
2197 2178 Note: opening at an exact line is only supported under Unix, and some
2198 2179 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2199 2180 '+NUMBER' parameter necessary for this feature. Good editors like
2200 2181 (X)Emacs, vi, jed, pico and joe all do.
2201 2182
2202 2183 - If the argument is not found as a variable, IPython will look for a
2203 2184 file with that name (adding .py if necessary) and load it into the
2204 2185 editor. It will execute its contents with execfile() when you exit,
2205 2186 loading any code in the file into your interactive namespace.
2206 2187
2207 2188 After executing your code, %edit will return as output the code you
2208 2189 typed in the editor (except when it was an existing file). This way
2209 2190 you can reload the code in further invocations of %edit as a variable,
2210 2191 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2211 2192 the output.
2212 2193
2213 2194 Note that %edit is also available through the alias %ed.
2214 2195
2215 2196 This is an example of creating a simple function inside the editor and
2216 2197 then modifying it. First, start up the editor:
2217 2198
2218 2199 In [1]: ed
2219 2200 Editing... done. Executing edited code...
2220 2201 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2221 2202
2222 2203 We can then call the function foo():
2223 2204
2224 2205 In [2]: foo()
2225 2206 foo() was defined in an editing session
2226 2207
2227 2208 Now we edit foo. IPython automatically loads the editor with the
2228 2209 (temporary) file where foo() was previously defined:
2229 2210
2230 2211 In [3]: ed foo
2231 2212 Editing... done. Executing edited code...
2232 2213
2233 2214 And if we call foo() again we get the modified version:
2234 2215
2235 2216 In [4]: foo()
2236 2217 foo() has now been changed!
2237 2218
2238 2219 Here is an example of how to edit a code snippet successive
2239 2220 times. First we call the editor:
2240 2221
2241 2222 In [5]: ed
2242 2223 Editing... done. Executing edited code...
2243 2224 hello
2244 2225 Out[5]: "print 'hello'n"
2245 2226
2246 2227 Now we call it again with the previous output (stored in _):
2247 2228
2248 2229 In [6]: ed _
2249 2230 Editing... done. Executing edited code...
2250 2231 hello world
2251 2232 Out[6]: "print 'hello world'n"
2252 2233
2253 2234 Now we call it with the output #8 (stored in _8, also as Out[8]):
2254 2235
2255 2236 In [7]: ed _8
2256 2237 Editing... done. Executing edited code...
2257 2238 hello again
2258 2239 Out[7]: "print 'hello again'n"
2259 2240
2260 2241
2261 2242 Changing the default editor hook:
2262 2243
2263 2244 If you wish to write your own editor hook, you can put it in a
2264 2245 configuration file which you load at startup time. The default hook
2265 2246 is defined in the IPython.core.hooks module, and you can use that as a
2266 2247 starting example for further modifications. That file also has
2267 2248 general instructions on how to set a new hook for use once you've
2268 2249 defined it."""
2269 2250
2270 2251 # FIXME: This function has become a convoluted mess. It needs a
2271 2252 # ground-up rewrite with clean, simple logic.
2272 2253
2273 2254 def make_filename(arg):
2274 2255 "Make a filename from the given args"
2275 2256 try:
2276 2257 filename = get_py_filename(arg)
2277 2258 except IOError:
2278 2259 if args.endswith('.py'):
2279 2260 filename = arg
2280 2261 else:
2281 2262 filename = None
2282 2263 return filename
2283 2264
2284 2265 # custom exceptions
2285 2266 class DataIsObject(Exception): pass
2286 2267
2287 2268 opts,args = self.parse_options(parameter_s,'prxn:')
2288 2269 # Set a few locals from the options for convenience:
2289 2270 opts_p = opts.has_key('p')
2290 2271 opts_r = opts.has_key('r')
2291 2272
2292 2273 # Default line number value
2293 2274 lineno = opts.get('n',None)
2294 2275
2295 2276 if opts_p:
2296 2277 args = '_%s' % last_call[0]
2297 2278 if not self.shell.user_ns.has_key(args):
2298 2279 args = last_call[1]
2299 2280
2300 2281 # use last_call to remember the state of the previous call, but don't
2301 2282 # let it be clobbered by successive '-p' calls.
2302 2283 try:
2303 2284 last_call[0] = self.shell.outputcache.prompt_count
2304 2285 if not opts_p:
2305 2286 last_call[1] = parameter_s
2306 2287 except:
2307 2288 pass
2308 2289
2309 2290 # by default this is done with temp files, except when the given
2310 2291 # arg is a filename
2311 2292 use_temp = 1
2312 2293
2313 2294 if re.match(r'\d',args):
2314 2295 # Mode where user specifies ranges of lines, like in %macro.
2315 2296 # This means that you can't edit files whose names begin with
2316 2297 # numbers this way. Tough.
2317 2298 ranges = args.split()
2318 2299 data = ''.join(self.extract_input_slices(ranges,opts_r))
2319 2300 elif args.endswith('.py'):
2320 2301 filename = make_filename(args)
2321 2302 data = ''
2322 2303 use_temp = 0
2323 2304 elif args:
2324 2305 try:
2325 2306 # Load the parameter given as a variable. If not a string,
2326 2307 # process it as an object instead (below)
2327 2308
2328 2309 #print '*** args',args,'type',type(args) # dbg
2329 2310 data = eval(args,self.shell.user_ns)
2330 2311 if not type(data) in StringTypes:
2331 2312 raise DataIsObject
2332 2313
2333 2314 except (NameError,SyntaxError):
2334 2315 # given argument is not a variable, try as a filename
2335 2316 filename = make_filename(args)
2336 2317 if filename is None:
2337 2318 warn("Argument given (%s) can't be found as a variable "
2338 2319 "or as a filename." % args)
2339 2320 return
2340 2321
2341 2322 data = ''
2342 2323 use_temp = 0
2343 2324 except DataIsObject:
2344 2325
2345 2326 # macros have a special edit function
2346 2327 if isinstance(data,Macro):
2347 2328 self._edit_macro(args,data)
2348 2329 return
2349 2330
2350 2331 # For objects, try to edit the file where they are defined
2351 2332 try:
2352 2333 filename = inspect.getabsfile(data)
2353 2334 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2354 2335 # class created by %edit? Try to find source
2355 2336 # by looking for method definitions instead, the
2356 2337 # __module__ in those classes is FakeModule.
2357 2338 attrs = [getattr(data, aname) for aname in dir(data)]
2358 2339 for attr in attrs:
2359 2340 if not inspect.ismethod(attr):
2360 2341 continue
2361 2342 filename = inspect.getabsfile(attr)
2362 2343 if filename and 'fakemodule' not in filename.lower():
2363 2344 # change the attribute to be the edit target instead
2364 2345 data = attr
2365 2346 break
2366 2347
2367 2348 datafile = 1
2368 2349 except TypeError:
2369 2350 filename = make_filename(args)
2370 2351 datafile = 1
2371 2352 warn('Could not find file where `%s` is defined.\n'
2372 2353 'Opening a file named `%s`' % (args,filename))
2373 2354 # Now, make sure we can actually read the source (if it was in
2374 2355 # a temp file it's gone by now).
2375 2356 if datafile:
2376 2357 try:
2377 2358 if lineno is None:
2378 2359 lineno = inspect.getsourcelines(data)[1]
2379 2360 except IOError:
2380 2361 filename = make_filename(args)
2381 2362 if filename is None:
2382 2363 warn('The file `%s` where `%s` was defined cannot '
2383 2364 'be read.' % (filename,data))
2384 2365 return
2385 2366 use_temp = 0
2386 2367 else:
2387 2368 data = ''
2388 2369
2389 2370 if use_temp:
2390 2371 filename = self.shell.mktempfile(data)
2391 2372 print 'IPython will make a temporary file named:',filename
2392 2373
2393 2374 # do actual editing here
2394 2375 print 'Editing...',
2395 2376 sys.stdout.flush()
2396 2377 try:
2397 2378 self.shell.hooks.editor(filename,lineno)
2398 2379 except TryNext:
2399 2380 warn('Could not open editor')
2400 2381 return
2401 2382
2402 2383 # XXX TODO: should this be generalized for all string vars?
2403 2384 # For now, this is special-cased to blocks created by cpaste
2404 2385 if args.strip() == 'pasted_block':
2405 2386 self.shell.user_ns['pasted_block'] = file_read(filename)
2406 2387
2407 2388 if opts.has_key('x'): # -x prevents actual execution
2408 2389 print
2409 2390 else:
2410 2391 print 'done. Executing edited code...'
2411 2392 if opts_r:
2412 2393 self.shell.runlines(file_read(filename))
2413 2394 else:
2414 2395 self.shell.safe_execfile(filename,self.shell.user_ns,
2415 2396 self.shell.user_ns)
2416 2397
2417 2398
2418 2399 if use_temp:
2419 2400 try:
2420 2401 return open(filename).read()
2421 2402 except IOError,msg:
2422 2403 if msg.filename == filename:
2423 2404 warn('File not found. Did you forget to save?')
2424 2405 return
2425 2406 else:
2426 2407 self.shell.showtraceback()
2427 2408
2428 2409 def magic_xmode(self,parameter_s = ''):
2429 2410 """Switch modes for the exception handlers.
2430 2411
2431 2412 Valid modes: Plain, Context and Verbose.
2432 2413
2433 2414 If called without arguments, acts as a toggle."""
2434 2415
2435 2416 def xmode_switch_err(name):
2436 2417 warn('Error changing %s exception modes.\n%s' %
2437 2418 (name,sys.exc_info()[1]))
2438 2419
2439 2420 shell = self.shell
2440 2421 new_mode = parameter_s.strip().capitalize()
2441 2422 try:
2442 2423 shell.InteractiveTB.set_mode(mode=new_mode)
2443 2424 print 'Exception reporting mode:',shell.InteractiveTB.mode
2444 2425 except:
2445 2426 xmode_switch_err('user')
2446 2427
2447 2428 # threaded shells use a special handler in sys.excepthook
2448 2429 if shell.isthreaded:
2449 2430 try:
2450 2431 shell.sys_excepthook.set_mode(mode=new_mode)
2451 2432 except:
2452 2433 xmode_switch_err('threaded')
2453 2434
2454 2435 def magic_colors(self,parameter_s = ''):
2455 2436 """Switch color scheme for prompts, info system and exception handlers.
2456 2437
2457 2438 Currently implemented schemes: NoColor, Linux, LightBG.
2458 2439
2459 2440 Color scheme names are not case-sensitive."""
2460 2441
2461 2442 def color_switch_err(name):
2462 2443 warn('Error changing %s color schemes.\n%s' %
2463 2444 (name,sys.exc_info()[1]))
2464 2445
2465 2446
2466 2447 new_scheme = parameter_s.strip()
2467 2448 if not new_scheme:
2468 2449 raise UsageError(
2469 2450 "%colors: you must specify a color scheme. See '%colors?'")
2470 2451 return
2471 2452 # local shortcut
2472 2453 shell = self.shell
2473 2454
2474 2455 import IPython.utils.rlineimpl as readline
2475 2456
2476 2457 if not readline.have_readline and sys.platform == "win32":
2477 2458 msg = """\
2478 2459 Proper color support under MS Windows requires the pyreadline library.
2479 2460 You can find it at:
2480 2461 http://ipython.scipy.org/moin/PyReadline/Intro
2481 2462 Gary's readline needs the ctypes module, from:
2482 2463 http://starship.python.net/crew/theller/ctypes
2483 2464 (Note that ctypes is already part of Python versions 2.5 and newer).
2484 2465
2485 2466 Defaulting color scheme to 'NoColor'"""
2486 2467 new_scheme = 'NoColor'
2487 2468 warn(msg)
2488 2469
2489 2470 # readline option is 0
2490 2471 if not shell.has_readline:
2491 2472 new_scheme = 'NoColor'
2492 2473
2493 2474 # Set prompt colors
2494 2475 try:
2495 2476 shell.outputcache.set_colors(new_scheme)
2496 2477 except:
2497 2478 color_switch_err('prompt')
2498 2479 else:
2499 2480 shell.colors = \
2500 2481 shell.outputcache.color_table.active_scheme_name
2501 2482 # Set exception colors
2502 2483 try:
2503 2484 shell.InteractiveTB.set_colors(scheme = new_scheme)
2504 2485 shell.SyntaxTB.set_colors(scheme = new_scheme)
2505 2486 except:
2506 2487 color_switch_err('exception')
2507 2488
2508 2489 # threaded shells use a verbose traceback in sys.excepthook
2509 2490 if shell.isthreaded:
2510 2491 try:
2511 2492 shell.sys_excepthook.set_colors(scheme=new_scheme)
2512 2493 except:
2513 2494 color_switch_err('system exception handler')
2514 2495
2515 2496 # Set info (for 'object?') colors
2516 2497 if shell.color_info:
2517 2498 try:
2518 2499 shell.inspector.set_active_scheme(new_scheme)
2519 2500 except:
2520 2501 color_switch_err('object inspector')
2521 2502 else:
2522 2503 shell.inspector.set_active_scheme('NoColor')
2523 2504
2524 2505 def magic_color_info(self,parameter_s = ''):
2525 2506 """Toggle color_info.
2526 2507
2527 2508 The color_info configuration parameter controls whether colors are
2528 2509 used for displaying object details (by things like %psource, %pfile or
2529 2510 the '?' system). This function toggles this value with each call.
2530 2511
2531 2512 Note that unless you have a fairly recent pager (less works better
2532 2513 than more) in your system, using colored object information displays
2533 2514 will not work properly. Test it and see."""
2534 2515
2535 2516 self.shell.color_info = not self.shell.color_info
2536 2517 self.magic_colors(self.shell.colors)
2537 2518 print 'Object introspection functions have now coloring:',
2538 2519 print ['OFF','ON'][int(self.shell.color_info)]
2539 2520
2540 2521 def magic_Pprint(self, parameter_s=''):
2541 2522 """Toggle pretty printing on/off."""
2542 2523
2543 2524 self.shell.pprint = 1 - self.shell.pprint
2544 2525 print 'Pretty printing has been turned', \
2545 2526 ['OFF','ON'][self.shell.pprint]
2546 2527
2547 2528 def magic_exit(self, parameter_s=''):
2548 2529 """Exit IPython, confirming if configured to do so.
2549 2530
2550 2531 You can configure whether IPython asks for confirmation upon exit by
2551 2532 setting the confirm_exit flag in the ipythonrc file."""
2552 2533
2553 2534 self.shell.exit()
2554 2535
2555 2536 def magic_quit(self, parameter_s=''):
2556 2537 """Exit IPython, confirming if configured to do so (like %exit)"""
2557 2538
2558 2539 self.shell.exit()
2559 2540
2560 2541 def magic_Exit(self, parameter_s=''):
2561 2542 """Exit IPython without confirmation."""
2562 2543
2563 2544 self.shell.ask_exit()
2564 2545
2565 2546 #......................................................................
2566 2547 # Functions to implement unix shell-type things
2567 2548
2568 2549 @testdec.skip_doctest
2569 2550 def magic_alias(self, parameter_s = ''):
2570 2551 """Define an alias for a system command.
2571 2552
2572 2553 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2573 2554
2574 2555 Then, typing 'alias_name params' will execute the system command 'cmd
2575 2556 params' (from your underlying operating system).
2576 2557
2577 2558 Aliases have lower precedence than magic functions and Python normal
2578 2559 variables, so if 'foo' is both a Python variable and an alias, the
2579 2560 alias can not be executed until 'del foo' removes the Python variable.
2580 2561
2581 2562 You can use the %l specifier in an alias definition to represent the
2582 2563 whole line when the alias is called. For example:
2583 2564
2584 2565 In [2]: alias all echo "Input in brackets: <%l>"
2585 2566 In [3]: all hello world
2586 2567 Input in brackets: <hello world>
2587 2568
2588 2569 You can also define aliases with parameters using %s specifiers (one
2589 2570 per parameter):
2590 2571
2591 2572 In [1]: alias parts echo first %s second %s
2592 2573 In [2]: %parts A B
2593 2574 first A second B
2594 2575 In [3]: %parts A
2595 2576 Incorrect number of arguments: 2 expected.
2596 2577 parts is an alias to: 'echo first %s second %s'
2597 2578
2598 2579 Note that %l and %s are mutually exclusive. You can only use one or
2599 2580 the other in your aliases.
2600 2581
2601 2582 Aliases expand Python variables just like system calls using ! or !!
2602 2583 do: all expressions prefixed with '$' get expanded. For details of
2603 2584 the semantic rules, see PEP-215:
2604 2585 http://www.python.org/peps/pep-0215.html. This is the library used by
2605 2586 IPython for variable expansion. If you want to access a true shell
2606 2587 variable, an extra $ is necessary to prevent its expansion by IPython:
2607 2588
2608 2589 In [6]: alias show echo
2609 2590 In [7]: PATH='A Python string'
2610 2591 In [8]: show $PATH
2611 2592 A Python string
2612 2593 In [9]: show $$PATH
2613 2594 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2614 2595
2615 2596 You can use the alias facility to acess all of $PATH. See the %rehash
2616 2597 and %rehashx functions, which automatically create aliases for the
2617 2598 contents of your $PATH.
2618 2599
2619 2600 If called with no parameters, %alias prints the current alias table."""
2620 2601
2621 2602 par = parameter_s.strip()
2622 2603 if not par:
2623 2604 stored = self.db.get('stored_aliases', {} )
2624 2605 aliases = sorted(self.shell.alias_manager.aliases)
2625 2606 # for k, v in stored:
2626 2607 # atab.append(k, v[0])
2627 2608
2628 2609 print "Total number of aliases:", len(aliases)
2629 2610 return aliases
2630 2611
2631 2612 # Now try to define a new one
2632 2613 try:
2633 2614 alias,cmd = par.split(None, 1)
2634 2615 except:
2635 2616 print oinspect.getdoc(self.magic_alias)
2636 2617 else:
2637 2618 self.shell.alias_manager.soft_define_alias(alias, cmd)
2638 2619 # end magic_alias
2639 2620
2640 2621 def magic_unalias(self, parameter_s = ''):
2641 2622 """Remove an alias"""
2642 2623
2643 2624 aname = parameter_s.strip()
2644 2625 self.shell.alias_manager.undefine_alias(aname)
2645 2626 stored = self.db.get('stored_aliases', {} )
2646 2627 if aname in stored:
2647 2628 print "Removing %stored alias",aname
2648 2629 del stored[aname]
2649 2630 self.db['stored_aliases'] = stored
2650 2631
2651 2632
2652 2633 def magic_rehashx(self, parameter_s = ''):
2653 2634 """Update the alias table with all executable files in $PATH.
2654 2635
2655 2636 This version explicitly checks that every entry in $PATH is a file
2656 2637 with execute access (os.X_OK), so it is much slower than %rehash.
2657 2638
2658 2639 Under Windows, it checks executability as a match agains a
2659 2640 '|'-separated string of extensions, stored in the IPython config
2660 2641 variable win_exec_ext. This defaults to 'exe|com|bat'.
2661 2642
2662 2643 This function also resets the root module cache of module completer,
2663 2644 used on slow filesystems.
2664 2645 """
2665 2646 from IPython.core.alias import InvalidAliasError
2666 2647
2667 2648 # for the benefit of module completer in ipy_completers.py
2668 2649 del self.db['rootmodules']
2669 2650
2670 2651 path = [os.path.abspath(os.path.expanduser(p)) for p in
2671 2652 os.environ.get('PATH','').split(os.pathsep)]
2672 2653 path = filter(os.path.isdir,path)
2673 2654
2674 2655 syscmdlist = []
2675 2656 # Now define isexec in a cross platform manner.
2676 2657 if os.name == 'posix':
2677 2658 isexec = lambda fname:os.path.isfile(fname) and \
2678 2659 os.access(fname,os.X_OK)
2679 2660 else:
2680 2661 try:
2681 2662 winext = os.environ['pathext'].replace(';','|').replace('.','')
2682 2663 except KeyError:
2683 2664 winext = 'exe|com|bat|py'
2684 2665 if 'py' not in winext:
2685 2666 winext += '|py'
2686 2667 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2687 2668 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2688 2669 savedir = os.getcwd()
2689 2670
2690 2671 # Now walk the paths looking for executables to alias.
2691 2672 try:
2692 2673 # write the whole loop for posix/Windows so we don't have an if in
2693 2674 # the innermost part
2694 2675 if os.name == 'posix':
2695 2676 for pdir in path:
2696 2677 os.chdir(pdir)
2697 2678 for ff in os.listdir(pdir):
2698 2679 if isexec(ff):
2699 2680 try:
2700 2681 # Removes dots from the name since ipython
2701 2682 # will assume names with dots to be python.
2702 2683 self.shell.alias_manager.define_alias(
2703 2684 ff.replace('.',''), ff)
2704 2685 except InvalidAliasError:
2705 2686 pass
2706 2687 else:
2707 2688 syscmdlist.append(ff)
2708 2689 else:
2709 2690 for pdir in path:
2710 2691 os.chdir(pdir)
2711 2692 for ff in os.listdir(pdir):
2712 2693 base, ext = os.path.splitext(ff)
2713 2694 if isexec(ff) and base.lower() not in self.shell.no_alias:
2714 2695 if ext.lower() == '.exe':
2715 2696 ff = base
2716 2697 try:
2717 2698 # Removes dots from the name since ipython
2718 2699 # will assume names with dots to be python.
2719 2700 self.shell.alias_manager.define_alias(
2720 2701 base.lower().replace('.',''), ff)
2721 2702 except InvalidAliasError:
2722 2703 pass
2723 2704 syscmdlist.append(ff)
2724 2705 db = self.db
2725 2706 db['syscmdlist'] = syscmdlist
2726 2707 finally:
2727 2708 os.chdir(savedir)
2728 2709
2729 2710 def magic_pwd(self, parameter_s = ''):
2730 2711 """Return the current working directory path."""
2731 2712 return os.getcwd()
2732 2713
2733 2714 def magic_cd(self, parameter_s=''):
2734 2715 """Change the current working directory.
2735 2716
2736 2717 This command automatically maintains an internal list of directories
2737 2718 you visit during your IPython session, in the variable _dh. The
2738 2719 command %dhist shows this history nicely formatted. You can also
2739 2720 do 'cd -<tab>' to see directory history conveniently.
2740 2721
2741 2722 Usage:
2742 2723
2743 2724 cd 'dir': changes to directory 'dir'.
2744 2725
2745 2726 cd -: changes to the last visited directory.
2746 2727
2747 2728 cd -<n>: changes to the n-th directory in the directory history.
2748 2729
2749 2730 cd --foo: change to directory that matches 'foo' in history
2750 2731
2751 2732 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2752 2733 (note: cd <bookmark_name> is enough if there is no
2753 2734 directory <bookmark_name>, but a bookmark with the name exists.)
2754 2735 'cd -b <tab>' allows you to tab-complete bookmark names.
2755 2736
2756 2737 Options:
2757 2738
2758 2739 -q: quiet. Do not print the working directory after the cd command is
2759 2740 executed. By default IPython's cd command does print this directory,
2760 2741 since the default prompts do not display path information.
2761 2742
2762 2743 Note that !cd doesn't work for this purpose because the shell where
2763 2744 !command runs is immediately discarded after executing 'command'."""
2764 2745
2765 2746 parameter_s = parameter_s.strip()
2766 2747 #bkms = self.shell.persist.get("bookmarks",{})
2767 2748
2768 2749 oldcwd = os.getcwd()
2769 2750 numcd = re.match(r'(-)(\d+)$',parameter_s)
2770 2751 # jump in directory history by number
2771 2752 if numcd:
2772 2753 nn = int(numcd.group(2))
2773 2754 try:
2774 2755 ps = self.shell.user_ns['_dh'][nn]
2775 2756 except IndexError:
2776 2757 print 'The requested directory does not exist in history.'
2777 2758 return
2778 2759 else:
2779 2760 opts = {}
2780 2761 elif parameter_s.startswith('--'):
2781 2762 ps = None
2782 2763 fallback = None
2783 2764 pat = parameter_s[2:]
2784 2765 dh = self.shell.user_ns['_dh']
2785 2766 # first search only by basename (last component)
2786 2767 for ent in reversed(dh):
2787 2768 if pat in os.path.basename(ent) and os.path.isdir(ent):
2788 2769 ps = ent
2789 2770 break
2790 2771
2791 2772 if fallback is None and pat in ent and os.path.isdir(ent):
2792 2773 fallback = ent
2793 2774
2794 2775 # if we have no last part match, pick the first full path match
2795 2776 if ps is None:
2796 2777 ps = fallback
2797 2778
2798 2779 if ps is None:
2799 2780 print "No matching entry in directory history"
2800 2781 return
2801 2782 else:
2802 2783 opts = {}
2803 2784
2804 2785
2805 2786 else:
2806 2787 #turn all non-space-escaping backslashes to slashes,
2807 2788 # for c:\windows\directory\names\
2808 2789 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2809 2790 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2810 2791 # jump to previous
2811 2792 if ps == '-':
2812 2793 try:
2813 2794 ps = self.shell.user_ns['_dh'][-2]
2814 2795 except IndexError:
2815 2796 raise UsageError('%cd -: No previous directory to change to.')
2816 2797 # jump to bookmark if needed
2817 2798 else:
2818 2799 if not os.path.isdir(ps) or opts.has_key('b'):
2819 2800 bkms = self.db.get('bookmarks', {})
2820 2801
2821 2802 if bkms.has_key(ps):
2822 2803 target = bkms[ps]
2823 2804 print '(bookmark:%s) -> %s' % (ps,target)
2824 2805 ps = target
2825 2806 else:
2826 2807 if opts.has_key('b'):
2827 2808 raise UsageError("Bookmark '%s' not found. "
2828 2809 "Use '%%bookmark -l' to see your bookmarks." % ps)
2829 2810
2830 2811 # at this point ps should point to the target dir
2831 2812 if ps:
2832 2813 try:
2833 2814 os.chdir(os.path.expanduser(ps))
2834 2815 if self.shell.term_title:
2835 2816 platutils.set_term_title('IPython: ' + abbrev_cwd())
2836 2817 except OSError:
2837 2818 print sys.exc_info()[1]
2838 2819 else:
2839 2820 cwd = os.getcwd()
2840 2821 dhist = self.shell.user_ns['_dh']
2841 2822 if oldcwd != cwd:
2842 2823 dhist.append(cwd)
2843 2824 self.db['dhist'] = compress_dhist(dhist)[-100:]
2844 2825
2845 2826 else:
2846 2827 os.chdir(self.shell.home_dir)
2847 2828 if self.shell.term_title:
2848 2829 platutils.set_term_title('IPython: ' + '~')
2849 2830 cwd = os.getcwd()
2850 2831 dhist = self.shell.user_ns['_dh']
2851 2832
2852 2833 if oldcwd != cwd:
2853 2834 dhist.append(cwd)
2854 2835 self.db['dhist'] = compress_dhist(dhist)[-100:]
2855 2836 if not 'q' in opts and self.shell.user_ns['_dh']:
2856 2837 print self.shell.user_ns['_dh'][-1]
2857 2838
2858 2839
2859 2840 def magic_env(self, parameter_s=''):
2860 2841 """List environment variables."""
2861 2842
2862 2843 return os.environ.data
2863 2844
2864 2845 def magic_pushd(self, parameter_s=''):
2865 2846 """Place the current dir on stack and change directory.
2866 2847
2867 2848 Usage:\\
2868 2849 %pushd ['dirname']
2869 2850 """
2870 2851
2871 2852 dir_s = self.shell.dir_stack
2872 2853 tgt = os.path.expanduser(parameter_s)
2873 2854 cwd = os.getcwd().replace(self.home_dir,'~')
2874 2855 if tgt:
2875 2856 self.magic_cd(parameter_s)
2876 2857 dir_s.insert(0,cwd)
2877 2858 return self.magic_dirs()
2878 2859
2879 2860 def magic_popd(self, parameter_s=''):
2880 2861 """Change to directory popped off the top of the stack.
2881 2862 """
2882 2863 if not self.shell.dir_stack:
2883 2864 raise UsageError("%popd on empty stack")
2884 2865 top = self.shell.dir_stack.pop(0)
2885 2866 self.magic_cd(top)
2886 2867 print "popd ->",top
2887 2868
2888 2869 def magic_dirs(self, parameter_s=''):
2889 2870 """Return the current directory stack."""
2890 2871
2891 2872 return self.shell.dir_stack
2892 2873
2893 2874 def magic_dhist(self, parameter_s=''):
2894 2875 """Print your history of visited directories.
2895 2876
2896 2877 %dhist -> print full history\\
2897 2878 %dhist n -> print last n entries only\\
2898 2879 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2899 2880
2900 2881 This history is automatically maintained by the %cd command, and
2901 2882 always available as the global list variable _dh. You can use %cd -<n>
2902 2883 to go to directory number <n>.
2903 2884
2904 2885 Note that most of time, you should view directory history by entering
2905 2886 cd -<TAB>.
2906 2887
2907 2888 """
2908 2889
2909 2890 dh = self.shell.user_ns['_dh']
2910 2891 if parameter_s:
2911 2892 try:
2912 2893 args = map(int,parameter_s.split())
2913 2894 except:
2914 2895 self.arg_err(Magic.magic_dhist)
2915 2896 return
2916 2897 if len(args) == 1:
2917 2898 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2918 2899 elif len(args) == 2:
2919 2900 ini,fin = args
2920 2901 else:
2921 2902 self.arg_err(Magic.magic_dhist)
2922 2903 return
2923 2904 else:
2924 2905 ini,fin = 0,len(dh)
2925 2906 nlprint(dh,
2926 2907 header = 'Directory history (kept in _dh)',
2927 2908 start=ini,stop=fin)
2928 2909
2929 2910 @testdec.skip_doctest
2930 2911 def magic_sc(self, parameter_s=''):
2931 2912 """Shell capture - execute a shell command and capture its output.
2932 2913
2933 2914 DEPRECATED. Suboptimal, retained for backwards compatibility.
2934 2915
2935 2916 You should use the form 'var = !command' instead. Example:
2936 2917
2937 2918 "%sc -l myfiles = ls ~" should now be written as
2938 2919
2939 2920 "myfiles = !ls ~"
2940 2921
2941 2922 myfiles.s, myfiles.l and myfiles.n still apply as documented
2942 2923 below.
2943 2924
2944 2925 --
2945 2926 %sc [options] varname=command
2946 2927
2947 2928 IPython will run the given command using commands.getoutput(), and
2948 2929 will then update the user's interactive namespace with a variable
2949 2930 called varname, containing the value of the call. Your command can
2950 2931 contain shell wildcards, pipes, etc.
2951 2932
2952 2933 The '=' sign in the syntax is mandatory, and the variable name you
2953 2934 supply must follow Python's standard conventions for valid names.
2954 2935
2955 2936 (A special format without variable name exists for internal use)
2956 2937
2957 2938 Options:
2958 2939
2959 2940 -l: list output. Split the output on newlines into a list before
2960 2941 assigning it to the given variable. By default the output is stored
2961 2942 as a single string.
2962 2943
2963 2944 -v: verbose. Print the contents of the variable.
2964 2945
2965 2946 In most cases you should not need to split as a list, because the
2966 2947 returned value is a special type of string which can automatically
2967 2948 provide its contents either as a list (split on newlines) or as a
2968 2949 space-separated string. These are convenient, respectively, either
2969 2950 for sequential processing or to be passed to a shell command.
2970 2951
2971 2952 For example:
2972 2953
2973 2954 # all-random
2974 2955
2975 2956 # Capture into variable a
2976 2957 In [1]: sc a=ls *py
2977 2958
2978 2959 # a is a string with embedded newlines
2979 2960 In [2]: a
2980 2961 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2981 2962
2982 2963 # which can be seen as a list:
2983 2964 In [3]: a.l
2984 2965 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2985 2966
2986 2967 # or as a whitespace-separated string:
2987 2968 In [4]: a.s
2988 2969 Out[4]: 'setup.py win32_manual_post_install.py'
2989 2970
2990 2971 # a.s is useful to pass as a single command line:
2991 2972 In [5]: !wc -l $a.s
2992 2973 146 setup.py
2993 2974 130 win32_manual_post_install.py
2994 2975 276 total
2995 2976
2996 2977 # while the list form is useful to loop over:
2997 2978 In [6]: for f in a.l:
2998 2979 ...: !wc -l $f
2999 2980 ...:
3000 2981 146 setup.py
3001 2982 130 win32_manual_post_install.py
3002 2983
3003 2984 Similiarly, the lists returned by the -l option are also special, in
3004 2985 the sense that you can equally invoke the .s attribute on them to
3005 2986 automatically get a whitespace-separated string from their contents:
3006 2987
3007 2988 In [7]: sc -l b=ls *py
3008 2989
3009 2990 In [8]: b
3010 2991 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3011 2992
3012 2993 In [9]: b.s
3013 2994 Out[9]: 'setup.py win32_manual_post_install.py'
3014 2995
3015 2996 In summary, both the lists and strings used for ouptut capture have
3016 2997 the following special attributes:
3017 2998
3018 2999 .l (or .list) : value as list.
3019 3000 .n (or .nlstr): value as newline-separated string.
3020 3001 .s (or .spstr): value as space-separated string.
3021 3002 """
3022 3003
3023 3004 opts,args = self.parse_options(parameter_s,'lv')
3024 3005 # Try to get a variable name and command to run
3025 3006 try:
3026 3007 # the variable name must be obtained from the parse_options
3027 3008 # output, which uses shlex.split to strip options out.
3028 3009 var,_ = args.split('=',1)
3029 3010 var = var.strip()
3030 3011 # But the the command has to be extracted from the original input
3031 3012 # parameter_s, not on what parse_options returns, to avoid the
3032 3013 # quote stripping which shlex.split performs on it.
3033 3014 _,cmd = parameter_s.split('=',1)
3034 3015 except ValueError:
3035 3016 var,cmd = '',''
3036 3017 # If all looks ok, proceed
3037 3018 out,err = self.shell.getoutputerror(cmd)
3038 3019 if err:
3039 3020 print >> Term.cerr,err
3040 3021 if opts.has_key('l'):
3041 3022 out = SList(out.split('\n'))
3042 3023 else:
3043 3024 out = LSString(out)
3044 3025 if opts.has_key('v'):
3045 3026 print '%s ==\n%s' % (var,pformat(out))
3046 3027 if var:
3047 3028 self.shell.user_ns.update({var:out})
3048 3029 else:
3049 3030 return out
3050 3031
3051 3032 def magic_sx(self, parameter_s=''):
3052 3033 """Shell execute - run a shell command and capture its output.
3053 3034
3054 3035 %sx command
3055 3036
3056 3037 IPython will run the given command using commands.getoutput(), and
3057 3038 return the result formatted as a list (split on '\\n'). Since the
3058 3039 output is _returned_, it will be stored in ipython's regular output
3059 3040 cache Out[N] and in the '_N' automatic variables.
3060 3041
3061 3042 Notes:
3062 3043
3063 3044 1) If an input line begins with '!!', then %sx is automatically
3064 3045 invoked. That is, while:
3065 3046 !ls
3066 3047 causes ipython to simply issue system('ls'), typing
3067 3048 !!ls
3068 3049 is a shorthand equivalent to:
3069 3050 %sx ls
3070 3051
3071 3052 2) %sx differs from %sc in that %sx automatically splits into a list,
3072 3053 like '%sc -l'. The reason for this is to make it as easy as possible
3073 3054 to process line-oriented shell output via further python commands.
3074 3055 %sc is meant to provide much finer control, but requires more
3075 3056 typing.
3076 3057
3077 3058 3) Just like %sc -l, this is a list with special attributes:
3078 3059
3079 3060 .l (or .list) : value as list.
3080 3061 .n (or .nlstr): value as newline-separated string.
3081 3062 .s (or .spstr): value as whitespace-separated string.
3082 3063
3083 3064 This is very useful when trying to use such lists as arguments to
3084 3065 system commands."""
3085 3066
3086 3067 if parameter_s:
3087 3068 out,err = self.shell.getoutputerror(parameter_s)
3088 3069 if err:
3089 3070 print >> Term.cerr,err
3090 3071 return SList(out.split('\n'))
3091 3072
3092 3073 def magic_bg(self, parameter_s=''):
3093 3074 """Run a job in the background, in a separate thread.
3094 3075
3095 3076 For example,
3096 3077
3097 3078 %bg myfunc(x,y,z=1)
3098 3079
3099 3080 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
3100 3081 execution starts, a message will be printed indicating the job
3101 3082 number. If your job number is 5, you can use
3102 3083
3103 3084 myvar = jobs.result(5) or myvar = jobs[5].result
3104 3085
3105 3086 to assign this result to variable 'myvar'.
3106 3087
3107 3088 IPython has a job manager, accessible via the 'jobs' object. You can
3108 3089 type jobs? to get more information about it, and use jobs.<TAB> to see
3109 3090 its attributes. All attributes not starting with an underscore are
3110 3091 meant for public use.
3111 3092
3112 3093 In particular, look at the jobs.new() method, which is used to create
3113 3094 new jobs. This magic %bg function is just a convenience wrapper
3114 3095 around jobs.new(), for expression-based jobs. If you want to create a
3115 3096 new job with an explicit function object and arguments, you must call
3116 3097 jobs.new() directly.
3117 3098
3118 3099 The jobs.new docstring also describes in detail several important
3119 3100 caveats associated with a thread-based model for background job
3120 3101 execution. Type jobs.new? for details.
3121 3102
3122 3103 You can check the status of all jobs with jobs.status().
3123 3104
3124 3105 The jobs variable is set by IPython into the Python builtin namespace.
3125 3106 If you ever declare a variable named 'jobs', you will shadow this
3126 3107 name. You can either delete your global jobs variable to regain
3127 3108 access to the job manager, or make a new name and assign it manually
3128 3109 to the manager (stored in IPython's namespace). For example, to
3129 3110 assign the job manager to the Jobs name, use:
3130 3111
3131 3112 Jobs = __builtins__.jobs"""
3132 3113
3133 3114 self.shell.jobs.new(parameter_s,self.shell.user_ns)
3134 3115
3135 3116 def magic_r(self, parameter_s=''):
3136 3117 """Repeat previous input.
3137 3118
3138 3119 Note: Consider using the more powerfull %rep instead!
3139 3120
3140 3121 If given an argument, repeats the previous command which starts with
3141 3122 the same string, otherwise it just repeats the previous input.
3142 3123
3143 3124 Shell escaped commands (with ! as first character) are not recognized
3144 3125 by this system, only pure python code and magic commands.
3145 3126 """
3146 3127
3147 3128 start = parameter_s.strip()
3148 3129 esc_magic = ESC_MAGIC
3149 3130 # Identify magic commands even if automagic is on (which means
3150 3131 # the in-memory version is different from that typed by the user).
3151 3132 if self.shell.automagic:
3152 3133 start_magic = esc_magic+start
3153 3134 else:
3154 3135 start_magic = start
3155 3136 # Look through the input history in reverse
3156 3137 for n in range(len(self.shell.input_hist)-2,0,-1):
3157 3138 input = self.shell.input_hist[n]
3158 3139 # skip plain 'r' lines so we don't recurse to infinity
3159 3140 if input != '_ip.magic("r")\n' and \
3160 3141 (input.startswith(start) or input.startswith(start_magic)):
3161 3142 #print 'match',`input` # dbg
3162 3143 print 'Executing:',input,
3163 3144 self.shell.runlines(input)
3164 3145 return
3165 3146 print 'No previous input matching `%s` found.' % start
3166 3147
3167 3148
3168 3149 def magic_bookmark(self, parameter_s=''):
3169 3150 """Manage IPython's bookmark system.
3170 3151
3171 3152 %bookmark <name> - set bookmark to current dir
3172 3153 %bookmark <name> <dir> - set bookmark to <dir>
3173 3154 %bookmark -l - list all bookmarks
3174 3155 %bookmark -d <name> - remove bookmark
3175 3156 %bookmark -r - remove all bookmarks
3176 3157
3177 3158 You can later on access a bookmarked folder with:
3178 3159 %cd -b <name>
3179 3160 or simply '%cd <name>' if there is no directory called <name> AND
3180 3161 there is such a bookmark defined.
3181 3162
3182 3163 Your bookmarks persist through IPython sessions, but they are
3183 3164 associated with each profile."""
3184 3165
3185 3166 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3186 3167 if len(args) > 2:
3187 3168 raise UsageError("%bookmark: too many arguments")
3188 3169
3189 3170 bkms = self.db.get('bookmarks',{})
3190 3171
3191 3172 if opts.has_key('d'):
3192 3173 try:
3193 3174 todel = args[0]
3194 3175 except IndexError:
3195 3176 raise UsageError(
3196 3177 "%bookmark -d: must provide a bookmark to delete")
3197 3178 else:
3198 3179 try:
3199 3180 del bkms[todel]
3200 3181 except KeyError:
3201 3182 raise UsageError(
3202 3183 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3203 3184
3204 3185 elif opts.has_key('r'):
3205 3186 bkms = {}
3206 3187 elif opts.has_key('l'):
3207 3188 bks = bkms.keys()
3208 3189 bks.sort()
3209 3190 if bks:
3210 3191 size = max(map(len,bks))
3211 3192 else:
3212 3193 size = 0
3213 3194 fmt = '%-'+str(size)+'s -> %s'
3214 3195 print 'Current bookmarks:'
3215 3196 for bk in bks:
3216 3197 print fmt % (bk,bkms[bk])
3217 3198 else:
3218 3199 if not args:
3219 3200 raise UsageError("%bookmark: You must specify the bookmark name")
3220 3201 elif len(args)==1:
3221 3202 bkms[args[0]] = os.getcwd()
3222 3203 elif len(args)==2:
3223 3204 bkms[args[0]] = args[1]
3224 3205 self.db['bookmarks'] = bkms
3225 3206
3226 3207 def magic_pycat(self, parameter_s=''):
3227 3208 """Show a syntax-highlighted file through a pager.
3228 3209
3229 3210 This magic is similar to the cat utility, but it will assume the file
3230 3211 to be Python source and will show it with syntax highlighting. """
3231 3212
3232 3213 try:
3233 3214 filename = get_py_filename(parameter_s)
3234 3215 cont = file_read(filename)
3235 3216 except IOError:
3236 3217 try:
3237 3218 cont = eval(parameter_s,self.user_ns)
3238 3219 except NameError:
3239 3220 cont = None
3240 3221 if cont is None:
3241 3222 print "Error: no such file or variable"
3242 3223 return
3243 3224
3244 3225 page(self.shell.pycolorize(cont),
3245 3226 screen_lines=self.shell.usable_screen_length)
3246 3227
3247 3228 def _rerun_pasted(self):
3248 3229 """ Rerun a previously pasted command.
3249 3230 """
3250 3231 b = self.user_ns.get('pasted_block', None)
3251 3232 if b is None:
3252 3233 raise UsageError('No previous pasted block available')
3253 3234 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3254 3235 exec b in self.user_ns
3255 3236
3256 3237 def _get_pasted_lines(self, sentinel):
3257 3238 """ Yield pasted lines until the user enters the given sentinel value.
3258 3239 """
3259 3240 from IPython.core import iplib
3260 3241 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3261 3242 while True:
3262 3243 l = iplib.raw_input_original(':')
3263 3244 if l == sentinel:
3264 3245 return
3265 3246 else:
3266 3247 yield l
3267 3248
3268 3249 def _strip_pasted_lines_for_code(self, raw_lines):
3269 3250 """ Strip non-code parts of a sequence of lines to return a block of
3270 3251 code.
3271 3252 """
3272 3253 # Regular expressions that declare text we strip from the input:
3273 3254 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3274 3255 r'^\s*(\s?>)+', # Python input prompt
3275 3256 r'^\s*\.{3,}', # Continuation prompts
3276 3257 r'^\++',
3277 3258 ]
3278 3259
3279 3260 strip_from_start = map(re.compile,strip_re)
3280 3261
3281 3262 lines = []
3282 3263 for l in raw_lines:
3283 3264 for pat in strip_from_start:
3284 3265 l = pat.sub('',l)
3285 3266 lines.append(l)
3286 3267
3287 3268 block = "\n".join(lines) + '\n'
3288 3269 #print "block:\n",block
3289 3270 return block
3290 3271
3291 3272 def _execute_block(self, block, par):
3292 3273 """ Execute a block, or store it in a variable, per the user's request.
3293 3274 """
3294 3275 if not par:
3295 3276 b = textwrap.dedent(block)
3296 3277 self.user_ns['pasted_block'] = b
3297 3278 exec b in self.user_ns
3298 3279 else:
3299 3280 self.user_ns[par] = SList(block.splitlines())
3300 3281 print "Block assigned to '%s'" % par
3301 3282
3302 3283 def magic_cpaste(self, parameter_s=''):
3303 3284 """Allows you to paste & execute a pre-formatted code block from clipboard.
3304 3285
3305 3286 You must terminate the block with '--' (two minus-signs) alone on the
3306 3287 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3307 3288 is the new sentinel for this operation)
3308 3289
3309 3290 The block is dedented prior to execution to enable execution of method
3310 3291 definitions. '>' and '+' characters at the beginning of a line are
3311 3292 ignored, to allow pasting directly from e-mails, diff files and
3312 3293 doctests (the '...' continuation prompt is also stripped). The
3313 3294 executed block is also assigned to variable named 'pasted_block' for
3314 3295 later editing with '%edit pasted_block'.
3315 3296
3316 3297 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3317 3298 This assigns the pasted block to variable 'foo' as string, without
3318 3299 dedenting or executing it (preceding >>> and + is still stripped)
3319 3300
3320 3301 '%cpaste -r' re-executes the block previously entered by cpaste.
3321 3302
3322 3303 Do not be alarmed by garbled output on Windows (it's a readline bug).
3323 3304 Just press enter and type -- (and press enter again) and the block
3324 3305 will be what was just pasted.
3325 3306
3326 3307 IPython statements (magics, shell escapes) are not supported (yet).
3327 3308
3328 3309 See also
3329 3310 --------
3330 3311 paste: automatically pull code from clipboard.
3331 3312 """
3332 3313
3333 3314 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3334 3315 par = args.strip()
3335 3316 if opts.has_key('r'):
3336 3317 self._rerun_pasted()
3337 3318 return
3338 3319
3339 3320 sentinel = opts.get('s','--')
3340 3321
3341 3322 block = self._strip_pasted_lines_for_code(
3342 3323 self._get_pasted_lines(sentinel))
3343 3324
3344 3325 self._execute_block(block, par)
3345 3326
3346 3327 def magic_paste(self, parameter_s=''):
3347 3328 """Allows you to paste & execute a pre-formatted code block from clipboard.
3348 3329
3349 3330 The text is pulled directly from the clipboard without user
3350 3331 intervention and printed back on the screen before execution (unless
3351 3332 the -q flag is given to force quiet mode).
3352 3333
3353 3334 The block is dedented prior to execution to enable execution of method
3354 3335 definitions. '>' and '+' characters at the beginning of a line are
3355 3336 ignored, to allow pasting directly from e-mails, diff files and
3356 3337 doctests (the '...' continuation prompt is also stripped). The
3357 3338 executed block is also assigned to variable named 'pasted_block' for
3358 3339 later editing with '%edit pasted_block'.
3359 3340
3360 3341 You can also pass a variable name as an argument, e.g. '%paste foo'.
3361 3342 This assigns the pasted block to variable 'foo' as string, without
3362 3343 dedenting or executing it (preceding >>> and + is still stripped)
3363 3344
3364 3345 Options
3365 3346 -------
3366 3347
3367 3348 -r: re-executes the block previously entered by cpaste.
3368 3349
3369 3350 -q: quiet mode: do not echo the pasted text back to the terminal.
3370 3351
3371 3352 IPython statements (magics, shell escapes) are not supported (yet).
3372 3353
3373 3354 See also
3374 3355 --------
3375 3356 cpaste: manually paste code into terminal until you mark its end.
3376 3357 """
3377 3358 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3378 3359 par = args.strip()
3379 3360 if opts.has_key('r'):
3380 3361 self._rerun_pasted()
3381 3362 return
3382 3363
3383 3364 text = self.shell.hooks.clipboard_get()
3384 3365 block = self._strip_pasted_lines_for_code(text.splitlines())
3385 3366
3386 3367 # By default, echo back to terminal unless quiet mode is requested
3387 3368 if not opts.has_key('q'):
3388 3369 write = self.shell.write
3389 3370 write(block)
3390 3371 if not block.endswith('\n'):
3391 3372 write('\n')
3392 3373 write("## -- End pasted text --\n")
3393 3374
3394 3375 self._execute_block(block, par)
3395 3376
3396 3377 def magic_quickref(self,arg):
3397 3378 """ Show a quick reference sheet """
3398 3379 import IPython.core.usage
3399 3380 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3400 3381
3401 3382 page(qr)
3402 3383
3403 3384 def magic_upgrade(self,arg):
3404 3385 """ Upgrade your IPython installation
3405 3386
3406 3387 This will copy the config files that don't yet exist in your
3407 3388 ipython dir from the system config dir. Use this after upgrading
3408 3389 IPython if you don't wish to delete your .ipython dir.
3409 3390
3410 3391 Call with -nolegacy to get rid of ipythonrc* files (recommended for
3411 3392 new users)
3412 3393
3413 3394 """
3414 3395 ip = self.getapi()
3415 3396 ipinstallation = path(IPython.__file__).dirname()
3416 3397 upgrade_script = '%s "%s"' % (sys.executable,ipinstallation / 'utils' / 'upgradedir.py')
3417 3398 src_config = ipinstallation / 'config' / 'userconfig'
3418 3399 userdir = path(ip.config.IPYTHONDIR)
3419 3400 cmd = '%s "%s" "%s"' % (upgrade_script, src_config, userdir)
3420 3401 print ">",cmd
3421 3402 shell(cmd)
3422 3403 if arg == '-nolegacy':
3423 3404 legacy = userdir.files('ipythonrc*')
3424 3405 print "Nuking legacy files:",legacy
3425 3406
3426 3407 [p.remove() for p in legacy]
3427 3408 suffix = (sys.platform == 'win32' and '.ini' or '')
3428 3409 (userdir / ('ipythonrc' + suffix)).write_text('# Empty, see ipy_user_conf.py\n')
3429 3410
3430 3411
3431 3412 def magic_doctest_mode(self,parameter_s=''):
3432 3413 """Toggle doctest mode on and off.
3433 3414
3434 3415 This mode allows you to toggle the prompt behavior between normal
3435 3416 IPython prompts and ones that are as similar to the default IPython
3436 3417 interpreter as possible.
3437 3418
3438 3419 It also supports the pasting of code snippets that have leading '>>>'
3439 3420 and '...' prompts in them. This means that you can paste doctests from
3440 3421 files or docstrings (even if they have leading whitespace), and the
3441 3422 code will execute correctly. You can then use '%history -tn' to see
3442 3423 the translated history without line numbers; this will give you the
3443 3424 input after removal of all the leading prompts and whitespace, which
3444 3425 can be pasted back into an editor.
3445 3426
3446 3427 With these features, you can switch into this mode easily whenever you
3447 3428 need to do testing and changes to doctests, without having to leave
3448 3429 your existing IPython session.
3449 3430 """
3450 3431
3451 3432 # XXX - Fix this to have cleaner activate/deactivate calls.
3452 3433 from IPython.extensions import InterpreterPasteInput as ipaste
3453 3434 from IPython.utils.ipstruct import Struct
3454 3435
3455 3436 # Shorthands
3456 3437 shell = self.shell
3457 3438 oc = shell.outputcache
3458 3439 meta = shell.meta
3459 3440 # dstore is a data store kept in the instance metadata bag to track any
3460 3441 # changes we make, so we can undo them later.
3461 3442 dstore = meta.setdefault('doctest_mode',Struct())
3462 3443 save_dstore = dstore.setdefault
3463 3444
3464 3445 # save a few values we'll need to recover later
3465 3446 mode = save_dstore('mode',False)
3466 3447 save_dstore('rc_pprint',shell.pprint)
3467 3448 save_dstore('xmode',shell.InteractiveTB.mode)
3468 3449 save_dstore('rc_separate_out',shell.separate_out)
3469 3450 save_dstore('rc_separate_out2',shell.separate_out2)
3470 3451 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3471 3452 save_dstore('rc_separate_in',shell.separate_in)
3472 3453
3473 3454 if mode == False:
3474 3455 # turn on
3475 3456 ipaste.activate_prefilter()
3476 3457
3477 3458 oc.prompt1.p_template = '>>> '
3478 3459 oc.prompt2.p_template = '... '
3479 3460 oc.prompt_out.p_template = ''
3480 3461
3481 3462 # Prompt separators like plain python
3482 3463 oc.input_sep = oc.prompt1.sep = ''
3483 3464 oc.output_sep = ''
3484 3465 oc.output_sep2 = ''
3485 3466
3486 3467 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3487 3468 oc.prompt_out.pad_left = False
3488 3469
3489 3470 shell.pprint = False
3490 3471
3491 3472 shell.magic_xmode('Plain')
3492 3473
3493 3474 else:
3494 3475 # turn off
3495 3476 ipaste.deactivate_prefilter()
3496 3477
3497 3478 oc.prompt1.p_template = shell.prompt_in1
3498 3479 oc.prompt2.p_template = shell.prompt_in2
3499 3480 oc.prompt_out.p_template = shell.prompt_out
3500 3481
3501 3482 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3502 3483
3503 3484 oc.output_sep = dstore.rc_separate_out
3504 3485 oc.output_sep2 = dstore.rc_separate_out2
3505 3486
3506 3487 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3507 3488 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3508 3489
3509 3490 rc.pprint = dstore.rc_pprint
3510 3491
3511 3492 shell.magic_xmode(dstore.xmode)
3512 3493
3513 3494 # Store new mode and inform
3514 3495 dstore.mode = bool(1-int(mode))
3515 3496 print 'Doctest mode is:',
3516 3497 print ['OFF','ON'][dstore.mode]
3517 3498
3518 3499 def magic_gui(self, parameter_s=''):
3519 3500 """Enable or disable IPython GUI event loop integration.
3520 3501
3521 3502 %gui [-a] [GUINAME]
3522 3503
3523 3504 This magic replaces IPython's threaded shells that were activated
3524 3505 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3525 3506 can now be enabled, disabled and swtiched at runtime and keyboard
3526 3507 interrupts should work without any problems. The following toolkits
3527 3508 are supports: wxPython, PyQt4, PyGTK, and Tk::
3528 3509
3529 3510 %gui wx # enable wxPython event loop integration
3530 3511 %gui qt4|qt # enable PyQt4 event loop integration
3531 3512 %gui gtk # enable PyGTK event loop integration
3532 3513 %gui tk # enable Tk event loop integration
3533 3514 %gui # disable all event loop integration
3534 3515
3535 3516 WARNING: after any of these has been called you can simply create
3536 3517 an application object, but DO NOT start the event loop yourself, as
3537 3518 we have already handled that.
3538 3519
3539 3520 If you want us to create an appropriate application object add the
3540 3521 "-a" flag to your command::
3541 3522
3542 3523 %gui -a wx
3543 3524
3544 3525 This is highly recommended for most users.
3545 3526 """
3546 3527 from IPython.lib import inputhook
3547 3528 if "-a" in parameter_s:
3548 3529 app = True
3549 3530 else:
3550 3531 app = False
3551 3532 if not parameter_s:
3552 3533 inputhook.clear_inputhook()
3553 3534 elif 'wx' in parameter_s:
3554 3535 return inputhook.enable_wx(app)
3555 3536 elif ('qt4' in parameter_s) or ('qt' in parameter_s):
3556 3537 return inputhook.enable_qt4(app)
3557 3538 elif 'gtk' in parameter_s:
3558 3539 return inputhook.enable_gtk(app)
3559 3540 elif 'tk' in parameter_s:
3560 3541 return inputhook.enable_tk(app)
3561 3542
3562 3543
3563 3544 # end Magic
@@ -1,306 +1,308
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 Paging capabilities for IPython.core
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10
11 11 Notes
12 12 -----
13 13
14 14 For now this uses ipapi, so it can't be in IPython.utils. If we can get
15 15 rid of that dependency, we could move it there.
16 16 -----
17 17 """
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Copyright (C) 2008-2009 The IPython Development Team
21 21 #
22 22 # Distributed under the terms of the BSD License. The full license is in
23 23 # the file COPYING, distributed as part of this software.
24 24 #-----------------------------------------------------------------------------
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Imports
28 28 #-----------------------------------------------------------------------------
29 29
30 30 import os
31 31 import re
32 32 import sys
33 33
34 34 from IPython.core import ipapi
35 35 from IPython.core.error import TryNext
36 36 from IPython.utils.genutils import (
37 37 chop, Term, USE_CURSES
38 38 )
39 39
40 40 if os.name == "nt":
41 41 from IPython.utils.winconsole import get_console_size
42 42
43 43
44 44 #-----------------------------------------------------------------------------
45 45 # Classes and functions
46 46 #-----------------------------------------------------------------------------
47 47
48 48 esc_re = re.compile(r"(\x1b[^m]+m)")
49 49
50 50 def page_dumb(strng,start=0,screen_lines=25):
51 51 """Very dumb 'pager' in Python, for when nothing else works.
52 52
53 53 Only moves forward, same interface as page(), except for pager_cmd and
54 54 mode."""
55 55
56 56 out_ln = strng.splitlines()[start:]
57 57 screens = chop(out_ln,screen_lines-1)
58 58 if len(screens) == 1:
59 59 print >>Term.cout, os.linesep.join(screens[0])
60 60 else:
61 61 last_escape = ""
62 62 for scr in screens[0:-1]:
63 63 hunk = os.linesep.join(scr)
64 64 print >>Term.cout, last_escape + hunk
65 65 if not page_more():
66 66 return
67 67 esc_list = esc_re.findall(hunk)
68 68 if len(esc_list) > 0:
69 69 last_escape = esc_list[-1]
70 70 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
71 71
72 72 #----------------------------------------------------------------------------
73 73 def page(strng,start=0,screen_lines=0,pager_cmd = None):
74 74 """Print a string, piping through a pager after a certain length.
75 75
76 76 The screen_lines parameter specifies the number of *usable* lines of your
77 77 terminal screen (total lines minus lines you need to reserve to show other
78 78 information).
79 79
80 80 If you set screen_lines to a number <=0, page() will try to auto-determine
81 81 your screen size and will only use up to (screen_size+screen_lines) for
82 82 printing, paging after that. That is, if you want auto-detection but need
83 83 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
84 84 auto-detection without any lines reserved simply use screen_lines = 0.
85 85
86 86 If a string won't fit in the allowed lines, it is sent through the
87 87 specified pager command. If none given, look for PAGER in the environment,
88 88 and ultimately default to less.
89 89
90 90 If no system pager works, the string is sent through a 'dumb pager'
91 91 written in python, very simplistic.
92 92 """
93 93
94 94 # Some routines may auto-compute start offsets incorrectly and pass a
95 95 # negative value. Offset to 0 for robustness.
96 96 start = max(0,start)
97 97
98 98 # first, try the hook
99 99 ip = ipapi.get()
100 100 if ip:
101 101 try:
102 102 ip.hooks.show_in_pager(strng)
103 103 return
104 104 except TryNext:
105 105 pass
106 106
107 107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
108 108 TERM = os.environ.get('TERM','dumb')
109 109 if TERM in ['dumb','emacs'] and os.name != 'nt':
110 110 print strng
111 111 return
112 112 # chop off the topmost part of the string we don't want to see
113 113 str_lines = strng.split(os.linesep)[start:]
114 114 str_toprint = os.linesep.join(str_lines)
115 115 num_newlines = len(str_lines)
116 116 len_str = len(str_toprint)
117 117
118 118 # Dumb heuristics to guesstimate number of on-screen lines the string
119 119 # takes. Very basic, but good enough for docstrings in reasonable
120 120 # terminals. If someone later feels like refining it, it's not hard.
121 121 numlines = max(num_newlines,int(len_str/80)+1)
122 122
123 123 if os.name == "nt":
124 124 screen_lines_def = get_console_size(defaulty=25)[1]
125 125 else:
126 126 screen_lines_def = 25 # default value if we can't auto-determine
127 127
128 128 # auto-determine screen size
129 129 if screen_lines <= 0:
130 if TERM=='xterm':
130 if TERM=='xterm' or TERM=='xterm-color':
131 131 use_curses = USE_CURSES
132 132 else:
133 133 # curses causes problems on many terminals other than xterm.
134 134 use_curses = False
135 135 if use_curses:
136 import termios
137 import curses
136 138 # There is a bug in curses, where *sometimes* it fails to properly
137 139 # initialize, and then after the endwin() call is made, the
138 140 # terminal is left in an unusable state. Rather than trying to
139 141 # check everytime for this (by requesting and comparing termios
140 142 # flags each time), we just save the initial terminal state and
141 143 # unconditionally reset it every time. It's cheaper than making
142 144 # the checks.
143 145 term_flags = termios.tcgetattr(sys.stdout)
144 146 scr = curses.initscr()
145 147 screen_lines_real,screen_cols = scr.getmaxyx()
146 148 curses.endwin()
147 149 # Restore terminal state in case endwin() didn't.
148 150 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
149 151 # Now we have what we needed: the screen size in rows/columns
150 152 screen_lines += screen_lines_real
151 153 #print '***Screen size:',screen_lines_real,'lines x',\
152 154 #screen_cols,'columns.' # dbg
153 155 else:
154 156 screen_lines += screen_lines_def
155 157
156 158 #print 'numlines',numlines,'screenlines',screen_lines # dbg
157 159 if numlines <= screen_lines :
158 160 #print '*** normal print' # dbg
159 161 print >>Term.cout, str_toprint
160 162 else:
161 163 # Try to open pager and default to internal one if that fails.
162 164 # All failure modes are tagged as 'retval=1', to match the return
163 165 # value of a failed system command. If any intermediate attempt
164 166 # sets retval to 1, at the end we resort to our own page_dumb() pager.
165 167 pager_cmd = get_pager_cmd(pager_cmd)
166 168 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
167 169 if os.name == 'nt':
168 170 if pager_cmd.startswith('type'):
169 171 # The default WinXP 'type' command is failing on complex strings.
170 172 retval = 1
171 173 else:
172 174 tmpname = tempfile.mktemp('.txt')
173 175 tmpfile = file(tmpname,'wt')
174 176 tmpfile.write(strng)
175 177 tmpfile.close()
176 178 cmd = "%s < %s" % (pager_cmd,tmpname)
177 179 if os.system(cmd):
178 180 retval = 1
179 181 else:
180 182 retval = None
181 183 os.remove(tmpname)
182 184 else:
183 185 try:
184 186 retval = None
185 187 # if I use popen4, things hang. No idea why.
186 188 #pager,shell_out = os.popen4(pager_cmd)
187 189 pager = os.popen(pager_cmd,'w')
188 190 pager.write(strng)
189 191 pager.close()
190 192 retval = pager.close() # success returns None
191 193 except IOError,msg: # broken pipe when user quits
192 194 if msg.args == (32,'Broken pipe'):
193 195 retval = None
194 196 else:
195 197 retval = 1
196 198 except OSError:
197 199 # Other strange problems, sometimes seen in Win2k/cygwin
198 200 retval = 1
199 201 if retval is not None:
200 202 page_dumb(strng,screen_lines=screen_lines)
201 203
202 204 #----------------------------------------------------------------------------
203 205 def page_file(fname,start = 0, pager_cmd = None):
204 206 """Page a file, using an optional pager command and starting line.
205 207 """
206 208
207 209 pager_cmd = get_pager_cmd(pager_cmd)
208 210 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
209 211
210 212 try:
211 213 if os.environ['TERM'] in ['emacs','dumb']:
212 214 raise EnvironmentError
213 215 xsys(pager_cmd + ' ' + fname)
214 216 except:
215 217 try:
216 218 if start > 0:
217 219 start -= 1
218 220 page(open(fname).read(),start)
219 221 except:
220 222 print 'Unable to show file',`fname`
221 223
222 224 #----------------------------------------------------------------------------
223 225 def get_pager_cmd(pager_cmd = None):
224 226 """Return a pager command.
225 227
226 228 Makes some attempts at finding an OS-correct one."""
227 229
228 230 if os.name == 'posix':
229 231 default_pager_cmd = 'less -r' # -r for color control sequences
230 232 elif os.name in ['nt','dos']:
231 233 default_pager_cmd = 'type'
232 234
233 235 if pager_cmd is None:
234 236 try:
235 237 pager_cmd = os.environ['PAGER']
236 238 except:
237 239 pager_cmd = default_pager_cmd
238 240 return pager_cmd
239 241
240 242 #-----------------------------------------------------------------------------
241 243 def get_pager_start(pager,start):
242 244 """Return the string for paging files with an offset.
243 245
244 246 This is the '+N' argument which less and more (under Unix) accept.
245 247 """
246 248
247 249 if pager in ['less','more']:
248 250 if start:
249 251 start_string = '+' + str(start)
250 252 else:
251 253 start_string = ''
252 254 else:
253 255 start_string = ''
254 256 return start_string
255 257
256 258 #----------------------------------------------------------------------------
257 259 # (X)emacs on W32 doesn't like to be bypassed with msvcrt.getch()
258 260 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
259 261 import msvcrt
260 262 def page_more():
261 263 """ Smart pausing between pages
262 264
263 265 @return: True if need print more lines, False if quit
264 266 """
265 267 Term.cout.write('---Return to continue, q to quit--- ')
266 268 ans = msvcrt.getch()
267 269 if ans in ("q", "Q"):
268 270 result = False
269 271 else:
270 272 result = True
271 273 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
272 274 return result
273 275 else:
274 276 def page_more():
275 277 ans = raw_input('---Return to continue, q to quit--- ')
276 278 if ans.lower().startswith('q'):
277 279 return False
278 280 else:
279 281 return True
280 282
281 283 #----------------------------------------------------------------------------
282 284 def snip_print(str,width = 75,print_full = 0,header = ''):
283 285 """Print a string snipping the midsection to fit in width.
284 286
285 287 print_full: mode control:
286 288 - 0: only snip long strings
287 289 - 1: send to page() directly.
288 290 - 2: snip long strings and ask for full length viewing with page()
289 291 Return 1 if snipping was necessary, 0 otherwise."""
290 292
291 293 if print_full == 1:
292 294 page(header+str)
293 295 return 0
294 296
295 297 print header,
296 298 if len(str) < width:
297 299 print str
298 300 snip = 0
299 301 else:
300 302 whalf = int((width -5)/2)
301 303 print str[:whalf] + ' <...> ' + str[-whalf:]
302 304 snip = 1
303 305 if snip and print_full == 2:
304 306 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
305 307 page(str)
306 308 return snip No newline at end of file
@@ -1,777 +1,772
1 1 #!/usr/bin/env python
2 2 # encoding: utf-8
3 3 """
4 4 Prefiltering components.
5 5
6 6 Authors:
7 7
8 8 * Brian Granger
9 9 * Fernando Perez
10 10 * Dan Milstein
11 11 """
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Copyright (C) 2008-2009 The IPython Development Team
15 15 #
16 16 # Distributed under the terms of the BSD License. The full license is in
17 17 # the file COPYING, distributed as part of this software.
18 18 #-----------------------------------------------------------------------------
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Imports
22 22 #-----------------------------------------------------------------------------
23 23
24 24 import __builtin__
25 25 import codeop
26 26 import keyword
27 27 import os
28 28 import re
29 29 import sys
30 30
31 31 from IPython.core.alias import AliasManager
32 32 from IPython.core.autocall import IPyAutocall
33 33 from IPython.core.component import Component
34 34 from IPython.core.splitinput import split_user_input
35 from IPython.core.page import page
35 36
36 37 from IPython.utils.traitlets import List, Int, Any, Str, CBool
37 38 from IPython.utils.genutils import make_quoted_expr
38 39 from IPython.utils.autoattr import auto_attr
39 40
40 41 #-----------------------------------------------------------------------------
41 42 # Global utilities, errors and constants
42 43 #-----------------------------------------------------------------------------
43 44
44 45
45 46 ESC_SHELL = '!'
46 47 ESC_SH_CAP = '!!'
47 48 ESC_HELP = '?'
48 49 ESC_MAGIC = '%'
49 50 ESC_QUOTE = ','
50 51 ESC_QUOTE2 = ';'
51 52 ESC_PAREN = '/'
52 53
53 54
54 55 class PrefilterError(Exception):
55 56 pass
56 57
57 58
58 59 # RegExp to identify potential function names
59 60 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
60 61
61 62 # RegExp to exclude strings with this start from autocalling. In
62 63 # particular, all binary operators should be excluded, so that if foo is
63 64 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
64 65 # characters '!=()' don't need to be checked for, as the checkPythonChars
65 66 # routine explicitely does so, to catch direct calls and rebindings of
66 67 # existing names.
67 68
68 69 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
69 70 # it affects the rest of the group in square brackets.
70 71 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
71 72 r'|^is |^not |^in |^and |^or ')
72 73
73 74 # try to catch also methods for stuff in lists/tuples/dicts: off
74 75 # (experimental). For this to work, the line_split regexp would need
75 76 # to be modified so it wouldn't break things at '['. That line is
76 77 # nasty enough that I shouldn't change it until I can test it _well_.
77 78 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
78 79
79 80
80 81 # Handler Check Utilities
81 82 def is_shadowed(identifier, ip):
82 83 """Is the given identifier defined in one of the namespaces which shadow
83 84 the alias and magic namespaces? Note that an identifier is different
84 85 than ifun, because it can not contain a '.' character."""
85 86 # This is much safer than calling ofind, which can change state
86 87 return (identifier in ip.user_ns \
87 88 or identifier in ip.internal_ns \
88 89 or identifier in ip.ns_table['builtin'])
89 90
90 91
91 92 #-----------------------------------------------------------------------------
92 93 # The LineInfo class used throughout
93 94 #-----------------------------------------------------------------------------
94 95
95 96
96 97 class LineInfo(object):
97 98 """A single line of input and associated info.
98 99
99 100 Includes the following as properties:
100 101
101 102 line
102 103 The original, raw line
103 104
104 105 continue_prompt
105 106 Is this line a continuation in a sequence of multiline input?
106 107
107 108 pre
108 109 The initial esc character or whitespace.
109 110
110 111 pre_char
111 112 The escape character(s) in pre or the empty string if there isn't one.
112 113 Note that '!!' is a possible value for pre_char. Otherwise it will
113 114 always be a single character.
114 115
115 116 pre_whitespace
116 117 The leading whitespace from pre if it exists. If there is a pre_char,
117 118 this is just ''.
118 119
119 120 ifun
120 121 The 'function part', which is basically the maximal initial sequence
121 122 of valid python identifiers and the '.' character. This is what is
122 123 checked for alias and magic transformations, used for auto-calling,
123 124 etc.
124 125
125 126 the_rest
126 127 Everything else on the line.
127 128 """
128 129 def __init__(self, line, continue_prompt):
129 130 self.line = line
130 131 self.continue_prompt = continue_prompt
131 132 self.pre, self.ifun, self.the_rest = split_user_input(line)
132 133
133 134 self.pre_char = self.pre.strip()
134 135 if self.pre_char:
135 136 self.pre_whitespace = '' # No whitespace allowd before esc chars
136 137 else:
137 138 self.pre_whitespace = self.pre
138 139
139 140 self._oinfo = None
140 141
141 142 def ofind(self, ip):
142 143 """Do a full, attribute-walking lookup of the ifun in the various
143 144 namespaces for the given IPython InteractiveShell instance.
144 145
145 146 Return a dict with keys: found,obj,ospace,ismagic
146 147
147 148 Note: can cause state changes because of calling getattr, but should
148 149 only be run if autocall is on and if the line hasn't matched any
149 150 other, less dangerous handlers.
150 151
151 152 Does cache the results of the call, so can be called multiple times
152 153 without worrying about *further* damaging state.
153 154 """
154 155 if not self._oinfo:
155 156 self._oinfo = ip._ofind(self.ifun)
156 157 return self._oinfo
157 158
158 159 def __str__(self):
159 160 return "Lineinfo [%s|%s|%s]" %(self.pre,self.ifun,self.the_rest)
160 161
161 162
162 163 #-----------------------------------------------------------------------------
163 164 # Main Prefilter manager
164 165 #-----------------------------------------------------------------------------
165 166
166 167
167 168 class PrefilterManager(Component):
168 169 """Main prefilter component.
169 170
170 171 The IPython prefilter is run on all user input before it is run. The
171 172 prefilter consumes lines of input and produces transformed lines of
172 173 input. The implementation consists of checkers and handlers. The
173 174 checkers inspect the input line and select which handler will be used
174 175 to transform the input line.
175 176 """
176 177
177 178 multi_line_specials = CBool(True, config=True)
178 179
179 180 def __init__(self, parent, config=None):
180 181 super(PrefilterManager, self).__init__(parent, config=config)
181 182 self.init_handlers()
182 183 self.init_checkers()
183 184
184 185 @auto_attr
185 186 def shell(self):
186 shell = Component.get_instances(
187 return Component.get_instances(
187 188 root=self.root,
188 klass='IPython.core.iplib.InteractiveShell'
189 )[0]
190 return shell
189 klass='IPython.core.iplib.InteractiveShell')[0]
191 190
192 191 def init_checkers(self):
193 192 self._checkers = []
194 193 for checker in _default_checkers:
195 194 self._checkers.append(checker(self, config=self.config))
196 195
197 196 def init_handlers(self):
198 197 self._handlers = {}
199 198 self._esc_handlers = {}
200 199 for handler in _default_handlers:
201 200 handler(self, config=self.config)
202 201
203 202 @property
204 203 def sorted_checkers(self):
205 204 """Return a list of checkers, sorted by priority."""
206 205 return sorted(self._checkers, cmp=lambda x,y: x.priority-y.priority)
207 206
208 207 def register_handler(self, name, handler, esc_strings):
209 208 """Register a handler instance by name with esc_strings."""
210 209 self._handlers[name] = handler
211 210 for esc_str in esc_strings:
212 211 self._esc_handlers[esc_str] = handler
213 212
214 213 def unregister_handler(self, name, handler, esc_strings):
215 214 """Unregister a handler instance by name with esc_strings."""
216 215 try:
217 216 del self._handlers[name]
218 217 except KeyError:
219 218 pass
220 219 for esc_str in esc_strings:
221 220 h = self._esc_handlers.get(esc_str)
222 221 if h is handler:
223 222 del self._esc_handlers[esc_str]
224 223
225 224 def get_handler_by_name(self, name):
226 225 """Get a handler by its name."""
227 226 return self._handlers.get(name)
228 227
229 228 def get_handler_by_esc(self, esc_str):
230 229 """Get a handler by its escape string."""
231 230 return self._esc_handlers.get(esc_str)
232 231
233 232 def prefilter_line_info(self, line_info):
234 233 """Prefilter a line that has been converted to a LineInfo object."""
235 234 handler = self.find_handler(line_info)
236 235 return handler.handle(line_info)
237 236
238 237 def find_handler(self, line_info):
239 238 """Find a handler for the line_info by trying checkers."""
240 239 for checker in self.sorted_checkers:
241 240 handler = checker.check(line_info)
242 241 if handler:
243 242 return handler
244 243 return self.get_handler_by_name('normal')
245 244
246 245 def prefilter_line(self, line, continue_prompt):
247 246 """Prefilter a single input line as text."""
248 247
249 248 # All handlers *must* return a value, even if it's blank ('').
250 249
251 250 # Lines are NOT logged here. Handlers should process the line as
252 251 # needed, update the cache AND log it (so that the input cache array
253 252 # stays synced).
254 253
255 254 # growl.notify("_prefilter: ", "line = %s\ncontinue_prompt = %s" % (line, continue_prompt))
256 255
257 256 # save the line away in case we crash, so the post-mortem handler can
258 257 # record it
259 258 self.shell._last_input_line = line
260 259
261 260 if not line:
262 261 # Return immediately on purely empty lines, so that if the user
263 262 # previously typed some whitespace that started a continuation
264 263 # prompt, he can break out of that loop with just an empty line.
265 264 # This is how the default python prompt works.
266 265
267 266 # Only return if the accumulated input buffer was just whitespace!
268 267 if ''.join(self.shell.buffer).isspace():
269 268 self.shell.buffer[:] = []
270 269 return ''
271 270
272 271 line_info = LineInfo(line, continue_prompt)
273 272
274 273 # the input history needs to track even empty lines
275 274 stripped = line.strip()
276 275
277 276 normal_handler = self.get_handler_by_name('normal')
278 277 if not stripped:
279 278 if not continue_prompt:
280 279 self.shell.outputcache.prompt_count -= 1
281 280
282 281 return normal_handler.handle(line_info)
283 282
284 283 # special handlers are only allowed for single line statements
285 284 if continue_prompt and not self.multi_line_specials:
286 285 return normal_handler.handle(line_info)
287 286
288 287 return self.prefilter_line_info(line_info)
289 288
290 289 def prefilter_lines(self, lines, continue_prompt):
291 290 """Prefilter multiple input lines of text.
292 291
293 292 Covers cases where there are multiple lines in the user entry,
294 293 which is the case when the user goes back to a multiline history
295 294 entry and presses enter.
296 295 """
297 296 # growl.notify("multiline_prefilter: ", "%s\n%s" % (line, continue_prompt))
298 297 out = []
299 298 for line in lines.rstrip('\n').split('\n'):
300 299 out.append(self.prefilter_line(line, continue_prompt))
301 300 # growl.notify("multiline_prefilter return: ", '\n'.join(out))
302 301 return '\n'.join(out)
303 302
304 303
305 304 #-----------------------------------------------------------------------------
306 305 # Prefilter checkers
307 306 #-----------------------------------------------------------------------------
308 307
309 308
310 309 class PrefilterChecker(Component):
311 310 """Inspect an input line and return a handler for that line."""
312 311
313 312 priority = Int(100, config=True)
314 313 shell = Any
315 314 prefilter_manager = Any
316 315
317 316 def __init__(self, parent, config=None):
318 317 super(PrefilterChecker, self).__init__(parent, config=config)
319 318
320 319 @auto_attr
321 320 def shell(self):
322 shell = Component.get_instances(
321 return Component.get_instances(
323 322 root=self.root,
324 klass='IPython.core.iplib.InteractiveShell'
325 )[0]
326 return shell
323 klass='IPython.core.iplib.InteractiveShell')[0]
327 324
328 325 @auto_attr
329 326 def prefilter_manager(self):
330 327 return PrefilterManager.get_instances(root=self.root)[0]
331 328
332 329 def check(self, line_info):
333 330 """Inspect line_info and return a handler or None."""
334 331 return None
335 332
336 333
337 334 class EmacsChecker(PrefilterChecker):
338 335
339 336 priority = Int(100, config=True)
340 337
341 338 def check(self, line_info):
342 339 "Emacs ipython-mode tags certain input lines."
343 340 if line_info.line.endswith('# PYTHON-MODE'):
344 341 return self.prefilter_manager.get_handler_by_name('emacs')
345 342 else:
346 343 return None
347 344
348 345
349 346 class ShellEscapeChecker(PrefilterChecker):
350 347
351 348 priority = Int(200, config=True)
352 349
353 350 def check(self, line_info):
354 351 if line_info.line.lstrip().startswith(ESC_SHELL):
355 352 return self.prefilter_manager.get_handler_by_name('shell')
356 353
357 354
358 355 class IPyAutocallChecker(PrefilterChecker):
359 356
360 357 priority = Int(300, config=True)
361 358
362 359 def check(self, line_info):
363 360 "Instances of IPyAutocall in user_ns get autocalled immediately"
364 361 obj = self.shell.user_ns.get(line_info.ifun, None)
365 362 if isinstance(obj, IPyAutocall):
366 363 obj.set_ip(self.shell)
367 364 return self.prefilter_manager.get_handler_by_name('auto')
368 365 else:
369 366 return None
370 367
371 368
372 369 class MultiLineMagicChecker(PrefilterChecker):
373 370
374 371 priority = Int(400, config=True)
375 372
376 373 def check(self, line_info):
377 374 "Allow ! and !! in multi-line statements if multi_line_specials is on"
378 375 # Note that this one of the only places we check the first character of
379 376 # ifun and *not* the pre_char. Also note that the below test matches
380 377 # both ! and !!.
381 378 if line_info.continue_prompt \
382 379 and self.prefilter_manager.multi_line_specials:
383 380 if line_info.ifun.startswith(ESC_MAGIC):
384 381 return self.prefilter_manager.get_handler_by_name('magic')
385 382 else:
386 383 return None
387 384
388 385
389 386 class EscCharsChecker(PrefilterChecker):
390 387
391 388 priority = Int(500, config=True)
392 389
393 390 def check(self, line_info):
394 391 """Check for escape character and return either a handler to handle it,
395 392 or None if there is no escape char."""
396 393 if line_info.line[-1] == ESC_HELP \
397 394 and line_info.pre_char != ESC_SHELL \
398 395 and line_info.pre_char != ESC_SH_CAP:
399 396 # the ? can be at the end, but *not* for either kind of shell escape,
400 397 # because a ? can be a vaild final char in a shell cmd
401 398 return self.prefilter_manager.get_handler_by_name('help')
402 399 else:
403 400 # This returns None like it should if no handler exists
404 401 return self.prefilter_manager.get_handler_by_esc(line_info.pre_char)
405 402
406 403
407 404 class AssignmentChecker(PrefilterChecker):
408 405
409 406 priority = Int(600, config=True)
410 407
411 408 def check(self, line_info):
412 409 """Check to see if user is assigning to a var for the first time, in
413 410 which case we want to avoid any sort of automagic / autocall games.
414 411
415 412 This allows users to assign to either alias or magic names true python
416 413 variables (the magic/alias systems always take second seat to true
417 414 python code). E.g. ls='hi', or ls,that=1,2"""
418 415 if line_info.the_rest and line_info.the_rest[0] in '=,':
419 416 return self.prefilter_manager.get_handler_by_name('normal')
420 417 else:
421 418 return None
422 419
423 420
424 421 class AutoMagicChecker(PrefilterChecker):
425 422
426 423 priority = Int(700, config=True)
427 424
428 425 def check(self, line_info):
429 426 """If the ifun is magic, and automagic is on, run it. Note: normal,
430 427 non-auto magic would already have been triggered via '%' in
431 428 check_esc_chars. This just checks for automagic. Also, before
432 429 triggering the magic handler, make sure that there is nothing in the
433 430 user namespace which could shadow it."""
434 431 if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun):
435 432 return None
436 433
437 434 # We have a likely magic method. Make sure we should actually call it.
438 435 if line_info.continue_prompt and not self.shell.multi_line_specials:
439 436 return None
440 437
441 438 head = line_info.ifun.split('.',1)[0]
442 439 if is_shadowed(head, self.shell):
443 440 return None
444 441
445 442 return self.prefilter_manager.get_handler_by_name('magic')
446 443
447 444
448 445 class AliasChecker(PrefilterChecker):
449 446
450 447 priority = Int(800, config=True)
451 448
452 449 @auto_attr
453 450 def alias_manager(self):
454 451 return AliasManager.get_instances(root=self.root)[0]
455 452
456 453 def check(self, line_info):
457 454 "Check if the initital identifier on the line is an alias."
458 455 # Note: aliases can not contain '.'
459 456 head = line_info.ifun.split('.',1)[0]
460 457 if line_info.ifun not in self.alias_manager \
461 458 or head not in self.alias_manager \
462 459 or is_shadowed(head, self.shell):
463 460 return None
464 461
465 462 return self.prefilter_manager.get_handler_by_name('alias')
466 463
467 464
468 465 class PythonOpsChecker(PrefilterChecker):
469 466
470 467 priority = Int(900, config=True)
471 468
472 469 def check(self, line_info):
473 470 """If the 'rest' of the line begins with a function call or pretty much
474 471 any python operator, we should simply execute the line (regardless of
475 472 whether or not there's a possible autocall expansion). This avoids
476 473 spurious (and very confusing) geattr() accesses."""
477 474 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
478 475 return self.prefilter_manager.get_handler_by_name('normal')
479 476 else:
480 477 return None
481 478
482 479
483 480 class AutocallChecker(PrefilterChecker):
484 481
485 482 priority = Int(1000, config=True)
486 483
487 484 def check(self, line_info):
488 485 "Check if the initial word/function is callable and autocall is on."
489 486 if not self.shell.autocall:
490 487 return None
491 488
492 489 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
493 490 if not oinfo['found']:
494 491 return None
495 492
496 493 if callable(oinfo['obj']) \
497 494 and (not re_exclude_auto.match(line_info.the_rest)) \
498 495 and re_fun_name.match(line_info.ifun):
499 496 return self.prefilter_manager.get_handler_by_name('auto')
500 497 else:
501 498 return None
502 499
503 500
504 501 #-----------------------------------------------------------------------------
505 502 # Prefilter handlers
506 503 #-----------------------------------------------------------------------------
507 504
508 505
509 506 class PrefilterHandler(Component):
510 507
511 508 handler_name = Str('normal')
512 509 esc_strings = List([])
513 510 shell = Any
514 511 prefilter_manager = Any
515 512
516 513 def __init__(self, parent, config=None):
517 514 super(PrefilterHandler, self).__init__(parent, config=config)
518 515 self.prefilter_manager.register_handler(
519 516 self.handler_name,
520 517 self,
521 518 self.esc_strings
522 519 )
523 520
524 521 @auto_attr
525 522 def shell(self):
526 shell = Component.get_instances(
523 return Component.get_instances(
527 524 root=self.root,
528 klass='IPython.core.iplib.InteractiveShell'
529 )[0]
530 return shell
525 klass='IPython.core.iplib.InteractiveShell')[0]
531 526
532 527 @auto_attr
533 528 def prefilter_manager(self):
534 529 return PrefilterManager.get_instances(root=self.root)[0]
535 530
536 531 def handle(self, line_info):
537 532 """Handle normal input lines. Use as a template for handlers."""
538 533
539 534 # With autoindent on, we need some way to exit the input loop, and I
540 535 # don't want to force the user to have to backspace all the way to
541 536 # clear the line. The rule will be in this case, that either two
542 537 # lines of pure whitespace in a row, or a line of pure whitespace but
543 538 # of a size different to the indent level, will exit the input loop.
544 539 line = line_info.line
545 540 continue_prompt = line_info.continue_prompt
546 541
547 542 if (continue_prompt and self.shell.autoindent and line.isspace() and
548 543 (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2 or
549 544 (self.shell.buffer[-1]).isspace() )):
550 545 line = ''
551 546
552 547 self.shell.log(line, line, continue_prompt)
553 548 return line
554 549
555 550
556 551 class AliasHandler(PrefilterHandler):
557 552
558 553 handler_name = Str('alias')
559 554 esc_strings = List([])
560 555
561 556 @auto_attr
562 557 def alias_manager(self):
563 558 return AliasManager.get_instances(root=self.root)[0]
564 559
565 560 def handle(self, line_info):
566 561 """Handle alias input lines. """
567 562 transformed = self.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
568 563 # pre is needed, because it carries the leading whitespace. Otherwise
569 564 # aliases won't work in indented sections.
570 565 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
571 566 make_quoted_expr(transformed))
572 567
573 568 self.shell.log(line_info.line, line_out, line_info.continue_prompt)
574 569 return line_out
575 570
576 571
577 572 class ShellEscapeHandler(PrefilterHandler):
578 573
579 574 handler_name = Str('shell')
580 575 esc_strings = List([ESC_SHELL, ESC_SH_CAP])
581 576
582 577 def handle(self, line_info):
583 578 """Execute the line in a shell, empty return value"""
584 579 magic_handler = self.prefilter_manager.get_handler_by_name('magic')
585 580
586 581 line = line_info.line
587 582 if line.lstrip().startswith(ESC_SH_CAP):
588 583 # rewrite LineInfo's line, ifun and the_rest to properly hold the
589 584 # call to %sx and the actual command to be executed, so
590 585 # handle_magic can work correctly. Note that this works even if
591 586 # the line is indented, so it handles multi_line_specials
592 587 # properly.
593 588 new_rest = line.lstrip()[2:]
594 589 line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
595 590 line_info.ifun = 'sx'
596 591 line_info.the_rest = new_rest
597 592 return magic_handler.handle(line_info)
598 593 else:
599 594 cmd = line.lstrip().lstrip(ESC_SHELL)
600 595 line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace,
601 596 make_quoted_expr(cmd))
602 597 # update cache/log and return
603 598 self.shell.log(line, line_out, line_info.continue_prompt)
604 599 return line_out
605 600
606 601
607 602 class MagicHandler(PrefilterHandler):
608 603
609 604 handler_name = Str('magic')
610 605 esc_strings = List([ESC_MAGIC])
611 606
612 607 def handle(self, line_info):
613 608 """Execute magic functions."""
614 609 ifun = line_info.ifun
615 610 the_rest = line_info.the_rest
616 611 cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace,
617 612 make_quoted_expr(ifun + " " + the_rest))
618 613 self.shell.log(line_info.line, cmd, line_info.continue_prompt)
619 614 return cmd
620 615
621 616
622 617 class AutoHandler(PrefilterHandler):
623 618
624 619 handler_name = Str('auto')
625 620 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
626 621
627 622 def handle(self, line_info):
628 623 """Hande lines which can be auto-executed, quoting if requested."""
629 624 line = line_info.line
630 625 ifun = line_info.ifun
631 626 the_rest = line_info.the_rest
632 627 pre = line_info.pre
633 628 continue_prompt = line_info.continue_prompt
634 629 obj = line_info.ofind(self)['obj']
635 630
636 631 #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg
637 632
638 633 # This should only be active for single-line input!
639 634 if continue_prompt:
640 635 self.log(line,line,continue_prompt)
641 636 return line
642 637
643 638 force_auto = isinstance(obj, IPyAutocall)
644 639 auto_rewrite = True
645 640
646 641 if pre == ESC_QUOTE:
647 642 # Auto-quote splitting on whitespace
648 643 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
649 644 elif pre == ESC_QUOTE2:
650 645 # Auto-quote whole string
651 646 newcmd = '%s("%s")' % (ifun,the_rest)
652 647 elif pre == ESC_PAREN:
653 648 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
654 649 else:
655 650 # Auto-paren.
656 651 # We only apply it to argument-less calls if the autocall
657 652 # parameter is set to 2. We only need to check that autocall is <
658 653 # 2, since this function isn't called unless it's at least 1.
659 654 if not the_rest and (self.shell.autocall < 2) and not force_auto:
660 655 newcmd = '%s %s' % (ifun,the_rest)
661 656 auto_rewrite = False
662 657 else:
663 658 if not force_auto and the_rest.startswith('['):
664 659 if hasattr(obj,'__getitem__'):
665 660 # Don't autocall in this case: item access for an object
666 661 # which is BOTH callable and implements __getitem__.
667 662 newcmd = '%s %s' % (ifun,the_rest)
668 663 auto_rewrite = False
669 664 else:
670 665 # if the object doesn't support [] access, go ahead and
671 666 # autocall
672 667 newcmd = '%s(%s)' % (ifun.rstrip(),the_rest)
673 668 elif the_rest.endswith(';'):
674 669 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
675 670 else:
676 671 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
677 672
678 673 if auto_rewrite:
679 674 rw = self.shell.outputcache.prompt1.auto_rewrite() + newcmd
680 675
681 676 try:
682 677 # plain ascii works better w/ pyreadline, on some machines, so
683 678 # we use it and only print uncolored rewrite if we have unicode
684 679 rw = str(rw)
685 680 print >>Term.cout, rw
686 681 except UnicodeEncodeError:
687 682 print "-------------->" + newcmd
688 683
689 684 # log what is now valid Python, not the actual user input (without the
690 685 # final newline)
691 686 self.shell.log(line,newcmd,continue_prompt)
692 687 return newcmd
693 688
694 689
695 690 class HelpHandler(PrefilterHandler):
696 691
697 692 handler_name = Str('help')
698 693 esc_strings = List([ESC_HELP])
699 694
700 695 def handle(self, line_info):
701 696 """Try to get some help for the object.
702 697
703 698 obj? or ?obj -> basic information.
704 699 obj?? or ??obj -> more details.
705 700 """
706 701 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
707 702 line = line_info.line
708 703 # We need to make sure that we don't process lines which would be
709 704 # otherwise valid python, such as "x=1 # what?"
710 705 try:
711 706 codeop.compile_command(line)
712 707 except SyntaxError:
713 708 # We should only handle as help stuff which is NOT valid syntax
714 709 if line[0]==ESC_HELP:
715 710 line = line[1:]
716 711 elif line[-1]==ESC_HELP:
717 712 line = line[:-1]
718 713 self.shell.log(line, '#?'+line, line_info.continue_prompt)
719 714 if line:
720 715 #print 'line:<%r>' % line # dbg
721 716 self.shell.magic_pinfo(line)
722 717 else:
723 718 page(self.shell.usage, screen_lines=self.shell.usable_screen_length)
724 719 return '' # Empty string is needed here!
725 720 except:
726 721 raise
727 722 # Pass any other exceptions through to the normal handler
728 723 return normal_handler.handle(line_info)
729 724 else:
730 725 raise
731 726 # If the code compiles ok, we should handle it normally
732 727 return normal_handler.handle(line_info)
733 728
734 729
735 730 class EmacsHandler(PrefilterHandler):
736 731
737 732 handler_name = Str('emacs')
738 733 esc_strings = List([])
739 734
740 735 def handle(self, line_info):
741 736 """Handle input lines marked by python-mode."""
742 737
743 738 # Currently, nothing is done. Later more functionality can be added
744 739 # here if needed.
745 740
746 741 # The input cache shouldn't be updated
747 742 return line_info.line
748 743
749 744
750 745 #-----------------------------------------------------------------------------
751 746 # Defaults
752 747 #-----------------------------------------------------------------------------
753 748
754 749
755 750 _default_checkers = [
756 751 EmacsChecker,
757 752 ShellEscapeChecker,
758 753 IPyAutocallChecker,
759 754 MultiLineMagicChecker,
760 755 EscCharsChecker,
761 756 AssignmentChecker,
762 757 AutoMagicChecker,
763 758 AliasChecker,
764 759 PythonOpsChecker,
765 760 AutocallChecker
766 761 ]
767 762
768 763 _default_handlers = [
769 764 PrefilterHandler,
770 765 AliasHandler,
771 766 ShellEscapeHandler,
772 767 MagicHandler,
773 768 AutoHandler,
774 769 HelpHandler,
775 770 EmacsHandler
776 771 ]
777 772
General Comments 0
You need to be logged in to leave comments. Login now