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