##// 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 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import abc
21 import abc
22 import codeop
22 import codeop
23 import exceptions
23 import exceptions
24 import new
24 import new
25 import os
25 import os
26 import re
26 import re
27 import string
27 import string
28 import sys
28 import sys
29 import tempfile
29 import tempfile
30 from contextlib import nested
30 from contextlib import nested
31
31
32 from IPython.config.configurable import Configurable
32 from IPython.config.configurable import Configurable
33 from IPython.core import debugger, oinspect
33 from IPython.core import debugger, oinspect
34 from IPython.core import history as ipcorehist
34 from IPython.core import history as ipcorehist
35 from IPython.core import page
35 from IPython.core import page
36 from IPython.core import prefilter
36 from IPython.core import prefilter
37 from IPython.core import shadowns
37 from IPython.core import shadowns
38 from IPython.core import ultratb
38 from IPython.core import ultratb
39 from IPython.core.alias import AliasManager
39 from IPython.core.alias import AliasManager
40 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.displayhook import DisplayHook
42 from IPython.core.displayhook import DisplayHook
43 from IPython.core.error import UsageError
43 from IPython.core.error import UsageError
44 from IPython.core.extensions import ExtensionManager
44 from IPython.core.extensions import ExtensionManager
45 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
45 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
46 from IPython.core.inputlist import InputList
46 from IPython.core.inputlist import InputList
47 from IPython.core.logger import Logger
47 from IPython.core.logger import Logger
48 from IPython.core.magic import Magic
48 from IPython.core.magic import Magic
49 from IPython.core.payload import PayloadManager
49 from IPython.core.payload import PayloadManager
50 from IPython.core.plugin import PluginManager
50 from IPython.core.plugin import PluginManager
51 from IPython.core.prefilter import PrefilterManager
51 from IPython.core.prefilter import PrefilterManager
52 from IPython.external.Itpl import ItplNS
52 from IPython.external.Itpl import ItplNS
53 from IPython.utils import PyColorize
53 from IPython.utils import PyColorize
54 from IPython.utils import io
54 from IPython.utils import io
55 from IPython.utils import pickleshare
55 from IPython.utils import pickleshare
56 from IPython.utils.doctestreload import doctest_reload
56 from IPython.utils.doctestreload import doctest_reload
57 from IPython.utils.io import ask_yes_no, rprint
57 from IPython.utils.io import ask_yes_no, rprint
58 from IPython.utils.ipstruct import Struct
58 from IPython.utils.ipstruct import Struct
59 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
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 from IPython.utils.strdispatch import StrDispatch
61 from IPython.utils.strdispatch import StrDispatch
62 from IPython.utils.syspathcontext import prepended_to_syspath
62 from IPython.utils.syspathcontext import prepended_to_syspath
63 from IPython.utils.text import num_ini_spaces
63 from IPython.utils.text import num_ini_spaces
64 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
64 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
65 List, Unicode, Instance, Type)
65 List, Unicode, Instance, Type)
66 from IPython.utils.warn import warn, error, fatal
66 from IPython.utils.warn import warn, error, fatal
67 import IPython.core.hooks
67 import IPython.core.hooks
68
68
69 # from IPython.utils import growl
69 # from IPython.utils import growl
70 # growl.start("IPython")
70 # growl.start("IPython")
71
71
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 # Globals
73 # Globals
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75
75
76 # compiled regexps for autoindent management
76 # compiled regexps for autoindent management
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
78
78
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80 # Utilities
80 # Utilities
81 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
82
82
83 # store the builtin raw_input globally, and use this always, in case user code
83 # store the builtin raw_input globally, and use this always, in case user code
84 # overwrites it (like wx.py.PyShell does)
84 # overwrites it (like wx.py.PyShell does)
85 raw_input_original = raw_input
85 raw_input_original = raw_input
86
86
87 def softspace(file, newvalue):
87 def softspace(file, newvalue):
88 """Copied from code.py, to remove the dependency"""
88 """Copied from code.py, to remove the dependency"""
89
89
90 oldvalue = 0
90 oldvalue = 0
91 try:
91 try:
92 oldvalue = file.softspace
92 oldvalue = file.softspace
93 except AttributeError:
93 except AttributeError:
94 pass
94 pass
95 try:
95 try:
96 file.softspace = newvalue
96 file.softspace = newvalue
97 except (AttributeError, TypeError):
97 except (AttributeError, TypeError):
98 # "attribute-less object" or "read-only attributes"
98 # "attribute-less object" or "read-only attributes"
99 pass
99 pass
100 return oldvalue
100 return oldvalue
101
101
102
102
103 def no_op(*a, **kw): pass
103 def no_op(*a, **kw): pass
104
104
105 class SpaceInInput(exceptions.Exception): pass
105 class SpaceInInput(exceptions.Exception): pass
106
106
107 class Bunch: pass
107 class Bunch: pass
108
108
109
109
110 def get_default_colors():
110 def get_default_colors():
111 if sys.platform=='darwin':
111 if sys.platform=='darwin':
112 return "LightBG"
112 return "LightBG"
113 elif os.name=='nt':
113 elif os.name=='nt':
114 return 'Linux'
114 return 'Linux'
115 else:
115 else:
116 return 'Linux'
116 return 'Linux'
117
117
118
118
119 class SeparateStr(Str):
119 class SeparateStr(Str):
120 """A Str subclass to validate separate_in, separate_out, etc.
120 """A Str subclass to validate separate_in, separate_out, etc.
121
121
122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
123 """
123 """
124
124
125 def validate(self, obj, value):
125 def validate(self, obj, value):
126 if value == '0': value = ''
126 if value == '0': value = ''
127 value = value.replace('\\n','\n')
127 value = value.replace('\\n','\n')
128 return super(SeparateStr, self).validate(obj, value)
128 return super(SeparateStr, self).validate(obj, value)
129
129
130 class MultipleInstanceError(Exception):
130 class MultipleInstanceError(Exception):
131 pass
131 pass
132
132
133
133
134 #-----------------------------------------------------------------------------
134 #-----------------------------------------------------------------------------
135 # Main IPython class
135 # Main IPython class
136 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
137
137
138
138
139 class InteractiveShell(Configurable, Magic):
139 class InteractiveShell(Configurable, Magic):
140 """An enhanced, interactive shell for Python."""
140 """An enhanced, interactive shell for Python."""
141
141
142 _instance = None
142 _instance = None
143 autocall = Enum((0,1,2), default_value=1, config=True)
143 autocall = Enum((0,1,2), default_value=1, config=True)
144 # TODO: remove all autoindent logic and put into frontends.
144 # TODO: remove all autoindent logic and put into frontends.
145 # We can't do this yet because even runlines uses the autoindent.
145 # We can't do this yet because even runlines uses the autoindent.
146 autoindent = CBool(True, config=True)
146 autoindent = CBool(True, config=True)
147 automagic = CBool(True, config=True)
147 automagic = CBool(True, config=True)
148 cache_size = Int(1000, config=True)
148 cache_size = Int(1000, config=True)
149 color_info = CBool(True, config=True)
149 color_info = CBool(True, config=True)
150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
151 default_value=get_default_colors(), config=True)
151 default_value=get_default_colors(), config=True)
152 debug = CBool(False, config=True)
152 debug = CBool(False, config=True)
153 deep_reload = CBool(False, config=True)
153 deep_reload = CBool(False, config=True)
154 displayhook_class = Type(DisplayHook)
154 displayhook_class = Type(DisplayHook)
155 filename = Str("<ipython console>")
155 filename = Str("<ipython console>")
156 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
156 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
157 logstart = CBool(False, config=True)
157 logstart = CBool(False, config=True)
158 logfile = Str('', config=True)
158 logfile = Str('', config=True)
159 logappend = Str('', config=True)
159 logappend = Str('', config=True)
160 object_info_string_level = Enum((0,1,2), default_value=0,
160 object_info_string_level = Enum((0,1,2), default_value=0,
161 config=True)
161 config=True)
162 pdb = CBool(False, config=True)
162 pdb = CBool(False, config=True)
163 pprint = CBool(True, config=True)
163 pprint = CBool(True, config=True)
164 profile = Str('', config=True)
164 profile = Str('', config=True)
165 prompt_in1 = Str('In [\\#]: ', config=True)
165 prompt_in1 = Str('In [\\#]: ', config=True)
166 prompt_in2 = Str(' .\\D.: ', config=True)
166 prompt_in2 = Str(' .\\D.: ', config=True)
167 prompt_out = Str('Out[\\#]: ', config=True)
167 prompt_out = Str('Out[\\#]: ', config=True)
168 prompts_pad_left = CBool(True, config=True)
168 prompts_pad_left = CBool(True, config=True)
169 quiet = CBool(False, config=True)
169 quiet = CBool(False, config=True)
170
170
171 # The readline stuff will eventually be moved to the terminal subclass
171 # The readline stuff will eventually be moved to the terminal subclass
172 # but for now, we can't do that as readline is welded in everywhere.
172 # but for now, we can't do that as readline is welded in everywhere.
173 readline_use = CBool(True, config=True)
173 readline_use = CBool(True, config=True)
174 readline_merge_completions = CBool(True, config=True)
174 readline_merge_completions = CBool(True, config=True)
175 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
175 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
176 readline_remove_delims = Str('-/~', config=True)
176 readline_remove_delims = Str('-/~', config=True)
177 readline_parse_and_bind = List([
177 readline_parse_and_bind = List([
178 'tab: complete',
178 'tab: complete',
179 '"\C-l": clear-screen',
179 '"\C-l": clear-screen',
180 'set show-all-if-ambiguous on',
180 'set show-all-if-ambiguous on',
181 '"\C-o": tab-insert',
181 '"\C-o": tab-insert',
182 '"\M-i": " "',
182 '"\M-i": " "',
183 '"\M-o": "\d\d\d\d"',
183 '"\M-o": "\d\d\d\d"',
184 '"\M-I": "\d\d\d\d"',
184 '"\M-I": "\d\d\d\d"',
185 '"\C-r": reverse-search-history',
185 '"\C-r": reverse-search-history',
186 '"\C-s": forward-search-history',
186 '"\C-s": forward-search-history',
187 '"\C-p": history-search-backward',
187 '"\C-p": history-search-backward',
188 '"\C-n": history-search-forward',
188 '"\C-n": history-search-forward',
189 '"\e[A": history-search-backward',
189 '"\e[A": history-search-backward',
190 '"\e[B": history-search-forward',
190 '"\e[B": history-search-forward',
191 '"\C-k": kill-line',
191 '"\C-k": kill-line',
192 '"\C-u": unix-line-discard',
192 '"\C-u": unix-line-discard',
193 ], allow_none=False, config=True)
193 ], allow_none=False, config=True)
194
194
195 # TODO: this part of prompt management should be moved to the frontends.
195 # TODO: this part of prompt management should be moved to the frontends.
196 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
196 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
197 separate_in = SeparateStr('\n', config=True)
197 separate_in = SeparateStr('\n', config=True)
198 separate_out = SeparateStr('', config=True)
198 separate_out = SeparateStr('', config=True)
199 separate_out2 = SeparateStr('', config=True)
199 separate_out2 = SeparateStr('', config=True)
200 wildcards_case_sensitive = CBool(True, config=True)
200 wildcards_case_sensitive = CBool(True, config=True)
201 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
201 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
202 default_value='Context', config=True)
202 default_value='Context', config=True)
203
203
204 # Subcomponents of InteractiveShell
204 # Subcomponents of InteractiveShell
205 alias_manager = Instance('IPython.core.alias.AliasManager')
205 alias_manager = Instance('IPython.core.alias.AliasManager')
206 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
206 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
207 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
207 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
208 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
208 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
209 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
209 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
210 plugin_manager = Instance('IPython.core.plugin.PluginManager')
210 plugin_manager = Instance('IPython.core.plugin.PluginManager')
211 payload_manager = Instance('IPython.core.payload.PayloadManager')
211 payload_manager = Instance('IPython.core.payload.PayloadManager')
212
212
213 def __init__(self, config=None, ipython_dir=None,
213 def __init__(self, config=None, ipython_dir=None,
214 user_ns=None, user_global_ns=None,
214 user_ns=None, user_global_ns=None,
215 custom_exceptions=((),None)):
215 custom_exceptions=((),None)):
216
216
217 # This is where traits with a config_key argument are updated
217 # This is where traits with a config_key argument are updated
218 # from the values on config.
218 # from the values on config.
219 super(InteractiveShell, self).__init__(config=config)
219 super(InteractiveShell, self).__init__(config=config)
220
220
221 # These are relatively independent and stateless
221 # These are relatively independent and stateless
222 self.init_ipython_dir(ipython_dir)
222 self.init_ipython_dir(ipython_dir)
223 self.init_instance_attrs()
223 self.init_instance_attrs()
224
224
225 # Create namespaces (user_ns, user_global_ns, etc.)
225 # Create namespaces (user_ns, user_global_ns, etc.)
226 self.init_create_namespaces(user_ns, user_global_ns)
226 self.init_create_namespaces(user_ns, user_global_ns)
227 # This has to be done after init_create_namespaces because it uses
227 # This has to be done after init_create_namespaces because it uses
228 # something in self.user_ns, but before init_sys_modules, which
228 # something in self.user_ns, but before init_sys_modules, which
229 # is the first thing to modify sys.
229 # is the first thing to modify sys.
230 # TODO: When we override sys.stdout and sys.stderr before this class
230 # TODO: When we override sys.stdout and sys.stderr before this class
231 # is created, we are saving the overridden ones here. Not sure if this
231 # is created, we are saving the overridden ones here. Not sure if this
232 # is what we want to do.
232 # is what we want to do.
233 self.save_sys_module_state()
233 self.save_sys_module_state()
234 self.init_sys_modules()
234 self.init_sys_modules()
235
235
236 self.init_history()
236 self.init_history()
237 self.init_encoding()
237 self.init_encoding()
238 self.init_prefilter()
238 self.init_prefilter()
239
239
240 Magic.__init__(self, self)
240 Magic.__init__(self, self)
241
241
242 self.init_syntax_highlighting()
242 self.init_syntax_highlighting()
243 self.init_hooks()
243 self.init_hooks()
244 self.init_pushd_popd_magic()
244 self.init_pushd_popd_magic()
245 # self.init_traceback_handlers use to be here, but we moved it below
245 # self.init_traceback_handlers use to be here, but we moved it below
246 # because it and init_io have to come after init_readline.
246 # because it and init_io have to come after init_readline.
247 self.init_user_ns()
247 self.init_user_ns()
248 self.init_logger()
248 self.init_logger()
249 self.init_alias()
249 self.init_alias()
250 self.init_builtins()
250 self.init_builtins()
251
251
252 # pre_config_initialization
252 # pre_config_initialization
253 self.init_shadow_hist()
253 self.init_shadow_hist()
254
254
255 # The next section should contain averything that was in ipmaker.
255 # The next section should contain averything that was in ipmaker.
256 self.init_logstart()
256 self.init_logstart()
257
257
258 # The following was in post_config_initialization
258 # The following was in post_config_initialization
259 self.init_inspector()
259 self.init_inspector()
260 # init_readline() must come before init_io(), because init_io uses
260 # init_readline() must come before init_io(), because init_io uses
261 # readline related things.
261 # readline related things.
262 self.init_readline()
262 self.init_readline()
263 # TODO: init_io() needs to happen before init_traceback handlers
263 # TODO: init_io() needs to happen before init_traceback handlers
264 # because the traceback handlers hardcode the stdout/stderr streams.
264 # because the traceback handlers hardcode the stdout/stderr streams.
265 # This logic in in debugger.Pdb and should eventually be changed.
265 # This logic in in debugger.Pdb and should eventually be changed.
266 self.init_io()
266 self.init_io()
267 self.init_traceback_handlers(custom_exceptions)
267 self.init_traceback_handlers(custom_exceptions)
268 self.init_prompts()
268 self.init_prompts()
269 self.init_displayhook()
269 self.init_displayhook()
270 self.init_reload_doctest()
270 self.init_reload_doctest()
271 self.init_magics()
271 self.init_magics()
272 self.init_pdb()
272 self.init_pdb()
273 self.init_extension_manager()
273 self.init_extension_manager()
274 self.init_plugin_manager()
274 self.init_plugin_manager()
275 self.init_payload()
275 self.init_payload()
276 self.hooks.late_startup_hook()
276 self.hooks.late_startup_hook()
277
277
278 @classmethod
278 @classmethod
279 def instance(cls, *args, **kwargs):
279 def instance(cls, *args, **kwargs):
280 """Returns a global InteractiveShell instance."""
280 """Returns a global InteractiveShell instance."""
281 if cls._instance is None:
281 if cls._instance is None:
282 inst = cls(*args, **kwargs)
282 inst = cls(*args, **kwargs)
283 # Now make sure that the instance will also be returned by
283 # Now make sure that the instance will also be returned by
284 # the subclasses instance attribute.
284 # the subclasses instance attribute.
285 for subclass in cls.mro():
285 for subclass in cls.mro():
286 if issubclass(cls, subclass) and issubclass(subclass, InteractiveShell):
286 if issubclass(cls, subclass) and issubclass(subclass, InteractiveShell):
287 subclass._instance = inst
287 subclass._instance = inst
288 else:
288 else:
289 break
289 break
290 if isinstance(cls._instance, cls):
290 if isinstance(cls._instance, cls):
291 return cls._instance
291 return cls._instance
292 else:
292 else:
293 raise MultipleInstanceError(
293 raise MultipleInstanceError(
294 'Multiple incompatible subclass instances of '
294 'Multiple incompatible subclass instances of '
295 'InteractiveShell are being created.'
295 'InteractiveShell are being created.'
296 )
296 )
297
297
298 @classmethod
298 @classmethod
299 def initialized(cls):
299 def initialized(cls):
300 return hasattr(cls, "_instance")
300 return hasattr(cls, "_instance")
301
301
302 def get_ipython(self):
302 def get_ipython(self):
303 """Return the currently running IPython instance."""
303 """Return the currently running IPython instance."""
304 return self
304 return self
305
305
306 #-------------------------------------------------------------------------
306 #-------------------------------------------------------------------------
307 # Trait changed handlers
307 # Trait changed handlers
308 #-------------------------------------------------------------------------
308 #-------------------------------------------------------------------------
309
309
310 def _ipython_dir_changed(self, name, new):
310 def _ipython_dir_changed(self, name, new):
311 if not os.path.isdir(new):
311 if not os.path.isdir(new):
312 os.makedirs(new, mode = 0777)
312 os.makedirs(new, mode = 0777)
313
313
314 def set_autoindent(self,value=None):
314 def set_autoindent(self,value=None):
315 """Set the autoindent flag, checking for readline support.
315 """Set the autoindent flag, checking for readline support.
316
316
317 If called with no arguments, it acts as a toggle."""
317 If called with no arguments, it acts as a toggle."""
318
318
319 if not self.has_readline:
319 if not self.has_readline:
320 if os.name == 'posix':
320 if os.name == 'posix':
321 warn("The auto-indent feature requires the readline library")
321 warn("The auto-indent feature requires the readline library")
322 self.autoindent = 0
322 self.autoindent = 0
323 return
323 return
324 if value is None:
324 if value is None:
325 self.autoindent = not self.autoindent
325 self.autoindent = not self.autoindent
326 else:
326 else:
327 self.autoindent = value
327 self.autoindent = value
328
328
329 #-------------------------------------------------------------------------
329 #-------------------------------------------------------------------------
330 # init_* methods called by __init__
330 # init_* methods called by __init__
331 #-------------------------------------------------------------------------
331 #-------------------------------------------------------------------------
332
332
333 def init_ipython_dir(self, ipython_dir):
333 def init_ipython_dir(self, ipython_dir):
334 if ipython_dir is not None:
334 if ipython_dir is not None:
335 self.ipython_dir = ipython_dir
335 self.ipython_dir = ipython_dir
336 self.config.Global.ipython_dir = self.ipython_dir
336 self.config.Global.ipython_dir = self.ipython_dir
337 return
337 return
338
338
339 if hasattr(self.config.Global, 'ipython_dir'):
339 if hasattr(self.config.Global, 'ipython_dir'):
340 self.ipython_dir = self.config.Global.ipython_dir
340 self.ipython_dir = self.config.Global.ipython_dir
341 else:
341 else:
342 self.ipython_dir = get_ipython_dir()
342 self.ipython_dir = get_ipython_dir()
343
343
344 # All children can just read this
344 # All children can just read this
345 self.config.Global.ipython_dir = self.ipython_dir
345 self.config.Global.ipython_dir = self.ipython_dir
346
346
347 def init_instance_attrs(self):
347 def init_instance_attrs(self):
348 self.more = False
348 self.more = False
349
349
350 # command compiler
350 # command compiler
351 self.compile = codeop.CommandCompiler()
351 self.compile = codeop.CommandCompiler()
352
352
353 # User input buffer
353 # User input buffer
354 self.buffer = []
354 self.buffer = []
355
355
356 # Make an empty namespace, which extension writers can rely on both
356 # Make an empty namespace, which extension writers can rely on both
357 # existing and NEVER being used by ipython itself. This gives them a
357 # existing and NEVER being used by ipython itself. This gives them a
358 # convenient location for storing additional information and state
358 # convenient location for storing additional information and state
359 # their extensions may require, without fear of collisions with other
359 # their extensions may require, without fear of collisions with other
360 # ipython names that may develop later.
360 # ipython names that may develop later.
361 self.meta = Struct()
361 self.meta = Struct()
362
362
363 # Object variable to store code object waiting execution. This is
363 # Object variable to store code object waiting execution. This is
364 # used mainly by the multithreaded shells, but it can come in handy in
364 # used mainly by the multithreaded shells, but it can come in handy in
365 # other situations. No need to use a Queue here, since it's a single
365 # other situations. No need to use a Queue here, since it's a single
366 # item which gets cleared once run.
366 # item which gets cleared once run.
367 self.code_to_run = None
367 self.code_to_run = None
368
368
369 # Temporary files used for various purposes. Deleted at exit.
369 # Temporary files used for various purposes. Deleted at exit.
370 self.tempfiles = []
370 self.tempfiles = []
371
371
372 # Keep track of readline usage (later set by init_readline)
372 # Keep track of readline usage (later set by init_readline)
373 self.has_readline = False
373 self.has_readline = False
374
374
375 # keep track of where we started running (mainly for crash post-mortem)
375 # keep track of where we started running (mainly for crash post-mortem)
376 # This is not being used anywhere currently.
376 # This is not being used anywhere currently.
377 self.starting_dir = os.getcwd()
377 self.starting_dir = os.getcwd()
378
378
379 # Indentation management
379 # Indentation management
380 self.indent_current_nsp = 0
380 self.indent_current_nsp = 0
381
381
382 def init_encoding(self):
382 def init_encoding(self):
383 # Get system encoding at startup time. Certain terminals (like Emacs
383 # Get system encoding at startup time. Certain terminals (like Emacs
384 # under Win32 have it set to None, and we need to have a known valid
384 # under Win32 have it set to None, and we need to have a known valid
385 # encoding to use in the raw_input() method
385 # encoding to use in the raw_input() method
386 try:
386 try:
387 self.stdin_encoding = sys.stdin.encoding or 'ascii'
387 self.stdin_encoding = sys.stdin.encoding or 'ascii'
388 except AttributeError:
388 except AttributeError:
389 self.stdin_encoding = 'ascii'
389 self.stdin_encoding = 'ascii'
390
390
391 def init_syntax_highlighting(self):
391 def init_syntax_highlighting(self):
392 # Python source parser/formatter for syntax highlighting
392 # Python source parser/formatter for syntax highlighting
393 pyformat = PyColorize.Parser().format
393 pyformat = PyColorize.Parser().format
394 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
394 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
395
395
396 def init_pushd_popd_magic(self):
396 def init_pushd_popd_magic(self):
397 # for pushd/popd management
397 # for pushd/popd management
398 try:
398 try:
399 self.home_dir = get_home_dir()
399 self.home_dir = get_home_dir()
400 except HomeDirError, msg:
400 except HomeDirError, msg:
401 fatal(msg)
401 fatal(msg)
402
402
403 self.dir_stack = []
403 self.dir_stack = []
404
404
405 def init_logger(self):
405 def init_logger(self):
406 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
406 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
407 # local shortcut, this is used a LOT
407 # local shortcut, this is used a LOT
408 self.log = self.logger.log
408 self.log = self.logger.log
409
409
410 def init_logstart(self):
410 def init_logstart(self):
411 if self.logappend:
411 if self.logappend:
412 self.magic_logstart(self.logappend + ' append')
412 self.magic_logstart(self.logappend + ' append')
413 elif self.logfile:
413 elif self.logfile:
414 self.magic_logstart(self.logfile)
414 self.magic_logstart(self.logfile)
415 elif self.logstart:
415 elif self.logstart:
416 self.magic_logstart()
416 self.magic_logstart()
417
417
418 def init_builtins(self):
418 def init_builtins(self):
419 self.builtin_trap = BuiltinTrap(shell=self)
419 self.builtin_trap = BuiltinTrap(shell=self)
420
420
421 def init_inspector(self):
421 def init_inspector(self):
422 # Object inspector
422 # Object inspector
423 self.inspector = oinspect.Inspector(oinspect.InspectColors,
423 self.inspector = oinspect.Inspector(oinspect.InspectColors,
424 PyColorize.ANSICodeColors,
424 PyColorize.ANSICodeColors,
425 'NoColor',
425 'NoColor',
426 self.object_info_string_level)
426 self.object_info_string_level)
427
427
428 def init_io(self):
428 def init_io(self):
429 import IPython.utils.io
429 import IPython.utils.io
430 if sys.platform == 'win32' and self.has_readline:
430 if sys.platform == 'win32' and self.has_readline:
431 Term = io.IOTerm(
431 Term = io.IOTerm(
432 cout=self.readline._outputfile,cerr=self.readline._outputfile
432 cout=self.readline._outputfile,cerr=self.readline._outputfile
433 )
433 )
434 else:
434 else:
435 Term = io.IOTerm()
435 Term = io.IOTerm()
436 io.Term = Term
436 io.Term = Term
437
437
438 def init_prompts(self):
438 def init_prompts(self):
439 # TODO: This is a pass for now because the prompts are managed inside
439 # TODO: This is a pass for now because the prompts are managed inside
440 # the DisplayHook. Once there is a separate prompt manager, this
440 # the DisplayHook. Once there is a separate prompt manager, this
441 # will initialize that object and all prompt related information.
441 # will initialize that object and all prompt related information.
442 pass
442 pass
443
443
444 def init_displayhook(self):
444 def init_displayhook(self):
445 # Initialize displayhook, set in/out prompts and printing system
445 # Initialize displayhook, set in/out prompts and printing system
446 self.displayhook = self.displayhook_class(
446 self.displayhook = self.displayhook_class(
447 shell=self,
447 shell=self,
448 cache_size=self.cache_size,
448 cache_size=self.cache_size,
449 input_sep = self.separate_in,
449 input_sep = self.separate_in,
450 output_sep = self.separate_out,
450 output_sep = self.separate_out,
451 output_sep2 = self.separate_out2,
451 output_sep2 = self.separate_out2,
452 ps1 = self.prompt_in1,
452 ps1 = self.prompt_in1,
453 ps2 = self.prompt_in2,
453 ps2 = self.prompt_in2,
454 ps_out = self.prompt_out,
454 ps_out = self.prompt_out,
455 pad_left = self.prompts_pad_left
455 pad_left = self.prompts_pad_left
456 )
456 )
457 # This is a context manager that installs/revmoes the displayhook at
457 # This is a context manager that installs/revmoes the displayhook at
458 # the appropriate time.
458 # the appropriate time.
459 self.display_trap = DisplayTrap(hook=self.displayhook)
459 self.display_trap = DisplayTrap(hook=self.displayhook)
460
460
461 def init_reload_doctest(self):
461 def init_reload_doctest(self):
462 # Do a proper resetting of doctest, including the necessary displayhook
462 # Do a proper resetting of doctest, including the necessary displayhook
463 # monkeypatching
463 # monkeypatching
464 try:
464 try:
465 doctest_reload()
465 doctest_reload()
466 except ImportError:
466 except ImportError:
467 warn("doctest module does not exist.")
467 warn("doctest module does not exist.")
468
468
469 #-------------------------------------------------------------------------
469 #-------------------------------------------------------------------------
470 # Things related to injections into the sys module
470 # Things related to injections into the sys module
471 #-------------------------------------------------------------------------
471 #-------------------------------------------------------------------------
472
472
473 def save_sys_module_state(self):
473 def save_sys_module_state(self):
474 """Save the state of hooks in the sys module.
474 """Save the state of hooks in the sys module.
475
475
476 This has to be called after self.user_ns is created.
476 This has to be called after self.user_ns is created.
477 """
477 """
478 self._orig_sys_module_state = {}
478 self._orig_sys_module_state = {}
479 self._orig_sys_module_state['stdin'] = sys.stdin
479 self._orig_sys_module_state['stdin'] = sys.stdin
480 self._orig_sys_module_state['stdout'] = sys.stdout
480 self._orig_sys_module_state['stdout'] = sys.stdout
481 self._orig_sys_module_state['stderr'] = sys.stderr
481 self._orig_sys_module_state['stderr'] = sys.stderr
482 self._orig_sys_module_state['excepthook'] = sys.excepthook
482 self._orig_sys_module_state['excepthook'] = sys.excepthook
483 try:
483 try:
484 self._orig_sys_modules_main_name = self.user_ns['__name__']
484 self._orig_sys_modules_main_name = self.user_ns['__name__']
485 except KeyError:
485 except KeyError:
486 pass
486 pass
487
487
488 def restore_sys_module_state(self):
488 def restore_sys_module_state(self):
489 """Restore the state of the sys module."""
489 """Restore the state of the sys module."""
490 try:
490 try:
491 for k, v in self._orig_sys_module_state.items():
491 for k, v in self._orig_sys_module_state.items():
492 setattr(sys, k, v)
492 setattr(sys, k, v)
493 except AttributeError:
493 except AttributeError:
494 pass
494 pass
495 try:
495 try:
496 delattr(sys, 'ipcompleter')
496 delattr(sys, 'ipcompleter')
497 except AttributeError:
497 except AttributeError:
498 pass
498 pass
499 # Reset what what done in self.init_sys_modules
499 # Reset what what done in self.init_sys_modules
500 try:
500 try:
501 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
501 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
502 except (AttributeError, KeyError):
502 except (AttributeError, KeyError):
503 pass
503 pass
504
504
505 #-------------------------------------------------------------------------
505 #-------------------------------------------------------------------------
506 # Things related to hooks
506 # Things related to hooks
507 #-------------------------------------------------------------------------
507 #-------------------------------------------------------------------------
508
508
509 def init_hooks(self):
509 def init_hooks(self):
510 # hooks holds pointers used for user-side customizations
510 # hooks holds pointers used for user-side customizations
511 self.hooks = Struct()
511 self.hooks = Struct()
512
512
513 self.strdispatchers = {}
513 self.strdispatchers = {}
514
514
515 # Set all default hooks, defined in the IPython.hooks module.
515 # Set all default hooks, defined in the IPython.hooks module.
516 hooks = IPython.core.hooks
516 hooks = IPython.core.hooks
517 for hook_name in hooks.__all__:
517 for hook_name in hooks.__all__:
518 # default hooks have priority 100, i.e. low; user hooks should have
518 # default hooks have priority 100, i.e. low; user hooks should have
519 # 0-100 priority
519 # 0-100 priority
520 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
520 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
521
521
522 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
522 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
523 """set_hook(name,hook) -> sets an internal IPython hook.
523 """set_hook(name,hook) -> sets an internal IPython hook.
524
524
525 IPython exposes some of its internal API as user-modifiable hooks. By
525 IPython exposes some of its internal API as user-modifiable hooks. By
526 adding your function to one of these hooks, you can modify IPython's
526 adding your function to one of these hooks, you can modify IPython's
527 behavior to call at runtime your own routines."""
527 behavior to call at runtime your own routines."""
528
528
529 # At some point in the future, this should validate the hook before it
529 # At some point in the future, this should validate the hook before it
530 # accepts it. Probably at least check that the hook takes the number
530 # accepts it. Probably at least check that the hook takes the number
531 # of args it's supposed to.
531 # of args it's supposed to.
532
532
533 f = new.instancemethod(hook,self,self.__class__)
533 f = new.instancemethod(hook,self,self.__class__)
534
534
535 # check if the hook is for strdispatcher first
535 # check if the hook is for strdispatcher first
536 if str_key is not None:
536 if str_key is not None:
537 sdp = self.strdispatchers.get(name, StrDispatch())
537 sdp = self.strdispatchers.get(name, StrDispatch())
538 sdp.add_s(str_key, f, priority )
538 sdp.add_s(str_key, f, priority )
539 self.strdispatchers[name] = sdp
539 self.strdispatchers[name] = sdp
540 return
540 return
541 if re_key is not None:
541 if re_key is not None:
542 sdp = self.strdispatchers.get(name, StrDispatch())
542 sdp = self.strdispatchers.get(name, StrDispatch())
543 sdp.add_re(re.compile(re_key), f, priority )
543 sdp.add_re(re.compile(re_key), f, priority )
544 self.strdispatchers[name] = sdp
544 self.strdispatchers[name] = sdp
545 return
545 return
546
546
547 dp = getattr(self.hooks, name, None)
547 dp = getattr(self.hooks, name, None)
548 if name not in IPython.core.hooks.__all__:
548 if name not in IPython.core.hooks.__all__:
549 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
549 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
550 if not dp:
550 if not dp:
551 dp = IPython.core.hooks.CommandChainDispatcher()
551 dp = IPython.core.hooks.CommandChainDispatcher()
552
552
553 try:
553 try:
554 dp.add(f,priority)
554 dp.add(f,priority)
555 except AttributeError:
555 except AttributeError:
556 # it was not commandchain, plain old func - replace
556 # it was not commandchain, plain old func - replace
557 dp = f
557 dp = f
558
558
559 setattr(self.hooks,name, dp)
559 setattr(self.hooks,name, dp)
560
560
561 #-------------------------------------------------------------------------
561 #-------------------------------------------------------------------------
562 # Things related to the "main" module
562 # Things related to the "main" module
563 #-------------------------------------------------------------------------
563 #-------------------------------------------------------------------------
564
564
565 def new_main_mod(self,ns=None):
565 def new_main_mod(self,ns=None):
566 """Return a new 'main' module object for user code execution.
566 """Return a new 'main' module object for user code execution.
567 """
567 """
568 main_mod = self._user_main_module
568 main_mod = self._user_main_module
569 init_fakemod_dict(main_mod,ns)
569 init_fakemod_dict(main_mod,ns)
570 return main_mod
570 return main_mod
571
571
572 def cache_main_mod(self,ns,fname):
572 def cache_main_mod(self,ns,fname):
573 """Cache a main module's namespace.
573 """Cache a main module's namespace.
574
574
575 When scripts are executed via %run, we must keep a reference to the
575 When scripts are executed via %run, we must keep a reference to the
576 namespace of their __main__ module (a FakeModule instance) around so
576 namespace of their __main__ module (a FakeModule instance) around so
577 that Python doesn't clear it, rendering objects defined therein
577 that Python doesn't clear it, rendering objects defined therein
578 useless.
578 useless.
579
579
580 This method keeps said reference in a private dict, keyed by the
580 This method keeps said reference in a private dict, keyed by the
581 absolute path of the module object (which corresponds to the script
581 absolute path of the module object (which corresponds to the script
582 path). This way, for multiple executions of the same script we only
582 path). This way, for multiple executions of the same script we only
583 keep one copy of the namespace (the last one), thus preventing memory
583 keep one copy of the namespace (the last one), thus preventing memory
584 leaks from old references while allowing the objects from the last
584 leaks from old references while allowing the objects from the last
585 execution to be accessible.
585 execution to be accessible.
586
586
587 Note: we can not allow the actual FakeModule instances to be deleted,
587 Note: we can not allow the actual FakeModule instances to be deleted,
588 because of how Python tears down modules (it hard-sets all their
588 because of how Python tears down modules (it hard-sets all their
589 references to None without regard for reference counts). This method
589 references to None without regard for reference counts). This method
590 must therefore make a *copy* of the given namespace, to allow the
590 must therefore make a *copy* of the given namespace, to allow the
591 original module's __dict__ to be cleared and reused.
591 original module's __dict__ to be cleared and reused.
592
592
593
593
594 Parameters
594 Parameters
595 ----------
595 ----------
596 ns : a namespace (a dict, typically)
596 ns : a namespace (a dict, typically)
597
597
598 fname : str
598 fname : str
599 Filename associated with the namespace.
599 Filename associated with the namespace.
600
600
601 Examples
601 Examples
602 --------
602 --------
603
603
604 In [10]: import IPython
604 In [10]: import IPython
605
605
606 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
606 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
607
607
608 In [12]: IPython.__file__ in _ip._main_ns_cache
608 In [12]: IPython.__file__ in _ip._main_ns_cache
609 Out[12]: True
609 Out[12]: True
610 """
610 """
611 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
611 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
612
612
613 def clear_main_mod_cache(self):
613 def clear_main_mod_cache(self):
614 """Clear the cache of main modules.
614 """Clear the cache of main modules.
615
615
616 Mainly for use by utilities like %reset.
616 Mainly for use by utilities like %reset.
617
617
618 Examples
618 Examples
619 --------
619 --------
620
620
621 In [15]: import IPython
621 In [15]: import IPython
622
622
623 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
623 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
624
624
625 In [17]: len(_ip._main_ns_cache) > 0
625 In [17]: len(_ip._main_ns_cache) > 0
626 Out[17]: True
626 Out[17]: True
627
627
628 In [18]: _ip.clear_main_mod_cache()
628 In [18]: _ip.clear_main_mod_cache()
629
629
630 In [19]: len(_ip._main_ns_cache) == 0
630 In [19]: len(_ip._main_ns_cache) == 0
631 Out[19]: True
631 Out[19]: True
632 """
632 """
633 self._main_ns_cache.clear()
633 self._main_ns_cache.clear()
634
634
635 #-------------------------------------------------------------------------
635 #-------------------------------------------------------------------------
636 # Things related to debugging
636 # Things related to debugging
637 #-------------------------------------------------------------------------
637 #-------------------------------------------------------------------------
638
638
639 def init_pdb(self):
639 def init_pdb(self):
640 # Set calling of pdb on exceptions
640 # Set calling of pdb on exceptions
641 # self.call_pdb is a property
641 # self.call_pdb is a property
642 self.call_pdb = self.pdb
642 self.call_pdb = self.pdb
643
643
644 def _get_call_pdb(self):
644 def _get_call_pdb(self):
645 return self._call_pdb
645 return self._call_pdb
646
646
647 def _set_call_pdb(self,val):
647 def _set_call_pdb(self,val):
648
648
649 if val not in (0,1,False,True):
649 if val not in (0,1,False,True):
650 raise ValueError,'new call_pdb value must be boolean'
650 raise ValueError,'new call_pdb value must be boolean'
651
651
652 # store value in instance
652 # store value in instance
653 self._call_pdb = val
653 self._call_pdb = val
654
654
655 # notify the actual exception handlers
655 # notify the actual exception handlers
656 self.InteractiveTB.call_pdb = val
656 self.InteractiveTB.call_pdb = val
657
657
658 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
658 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
659 'Control auto-activation of pdb at exceptions')
659 'Control auto-activation of pdb at exceptions')
660
660
661 def debugger(self,force=False):
661 def debugger(self,force=False):
662 """Call the pydb/pdb debugger.
662 """Call the pydb/pdb debugger.
663
663
664 Keywords:
664 Keywords:
665
665
666 - force(False): by default, this routine checks the instance call_pdb
666 - force(False): by default, this routine checks the instance call_pdb
667 flag and does not actually invoke the debugger if the flag is false.
667 flag and does not actually invoke the debugger if the flag is false.
668 The 'force' option forces the debugger to activate even if the flag
668 The 'force' option forces the debugger to activate even if the flag
669 is false.
669 is false.
670 """
670 """
671
671
672 if not (force or self.call_pdb):
672 if not (force or self.call_pdb):
673 return
673 return
674
674
675 if not hasattr(sys,'last_traceback'):
675 if not hasattr(sys,'last_traceback'):
676 error('No traceback has been produced, nothing to debug.')
676 error('No traceback has been produced, nothing to debug.')
677 return
677 return
678
678
679 # use pydb if available
679 # use pydb if available
680 if debugger.has_pydb:
680 if debugger.has_pydb:
681 from pydb import pm
681 from pydb import pm
682 else:
682 else:
683 # fallback to our internal debugger
683 # fallback to our internal debugger
684 pm = lambda : self.InteractiveTB.debugger(force=True)
684 pm = lambda : self.InteractiveTB.debugger(force=True)
685 self.history_saving_wrapper(pm)()
685 self.history_saving_wrapper(pm)()
686
686
687 #-------------------------------------------------------------------------
687 #-------------------------------------------------------------------------
688 # Things related to IPython's various namespaces
688 # Things related to IPython's various namespaces
689 #-------------------------------------------------------------------------
689 #-------------------------------------------------------------------------
690
690
691 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
691 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
692 # Create the namespace where the user will operate. user_ns is
692 # Create the namespace where the user will operate. user_ns is
693 # normally the only one used, and it is passed to the exec calls as
693 # normally the only one used, and it is passed to the exec calls as
694 # the locals argument. But we do carry a user_global_ns namespace
694 # the locals argument. But we do carry a user_global_ns namespace
695 # given as the exec 'globals' argument, This is useful in embedding
695 # given as the exec 'globals' argument, This is useful in embedding
696 # situations where the ipython shell opens in a context where the
696 # situations where the ipython shell opens in a context where the
697 # distinction between locals and globals is meaningful. For
697 # distinction between locals and globals is meaningful. For
698 # non-embedded contexts, it is just the same object as the user_ns dict.
698 # non-embedded contexts, it is just the same object as the user_ns dict.
699
699
700 # FIXME. For some strange reason, __builtins__ is showing up at user
700 # FIXME. For some strange reason, __builtins__ is showing up at user
701 # level as a dict instead of a module. This is a manual fix, but I
701 # level as a dict instead of a module. This is a manual fix, but I
702 # should really track down where the problem is coming from. Alex
702 # should really track down where the problem is coming from. Alex
703 # Schmolck reported this problem first.
703 # Schmolck reported this problem first.
704
704
705 # A useful post by Alex Martelli on this topic:
705 # A useful post by Alex Martelli on this topic:
706 # Re: inconsistent value from __builtins__
706 # Re: inconsistent value from __builtins__
707 # Von: Alex Martelli <aleaxit@yahoo.com>
707 # Von: Alex Martelli <aleaxit@yahoo.com>
708 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
708 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
709 # Gruppen: comp.lang.python
709 # Gruppen: comp.lang.python
710
710
711 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
711 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
712 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
712 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
713 # > <type 'dict'>
713 # > <type 'dict'>
714 # > >>> print type(__builtins__)
714 # > >>> print type(__builtins__)
715 # > <type 'module'>
715 # > <type 'module'>
716 # > Is this difference in return value intentional?
716 # > Is this difference in return value intentional?
717
717
718 # Well, it's documented that '__builtins__' can be either a dictionary
718 # Well, it's documented that '__builtins__' can be either a dictionary
719 # or a module, and it's been that way for a long time. Whether it's
719 # or a module, and it's been that way for a long time. Whether it's
720 # intentional (or sensible), I don't know. In any case, the idea is
720 # intentional (or sensible), I don't know. In any case, the idea is
721 # that if you need to access the built-in namespace directly, you
721 # that if you need to access the built-in namespace directly, you
722 # should start with "import __builtin__" (note, no 's') which will
722 # should start with "import __builtin__" (note, no 's') which will
723 # definitely give you a module. Yeah, it's somewhat confusing:-(.
723 # definitely give you a module. Yeah, it's somewhat confusing:-(.
724
724
725 # These routines return properly built dicts as needed by the rest of
725 # These routines return properly built dicts as needed by the rest of
726 # the code, and can also be used by extension writers to generate
726 # the code, and can also be used by extension writers to generate
727 # properly initialized namespaces.
727 # properly initialized namespaces.
728 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
728 user_ns, user_global_ns = self.make_user_namespaces(user_ns, user_global_ns)
729
729
730 # Assign namespaces
730 # Assign namespaces
731 # This is the namespace where all normal user variables live
731 # This is the namespace where all normal user variables live
732 self.user_ns = user_ns
732 self.user_ns = user_ns
733 self.user_global_ns = user_global_ns
733 self.user_global_ns = user_global_ns
734
734
735 # An auxiliary namespace that checks what parts of the user_ns were
735 # An auxiliary namespace that checks what parts of the user_ns were
736 # loaded at startup, so we can list later only variables defined in
736 # loaded at startup, so we can list later only variables defined in
737 # actual interactive use. Since it is always a subset of user_ns, it
737 # actual interactive use. Since it is always a subset of user_ns, it
738 # doesn't need to be separately tracked in the ns_table.
738 # doesn't need to be separately tracked in the ns_table.
739 self.user_ns_hidden = {}
739 self.user_ns_hidden = {}
740
740
741 # A namespace to keep track of internal data structures to prevent
741 # A namespace to keep track of internal data structures to prevent
742 # them from cluttering user-visible stuff. Will be updated later
742 # them from cluttering user-visible stuff. Will be updated later
743 self.internal_ns = {}
743 self.internal_ns = {}
744
744
745 # Now that FakeModule produces a real module, we've run into a nasty
745 # Now that FakeModule produces a real module, we've run into a nasty
746 # problem: after script execution (via %run), the module where the user
746 # problem: after script execution (via %run), the module where the user
747 # code ran is deleted. Now that this object is a true module (needed
747 # code ran is deleted. Now that this object is a true module (needed
748 # so docetst and other tools work correctly), the Python module
748 # so docetst and other tools work correctly), the Python module
749 # teardown mechanism runs over it, and sets to None every variable
749 # teardown mechanism runs over it, and sets to None every variable
750 # present in that module. Top-level references to objects from the
750 # present in that module. Top-level references to objects from the
751 # script survive, because the user_ns is updated with them. However,
751 # script survive, because the user_ns is updated with them. However,
752 # calling functions defined in the script that use other things from
752 # calling functions defined in the script that use other things from
753 # the script will fail, because the function's closure had references
753 # the script will fail, because the function's closure had references
754 # to the original objects, which are now all None. So we must protect
754 # to the original objects, which are now all None. So we must protect
755 # these modules from deletion by keeping a cache.
755 # these modules from deletion by keeping a cache.
756 #
756 #
757 # To avoid keeping stale modules around (we only need the one from the
757 # To avoid keeping stale modules around (we only need the one from the
758 # last run), we use a dict keyed with the full path to the script, so
758 # last run), we use a dict keyed with the full path to the script, so
759 # only the last version of the module is held in the cache. Note,
759 # only the last version of the module is held in the cache. Note,
760 # however, that we must cache the module *namespace contents* (their
760 # however, that we must cache the module *namespace contents* (their
761 # __dict__). Because if we try to cache the actual modules, old ones
761 # __dict__). Because if we try to cache the actual modules, old ones
762 # (uncached) could be destroyed while still holding references (such as
762 # (uncached) could be destroyed while still holding references (such as
763 # those held by GUI objects that tend to be long-lived)>
763 # those held by GUI objects that tend to be long-lived)>
764 #
764 #
765 # The %reset command will flush this cache. See the cache_main_mod()
765 # The %reset command will flush this cache. See the cache_main_mod()
766 # and clear_main_mod_cache() methods for details on use.
766 # and clear_main_mod_cache() methods for details on use.
767
767
768 # This is the cache used for 'main' namespaces
768 # This is the cache used for 'main' namespaces
769 self._main_ns_cache = {}
769 self._main_ns_cache = {}
770 # And this is the single instance of FakeModule whose __dict__ we keep
770 # And this is the single instance of FakeModule whose __dict__ we keep
771 # copying and clearing for reuse on each %run
771 # copying and clearing for reuse on each %run
772 self._user_main_module = FakeModule()
772 self._user_main_module = FakeModule()
773
773
774 # A table holding all the namespaces IPython deals with, so that
774 # A table holding all the namespaces IPython deals with, so that
775 # introspection facilities can search easily.
775 # introspection facilities can search easily.
776 self.ns_table = {'user':user_ns,
776 self.ns_table = {'user':user_ns,
777 'user_global':user_global_ns,
777 'user_global':user_global_ns,
778 'internal':self.internal_ns,
778 'internal':self.internal_ns,
779 'builtin':__builtin__.__dict__
779 'builtin':__builtin__.__dict__
780 }
780 }
781
781
782 # Similarly, track all namespaces where references can be held and that
782 # Similarly, track all namespaces where references can be held and that
783 # we can safely clear (so it can NOT include builtin). This one can be
783 # we can safely clear (so it can NOT include builtin). This one can be
784 # a simple list.
784 # a simple list.
785 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
785 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
786 self.internal_ns, self._main_ns_cache ]
786 self.internal_ns, self._main_ns_cache ]
787
787
788 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
788 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
789 """Return a valid local and global user interactive namespaces.
789 """Return a valid local and global user interactive namespaces.
790
790
791 This builds a dict with the minimal information needed to operate as a
791 This builds a dict with the minimal information needed to operate as a
792 valid IPython user namespace, which you can pass to the various
792 valid IPython user namespace, which you can pass to the various
793 embedding classes in ipython. The default implementation returns the
793 embedding classes in ipython. The default implementation returns the
794 same dict for both the locals and the globals to allow functions to
794 same dict for both the locals and the globals to allow functions to
795 refer to variables in the namespace. Customized implementations can
795 refer to variables in the namespace. Customized implementations can
796 return different dicts. The locals dictionary can actually be anything
796 return different dicts. The locals dictionary can actually be anything
797 following the basic mapping protocol of a dict, but the globals dict
797 following the basic mapping protocol of a dict, but the globals dict
798 must be a true dict, not even a subclass. It is recommended that any
798 must be a true dict, not even a subclass. It is recommended that any
799 custom object for the locals namespace synchronize with the globals
799 custom object for the locals namespace synchronize with the globals
800 dict somehow.
800 dict somehow.
801
801
802 Raises TypeError if the provided globals namespace is not a true dict.
802 Raises TypeError if the provided globals namespace is not a true dict.
803
803
804 Parameters
804 Parameters
805 ----------
805 ----------
806 user_ns : dict-like, optional
806 user_ns : dict-like, optional
807 The current user namespace. The items in this namespace should
807 The current user namespace. The items in this namespace should
808 be included in the output. If None, an appropriate blank
808 be included in the output. If None, an appropriate blank
809 namespace should be created.
809 namespace should be created.
810 user_global_ns : dict, optional
810 user_global_ns : dict, optional
811 The current user global namespace. The items in this namespace
811 The current user global namespace. The items in this namespace
812 should be included in the output. If None, an appropriate
812 should be included in the output. If None, an appropriate
813 blank namespace should be created.
813 blank namespace should be created.
814
814
815 Returns
815 Returns
816 -------
816 -------
817 A pair of dictionary-like object to be used as the local namespace
817 A pair of dictionary-like object to be used as the local namespace
818 of the interpreter and a dict to be used as the global namespace.
818 of the interpreter and a dict to be used as the global namespace.
819 """
819 """
820
820
821
821
822 # We must ensure that __builtin__ (without the final 's') is always
822 # We must ensure that __builtin__ (without the final 's') is always
823 # available and pointing to the __builtin__ *module*. For more details:
823 # available and pointing to the __builtin__ *module*. For more details:
824 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
824 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
825
825
826 if user_ns is None:
826 if user_ns is None:
827 # Set __name__ to __main__ to better match the behavior of the
827 # Set __name__ to __main__ to better match the behavior of the
828 # normal interpreter.
828 # normal interpreter.
829 user_ns = {'__name__' :'__main__',
829 user_ns = {'__name__' :'__main__',
830 '__builtin__' : __builtin__,
830 '__builtin__' : __builtin__,
831 '__builtins__' : __builtin__,
831 '__builtins__' : __builtin__,
832 }
832 }
833 else:
833 else:
834 user_ns.setdefault('__name__','__main__')
834 user_ns.setdefault('__name__','__main__')
835 user_ns.setdefault('__builtin__',__builtin__)
835 user_ns.setdefault('__builtin__',__builtin__)
836 user_ns.setdefault('__builtins__',__builtin__)
836 user_ns.setdefault('__builtins__',__builtin__)
837
837
838 if user_global_ns is None:
838 if user_global_ns is None:
839 user_global_ns = user_ns
839 user_global_ns = user_ns
840 if type(user_global_ns) is not dict:
840 if type(user_global_ns) is not dict:
841 raise TypeError("user_global_ns must be a true dict; got %r"
841 raise TypeError("user_global_ns must be a true dict; got %r"
842 % type(user_global_ns))
842 % type(user_global_ns))
843
843
844 return user_ns, user_global_ns
844 return user_ns, user_global_ns
845
845
846 def init_sys_modules(self):
846 def init_sys_modules(self):
847 # We need to insert into sys.modules something that looks like a
847 # We need to insert into sys.modules something that looks like a
848 # module but which accesses the IPython namespace, for shelve and
848 # module but which accesses the IPython namespace, for shelve and
849 # pickle to work interactively. Normally they rely on getting
849 # pickle to work interactively. Normally they rely on getting
850 # everything out of __main__, but for embedding purposes each IPython
850 # everything out of __main__, but for embedding purposes each IPython
851 # instance has its own private namespace, so we can't go shoving
851 # instance has its own private namespace, so we can't go shoving
852 # everything into __main__.
852 # everything into __main__.
853
853
854 # note, however, that we should only do this for non-embedded
854 # note, however, that we should only do this for non-embedded
855 # ipythons, which really mimic the __main__.__dict__ with their own
855 # ipythons, which really mimic the __main__.__dict__ with their own
856 # namespace. Embedded instances, on the other hand, should not do
856 # namespace. Embedded instances, on the other hand, should not do
857 # this because they need to manage the user local/global namespaces
857 # this because they need to manage the user local/global namespaces
858 # only, but they live within a 'normal' __main__ (meaning, they
858 # only, but they live within a 'normal' __main__ (meaning, they
859 # shouldn't overtake the execution environment of the script they're
859 # shouldn't overtake the execution environment of the script they're
860 # embedded in).
860 # embedded in).
861
861
862 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
862 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
863
863
864 try:
864 try:
865 main_name = self.user_ns['__name__']
865 main_name = self.user_ns['__name__']
866 except KeyError:
866 except KeyError:
867 raise KeyError('user_ns dictionary MUST have a "__name__" key')
867 raise KeyError('user_ns dictionary MUST have a "__name__" key')
868 else:
868 else:
869 sys.modules[main_name] = FakeModule(self.user_ns)
869 sys.modules[main_name] = FakeModule(self.user_ns)
870
870
871 def init_user_ns(self):
871 def init_user_ns(self):
872 """Initialize all user-visible namespaces to their minimum defaults.
872 """Initialize all user-visible namespaces to their minimum defaults.
873
873
874 Certain history lists are also initialized here, as they effectively
874 Certain history lists are also initialized here, as they effectively
875 act as user namespaces.
875 act as user namespaces.
876
876
877 Notes
877 Notes
878 -----
878 -----
879 All data structures here are only filled in, they are NOT reset by this
879 All data structures here are only filled in, they are NOT reset by this
880 method. If they were not empty before, data will simply be added to
880 method. If they were not empty before, data will simply be added to
881 therm.
881 therm.
882 """
882 """
883 # This function works in two parts: first we put a few things in
883 # This function works in two parts: first we put a few things in
884 # user_ns, and we sync that contents into user_ns_hidden so that these
884 # user_ns, and we sync that contents into user_ns_hidden so that these
885 # initial variables aren't shown by %who. After the sync, we add the
885 # initial variables aren't shown by %who. After the sync, we add the
886 # rest of what we *do* want the user to see with %who even on a new
886 # rest of what we *do* want the user to see with %who even on a new
887 # session (probably nothing, so theye really only see their own stuff)
887 # session (probably nothing, so theye really only see their own stuff)
888
888
889 # The user dict must *always* have a __builtin__ reference to the
889 # The user dict must *always* have a __builtin__ reference to the
890 # Python standard __builtin__ namespace, which must be imported.
890 # Python standard __builtin__ namespace, which must be imported.
891 # This is so that certain operations in prompt evaluation can be
891 # This is so that certain operations in prompt evaluation can be
892 # reliably executed with builtins. Note that we can NOT use
892 # reliably executed with builtins. Note that we can NOT use
893 # __builtins__ (note the 's'), because that can either be a dict or a
893 # __builtins__ (note the 's'), because that can either be a dict or a
894 # module, and can even mutate at runtime, depending on the context
894 # module, and can even mutate at runtime, depending on the context
895 # (Python makes no guarantees on it). In contrast, __builtin__ is
895 # (Python makes no guarantees on it). In contrast, __builtin__ is
896 # always a module object, though it must be explicitly imported.
896 # always a module object, though it must be explicitly imported.
897
897
898 # For more details:
898 # For more details:
899 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
899 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
900 ns = dict(__builtin__ = __builtin__)
900 ns = dict(__builtin__ = __builtin__)
901
901
902 # Put 'help' in the user namespace
902 # Put 'help' in the user namespace
903 try:
903 try:
904 from site import _Helper
904 from site import _Helper
905 ns['help'] = _Helper()
905 ns['help'] = _Helper()
906 except ImportError:
906 except ImportError:
907 warn('help() not available - check site.py')
907 warn('help() not available - check site.py')
908
908
909 # make global variables for user access to the histories
909 # make global variables for user access to the histories
910 ns['_ih'] = self.input_hist
910 ns['_ih'] = self.input_hist
911 ns['_oh'] = self.output_hist
911 ns['_oh'] = self.output_hist
912 ns['_dh'] = self.dir_hist
912 ns['_dh'] = self.dir_hist
913
913
914 ns['_sh'] = shadowns
914 ns['_sh'] = shadowns
915
915
916 # user aliases to input and output histories. These shouldn't show up
916 # user aliases to input and output histories. These shouldn't show up
917 # in %who, as they can have very large reprs.
917 # in %who, as they can have very large reprs.
918 ns['In'] = self.input_hist
918 ns['In'] = self.input_hist
919 ns['Out'] = self.output_hist
919 ns['Out'] = self.output_hist
920
920
921 # Store myself as the public api!!!
921 # Store myself as the public api!!!
922 ns['get_ipython'] = self.get_ipython
922 ns['get_ipython'] = self.get_ipython
923
923
924 # Sync what we've added so far to user_ns_hidden so these aren't seen
924 # Sync what we've added so far to user_ns_hidden so these aren't seen
925 # by %who
925 # by %who
926 self.user_ns_hidden.update(ns)
926 self.user_ns_hidden.update(ns)
927
927
928 # Anything put into ns now would show up in %who. Think twice before
928 # Anything put into ns now would show up in %who. Think twice before
929 # putting anything here, as we really want %who to show the user their
929 # putting anything here, as we really want %who to show the user their
930 # stuff, not our variables.
930 # stuff, not our variables.
931
931
932 # Finally, update the real user's namespace
932 # Finally, update the real user's namespace
933 self.user_ns.update(ns)
933 self.user_ns.update(ns)
934
934
935
935
936 def reset(self):
936 def reset(self):
937 """Clear all internal namespaces.
937 """Clear all internal namespaces.
938
938
939 Note that this is much more aggressive than %reset, since it clears
939 Note that this is much more aggressive than %reset, since it clears
940 fully all namespaces, as well as all input/output lists.
940 fully all namespaces, as well as all input/output lists.
941 """
941 """
942 for ns in self.ns_refs_table:
942 for ns in self.ns_refs_table:
943 ns.clear()
943 ns.clear()
944
944
945 self.alias_manager.clear_aliases()
945 self.alias_manager.clear_aliases()
946
946
947 # Clear input and output histories
947 # Clear input and output histories
948 self.input_hist[:] = []
948 self.input_hist[:] = []
949 self.input_hist_raw[:] = []
949 self.input_hist_raw[:] = []
950 self.output_hist.clear()
950 self.output_hist.clear()
951
951
952 # Restore the user namespaces to minimal usability
952 # Restore the user namespaces to minimal usability
953 self.init_user_ns()
953 self.init_user_ns()
954
954
955 # Restore the default and user aliases
955 # Restore the default and user aliases
956 self.alias_manager.init_aliases()
956 self.alias_manager.init_aliases()
957
957
958 def reset_selective(self, regex=None):
958 def reset_selective(self, regex=None):
959 """Clear selective variables from internal namespaces based on a specified regular expression.
959 """Clear selective variables from internal namespaces based on a specified regular expression.
960
960
961 Parameters
961 Parameters
962 ----------
962 ----------
963 regex : string or compiled pattern, optional
963 regex : string or compiled pattern, optional
964 A regular expression pattern that will be used in searching variable names in the users
964 A regular expression pattern that will be used in searching variable names in the users
965 namespaces.
965 namespaces.
966 """
966 """
967 if regex is not None:
967 if regex is not None:
968 try:
968 try:
969 m = re.compile(regex)
969 m = re.compile(regex)
970 except TypeError:
970 except TypeError:
971 raise TypeError('regex must be a string or compiled pattern')
971 raise TypeError('regex must be a string or compiled pattern')
972 # Search for keys in each namespace that match the given regex
972 # Search for keys in each namespace that match the given regex
973 # If a match is found, delete the key/value pair.
973 # If a match is found, delete the key/value pair.
974 for ns in self.ns_refs_table:
974 for ns in self.ns_refs_table:
975 for var in ns:
975 for var in ns:
976 if m.search(var):
976 if m.search(var):
977 del ns[var]
977 del ns[var]
978
978
979 def push(self, variables, interactive=True):
979 def push(self, variables, interactive=True):
980 """Inject a group of variables into the IPython user namespace.
980 """Inject a group of variables into the IPython user namespace.
981
981
982 Parameters
982 Parameters
983 ----------
983 ----------
984 variables : dict, str or list/tuple of str
984 variables : dict, str or list/tuple of str
985 The variables to inject into the user's namespace. If a dict,
985 The variables to inject into the user's namespace. If a dict,
986 a simple update is done. If a str, the string is assumed to
986 a simple update is done. If a str, the string is assumed to
987 have variable names separated by spaces. A list/tuple of str
987 have variable names separated by spaces. A list/tuple of str
988 can also be used to give the variable names. If just the variable
988 can also be used to give the variable names. If just the variable
989 names are give (list/tuple/str) then the variable values looked
989 names are give (list/tuple/str) then the variable values looked
990 up in the callers frame.
990 up in the callers frame.
991 interactive : bool
991 interactive : bool
992 If True (default), the variables will be listed with the ``who``
992 If True (default), the variables will be listed with the ``who``
993 magic.
993 magic.
994 """
994 """
995 vdict = None
995 vdict = None
996
996
997 # We need a dict of name/value pairs to do namespace updates.
997 # We need a dict of name/value pairs to do namespace updates.
998 if isinstance(variables, dict):
998 if isinstance(variables, dict):
999 vdict = variables
999 vdict = variables
1000 elif isinstance(variables, (basestring, list, tuple)):
1000 elif isinstance(variables, (basestring, list, tuple)):
1001 if isinstance(variables, basestring):
1001 if isinstance(variables, basestring):
1002 vlist = variables.split()
1002 vlist = variables.split()
1003 else:
1003 else:
1004 vlist = variables
1004 vlist = variables
1005 vdict = {}
1005 vdict = {}
1006 cf = sys._getframe(1)
1006 cf = sys._getframe(1)
1007 for name in vlist:
1007 for name in vlist:
1008 try:
1008 try:
1009 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1009 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1010 except:
1010 except:
1011 print ('Could not get variable %s from %s' %
1011 print ('Could not get variable %s from %s' %
1012 (name,cf.f_code.co_name))
1012 (name,cf.f_code.co_name))
1013 else:
1013 else:
1014 raise ValueError('variables must be a dict/str/list/tuple')
1014 raise ValueError('variables must be a dict/str/list/tuple')
1015
1015
1016 # Propagate variables to user namespace
1016 # Propagate variables to user namespace
1017 self.user_ns.update(vdict)
1017 self.user_ns.update(vdict)
1018
1018
1019 # And configure interactive visibility
1019 # And configure interactive visibility
1020 config_ns = self.user_ns_hidden
1020 config_ns = self.user_ns_hidden
1021 if interactive:
1021 if interactive:
1022 for name, val in vdict.iteritems():
1022 for name, val in vdict.iteritems():
1023 config_ns.pop(name, None)
1023 config_ns.pop(name, None)
1024 else:
1024 else:
1025 for name,val in vdict.iteritems():
1025 for name,val in vdict.iteritems():
1026 config_ns[name] = val
1026 config_ns[name] = val
1027
1027
1028 #-------------------------------------------------------------------------
1028 #-------------------------------------------------------------------------
1029 # Things related to history management
1029 # Things related to history management
1030 #-------------------------------------------------------------------------
1030 #-------------------------------------------------------------------------
1031
1031
1032 def init_history(self):
1032 def init_history(self):
1033 # List of input with multi-line handling.
1033 # List of input with multi-line handling.
1034 self.input_hist = InputList()
1034 self.input_hist = InputList()
1035 # This one will hold the 'raw' input history, without any
1035 # This one will hold the 'raw' input history, without any
1036 # pre-processing. This will allow users to retrieve the input just as
1036 # pre-processing. This will allow users to retrieve the input just as
1037 # it was exactly typed in by the user, with %hist -r.
1037 # it was exactly typed in by the user, with %hist -r.
1038 self.input_hist_raw = InputList()
1038 self.input_hist_raw = InputList()
1039
1039
1040 # list of visited directories
1040 # list of visited directories
1041 try:
1041 try:
1042 self.dir_hist = [os.getcwd()]
1042 self.dir_hist = [os.getcwd()]
1043 except OSError:
1043 except OSError:
1044 self.dir_hist = []
1044 self.dir_hist = []
1045
1045
1046 # dict of output history
1046 # dict of output history
1047 self.output_hist = {}
1047 self.output_hist = {}
1048
1048
1049 # Now the history file
1049 # Now the history file
1050 if self.profile:
1050 if self.profile:
1051 histfname = 'history-%s' % self.profile
1051 histfname = 'history-%s' % self.profile
1052 else:
1052 else:
1053 histfname = 'history'
1053 histfname = 'history'
1054 self.histfile = os.path.join(self.ipython_dir, histfname)
1054 self.histfile = os.path.join(self.ipython_dir, histfname)
1055
1055
1056 # Fill the history zero entry, user counter starts at 1
1056 # Fill the history zero entry, user counter starts at 1
1057 self.input_hist.append('\n')
1057 self.input_hist.append('\n')
1058 self.input_hist_raw.append('\n')
1058 self.input_hist_raw.append('\n')
1059
1059
1060 def init_shadow_hist(self):
1060 def init_shadow_hist(self):
1061 try:
1061 try:
1062 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1062 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1063 except exceptions.UnicodeDecodeError:
1063 except exceptions.UnicodeDecodeError:
1064 print "Your ipython_dir can't be decoded to unicode!"
1064 print "Your ipython_dir can't be decoded to unicode!"
1065 print "Please set HOME environment variable to something that"
1065 print "Please set HOME environment variable to something that"
1066 print r"only has ASCII characters, e.g. c:\home"
1066 print r"only has ASCII characters, e.g. c:\home"
1067 print "Now it is", self.ipython_dir
1067 print "Now it is", self.ipython_dir
1068 sys.exit()
1068 sys.exit()
1069 self.shadowhist = ipcorehist.ShadowHist(self.db)
1069 self.shadowhist = ipcorehist.ShadowHist(self.db)
1070
1070
1071 def savehist(self):
1071 def savehist(self):
1072 """Save input history to a file (via readline library)."""
1072 """Save input history to a file (via readline library)."""
1073
1073
1074 try:
1074 try:
1075 self.readline.write_history_file(self.histfile)
1075 self.readline.write_history_file(self.histfile)
1076 except:
1076 except:
1077 print 'Unable to save IPython command history to file: ' + \
1077 print 'Unable to save IPython command history to file: ' + \
1078 `self.histfile`
1078 `self.histfile`
1079
1079
1080 def reloadhist(self):
1080 def reloadhist(self):
1081 """Reload the input history from disk file."""
1081 """Reload the input history from disk file."""
1082
1082
1083 try:
1083 try:
1084 self.readline.clear_history()
1084 self.readline.clear_history()
1085 self.readline.read_history_file(self.shell.histfile)
1085 self.readline.read_history_file(self.shell.histfile)
1086 except AttributeError:
1086 except AttributeError:
1087 pass
1087 pass
1088
1088
1089 def history_saving_wrapper(self, func):
1089 def history_saving_wrapper(self, func):
1090 """ Wrap func for readline history saving
1090 """ Wrap func for readline history saving
1091
1091
1092 Convert func into callable that saves & restores
1092 Convert func into callable that saves & restores
1093 history around the call """
1093 history around the call """
1094
1094
1095 if self.has_readline:
1095 if self.has_readline:
1096 from IPython.utils import rlineimpl as readline
1096 from IPython.utils import rlineimpl as readline
1097 else:
1097 else:
1098 return func
1098 return func
1099
1099
1100 def wrapper():
1100 def wrapper():
1101 self.savehist()
1101 self.savehist()
1102 try:
1102 try:
1103 func()
1103 func()
1104 finally:
1104 finally:
1105 readline.read_history_file(self.histfile)
1105 readline.read_history_file(self.histfile)
1106 return wrapper
1106 return wrapper
1107
1107
1108 def get_history(self, index=None, raw=False, output=True):
1108 def get_history(self, index=None, raw=False, output=True):
1109 """Get the history list.
1109 """Get the history list.
1110
1110
1111 Get the input and output history.
1111 Get the input and output history.
1112
1112
1113 Parameters
1113 Parameters
1114 ----------
1114 ----------
1115 index : n or (n1, n2) or None
1115 index : n or (n1, n2) or None
1116 If n, then the last entries. If a tuple, then all in
1116 If n, then the last entries. If a tuple, then all in
1117 range(n1, n2). If None, then all entries. Raises IndexError if
1117 range(n1, n2). If None, then all entries. Raises IndexError if
1118 the format of index is incorrect.
1118 the format of index is incorrect.
1119 raw : bool
1119 raw : bool
1120 If True, return the raw input.
1120 If True, return the raw input.
1121 output : bool
1121 output : bool
1122 If True, then return the output as well.
1122 If True, then return the output as well.
1123
1123
1124 Returns
1124 Returns
1125 -------
1125 -------
1126 If output is True, then return a dict of tuples, keyed by the prompt
1126 If output is True, then return a dict of tuples, keyed by the prompt
1127 numbers and with values of (input, output). If output is False, then
1127 numbers and with values of (input, output). If output is False, then
1128 a dict, keyed by the prompt number with the values of input. Raises
1128 a dict, keyed by the prompt number with the values of input. Raises
1129 IndexError if no history is found.
1129 IndexError if no history is found.
1130 """
1130 """
1131 if raw:
1131 if raw:
1132 input_hist = self.input_hist_raw
1132 input_hist = self.input_hist_raw
1133 else:
1133 else:
1134 input_hist = self.input_hist
1134 input_hist = self.input_hist
1135 if output:
1135 if output:
1136 output_hist = self.user_ns['Out']
1136 output_hist = self.user_ns['Out']
1137 n = len(input_hist)
1137 n = len(input_hist)
1138 if index is None:
1138 if index is None:
1139 start=0; stop=n
1139 start=0; stop=n
1140 elif isinstance(index, int):
1140 elif isinstance(index, int):
1141 start=n-index; stop=n
1141 start=n-index; stop=n
1142 elif isinstance(index, tuple) and len(index) == 2:
1142 elif isinstance(index, tuple) and len(index) == 2:
1143 start=index[0]; stop=index[1]
1143 start=index[0]; stop=index[1]
1144 else:
1144 else:
1145 raise IndexError('Not a valid index for the input history: %r' % index)
1145 raise IndexError('Not a valid index for the input history: %r' % index)
1146 hist = {}
1146 hist = {}
1147 for i in range(start, stop):
1147 for i in range(start, stop):
1148 if output:
1148 if output:
1149 hist[i] = (input_hist[i], output_hist.get(i))
1149 hist[i] = (input_hist[i], output_hist.get(i))
1150 else:
1150 else:
1151 hist[i] = input_hist[i]
1151 hist[i] = input_hist[i]
1152 if len(hist)==0:
1152 if len(hist)==0:
1153 raise IndexError('No history for range of indices: %r' % index)
1153 raise IndexError('No history for range of indices: %r' % index)
1154 return hist
1154 return hist
1155
1155
1156 #-------------------------------------------------------------------------
1156 #-------------------------------------------------------------------------
1157 # Things related to exception handling and tracebacks (not debugging)
1157 # Things related to exception handling and tracebacks (not debugging)
1158 #-------------------------------------------------------------------------
1158 #-------------------------------------------------------------------------
1159
1159
1160 def init_traceback_handlers(self, custom_exceptions):
1160 def init_traceback_handlers(self, custom_exceptions):
1161 # Syntax error handler.
1161 # Syntax error handler.
1162 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1162 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1163
1163
1164 # The interactive one is initialized with an offset, meaning we always
1164 # The interactive one is initialized with an offset, meaning we always
1165 # want to remove the topmost item in the traceback, which is our own
1165 # want to remove the topmost item in the traceback, which is our own
1166 # internal code. Valid modes: ['Plain','Context','Verbose']
1166 # internal code. Valid modes: ['Plain','Context','Verbose']
1167 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1167 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1168 color_scheme='NoColor',
1168 color_scheme='NoColor',
1169 tb_offset = 1)
1169 tb_offset = 1)
1170
1170
1171 # The instance will store a pointer to the system-wide exception hook,
1171 # The instance will store a pointer to the system-wide exception hook,
1172 # so that runtime code (such as magics) can access it. This is because
1172 # so that runtime code (such as magics) can access it. This is because
1173 # during the read-eval loop, it may get temporarily overwritten.
1173 # during the read-eval loop, it may get temporarily overwritten.
1174 self.sys_excepthook = sys.excepthook
1174 self.sys_excepthook = sys.excepthook
1175
1175
1176 # and add any custom exception handlers the user may have specified
1176 # and add any custom exception handlers the user may have specified
1177 self.set_custom_exc(*custom_exceptions)
1177 self.set_custom_exc(*custom_exceptions)
1178
1178
1179 # Set the exception mode
1179 # Set the exception mode
1180 self.InteractiveTB.set_mode(mode=self.xmode)
1180 self.InteractiveTB.set_mode(mode=self.xmode)
1181
1181
1182 def set_custom_exc(self, exc_tuple, handler):
1182 def set_custom_exc(self, exc_tuple, handler):
1183 """set_custom_exc(exc_tuple,handler)
1183 """set_custom_exc(exc_tuple,handler)
1184
1184
1185 Set a custom exception handler, which will be called if any of the
1185 Set a custom exception handler, which will be called if any of the
1186 exceptions in exc_tuple occur in the mainloop (specifically, in the
1186 exceptions in exc_tuple occur in the mainloop (specifically, in the
1187 runcode() method.
1187 runcode() method.
1188
1188
1189 Inputs:
1189 Inputs:
1190
1190
1191 - exc_tuple: a *tuple* of valid exceptions to call the defined
1191 - exc_tuple: a *tuple* of valid exceptions to call the defined
1192 handler for. It is very important that you use a tuple, and NOT A
1192 handler for. It is very important that you use a tuple, and NOT A
1193 LIST here, because of the way Python's except statement works. If
1193 LIST here, because of the way Python's except statement works. If
1194 you only want to trap a single exception, use a singleton tuple:
1194 you only want to trap a single exception, use a singleton tuple:
1195
1195
1196 exc_tuple == (MyCustomException,)
1196 exc_tuple == (MyCustomException,)
1197
1197
1198 - handler: this must be defined as a function with the following
1198 - handler: this must be defined as a function with the following
1199 basic interface::
1199 basic interface::
1200
1200
1201 def my_handler(self, etype, value, tb, tb_offset=None)
1201 def my_handler(self, etype, value, tb, tb_offset=None)
1202 ...
1202 ...
1203 # The return value must be
1203 # The return value must be
1204 return structured_traceback
1204 return structured_traceback
1205
1205
1206 This will be made into an instance method (via new.instancemethod)
1206 This will be made into an instance method (via new.instancemethod)
1207 of IPython itself, and it will be called if any of the exceptions
1207 of IPython itself, and it will be called if any of the exceptions
1208 listed in the exc_tuple are caught. If the handler is None, an
1208 listed in the exc_tuple are caught. If the handler is None, an
1209 internal basic one is used, which just prints basic info.
1209 internal basic one is used, which just prints basic info.
1210
1210
1211 WARNING: by putting in your own exception handler into IPython's main
1211 WARNING: by putting in your own exception handler into IPython's main
1212 execution loop, you run a very good chance of nasty crashes. This
1212 execution loop, you run a very good chance of nasty crashes. This
1213 facility should only be used if you really know what you are doing."""
1213 facility should only be used if you really know what you are doing."""
1214
1214
1215 assert type(exc_tuple)==type(()) , \
1215 assert type(exc_tuple)==type(()) , \
1216 "The custom exceptions must be given AS A TUPLE."
1216 "The custom exceptions must be given AS A TUPLE."
1217
1217
1218 def dummy_handler(self,etype,value,tb):
1218 def dummy_handler(self,etype,value,tb):
1219 print '*** Simple custom exception handler ***'
1219 print '*** Simple custom exception handler ***'
1220 print 'Exception type :',etype
1220 print 'Exception type :',etype
1221 print 'Exception value:',value
1221 print 'Exception value:',value
1222 print 'Traceback :',tb
1222 print 'Traceback :',tb
1223 print 'Source code :','\n'.join(self.buffer)
1223 print 'Source code :','\n'.join(self.buffer)
1224
1224
1225 if handler is None: handler = dummy_handler
1225 if handler is None: handler = dummy_handler
1226
1226
1227 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1227 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1228 self.custom_exceptions = exc_tuple
1228 self.custom_exceptions = exc_tuple
1229
1229
1230 def excepthook(self, etype, value, tb):
1230 def excepthook(self, etype, value, tb):
1231 """One more defense for GUI apps that call sys.excepthook.
1231 """One more defense for GUI apps that call sys.excepthook.
1232
1232
1233 GUI frameworks like wxPython trap exceptions and call
1233 GUI frameworks like wxPython trap exceptions and call
1234 sys.excepthook themselves. I guess this is a feature that
1234 sys.excepthook themselves. I guess this is a feature that
1235 enables them to keep running after exceptions that would
1235 enables them to keep running after exceptions that would
1236 otherwise kill their mainloop. This is a bother for IPython
1236 otherwise kill their mainloop. This is a bother for IPython
1237 which excepts to catch all of the program exceptions with a try:
1237 which excepts to catch all of the program exceptions with a try:
1238 except: statement.
1238 except: statement.
1239
1239
1240 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1240 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1241 any app directly invokes sys.excepthook, it will look to the user like
1241 any app directly invokes sys.excepthook, it will look to the user like
1242 IPython crashed. In order to work around this, we can disable the
1242 IPython crashed. In order to work around this, we can disable the
1243 CrashHandler and replace it with this excepthook instead, which prints a
1243 CrashHandler and replace it with this excepthook instead, which prints a
1244 regular traceback using our InteractiveTB. In this fashion, apps which
1244 regular traceback using our InteractiveTB. In this fashion, apps which
1245 call sys.excepthook will generate a regular-looking exception from
1245 call sys.excepthook will generate a regular-looking exception from
1246 IPython, and the CrashHandler will only be triggered by real IPython
1246 IPython, and the CrashHandler will only be triggered by real IPython
1247 crashes.
1247 crashes.
1248
1248
1249 This hook should be used sparingly, only in places which are not likely
1249 This hook should be used sparingly, only in places which are not likely
1250 to be true IPython errors.
1250 to be true IPython errors.
1251 """
1251 """
1252 self.showtraceback((etype,value,tb),tb_offset=0)
1252 self.showtraceback((etype,value,tb),tb_offset=0)
1253
1253
1254 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1254 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1255 exception_only=False):
1255 exception_only=False):
1256 """Display the exception that just occurred.
1256 """Display the exception that just occurred.
1257
1257
1258 If nothing is known about the exception, this is the method which
1258 If nothing is known about the exception, this is the method which
1259 should be used throughout the code for presenting user tracebacks,
1259 should be used throughout the code for presenting user tracebacks,
1260 rather than directly invoking the InteractiveTB object.
1260 rather than directly invoking the InteractiveTB object.
1261
1261
1262 A specific showsyntaxerror() also exists, but this method can take
1262 A specific showsyntaxerror() also exists, but this method can take
1263 care of calling it if needed, so unless you are explicitly catching a
1263 care of calling it if needed, so unless you are explicitly catching a
1264 SyntaxError exception, don't try to analyze the stack manually and
1264 SyntaxError exception, don't try to analyze the stack manually and
1265 simply call this method."""
1265 simply call this method."""
1266
1266
1267 try:
1267 try:
1268 if exc_tuple is None:
1268 if exc_tuple is None:
1269 etype, value, tb = sys.exc_info()
1269 etype, value, tb = sys.exc_info()
1270 else:
1270 else:
1271 etype, value, tb = exc_tuple
1271 etype, value, tb = exc_tuple
1272
1272
1273 if etype is None:
1273 if etype is None:
1274 if hasattr(sys, 'last_type'):
1274 if hasattr(sys, 'last_type'):
1275 etype, value, tb = sys.last_type, sys.last_value, \
1275 etype, value, tb = sys.last_type, sys.last_value, \
1276 sys.last_traceback
1276 sys.last_traceback
1277 else:
1277 else:
1278 self.write_err('No traceback available to show.\n')
1278 self.write_err('No traceback available to show.\n')
1279 return
1279 return
1280
1280
1281 if etype is SyntaxError:
1281 if etype is SyntaxError:
1282 # Though this won't be called by syntax errors in the input
1282 # Though this won't be called by syntax errors in the input
1283 # line, there may be SyntaxError cases whith imported code.
1283 # line, there may be SyntaxError cases whith imported code.
1284 self.showsyntaxerror(filename)
1284 self.showsyntaxerror(filename)
1285 elif etype is UsageError:
1285 elif etype is UsageError:
1286 print "UsageError:", value
1286 print "UsageError:", value
1287 else:
1287 else:
1288 # WARNING: these variables are somewhat deprecated and not
1288 # WARNING: these variables are somewhat deprecated and not
1289 # necessarily safe to use in a threaded environment, but tools
1289 # necessarily safe to use in a threaded environment, but tools
1290 # like pdb depend on their existence, so let's set them. If we
1290 # like pdb depend on their existence, so let's set them. If we
1291 # find problems in the field, we'll need to revisit their use.
1291 # find problems in the field, we'll need to revisit their use.
1292 sys.last_type = etype
1292 sys.last_type = etype
1293 sys.last_value = value
1293 sys.last_value = value
1294 sys.last_traceback = tb
1294 sys.last_traceback = tb
1295
1295
1296 if etype in self.custom_exceptions:
1296 if etype in self.custom_exceptions:
1297 # FIXME: Old custom traceback objects may just return a
1297 # FIXME: Old custom traceback objects may just return a
1298 # string, in that case we just put it into a list
1298 # string, in that case we just put it into a list
1299 stb = self.CustomTB(etype, value, tb, tb_offset)
1299 stb = self.CustomTB(etype, value, tb, tb_offset)
1300 if isinstance(ctb, basestring):
1300 if isinstance(ctb, basestring):
1301 stb = [stb]
1301 stb = [stb]
1302 else:
1302 else:
1303 if exception_only:
1303 if exception_only:
1304 stb = ['An exception has occurred, use %tb to see '
1304 stb = ['An exception has occurred, use %tb to see '
1305 'the full traceback.\n']
1305 'the full traceback.\n']
1306 stb.extend(self.InteractiveTB.get_exception_only(etype,
1306 stb.extend(self.InteractiveTB.get_exception_only(etype,
1307 value))
1307 value))
1308 else:
1308 else:
1309 stb = self.InteractiveTB.structured_traceback(etype,
1309 stb = self.InteractiveTB.structured_traceback(etype,
1310 value, tb, tb_offset=tb_offset)
1310 value, tb, tb_offset=tb_offset)
1311 # FIXME: the pdb calling should be done by us, not by
1311 # FIXME: the pdb calling should be done by us, not by
1312 # the code computing the traceback.
1312 # the code computing the traceback.
1313 if self.InteractiveTB.call_pdb:
1313 if self.InteractiveTB.call_pdb:
1314 # pdb mucks up readline, fix it back
1314 # pdb mucks up readline, fix it back
1315 self.set_completer()
1315 self.set_completer()
1316
1316
1317 # Actually show the traceback
1317 # Actually show the traceback
1318 self._showtraceback(etype, value, stb)
1318 self._showtraceback(etype, value, stb)
1319
1319
1320 except KeyboardInterrupt:
1320 except KeyboardInterrupt:
1321 self.write_err("\nKeyboardInterrupt\n")
1321 self.write_err("\nKeyboardInterrupt\n")
1322
1322
1323 def _showtraceback(self, etype, evalue, stb):
1323 def _showtraceback(self, etype, evalue, stb):
1324 """Actually show a traceback.
1324 """Actually show a traceback.
1325
1325
1326 Subclasses may override this method to put the traceback on a different
1326 Subclasses may override this method to put the traceback on a different
1327 place, like a side channel.
1327 place, like a side channel.
1328 """
1328 """
1329 # FIXME: this should use the proper write channels, but our test suite
1329 # FIXME: this should use the proper write channels, but our test suite
1330 # relies on it coming out of stdout...
1330 # relies on it coming out of stdout...
1331 print >> sys.stdout, self.InteractiveTB.stb2text(stb)
1331 print >> sys.stdout, self.InteractiveTB.stb2text(stb)
1332
1332
1333 def showsyntaxerror(self, filename=None):
1333 def showsyntaxerror(self, filename=None):
1334 """Display the syntax error that just occurred.
1334 """Display the syntax error that just occurred.
1335
1335
1336 This doesn't display a stack trace because there isn't one.
1336 This doesn't display a stack trace because there isn't one.
1337
1337
1338 If a filename is given, it is stuffed in the exception instead
1338 If a filename is given, it is stuffed in the exception instead
1339 of what was there before (because Python's parser always uses
1339 of what was there before (because Python's parser always uses
1340 "<string>" when reading from a string).
1340 "<string>" when reading from a string).
1341 """
1341 """
1342 etype, value, last_traceback = sys.exc_info()
1342 etype, value, last_traceback = sys.exc_info()
1343
1343
1344 # See note about these variables in showtraceback() above
1344 # See note about these variables in showtraceback() above
1345 sys.last_type = etype
1345 sys.last_type = etype
1346 sys.last_value = value
1346 sys.last_value = value
1347 sys.last_traceback = last_traceback
1347 sys.last_traceback = last_traceback
1348
1348
1349 if filename and etype is SyntaxError:
1349 if filename and etype is SyntaxError:
1350 # Work hard to stuff the correct filename in the exception
1350 # Work hard to stuff the correct filename in the exception
1351 try:
1351 try:
1352 msg, (dummy_filename, lineno, offset, line) = value
1352 msg, (dummy_filename, lineno, offset, line) = value
1353 except:
1353 except:
1354 # Not the format we expect; leave it alone
1354 # Not the format we expect; leave it alone
1355 pass
1355 pass
1356 else:
1356 else:
1357 # Stuff in the right filename
1357 # Stuff in the right filename
1358 try:
1358 try:
1359 # Assume SyntaxError is a class exception
1359 # Assume SyntaxError is a class exception
1360 value = SyntaxError(msg, (filename, lineno, offset, line))
1360 value = SyntaxError(msg, (filename, lineno, offset, line))
1361 except:
1361 except:
1362 # If that failed, assume SyntaxError is a string
1362 # If that failed, assume SyntaxError is a string
1363 value = msg, (filename, lineno, offset, line)
1363 value = msg, (filename, lineno, offset, line)
1364 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1364 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1365 self._showtraceback(etype, value, stb)
1365 self._showtraceback(etype, value, stb)
1366
1366
1367 #-------------------------------------------------------------------------
1367 #-------------------------------------------------------------------------
1368 # Things related to tab completion
1368 # Things related to tab completion
1369 #-------------------------------------------------------------------------
1369 #-------------------------------------------------------------------------
1370
1370
1371 def complete(self, text, line=None, cursor_pos=None):
1371 def complete(self, text, line=None, cursor_pos=None):
1372 """Return the completed text and a list of completions.
1372 """Return the completed text and a list of completions.
1373
1373
1374 Parameters
1374 Parameters
1375 ----------
1375 ----------
1376
1376
1377 text : string
1377 text : string
1378 A string of text to be completed on. It can be given as empty and
1378 A string of text to be completed on. It can be given as empty and
1379 instead a line/position pair are given. In this case, the
1379 instead a line/position pair are given. In this case, the
1380 completer itself will split the line like readline does.
1380 completer itself will split the line like readline does.
1381
1381
1382 line : string, optional
1382 line : string, optional
1383 The complete line that text is part of.
1383 The complete line that text is part of.
1384
1384
1385 cursor_pos : int, optional
1385 cursor_pos : int, optional
1386 The position of the cursor on the input line.
1386 The position of the cursor on the input line.
1387
1387
1388 Returns
1388 Returns
1389 -------
1389 -------
1390 text : string
1390 text : string
1391 The actual text that was completed.
1391 The actual text that was completed.
1392
1392
1393 matches : list
1393 matches : list
1394 A sorted list with all possible completions.
1394 A sorted list with all possible completions.
1395
1395
1396 The optional arguments allow the completion to take more context into
1396 The optional arguments allow the completion to take more context into
1397 account, and are part of the low-level completion API.
1397 account, and are part of the low-level completion API.
1398
1398
1399 This is a wrapper around the completion mechanism, similar to what
1399 This is a wrapper around the completion mechanism, similar to what
1400 readline does at the command line when the TAB key is hit. By
1400 readline does at the command line when the TAB key is hit. By
1401 exposing it as a method, it can be used by other non-readline
1401 exposing it as a method, it can be used by other non-readline
1402 environments (such as GUIs) for text completion.
1402 environments (such as GUIs) for text completion.
1403
1403
1404 Simple usage example:
1404 Simple usage example:
1405
1405
1406 In [1]: x = 'hello'
1406 In [1]: x = 'hello'
1407
1407
1408 In [2]: _ip.complete('x.l')
1408 In [2]: _ip.complete('x.l')
1409 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1409 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1410 """
1410 """
1411
1411
1412 # Inject names into __builtin__ so we can complete on the added names.
1412 # Inject names into __builtin__ so we can complete on the added names.
1413 with self.builtin_trap:
1413 with self.builtin_trap:
1414 return self.Completer.complete(text, line, cursor_pos)
1414 return self.Completer.complete(text, line, cursor_pos)
1415
1415
1416 def set_custom_completer(self, completer, pos=0):
1416 def set_custom_completer(self, completer, pos=0):
1417 """Adds a new custom completer function.
1417 """Adds a new custom completer function.
1418
1418
1419 The position argument (defaults to 0) is the index in the completers
1419 The position argument (defaults to 0) is the index in the completers
1420 list where you want the completer to be inserted."""
1420 list where you want the completer to be inserted."""
1421
1421
1422 newcomp = new.instancemethod(completer,self.Completer,
1422 newcomp = new.instancemethod(completer,self.Completer,
1423 self.Completer.__class__)
1423 self.Completer.__class__)
1424 self.Completer.matchers.insert(pos,newcomp)
1424 self.Completer.matchers.insert(pos,newcomp)
1425
1425
1426 def set_completer(self):
1426 def set_completer(self):
1427 """Reset readline's completer to be our own."""
1427 """Reset readline's completer to be our own."""
1428 self.readline.set_completer(self.Completer.rlcomplete)
1428 self.readline.set_completer(self.Completer.rlcomplete)
1429
1429
1430 def set_completer_frame(self, frame=None):
1430 def set_completer_frame(self, frame=None):
1431 """Set the frame of the completer."""
1431 """Set the frame of the completer."""
1432 if frame:
1432 if frame:
1433 self.Completer.namespace = frame.f_locals
1433 self.Completer.namespace = frame.f_locals
1434 self.Completer.global_namespace = frame.f_globals
1434 self.Completer.global_namespace = frame.f_globals
1435 else:
1435 else:
1436 self.Completer.namespace = self.user_ns
1436 self.Completer.namespace = self.user_ns
1437 self.Completer.global_namespace = self.user_global_ns
1437 self.Completer.global_namespace = self.user_global_ns
1438
1438
1439 #-------------------------------------------------------------------------
1439 #-------------------------------------------------------------------------
1440 # Things related to readline
1440 # Things related to readline
1441 #-------------------------------------------------------------------------
1441 #-------------------------------------------------------------------------
1442
1442
1443 def init_readline(self):
1443 def init_readline(self):
1444 """Command history completion/saving/reloading."""
1444 """Command history completion/saving/reloading."""
1445
1445
1446 if self.readline_use:
1446 if self.readline_use:
1447 import IPython.utils.rlineimpl as readline
1447 import IPython.utils.rlineimpl as readline
1448
1448
1449 self.rl_next_input = None
1449 self.rl_next_input = None
1450 self.rl_do_indent = False
1450 self.rl_do_indent = False
1451
1451
1452 if not self.readline_use or not readline.have_readline:
1452 if not self.readline_use or not readline.have_readline:
1453 self.has_readline = False
1453 self.has_readline = False
1454 self.readline = None
1454 self.readline = None
1455 # Set a number of methods that depend on readline to be no-op
1455 # Set a number of methods that depend on readline to be no-op
1456 self.savehist = no_op
1456 self.savehist = no_op
1457 self.reloadhist = no_op
1457 self.reloadhist = no_op
1458 self.set_completer = no_op
1458 self.set_completer = no_op
1459 self.set_custom_completer = no_op
1459 self.set_custom_completer = no_op
1460 self.set_completer_frame = no_op
1460 self.set_completer_frame = no_op
1461 warn('Readline services not available or not loaded.')
1461 warn('Readline services not available or not loaded.')
1462 else:
1462 else:
1463 self.has_readline = True
1463 self.has_readline = True
1464 self.readline = readline
1464 self.readline = readline
1465 sys.modules['readline'] = readline
1465 sys.modules['readline'] = readline
1466 import atexit
1466 import atexit
1467 from IPython.core.completer import IPCompleter
1467 from IPython.core.completer import IPCompleter
1468 self.Completer = IPCompleter(self,
1468 self.Completer = IPCompleter(self,
1469 self.user_ns,
1469 self.user_ns,
1470 self.user_global_ns,
1470 self.user_global_ns,
1471 self.readline_omit__names,
1471 self.readline_omit__names,
1472 self.alias_manager.alias_table)
1472 self.alias_manager.alias_table)
1473 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1473 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1474 self.strdispatchers['complete_command'] = sdisp
1474 self.strdispatchers['complete_command'] = sdisp
1475 self.Completer.custom_completers = sdisp
1475 self.Completer.custom_completers = sdisp
1476 # Platform-specific configuration
1476 # Platform-specific configuration
1477 if os.name == 'nt':
1477 if os.name == 'nt':
1478 self.readline_startup_hook = readline.set_pre_input_hook
1478 self.readline_startup_hook = readline.set_pre_input_hook
1479 else:
1479 else:
1480 self.readline_startup_hook = readline.set_startup_hook
1480 self.readline_startup_hook = readline.set_startup_hook
1481
1481
1482 # Load user's initrc file (readline config)
1482 # Load user's initrc file (readline config)
1483 # Or if libedit is used, load editrc.
1483 # Or if libedit is used, load editrc.
1484 inputrc_name = os.environ.get('INPUTRC')
1484 inputrc_name = os.environ.get('INPUTRC')
1485 if inputrc_name is None:
1485 if inputrc_name is None:
1486 home_dir = get_home_dir()
1486 home_dir = get_home_dir()
1487 if home_dir is not None:
1487 if home_dir is not None:
1488 inputrc_name = '.inputrc'
1488 inputrc_name = '.inputrc'
1489 if readline.uses_libedit:
1489 if readline.uses_libedit:
1490 inputrc_name = '.editrc'
1490 inputrc_name = '.editrc'
1491 inputrc_name = os.path.join(home_dir, inputrc_name)
1491 inputrc_name = os.path.join(home_dir, inputrc_name)
1492 if os.path.isfile(inputrc_name):
1492 if os.path.isfile(inputrc_name):
1493 try:
1493 try:
1494 readline.read_init_file(inputrc_name)
1494 readline.read_init_file(inputrc_name)
1495 except:
1495 except:
1496 warn('Problems reading readline initialization file <%s>'
1496 warn('Problems reading readline initialization file <%s>'
1497 % inputrc_name)
1497 % inputrc_name)
1498
1498
1499 # save this in sys so embedded copies can restore it properly
1499 # save this in sys so embedded copies can restore it properly
1500 sys.ipcompleter = self.Completer.rlcomplete
1500 sys.ipcompleter = self.Completer.rlcomplete
1501 self.set_completer()
1501 self.set_completer()
1502
1502
1503 # Configure readline according to user's prefs
1503 # Configure readline according to user's prefs
1504 # This is only done if GNU readline is being used. If libedit
1504 # This is only done if GNU readline is being used. If libedit
1505 # is being used (as on Leopard) the readline config is
1505 # is being used (as on Leopard) the readline config is
1506 # not run as the syntax for libedit is different.
1506 # not run as the syntax for libedit is different.
1507 if not readline.uses_libedit:
1507 if not readline.uses_libedit:
1508 for rlcommand in self.readline_parse_and_bind:
1508 for rlcommand in self.readline_parse_and_bind:
1509 #print "loading rl:",rlcommand # dbg
1509 #print "loading rl:",rlcommand # dbg
1510 readline.parse_and_bind(rlcommand)
1510 readline.parse_and_bind(rlcommand)
1511
1511
1512 # Remove some chars from the delimiters list. If we encounter
1512 # Remove some chars from the delimiters list. If we encounter
1513 # unicode chars, discard them.
1513 # unicode chars, discard them.
1514 delims = readline.get_completer_delims().encode("ascii", "ignore")
1514 delims = readline.get_completer_delims().encode("ascii", "ignore")
1515 delims = delims.translate(string._idmap,
1515 delims = delims.translate(string._idmap,
1516 self.readline_remove_delims)
1516 self.readline_remove_delims)
1517 readline.set_completer_delims(delims)
1517 readline.set_completer_delims(delims)
1518 # otherwise we end up with a monster history after a while:
1518 # otherwise we end up with a monster history after a while:
1519 readline.set_history_length(1000)
1519 readline.set_history_length(1000)
1520 try:
1520 try:
1521 #print '*** Reading readline history' # dbg
1521 #print '*** Reading readline history' # dbg
1522 readline.read_history_file(self.histfile)
1522 readline.read_history_file(self.histfile)
1523 except IOError:
1523 except IOError:
1524 pass # It doesn't exist yet.
1524 pass # It doesn't exist yet.
1525
1525
1526 atexit.register(self.atexit_operations)
1526 atexit.register(self.atexit_operations)
1527 del atexit
1527 del atexit
1528
1528
1529 # Configure auto-indent for all platforms
1529 # Configure auto-indent for all platforms
1530 self.set_autoindent(self.autoindent)
1530 self.set_autoindent(self.autoindent)
1531
1531
1532 def set_next_input(self, s):
1532 def set_next_input(self, s):
1533 """ Sets the 'default' input string for the next command line.
1533 """ Sets the 'default' input string for the next command line.
1534
1534
1535 Requires readline.
1535 Requires readline.
1536
1536
1537 Example:
1537 Example:
1538
1538
1539 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1539 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1540 [D:\ipython]|2> Hello Word_ # cursor is here
1540 [D:\ipython]|2> Hello Word_ # cursor is here
1541 """
1541 """
1542
1542
1543 self.rl_next_input = s
1543 self.rl_next_input = s
1544
1544
1545 # Maybe move this to the terminal subclass?
1545 # Maybe move this to the terminal subclass?
1546 def pre_readline(self):
1546 def pre_readline(self):
1547 """readline hook to be used at the start of each line.
1547 """readline hook to be used at the start of each line.
1548
1548
1549 Currently it handles auto-indent only."""
1549 Currently it handles auto-indent only."""
1550
1550
1551 if self.rl_do_indent:
1551 if self.rl_do_indent:
1552 self.readline.insert_text(self._indent_current_str())
1552 self.readline.insert_text(self._indent_current_str())
1553 if self.rl_next_input is not None:
1553 if self.rl_next_input is not None:
1554 self.readline.insert_text(self.rl_next_input)
1554 self.readline.insert_text(self.rl_next_input)
1555 self.rl_next_input = None
1555 self.rl_next_input = None
1556
1556
1557 def _indent_current_str(self):
1557 def _indent_current_str(self):
1558 """return the current level of indentation as a string"""
1558 """return the current level of indentation as a string"""
1559 return self.indent_current_nsp * ' '
1559 return self.indent_current_nsp * ' '
1560
1560
1561 #-------------------------------------------------------------------------
1561 #-------------------------------------------------------------------------
1562 # Things related to magics
1562 # Things related to magics
1563 #-------------------------------------------------------------------------
1563 #-------------------------------------------------------------------------
1564
1564
1565 def init_magics(self):
1565 def init_magics(self):
1566 # FIXME: Move the color initialization to the DisplayHook, which
1566 # FIXME: Move the color initialization to the DisplayHook, which
1567 # should be split into a prompt manager and displayhook. We probably
1567 # should be split into a prompt manager and displayhook. We probably
1568 # even need a centralize colors management object.
1568 # even need a centralize colors management object.
1569 self.magic_colors(self.colors)
1569 self.magic_colors(self.colors)
1570 # History was moved to a separate module
1570 # History was moved to a separate module
1571 from . import history
1571 from . import history
1572 history.init_ipython(self)
1572 history.init_ipython(self)
1573
1573
1574 def magic(self,arg_s):
1574 def magic(self,arg_s):
1575 """Call a magic function by name.
1575 """Call a magic function by name.
1576
1576
1577 Input: a string containing the name of the magic function to call and any
1577 Input: a string containing the name of the magic function to call and any
1578 additional arguments to be passed to the magic.
1578 additional arguments to be passed to the magic.
1579
1579
1580 magic('name -opt foo bar') is equivalent to typing at the ipython
1580 magic('name -opt foo bar') is equivalent to typing at the ipython
1581 prompt:
1581 prompt:
1582
1582
1583 In[1]: %name -opt foo bar
1583 In[1]: %name -opt foo bar
1584
1584
1585 To call a magic without arguments, simply use magic('name').
1585 To call a magic without arguments, simply use magic('name').
1586
1586
1587 This provides a proper Python function to call IPython's magics in any
1587 This provides a proper Python function to call IPython's magics in any
1588 valid Python code you can type at the interpreter, including loops and
1588 valid Python code you can type at the interpreter, including loops and
1589 compound statements.
1589 compound statements.
1590 """
1590 """
1591 args = arg_s.split(' ',1)
1591 args = arg_s.split(' ',1)
1592 magic_name = args[0]
1592 magic_name = args[0]
1593 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1593 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1594
1594
1595 try:
1595 try:
1596 magic_args = args[1]
1596 magic_args = args[1]
1597 except IndexError:
1597 except IndexError:
1598 magic_args = ''
1598 magic_args = ''
1599 fn = getattr(self,'magic_'+magic_name,None)
1599 fn = getattr(self,'magic_'+magic_name,None)
1600 if fn is None:
1600 if fn is None:
1601 error("Magic function `%s` not found." % magic_name)
1601 error("Magic function `%s` not found." % magic_name)
1602 else:
1602 else:
1603 magic_args = self.var_expand(magic_args,1)
1603 magic_args = self.var_expand(magic_args,1)
1604 with nested(self.builtin_trap,):
1604 with nested(self.builtin_trap,):
1605 result = fn(magic_args)
1605 result = fn(magic_args)
1606 return result
1606 return result
1607
1607
1608 def define_magic(self, magicname, func):
1608 def define_magic(self, magicname, func):
1609 """Expose own function as magic function for ipython
1609 """Expose own function as magic function for ipython
1610
1610
1611 def foo_impl(self,parameter_s=''):
1611 def foo_impl(self,parameter_s=''):
1612 'My very own magic!. (Use docstrings, IPython reads them).'
1612 'My very own magic!. (Use docstrings, IPython reads them).'
1613 print 'Magic function. Passed parameter is between < >:'
1613 print 'Magic function. Passed parameter is between < >:'
1614 print '<%s>' % parameter_s
1614 print '<%s>' % parameter_s
1615 print 'The self object is:',self
1615 print 'The self object is:',self
1616
1616
1617 self.define_magic('foo',foo_impl)
1617 self.define_magic('foo',foo_impl)
1618 """
1618 """
1619
1619
1620 import new
1620 import new
1621 im = new.instancemethod(func,self, self.__class__)
1621 im = new.instancemethod(func,self, self.__class__)
1622 old = getattr(self, "magic_" + magicname, None)
1622 old = getattr(self, "magic_" + magicname, None)
1623 setattr(self, "magic_" + magicname, im)
1623 setattr(self, "magic_" + magicname, im)
1624 return old
1624 return old
1625
1625
1626 #-------------------------------------------------------------------------
1626 #-------------------------------------------------------------------------
1627 # Things related to macros
1627 # Things related to macros
1628 #-------------------------------------------------------------------------
1628 #-------------------------------------------------------------------------
1629
1629
1630 def define_macro(self, name, themacro):
1630 def define_macro(self, name, themacro):
1631 """Define a new macro
1631 """Define a new macro
1632
1632
1633 Parameters
1633 Parameters
1634 ----------
1634 ----------
1635 name : str
1635 name : str
1636 The name of the macro.
1636 The name of the macro.
1637 themacro : str or Macro
1637 themacro : str or Macro
1638 The action to do upon invoking the macro. If a string, a new
1638 The action to do upon invoking the macro. If a string, a new
1639 Macro object is created by passing the string to it.
1639 Macro object is created by passing the string to it.
1640 """
1640 """
1641
1641
1642 from IPython.core import macro
1642 from IPython.core import macro
1643
1643
1644 if isinstance(themacro, basestring):
1644 if isinstance(themacro, basestring):
1645 themacro = macro.Macro(themacro)
1645 themacro = macro.Macro(themacro)
1646 if not isinstance(themacro, macro.Macro):
1646 if not isinstance(themacro, macro.Macro):
1647 raise ValueError('A macro must be a string or a Macro instance.')
1647 raise ValueError('A macro must be a string or a Macro instance.')
1648 self.user_ns[name] = themacro
1648 self.user_ns[name] = themacro
1649
1649
1650 #-------------------------------------------------------------------------
1650 #-------------------------------------------------------------------------
1651 # Things related to the running of system commands
1651 # Things related to the running of system commands
1652 #-------------------------------------------------------------------------
1652 #-------------------------------------------------------------------------
1653
1653
1654 def system(self, cmd):
1654 def system(self, cmd):
1655 """Call the given cmd in a subprocess."""
1655 """Call the given cmd in a subprocess."""
1656 # We do not support backgrounding processes because we either use
1656 # We do not support backgrounding processes because we either use
1657 # pexpect or pipes to read from. Users can always just call
1657 # pexpect or pipes to read from. Users can always just call
1658 # os.system() if they really want a background process.
1658 # os.system() if they really want a background process.
1659 if cmd.endswith('&'):
1659 if cmd.endswith('&'):
1660 raise OSError("Background processes not supported.")
1660 raise OSError("Background processes not supported.")
1661
1661
1662 return system(self.var_expand(cmd, depth=2))
1662 return system(self.var_expand(cmd, depth=2))
1663
1663
1664 def getoutput(self, cmd):
1664 def getoutput(self, cmd):
1665 """Get output (possibly including stderr) from a subprocess."""
1665 """Get output (possibly including stderr) from a subprocess."""
1666 if cmd.endswith('&'):
1666 if cmd.endswith('&'):
1667 raise OSError("Background processes not supported.")
1667 raise OSError("Background processes not supported.")
1668 return getoutput(self.var_expand(cmd, depth=2))
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 # Things related to aliases
1671 # Things related to aliases
1678 #-------------------------------------------------------------------------
1672 #-------------------------------------------------------------------------
1679
1673
1680 def init_alias(self):
1674 def init_alias(self):
1681 self.alias_manager = AliasManager(shell=self, config=self.config)
1675 self.alias_manager = AliasManager(shell=self, config=self.config)
1682 self.ns_table['alias'] = self.alias_manager.alias_table,
1676 self.ns_table['alias'] = self.alias_manager.alias_table,
1683
1677
1684 #-------------------------------------------------------------------------
1678 #-------------------------------------------------------------------------
1685 # Things related to extensions and plugins
1679 # Things related to extensions and plugins
1686 #-------------------------------------------------------------------------
1680 #-------------------------------------------------------------------------
1687
1681
1688 def init_extension_manager(self):
1682 def init_extension_manager(self):
1689 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1683 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1690
1684
1691 def init_plugin_manager(self):
1685 def init_plugin_manager(self):
1692 self.plugin_manager = PluginManager(config=self.config)
1686 self.plugin_manager = PluginManager(config=self.config)
1693
1687
1694 #-------------------------------------------------------------------------
1688 #-------------------------------------------------------------------------
1695 # Things related to payloads
1689 # Things related to payloads
1696 #-------------------------------------------------------------------------
1690 #-------------------------------------------------------------------------
1697
1691
1698 def init_payload(self):
1692 def init_payload(self):
1699 self.payload_manager = PayloadManager(config=self.config)
1693 self.payload_manager = PayloadManager(config=self.config)
1700
1694
1701 #-------------------------------------------------------------------------
1695 #-------------------------------------------------------------------------
1702 # Things related to the prefilter
1696 # Things related to the prefilter
1703 #-------------------------------------------------------------------------
1697 #-------------------------------------------------------------------------
1704
1698
1705 def init_prefilter(self):
1699 def init_prefilter(self):
1706 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1700 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1707 # Ultimately this will be refactored in the new interpreter code, but
1701 # Ultimately this will be refactored in the new interpreter code, but
1708 # for now, we should expose the main prefilter method (there's legacy
1702 # for now, we should expose the main prefilter method (there's legacy
1709 # code out there that may rely on this).
1703 # code out there that may rely on this).
1710 self.prefilter = self.prefilter_manager.prefilter_lines
1704 self.prefilter = self.prefilter_manager.prefilter_lines
1711
1705
1712 #-------------------------------------------------------------------------
1706 #-------------------------------------------------------------------------
1713 # Things related to the running of code
1707 # Things related to the running of code
1714 #-------------------------------------------------------------------------
1708 #-------------------------------------------------------------------------
1715
1709
1716 def ex(self, cmd):
1710 def ex(self, cmd):
1717 """Execute a normal python statement in user namespace."""
1711 """Execute a normal python statement in user namespace."""
1718 with nested(self.builtin_trap,):
1712 with nested(self.builtin_trap,):
1719 exec cmd in self.user_global_ns, self.user_ns
1713 exec cmd in self.user_global_ns, self.user_ns
1720
1714
1721 def ev(self, expr):
1715 def ev(self, expr):
1722 """Evaluate python expression expr in user namespace.
1716 """Evaluate python expression expr in user namespace.
1723
1717
1724 Returns the result of evaluation
1718 Returns the result of evaluation
1725 """
1719 """
1726 with nested(self.builtin_trap,):
1720 with nested(self.builtin_trap,):
1727 return eval(expr, self.user_global_ns, self.user_ns)
1721 return eval(expr, self.user_global_ns, self.user_ns)
1728
1722
1729 def safe_execfile(self, fname, *where, **kw):
1723 def safe_execfile(self, fname, *where, **kw):
1730 """A safe version of the builtin execfile().
1724 """A safe version of the builtin execfile().
1731
1725
1732 This version will never throw an exception, but instead print
1726 This version will never throw an exception, but instead print
1733 helpful error messages to the screen. This only works on pure
1727 helpful error messages to the screen. This only works on pure
1734 Python files with the .py extension.
1728 Python files with the .py extension.
1735
1729
1736 Parameters
1730 Parameters
1737 ----------
1731 ----------
1738 fname : string
1732 fname : string
1739 The name of the file to be executed.
1733 The name of the file to be executed.
1740 where : tuple
1734 where : tuple
1741 One or two namespaces, passed to execfile() as (globals,locals).
1735 One or two namespaces, passed to execfile() as (globals,locals).
1742 If only one is given, it is passed as both.
1736 If only one is given, it is passed as both.
1743 exit_ignore : bool (False)
1737 exit_ignore : bool (False)
1744 If True, then silence SystemExit for non-zero status (it is always
1738 If True, then silence SystemExit for non-zero status (it is always
1745 silenced for zero status, as it is so common).
1739 silenced for zero status, as it is so common).
1746 """
1740 """
1747 kw.setdefault('exit_ignore', False)
1741 kw.setdefault('exit_ignore', False)
1748
1742
1749 fname = os.path.abspath(os.path.expanduser(fname))
1743 fname = os.path.abspath(os.path.expanduser(fname))
1750
1744
1751 # Make sure we have a .py file
1745 # Make sure we have a .py file
1752 if not fname.endswith('.py'):
1746 if not fname.endswith('.py'):
1753 warn('File must end with .py to be run using execfile: <%s>' % fname)
1747 warn('File must end with .py to be run using execfile: <%s>' % fname)
1754
1748
1755 # Make sure we can open the file
1749 # Make sure we can open the file
1756 try:
1750 try:
1757 with open(fname) as thefile:
1751 with open(fname) as thefile:
1758 pass
1752 pass
1759 except:
1753 except:
1760 warn('Could not open file <%s> for safe execution.' % fname)
1754 warn('Could not open file <%s> for safe execution.' % fname)
1761 return
1755 return
1762
1756
1763 # Find things also in current directory. This is needed to mimic the
1757 # Find things also in current directory. This is needed to mimic the
1764 # behavior of running a script from the system command line, where
1758 # behavior of running a script from the system command line, where
1765 # Python inserts the script's directory into sys.path
1759 # Python inserts the script's directory into sys.path
1766 dname = os.path.dirname(fname)
1760 dname = os.path.dirname(fname)
1767
1761
1768 with prepended_to_syspath(dname):
1762 with prepended_to_syspath(dname):
1769 try:
1763 try:
1770 execfile(fname,*where)
1764 execfile(fname,*where)
1771 except SystemExit, status:
1765 except SystemExit, status:
1772 # If the call was made with 0 or None exit status (sys.exit(0)
1766 # If the call was made with 0 or None exit status (sys.exit(0)
1773 # or sys.exit() ), don't bother showing a traceback, as both of
1767 # or sys.exit() ), don't bother showing a traceback, as both of
1774 # these are considered normal by the OS:
1768 # these are considered normal by the OS:
1775 # > python -c'import sys;sys.exit(0)'; echo $?
1769 # > python -c'import sys;sys.exit(0)'; echo $?
1776 # 0
1770 # 0
1777 # > python -c'import sys;sys.exit()'; echo $?
1771 # > python -c'import sys;sys.exit()'; echo $?
1778 # 0
1772 # 0
1779 # For other exit status, we show the exception unless
1773 # For other exit status, we show the exception unless
1780 # explicitly silenced, but only in short form.
1774 # explicitly silenced, but only in short form.
1781 if status.code not in (0, None) and not kw['exit_ignore']:
1775 if status.code not in (0, None) and not kw['exit_ignore']:
1782 self.showtraceback(exception_only=True)
1776 self.showtraceback(exception_only=True)
1783 except:
1777 except:
1784 self.showtraceback()
1778 self.showtraceback()
1785
1779
1786 def safe_execfile_ipy(self, fname):
1780 def safe_execfile_ipy(self, fname):
1787 """Like safe_execfile, but for .ipy files with IPython syntax.
1781 """Like safe_execfile, but for .ipy files with IPython syntax.
1788
1782
1789 Parameters
1783 Parameters
1790 ----------
1784 ----------
1791 fname : str
1785 fname : str
1792 The name of the file to execute. The filename must have a
1786 The name of the file to execute. The filename must have a
1793 .ipy extension.
1787 .ipy extension.
1794 """
1788 """
1795 fname = os.path.abspath(os.path.expanduser(fname))
1789 fname = os.path.abspath(os.path.expanduser(fname))
1796
1790
1797 # Make sure we have a .py file
1791 # Make sure we have a .py file
1798 if not fname.endswith('.ipy'):
1792 if not fname.endswith('.ipy'):
1799 warn('File must end with .py to be run using execfile: <%s>' % fname)
1793 warn('File must end with .py to be run using execfile: <%s>' % fname)
1800
1794
1801 # Make sure we can open the file
1795 # Make sure we can open the file
1802 try:
1796 try:
1803 with open(fname) as thefile:
1797 with open(fname) as thefile:
1804 pass
1798 pass
1805 except:
1799 except:
1806 warn('Could not open file <%s> for safe execution.' % fname)
1800 warn('Could not open file <%s> for safe execution.' % fname)
1807 return
1801 return
1808
1802
1809 # Find things also in current directory. This is needed to mimic the
1803 # Find things also in current directory. This is needed to mimic the
1810 # behavior of running a script from the system command line, where
1804 # behavior of running a script from the system command line, where
1811 # Python inserts the script's directory into sys.path
1805 # Python inserts the script's directory into sys.path
1812 dname = os.path.dirname(fname)
1806 dname = os.path.dirname(fname)
1813
1807
1814 with prepended_to_syspath(dname):
1808 with prepended_to_syspath(dname):
1815 try:
1809 try:
1816 with open(fname) as thefile:
1810 with open(fname) as thefile:
1817 script = thefile.read()
1811 script = thefile.read()
1818 # self.runlines currently captures all exceptions
1812 # self.runlines currently captures all exceptions
1819 # raise in user code. It would be nice if there were
1813 # raise in user code. It would be nice if there were
1820 # versions of runlines, execfile that did raise, so
1814 # versions of runlines, execfile that did raise, so
1821 # we could catch the errors.
1815 # we could catch the errors.
1822 self.runlines(script, clean=True)
1816 self.runlines(script, clean=True)
1823 except:
1817 except:
1824 self.showtraceback()
1818 self.showtraceback()
1825 warn('Unknown failure executing file: <%s>' % fname)
1819 warn('Unknown failure executing file: <%s>' % fname)
1826
1820
1827 def runlines(self, lines, clean=False):
1821 def runlines(self, lines, clean=False):
1828 """Run a string of one or more lines of source.
1822 """Run a string of one or more lines of source.
1829
1823
1830 This method is capable of running a string containing multiple source
1824 This method is capable of running a string containing multiple source
1831 lines, as if they had been entered at the IPython prompt. Since it
1825 lines, as if they had been entered at the IPython prompt. Since it
1832 exposes IPython's processing machinery, the given strings can contain
1826 exposes IPython's processing machinery, the given strings can contain
1833 magic calls (%magic), special shell access (!cmd), etc.
1827 magic calls (%magic), special shell access (!cmd), etc.
1834 """
1828 """
1835
1829
1836 if isinstance(lines, (list, tuple)):
1830 if isinstance(lines, (list, tuple)):
1837 lines = '\n'.join(lines)
1831 lines = '\n'.join(lines)
1838
1832
1839 if clean:
1833 if clean:
1840 lines = self._cleanup_ipy_script(lines)
1834 lines = self._cleanup_ipy_script(lines)
1841
1835
1842 # We must start with a clean buffer, in case this is run from an
1836 # We must start with a clean buffer, in case this is run from an
1843 # interactive IPython session (via a magic, for example).
1837 # interactive IPython session (via a magic, for example).
1844 self.resetbuffer()
1838 self.resetbuffer()
1845 lines = lines.splitlines()
1839 lines = lines.splitlines()
1846 more = 0
1840 more = 0
1847 with nested(self.builtin_trap, self.display_trap):
1841 with nested(self.builtin_trap, self.display_trap):
1848 for line in lines:
1842 for line in lines:
1849 # skip blank lines so we don't mess up the prompt counter, but do
1843 # skip blank lines so we don't mess up the prompt counter, but do
1850 # NOT skip even a blank line if we are in a code block (more is
1844 # NOT skip even a blank line if we are in a code block (more is
1851 # true)
1845 # true)
1852
1846
1853 if line or more:
1847 if line or more:
1854 # push to raw history, so hist line numbers stay in sync
1848 # push to raw history, so hist line numbers stay in sync
1855 self.input_hist_raw.append(line + '\n')
1849 self.input_hist_raw.append(line + '\n')
1856 prefiltered = self.prefilter_manager.prefilter_lines(line,
1850 prefiltered = self.prefilter_manager.prefilter_lines(line,
1857 more)
1851 more)
1858 more = self.push_line(prefiltered)
1852 more = self.push_line(prefiltered)
1859 # IPython's runsource returns None if there was an error
1853 # IPython's runsource returns None if there was an error
1860 # compiling the code. This allows us to stop processing right
1854 # compiling the code. This allows us to stop processing right
1861 # away, so the user gets the error message at the right place.
1855 # away, so the user gets the error message at the right place.
1862 if more is None:
1856 if more is None:
1863 break
1857 break
1864 else:
1858 else:
1865 self.input_hist_raw.append("\n")
1859 self.input_hist_raw.append("\n")
1866 # final newline in case the input didn't have it, so that the code
1860 # final newline in case the input didn't have it, so that the code
1867 # actually does get executed
1861 # actually does get executed
1868 if more:
1862 if more:
1869 self.push_line('\n')
1863 self.push_line('\n')
1870
1864
1871 def runsource(self, source, filename='<input>', symbol='single'):
1865 def runsource(self, source, filename='<input>', symbol='single'):
1872 """Compile and run some source in the interpreter.
1866 """Compile and run some source in the interpreter.
1873
1867
1874 Arguments are as for compile_command().
1868 Arguments are as for compile_command().
1875
1869
1876 One several things can happen:
1870 One several things can happen:
1877
1871
1878 1) The input is incorrect; compile_command() raised an
1872 1) The input is incorrect; compile_command() raised an
1879 exception (SyntaxError or OverflowError). A syntax traceback
1873 exception (SyntaxError or OverflowError). A syntax traceback
1880 will be printed by calling the showsyntaxerror() method.
1874 will be printed by calling the showsyntaxerror() method.
1881
1875
1882 2) The input is incomplete, and more input is required;
1876 2) The input is incomplete, and more input is required;
1883 compile_command() returned None. Nothing happens.
1877 compile_command() returned None. Nothing happens.
1884
1878
1885 3) The input is complete; compile_command() returned a code
1879 3) The input is complete; compile_command() returned a code
1886 object. The code is executed by calling self.runcode() (which
1880 object. The code is executed by calling self.runcode() (which
1887 also handles run-time exceptions, except for SystemExit).
1881 also handles run-time exceptions, except for SystemExit).
1888
1882
1889 The return value is:
1883 The return value is:
1890
1884
1891 - True in case 2
1885 - True in case 2
1892
1886
1893 - False in the other cases, unless an exception is raised, where
1887 - False in the other cases, unless an exception is raised, where
1894 None is returned instead. This can be used by external callers to
1888 None is returned instead. This can be used by external callers to
1895 know whether to continue feeding input or not.
1889 know whether to continue feeding input or not.
1896
1890
1897 The return value can be used to decide whether to use sys.ps1 or
1891 The return value can be used to decide whether to use sys.ps1 or
1898 sys.ps2 to prompt the next line."""
1892 sys.ps2 to prompt the next line."""
1899
1893
1900 # if the source code has leading blanks, add 'if 1:\n' to it
1894 # if the source code has leading blanks, add 'if 1:\n' to it
1901 # this allows execution of indented pasted code. It is tempting
1895 # this allows execution of indented pasted code. It is tempting
1902 # to add '\n' at the end of source to run commands like ' a=1'
1896 # to add '\n' at the end of source to run commands like ' a=1'
1903 # directly, but this fails for more complicated scenarios
1897 # directly, but this fails for more complicated scenarios
1904 source=source.encode(self.stdin_encoding)
1898 source=source.encode(self.stdin_encoding)
1905 if source[:1] in [' ', '\t']:
1899 if source[:1] in [' ', '\t']:
1906 source = 'if 1:\n%s' % source
1900 source = 'if 1:\n%s' % source
1907
1901
1908 try:
1902 try:
1909 code = self.compile(source,filename,symbol)
1903 code = self.compile(source,filename,symbol)
1910 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1904 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
1911 # Case 1
1905 # Case 1
1912 self.showsyntaxerror(filename)
1906 self.showsyntaxerror(filename)
1913 return None
1907 return None
1914
1908
1915 if code is None:
1909 if code is None:
1916 # Case 2
1910 # Case 2
1917 return True
1911 return True
1918
1912
1919 # Case 3
1913 # Case 3
1920 # We store the code object so that threaded shells and
1914 # We store the code object so that threaded shells and
1921 # custom exception handlers can access all this info if needed.
1915 # custom exception handlers can access all this info if needed.
1922 # The source corresponding to this can be obtained from the
1916 # The source corresponding to this can be obtained from the
1923 # buffer attribute as '\n'.join(self.buffer).
1917 # buffer attribute as '\n'.join(self.buffer).
1924 self.code_to_run = code
1918 self.code_to_run = code
1925 # now actually execute the code object
1919 # now actually execute the code object
1926 if self.runcode(code) == 0:
1920 if self.runcode(code) == 0:
1927 return False
1921 return False
1928 else:
1922 else:
1929 return None
1923 return None
1930
1924
1931 def runcode(self,code_obj):
1925 def runcode(self,code_obj):
1932 """Execute a code object.
1926 """Execute a code object.
1933
1927
1934 When an exception occurs, self.showtraceback() is called to display a
1928 When an exception occurs, self.showtraceback() is called to display a
1935 traceback.
1929 traceback.
1936
1930
1937 Return value: a flag indicating whether the code to be run completed
1931 Return value: a flag indicating whether the code to be run completed
1938 successfully:
1932 successfully:
1939
1933
1940 - 0: successful execution.
1934 - 0: successful execution.
1941 - 1: an error occurred.
1935 - 1: an error occurred.
1942 """
1936 """
1943
1937
1944 # Set our own excepthook in case the user code tries to call it
1938 # Set our own excepthook in case the user code tries to call it
1945 # directly, so that the IPython crash handler doesn't get triggered
1939 # directly, so that the IPython crash handler doesn't get triggered
1946 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1940 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1947
1941
1948 # we save the original sys.excepthook in the instance, in case config
1942 # we save the original sys.excepthook in the instance, in case config
1949 # code (such as magics) needs access to it.
1943 # code (such as magics) needs access to it.
1950 self.sys_excepthook = old_excepthook
1944 self.sys_excepthook = old_excepthook
1951 outflag = 1 # happens in more places, so it's easier as default
1945 outflag = 1 # happens in more places, so it's easier as default
1952 try:
1946 try:
1953 try:
1947 try:
1954 self.hooks.pre_runcode_hook()
1948 self.hooks.pre_runcode_hook()
1955 #rprint('Running code') # dbg
1949 #rprint('Running code') # dbg
1956 exec code_obj in self.user_global_ns, self.user_ns
1950 exec code_obj in self.user_global_ns, self.user_ns
1957 finally:
1951 finally:
1958 # Reset our crash handler in place
1952 # Reset our crash handler in place
1959 sys.excepthook = old_excepthook
1953 sys.excepthook = old_excepthook
1960 except SystemExit:
1954 except SystemExit:
1961 self.resetbuffer()
1955 self.resetbuffer()
1962 self.showtraceback(exception_only=True)
1956 self.showtraceback(exception_only=True)
1963 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1957 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
1964 except self.custom_exceptions:
1958 except self.custom_exceptions:
1965 etype,value,tb = sys.exc_info()
1959 etype,value,tb = sys.exc_info()
1966 self.CustomTB(etype,value,tb)
1960 self.CustomTB(etype,value,tb)
1967 except:
1961 except:
1968 self.showtraceback()
1962 self.showtraceback()
1969 else:
1963 else:
1970 outflag = 0
1964 outflag = 0
1971 if softspace(sys.stdout, 0):
1965 if softspace(sys.stdout, 0):
1972 print
1966 print
1973 # Flush out code object which has been run (and source)
1967 # Flush out code object which has been run (and source)
1974 self.code_to_run = None
1968 self.code_to_run = None
1975 return outflag
1969 return outflag
1976
1970
1977 def push_line(self, line):
1971 def push_line(self, line):
1978 """Push a line to the interpreter.
1972 """Push a line to the interpreter.
1979
1973
1980 The line should not have a trailing newline; it may have
1974 The line should not have a trailing newline; it may have
1981 internal newlines. The line is appended to a buffer and the
1975 internal newlines. The line is appended to a buffer and the
1982 interpreter's runsource() method is called with the
1976 interpreter's runsource() method is called with the
1983 concatenated contents of the buffer as source. If this
1977 concatenated contents of the buffer as source. If this
1984 indicates that the command was executed or invalid, the buffer
1978 indicates that the command was executed or invalid, the buffer
1985 is reset; otherwise, the command is incomplete, and the buffer
1979 is reset; otherwise, the command is incomplete, and the buffer
1986 is left as it was after the line was appended. The return
1980 is left as it was after the line was appended. The return
1987 value is 1 if more input is required, 0 if the line was dealt
1981 value is 1 if more input is required, 0 if the line was dealt
1988 with in some way (this is the same as runsource()).
1982 with in some way (this is the same as runsource()).
1989 """
1983 """
1990
1984
1991 # autoindent management should be done here, and not in the
1985 # autoindent management should be done here, and not in the
1992 # interactive loop, since that one is only seen by keyboard input. We
1986 # interactive loop, since that one is only seen by keyboard input. We
1993 # need this done correctly even for code run via runlines (which uses
1987 # need this done correctly even for code run via runlines (which uses
1994 # push).
1988 # push).
1995
1989
1996 #print 'push line: <%s>' % line # dbg
1990 #print 'push line: <%s>' % line # dbg
1997 for subline in line.splitlines():
1991 for subline in line.splitlines():
1998 self._autoindent_update(subline)
1992 self._autoindent_update(subline)
1999 self.buffer.append(line)
1993 self.buffer.append(line)
2000 more = self.runsource('\n'.join(self.buffer), self.filename)
1994 more = self.runsource('\n'.join(self.buffer), self.filename)
2001 if not more:
1995 if not more:
2002 self.resetbuffer()
1996 self.resetbuffer()
2003 return more
1997 return more
2004
1998
2005 def resetbuffer(self):
1999 def resetbuffer(self):
2006 """Reset the input buffer."""
2000 """Reset the input buffer."""
2007 self.buffer[:] = []
2001 self.buffer[:] = []
2008
2002
2009 def _is_secondary_block_start(self, s):
2003 def _is_secondary_block_start(self, s):
2010 if not s.endswith(':'):
2004 if not s.endswith(':'):
2011 return False
2005 return False
2012 if (s.startswith('elif') or
2006 if (s.startswith('elif') or
2013 s.startswith('else') or
2007 s.startswith('else') or
2014 s.startswith('except') or
2008 s.startswith('except') or
2015 s.startswith('finally')):
2009 s.startswith('finally')):
2016 return True
2010 return True
2017
2011
2018 def _cleanup_ipy_script(self, script):
2012 def _cleanup_ipy_script(self, script):
2019 """Make a script safe for self.runlines()
2013 """Make a script safe for self.runlines()
2020
2014
2021 Currently, IPython is lines based, with blocks being detected by
2015 Currently, IPython is lines based, with blocks being detected by
2022 empty lines. This is a problem for block based scripts that may
2016 empty lines. This is a problem for block based scripts that may
2023 not have empty lines after blocks. This script adds those empty
2017 not have empty lines after blocks. This script adds those empty
2024 lines to make scripts safe for running in the current line based
2018 lines to make scripts safe for running in the current line based
2025 IPython.
2019 IPython.
2026 """
2020 """
2027 res = []
2021 res = []
2028 lines = script.splitlines()
2022 lines = script.splitlines()
2029 level = 0
2023 level = 0
2030
2024
2031 for l in lines:
2025 for l in lines:
2032 lstripped = l.lstrip()
2026 lstripped = l.lstrip()
2033 stripped = l.strip()
2027 stripped = l.strip()
2034 if not stripped:
2028 if not stripped:
2035 continue
2029 continue
2036 newlevel = len(l) - len(lstripped)
2030 newlevel = len(l) - len(lstripped)
2037 if level > 0 and newlevel == 0 and \
2031 if level > 0 and newlevel == 0 and \
2038 not self._is_secondary_block_start(stripped):
2032 not self._is_secondary_block_start(stripped):
2039 # add empty line
2033 # add empty line
2040 res.append('')
2034 res.append('')
2041 res.append(l)
2035 res.append(l)
2042 level = newlevel
2036 level = newlevel
2043
2037
2044 return '\n'.join(res) + '\n'
2038 return '\n'.join(res) + '\n'
2045
2039
2046 def _autoindent_update(self,line):
2040 def _autoindent_update(self,line):
2047 """Keep track of the indent level."""
2041 """Keep track of the indent level."""
2048
2042
2049 #debugx('line')
2043 #debugx('line')
2050 #debugx('self.indent_current_nsp')
2044 #debugx('self.indent_current_nsp')
2051 if self.autoindent:
2045 if self.autoindent:
2052 if line:
2046 if line:
2053 inisp = num_ini_spaces(line)
2047 inisp = num_ini_spaces(line)
2054 if inisp < self.indent_current_nsp:
2048 if inisp < self.indent_current_nsp:
2055 self.indent_current_nsp = inisp
2049 self.indent_current_nsp = inisp
2056
2050
2057 if line[-1] == ':':
2051 if line[-1] == ':':
2058 self.indent_current_nsp += 4
2052 self.indent_current_nsp += 4
2059 elif dedent_re.match(line):
2053 elif dedent_re.match(line):
2060 self.indent_current_nsp -= 4
2054 self.indent_current_nsp -= 4
2061 else:
2055 else:
2062 self.indent_current_nsp = 0
2056 self.indent_current_nsp = 0
2063
2057
2064 #-------------------------------------------------------------------------
2058 #-------------------------------------------------------------------------
2065 # Things related to GUI support and pylab
2059 # Things related to GUI support and pylab
2066 #-------------------------------------------------------------------------
2060 #-------------------------------------------------------------------------
2067
2061
2068 def enable_pylab(self, gui=None):
2062 def enable_pylab(self, gui=None):
2069 raise NotImplementedError('Implement enable_pylab in a subclass')
2063 raise NotImplementedError('Implement enable_pylab in a subclass')
2070
2064
2071 #-------------------------------------------------------------------------
2065 #-------------------------------------------------------------------------
2072 # Utilities
2066 # Utilities
2073 #-------------------------------------------------------------------------
2067 #-------------------------------------------------------------------------
2074
2068
2075 def var_expand(self,cmd,depth=0):
2069 def var_expand(self,cmd,depth=0):
2076 """Expand python variables in a string.
2070 """Expand python variables in a string.
2077
2071
2078 The depth argument indicates how many frames above the caller should
2072 The depth argument indicates how many frames above the caller should
2079 be walked to look for the local namespace where to expand variables.
2073 be walked to look for the local namespace where to expand variables.
2080
2074
2081 The global namespace for expansion is always the user's interactive
2075 The global namespace for expansion is always the user's interactive
2082 namespace.
2076 namespace.
2083 """
2077 """
2084
2078
2085 return str(ItplNS(cmd,
2079 return str(ItplNS(cmd,
2086 self.user_ns, # globals
2080 self.user_ns, # globals
2087 # Skip our own frame in searching for locals:
2081 # Skip our own frame in searching for locals:
2088 sys._getframe(depth+1).f_locals # locals
2082 sys._getframe(depth+1).f_locals # locals
2089 ))
2083 ))
2090
2084
2091 def mktempfile(self,data=None):
2085 def mktempfile(self,data=None):
2092 """Make a new tempfile and return its filename.
2086 """Make a new tempfile and return its filename.
2093
2087
2094 This makes a call to tempfile.mktemp, but it registers the created
2088 This makes a call to tempfile.mktemp, but it registers the created
2095 filename internally so ipython cleans it up at exit time.
2089 filename internally so ipython cleans it up at exit time.
2096
2090
2097 Optional inputs:
2091 Optional inputs:
2098
2092
2099 - data(None): if data is given, it gets written out to the temp file
2093 - data(None): if data is given, it gets written out to the temp file
2100 immediately, and the file is closed again."""
2094 immediately, and the file is closed again."""
2101
2095
2102 filename = tempfile.mktemp('.py','ipython_edit_')
2096 filename = tempfile.mktemp('.py','ipython_edit_')
2103 self.tempfiles.append(filename)
2097 self.tempfiles.append(filename)
2104
2098
2105 if data:
2099 if data:
2106 tmp_file = open(filename,'w')
2100 tmp_file = open(filename,'w')
2107 tmp_file.write(data)
2101 tmp_file.write(data)
2108 tmp_file.close()
2102 tmp_file.close()
2109 return filename
2103 return filename
2110
2104
2111 # TODO: This should be removed when Term is refactored.
2105 # TODO: This should be removed when Term is refactored.
2112 def write(self,data):
2106 def write(self,data):
2113 """Write a string to the default output"""
2107 """Write a string to the default output"""
2114 io.Term.cout.write(data)
2108 io.Term.cout.write(data)
2115
2109
2116 # TODO: This should be removed when Term is refactored.
2110 # TODO: This should be removed when Term is refactored.
2117 def write_err(self,data):
2111 def write_err(self,data):
2118 """Write a string to the default error output"""
2112 """Write a string to the default error output"""
2119 io.Term.cerr.write(data)
2113 io.Term.cerr.write(data)
2120
2114
2121 def ask_yes_no(self,prompt,default=True):
2115 def ask_yes_no(self,prompt,default=True):
2122 if self.quiet:
2116 if self.quiet:
2123 return True
2117 return True
2124 return ask_yes_no(prompt,default)
2118 return ask_yes_no(prompt,default)
2125
2119
2126 def show_usage(self):
2120 def show_usage(self):
2127 """Show a usage message"""
2121 """Show a usage message"""
2128 page.page(IPython.core.usage.interactive_usage)
2122 page.page(IPython.core.usage.interactive_usage)
2129
2123
2130 #-------------------------------------------------------------------------
2124 #-------------------------------------------------------------------------
2131 # Things related to IPython exiting
2125 # Things related to IPython exiting
2132 #-------------------------------------------------------------------------
2126 #-------------------------------------------------------------------------
2133
2127
2134 def atexit_operations(self):
2128 def atexit_operations(self):
2135 """This will be executed at the time of exit.
2129 """This will be executed at the time of exit.
2136
2130
2137 Saving of persistent data should be performed here.
2131 Saving of persistent data should be performed here.
2138 """
2132 """
2139 self.savehist()
2133 self.savehist()
2140
2134
2141 # Cleanup all tempfiles left around
2135 # Cleanup all tempfiles left around
2142 for tfile in self.tempfiles:
2136 for tfile in self.tempfiles:
2143 try:
2137 try:
2144 os.unlink(tfile)
2138 os.unlink(tfile)
2145 except OSError:
2139 except OSError:
2146 pass
2140 pass
2147
2141
2148 # Clear all user namespaces to release all references cleanly.
2142 # Clear all user namespaces to release all references cleanly.
2149 self.reset()
2143 self.reset()
2150
2144
2151 # Run user hooks
2145 # Run user hooks
2152 self.hooks.shutdown_hook()
2146 self.hooks.shutdown_hook()
2153
2147
2154 def cleanup(self):
2148 def cleanup(self):
2155 self.restore_sys_module_state()
2149 self.restore_sys_module_state()
2156
2150
2157
2151
2158 class InteractiveShellABC(object):
2152 class InteractiveShellABC(object):
2159 """An abstract base class for InteractiveShell."""
2153 """An abstract base class for InteractiveShell."""
2160 __metaclass__ = abc.ABCMeta
2154 __metaclass__ = abc.ABCMeta
2161
2155
2162 InteractiveShellABC.register(InteractiveShell)
2156 InteractiveShellABC.register(InteractiveShell)
@@ -1,3631 +1,3628 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__
18 import __builtin__
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import os
22 import os
23 import sys
23 import sys
24 import shutil
24 import shutil
25 import re
25 import re
26 import time
26 import time
27 import textwrap
27 import textwrap
28 import types
28 import types
29 from cStringIO import StringIO
29 from cStringIO import StringIO
30 from getopt import getopt,GetoptError
30 from getopt import getopt,GetoptError
31 from pprint import pformat
31 from pprint import pformat
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 # print_function was added to __future__ in Python2.6, remove this when we drop
44 # print_function was added to __future__ in Python2.6, remove this when we drop
45 # 2.5 compatibility
45 # 2.5 compatibility
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
46 if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'):
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
47 __future__.CO_FUTURE_PRINT_FUNCTION = 65536
48
48
49 import IPython
49 import IPython
50 from IPython.core import debugger, oinspect
50 from IPython.core import debugger, oinspect
51 from IPython.core.error import TryNext
51 from IPython.core.error import TryNext
52 from IPython.core.error import UsageError
52 from IPython.core.error import UsageError
53 from IPython.core.fakemodule import FakeModule
53 from IPython.core.fakemodule import FakeModule
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core import page
55 from IPython.core import page
56 from IPython.core.prefilter import ESC_MAGIC
56 from IPython.core.prefilter import ESC_MAGIC
57 from IPython.lib.pylabtools import mpl_runner
57 from IPython.lib.pylabtools import mpl_runner
58 from IPython.lib.inputhook import enable_gui
58 from IPython.lib.inputhook import enable_gui
59 from IPython.external.Itpl import itpl, printpl
59 from IPython.external.Itpl import itpl, printpl
60 from IPython.testing import decorators as testdec
60 from IPython.testing import decorators as testdec
61 from IPython.utils.io import file_read, nlprint
61 from IPython.utils.io import file_read, nlprint
62 import IPython.utils.io
62 import IPython.utils.io
63 from IPython.utils.path import get_py_filename
63 from IPython.utils.path import get_py_filename
64 from IPython.utils.process import arg_split, abbrev_cwd
64 from IPython.utils.process import arg_split, abbrev_cwd
65 from IPython.utils.terminal import set_term_title
65 from IPython.utils.terminal import set_term_title
66 from IPython.utils.text import LSString, SList, StringTypes
66 from IPython.utils.text import LSString, SList, StringTypes
67 from IPython.utils.timing import clock, clock2
67 from IPython.utils.timing import clock, clock2
68 from IPython.utils.warn import warn, error
68 from IPython.utils.warn import warn, error
69 from IPython.utils.ipstruct import Struct
69 from IPython.utils.ipstruct import Struct
70 import IPython.utils.generics
70 import IPython.utils.generics
71
71
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 # Utility functions
73 # Utility functions
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75
75
76 def on_off(tag):
76 def on_off(tag):
77 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
77 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
78 return ['OFF','ON'][tag]
78 return ['OFF','ON'][tag]
79
79
80 class Bunch: pass
80 class Bunch: pass
81
81
82 def compress_dhist(dh):
82 def compress_dhist(dh):
83 head, tail = dh[:-10], dh[-10:]
83 head, tail = dh[:-10], dh[-10:]
84
84
85 newhead = []
85 newhead = []
86 done = set()
86 done = set()
87 for h in head:
87 for h in head:
88 if h in done:
88 if h in done:
89 continue
89 continue
90 newhead.append(h)
90 newhead.append(h)
91 done.add(h)
91 done.add(h)
92
92
93 return newhead + tail
93 return newhead + tail
94
94
95
95
96 #***************************************************************************
96 #***************************************************************************
97 # Main class implementing Magic functionality
97 # Main class implementing Magic functionality
98
98
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
100 # on construction of the main InteractiveShell object. Something odd is going
100 # on construction of the main InteractiveShell object. Something odd is going
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
102 # eventually this needs to be clarified.
102 # eventually this needs to be clarified.
103 # BG: This is because InteractiveShell inherits from this, but is itself a
103 # BG: This is because InteractiveShell inherits from this, but is itself a
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
105 # make Magic a configurable that InteractiveShell does not subclass.
105 # make Magic a configurable that InteractiveShell does not subclass.
106
106
107 class Magic:
107 class Magic:
108 """Magic functions for InteractiveShell.
108 """Magic functions for InteractiveShell.
109
109
110 Shell functions which can be reached as %function_name. All magic
110 Shell functions which can be reached as %function_name. All magic
111 functions should accept a string, which they can parse for their own
111 functions should accept a string, which they can parse for their own
112 needs. This can make some functions easier to type, eg `%cd ../`
112 needs. This can make some functions easier to type, eg `%cd ../`
113 vs. `%cd("../")`
113 vs. `%cd("../")`
114
114
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
116 at the command line, but it is is needed in the definition. """
116 at the command line, but it is is needed in the definition. """
117
117
118 # class globals
118 # class globals
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
120 'Automagic is ON, % prefix NOT needed for magic functions.']
120 'Automagic is ON, % prefix NOT needed for magic functions.']
121
121
122 #......................................................................
122 #......................................................................
123 # some utility functions
123 # some utility functions
124
124
125 def __init__(self,shell):
125 def __init__(self,shell):
126
126
127 self.options_table = {}
127 self.options_table = {}
128 if profile is None:
128 if profile is None:
129 self.magic_prun = self.profile_missing_notice
129 self.magic_prun = self.profile_missing_notice
130 self.shell = shell
130 self.shell = shell
131
131
132 # namespace for holding state we may need
132 # namespace for holding state we may need
133 self._magic_state = Bunch()
133 self._magic_state = Bunch()
134
134
135 def profile_missing_notice(self, *args, **kwargs):
135 def profile_missing_notice(self, *args, **kwargs):
136 error("""\
136 error("""\
137 The profile module could not be found. It has been removed from the standard
137 The profile module could not be found. It has been removed from the standard
138 python packages because of its non-free license. To use profiling, install the
138 python packages because of its non-free license. To use profiling, install the
139 python-profiler package from non-free.""")
139 python-profiler package from non-free.""")
140
140
141 def default_option(self,fn,optstr):
141 def default_option(self,fn,optstr):
142 """Make an entry in the options_table for fn, with value optstr"""
142 """Make an entry in the options_table for fn, with value optstr"""
143
143
144 if fn not in self.lsmagic():
144 if fn not in self.lsmagic():
145 error("%s is not a magic function" % fn)
145 error("%s is not a magic function" % fn)
146 self.options_table[fn] = optstr
146 self.options_table[fn] = optstr
147
147
148 def lsmagic(self):
148 def lsmagic(self):
149 """Return a list of currently available magic functions.
149 """Return a list of currently available magic functions.
150
150
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
152 ['magic_ls','magic_cd',...]"""
152 ['magic_ls','magic_cd',...]"""
153
153
154 # FIXME. This needs a cleanup, in the way the magics list is built.
154 # FIXME. This needs a cleanup, in the way the magics list is built.
155
155
156 # magics in class definition
156 # magics in class definition
157 class_magic = lambda fn: fn.startswith('magic_') and \
157 class_magic = lambda fn: fn.startswith('magic_') and \
158 callable(Magic.__dict__[fn])
158 callable(Magic.__dict__[fn])
159 # in instance namespace (run-time user additions)
159 # in instance namespace (run-time user additions)
160 inst_magic = lambda fn: fn.startswith('magic_') and \
160 inst_magic = lambda fn: fn.startswith('magic_') and \
161 callable(self.__dict__[fn])
161 callable(self.__dict__[fn])
162 # and bound magics by user (so they can access self):
162 # and bound magics by user (so they can access self):
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
164 callable(self.__class__.__dict__[fn])
164 callable(self.__class__.__dict__[fn])
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
168 out = []
168 out = []
169 for fn in set(magics):
169 for fn in set(magics):
170 out.append(fn.replace('magic_','',1))
170 out.append(fn.replace('magic_','',1))
171 out.sort()
171 out.sort()
172 return out
172 return out
173
173
174 def extract_input_slices(self,slices,raw=False):
174 def extract_input_slices(self,slices,raw=False):
175 """Return as a string a set of input history slices.
175 """Return as a string a set of input history slices.
176
176
177 Inputs:
177 Inputs:
178
178
179 - slices: the set of slices is given as a list of strings (like
179 - slices: the set of slices is given as a list of strings (like
180 ['1','4:8','9'], since this function is for use by magic functions
180 ['1','4:8','9'], since this function is for use by magic functions
181 which get their arguments as strings.
181 which get their arguments as strings.
182
182
183 Optional inputs:
183 Optional inputs:
184
184
185 - raw(False): by default, the processed input is used. If this is
185 - raw(False): by default, the processed input is used. If this is
186 true, the raw input history is used instead.
186 true, the raw input history is used instead.
187
187
188 Note that slices can be called with two notations:
188 Note that slices can be called with two notations:
189
189
190 N:M -> standard python form, means including items N...(M-1).
190 N:M -> standard python form, means including items N...(M-1).
191
191
192 N-M -> include items N..M (closed endpoint)."""
192 N-M -> include items N..M (closed endpoint)."""
193
193
194 if raw:
194 if raw:
195 hist = self.shell.input_hist_raw
195 hist = self.shell.input_hist_raw
196 else:
196 else:
197 hist = self.shell.input_hist
197 hist = self.shell.input_hist
198
198
199 cmds = []
199 cmds = []
200 for chunk in slices:
200 for chunk in slices:
201 if ':' in chunk:
201 if ':' in chunk:
202 ini,fin = map(int,chunk.split(':'))
202 ini,fin = map(int,chunk.split(':'))
203 elif '-' in chunk:
203 elif '-' in chunk:
204 ini,fin = map(int,chunk.split('-'))
204 ini,fin = map(int,chunk.split('-'))
205 fin += 1
205 fin += 1
206 else:
206 else:
207 ini = int(chunk)
207 ini = int(chunk)
208 fin = ini+1
208 fin = ini+1
209 cmds.append(hist[ini:fin])
209 cmds.append(hist[ini:fin])
210 return cmds
210 return cmds
211
211
212 def _ofind(self, oname, namespaces=None):
212 def _ofind(self, oname, namespaces=None):
213 """Find an object in the available namespaces.
213 """Find an object in the available namespaces.
214
214
215 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
215 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
216
216
217 Has special code to detect magic functions.
217 Has special code to detect magic functions.
218 """
218 """
219 oname = oname.strip()
219 oname = oname.strip()
220 alias_ns = None
220 alias_ns = None
221 if namespaces is None:
221 if namespaces is None:
222 # Namespaces to search in:
222 # Namespaces to search in:
223 # Put them in a list. The order is important so that we
223 # Put them in a list. The order is important so that we
224 # find things in the same order that Python finds them.
224 # find things in the same order that Python finds them.
225 namespaces = [ ('Interactive', self.shell.user_ns),
225 namespaces = [ ('Interactive', self.shell.user_ns),
226 ('IPython internal', self.shell.internal_ns),
226 ('IPython internal', self.shell.internal_ns),
227 ('Python builtin', __builtin__.__dict__),
227 ('Python builtin', __builtin__.__dict__),
228 ('Alias', self.shell.alias_manager.alias_table),
228 ('Alias', self.shell.alias_manager.alias_table),
229 ]
229 ]
230 alias_ns = self.shell.alias_manager.alias_table
230 alias_ns = self.shell.alias_manager.alias_table
231
231
232 # initialize results to 'null'
232 # initialize results to 'null'
233 found = False; obj = None; ospace = None; ds = None;
233 found = False; obj = None; ospace = None; ds = None;
234 ismagic = False; isalias = False; parent = None
234 ismagic = False; isalias = False; parent = None
235
235
236 # We need to special-case 'print', which as of python2.6 registers as a
236 # We need to special-case 'print', which as of python2.6 registers as a
237 # function but should only be treated as one if print_function was
237 # function but should only be treated as one if print_function was
238 # loaded with a future import. In this case, just bail.
238 # loaded with a future import. In this case, just bail.
239 if (oname == 'print' and not (self.shell.compile.compiler.flags &
239 if (oname == 'print' and not (self.shell.compile.compiler.flags &
240 __future__.CO_FUTURE_PRINT_FUNCTION)):
240 __future__.CO_FUTURE_PRINT_FUNCTION)):
241 return {'found':found, 'obj':obj, 'namespace':ospace,
241 return {'found':found, 'obj':obj, 'namespace':ospace,
242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
243
243
244 # Look for the given name by splitting it in parts. If the head is
244 # Look for the given name by splitting it in parts. If the head is
245 # found, then we look for all the remaining parts as members, and only
245 # found, then we look for all the remaining parts as members, and only
246 # declare success if we can find them all.
246 # declare success if we can find them all.
247 oname_parts = oname.split('.')
247 oname_parts = oname.split('.')
248 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
248 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
249 for nsname,ns in namespaces:
249 for nsname,ns in namespaces:
250 try:
250 try:
251 obj = ns[oname_head]
251 obj = ns[oname_head]
252 except KeyError:
252 except KeyError:
253 continue
253 continue
254 else:
254 else:
255 #print 'oname_rest:', oname_rest # dbg
255 #print 'oname_rest:', oname_rest # dbg
256 for part in oname_rest:
256 for part in oname_rest:
257 try:
257 try:
258 parent = obj
258 parent = obj
259 obj = getattr(obj,part)
259 obj = getattr(obj,part)
260 except:
260 except:
261 # Blanket except b/c some badly implemented objects
261 # Blanket except b/c some badly implemented objects
262 # allow __getattr__ to raise exceptions other than
262 # allow __getattr__ to raise exceptions other than
263 # AttributeError, which then crashes IPython.
263 # AttributeError, which then crashes IPython.
264 break
264 break
265 else:
265 else:
266 # If we finish the for loop (no break), we got all members
266 # If we finish the for loop (no break), we got all members
267 found = True
267 found = True
268 ospace = nsname
268 ospace = nsname
269 if ns == alias_ns:
269 if ns == alias_ns:
270 isalias = True
270 isalias = True
271 break # namespace loop
271 break # namespace loop
272
272
273 # Try to see if it's magic
273 # Try to see if it's magic
274 if not found:
274 if not found:
275 if oname.startswith(ESC_MAGIC):
275 if oname.startswith(ESC_MAGIC):
276 oname = oname[1:]
276 oname = oname[1:]
277 obj = getattr(self,'magic_'+oname,None)
277 obj = getattr(self,'magic_'+oname,None)
278 if obj is not None:
278 if obj is not None:
279 found = True
279 found = True
280 ospace = 'IPython internal'
280 ospace = 'IPython internal'
281 ismagic = True
281 ismagic = True
282
282
283 # Last try: special-case some literals like '', [], {}, etc:
283 # Last try: special-case some literals like '', [], {}, etc:
284 if not found and oname_head in ["''",'""','[]','{}','()']:
284 if not found and oname_head in ["''",'""','[]','{}','()']:
285 obj = eval(oname_head)
285 obj = eval(oname_head)
286 found = True
286 found = True
287 ospace = 'Interactive'
287 ospace = 'Interactive'
288
288
289 return {'found':found, 'obj':obj, 'namespace':ospace,
289 return {'found':found, 'obj':obj, 'namespace':ospace,
290 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
290 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
291
291
292 def arg_err(self,func):
292 def arg_err(self,func):
293 """Print docstring if incorrect arguments were passed"""
293 """Print docstring if incorrect arguments were passed"""
294 print 'Error in arguments:'
294 print 'Error in arguments:'
295 print oinspect.getdoc(func)
295 print oinspect.getdoc(func)
296
296
297 def format_latex(self,strng):
297 def format_latex(self,strng):
298 """Format a string for latex inclusion."""
298 """Format a string for latex inclusion."""
299
299
300 # Characters that need to be escaped for latex:
300 # Characters that need to be escaped for latex:
301 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
301 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
302 # Magic command names as headers:
302 # Magic command names as headers:
303 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
303 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
304 re.MULTILINE)
304 re.MULTILINE)
305 # Magic commands
305 # Magic commands
306 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
306 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
307 re.MULTILINE)
307 re.MULTILINE)
308 # Paragraph continue
308 # Paragraph continue
309 par_re = re.compile(r'\\$',re.MULTILINE)
309 par_re = re.compile(r'\\$',re.MULTILINE)
310
310
311 # The "\n" symbol
311 # The "\n" symbol
312 newline_re = re.compile(r'\\n')
312 newline_re = re.compile(r'\\n')
313
313
314 # Now build the string for output:
314 # Now build the string for output:
315 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
315 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
316 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
316 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
317 strng)
317 strng)
318 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
318 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
319 strng = par_re.sub(r'\\\\',strng)
319 strng = par_re.sub(r'\\\\',strng)
320 strng = escape_re.sub(r'\\\1',strng)
320 strng = escape_re.sub(r'\\\1',strng)
321 strng = newline_re.sub(r'\\textbackslash{}n',strng)
321 strng = newline_re.sub(r'\\textbackslash{}n',strng)
322 return strng
322 return strng
323
323
324 def format_screen(self,strng):
324 def format_screen(self,strng):
325 """Format a string for screen printing.
325 """Format a string for screen printing.
326
326
327 This removes some latex-type format codes."""
327 This removes some latex-type format codes."""
328 # Paragraph continue
328 # Paragraph continue
329 par_re = re.compile(r'\\$',re.MULTILINE)
329 par_re = re.compile(r'\\$',re.MULTILINE)
330 strng = par_re.sub('',strng)
330 strng = par_re.sub('',strng)
331 return strng
331 return strng
332
332
333 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
333 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
334 """Parse options passed to an argument string.
334 """Parse options passed to an argument string.
335
335
336 The interface is similar to that of getopt(), but it returns back a
336 The interface is similar to that of getopt(), but it returns back a
337 Struct with the options as keys and the stripped argument string still
337 Struct with the options as keys and the stripped argument string still
338 as a string.
338 as a string.
339
339
340 arg_str is quoted as a true sys.argv vector by using shlex.split.
340 arg_str is quoted as a true sys.argv vector by using shlex.split.
341 This allows us to easily expand variables, glob files, quote
341 This allows us to easily expand variables, glob files, quote
342 arguments, etc.
342 arguments, etc.
343
343
344 Options:
344 Options:
345 -mode: default 'string'. If given as 'list', the argument string is
345 -mode: default 'string'. If given as 'list', the argument string is
346 returned as a list (split on whitespace) instead of a string.
346 returned as a list (split on whitespace) instead of a string.
347
347
348 -list_all: put all option values in lists. Normally only options
348 -list_all: put all option values in lists. Normally only options
349 appearing more than once are put in a list.
349 appearing more than once are put in a list.
350
350
351 -posix (True): whether to split the input line in POSIX mode or not,
351 -posix (True): whether to split the input line in POSIX mode or not,
352 as per the conventions outlined in the shlex module from the
352 as per the conventions outlined in the shlex module from the
353 standard library."""
353 standard library."""
354
354
355 # inject default options at the beginning of the input line
355 # inject default options at the beginning of the input line
356 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
356 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
357 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
357 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
358
358
359 mode = kw.get('mode','string')
359 mode = kw.get('mode','string')
360 if mode not in ['string','list']:
360 if mode not in ['string','list']:
361 raise ValueError,'incorrect mode given: %s' % mode
361 raise ValueError,'incorrect mode given: %s' % mode
362 # Get options
362 # Get options
363 list_all = kw.get('list_all',0)
363 list_all = kw.get('list_all',0)
364 posix = kw.get('posix', os.name == 'posix')
364 posix = kw.get('posix', os.name == 'posix')
365
365
366 # Check if we have more than one argument to warrant extra processing:
366 # Check if we have more than one argument to warrant extra processing:
367 odict = {} # Dictionary with options
367 odict = {} # Dictionary with options
368 args = arg_str.split()
368 args = arg_str.split()
369 if len(args) >= 1:
369 if len(args) >= 1:
370 # If the list of inputs only has 0 or 1 thing in it, there's no
370 # If the list of inputs only has 0 or 1 thing in it, there's no
371 # need to look for options
371 # need to look for options
372 argv = arg_split(arg_str,posix)
372 argv = arg_split(arg_str,posix)
373 # Do regular option processing
373 # Do regular option processing
374 try:
374 try:
375 opts,args = getopt(argv,opt_str,*long_opts)
375 opts,args = getopt(argv,opt_str,*long_opts)
376 except GetoptError,e:
376 except GetoptError,e:
377 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
377 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
378 " ".join(long_opts)))
378 " ".join(long_opts)))
379 for o,a in opts:
379 for o,a in opts:
380 if o.startswith('--'):
380 if o.startswith('--'):
381 o = o[2:]
381 o = o[2:]
382 else:
382 else:
383 o = o[1:]
383 o = o[1:]
384 try:
384 try:
385 odict[o].append(a)
385 odict[o].append(a)
386 except AttributeError:
386 except AttributeError:
387 odict[o] = [odict[o],a]
387 odict[o] = [odict[o],a]
388 except KeyError:
388 except KeyError:
389 if list_all:
389 if list_all:
390 odict[o] = [a]
390 odict[o] = [a]
391 else:
391 else:
392 odict[o] = a
392 odict[o] = a
393
393
394 # Prepare opts,args for return
394 # Prepare opts,args for return
395 opts = Struct(odict)
395 opts = Struct(odict)
396 if mode == 'string':
396 if mode == 'string':
397 args = ' '.join(args)
397 args = ' '.join(args)
398
398
399 return opts,args
399 return opts,args
400
400
401 #......................................................................
401 #......................................................................
402 # And now the actual magic functions
402 # And now the actual magic functions
403
403
404 # Functions for IPython shell work (vars,funcs, config, etc)
404 # Functions for IPython shell work (vars,funcs, config, etc)
405 def magic_lsmagic(self, parameter_s = ''):
405 def magic_lsmagic(self, parameter_s = ''):
406 """List currently available magic functions."""
406 """List currently available magic functions."""
407 mesc = ESC_MAGIC
407 mesc = ESC_MAGIC
408 print 'Available magic functions:\n'+mesc+\
408 print 'Available magic functions:\n'+mesc+\
409 (' '+mesc).join(self.lsmagic())
409 (' '+mesc).join(self.lsmagic())
410 print '\n' + Magic.auto_status[self.shell.automagic]
410 print '\n' + Magic.auto_status[self.shell.automagic]
411 return None
411 return None
412
412
413 def magic_magic(self, parameter_s = ''):
413 def magic_magic(self, parameter_s = ''):
414 """Print information about the magic function system.
414 """Print information about the magic function system.
415
415
416 Supported formats: -latex, -brief, -rest
416 Supported formats: -latex, -brief, -rest
417 """
417 """
418
418
419 mode = ''
419 mode = ''
420 try:
420 try:
421 if parameter_s.split()[0] == '-latex':
421 if parameter_s.split()[0] == '-latex':
422 mode = 'latex'
422 mode = 'latex'
423 if parameter_s.split()[0] == '-brief':
423 if parameter_s.split()[0] == '-brief':
424 mode = 'brief'
424 mode = 'brief'
425 if parameter_s.split()[0] == '-rest':
425 if parameter_s.split()[0] == '-rest':
426 mode = 'rest'
426 mode = 'rest'
427 rest_docs = []
427 rest_docs = []
428 except:
428 except:
429 pass
429 pass
430
430
431 magic_docs = []
431 magic_docs = []
432 for fname in self.lsmagic():
432 for fname in self.lsmagic():
433 mname = 'magic_' + fname
433 mname = 'magic_' + fname
434 for space in (Magic,self,self.__class__):
434 for space in (Magic,self,self.__class__):
435 try:
435 try:
436 fn = space.__dict__[mname]
436 fn = space.__dict__[mname]
437 except KeyError:
437 except KeyError:
438 pass
438 pass
439 else:
439 else:
440 break
440 break
441 if mode == 'brief':
441 if mode == 'brief':
442 # only first line
442 # only first line
443 if fn.__doc__:
443 if fn.__doc__:
444 fndoc = fn.__doc__.split('\n',1)[0]
444 fndoc = fn.__doc__.split('\n',1)[0]
445 else:
445 else:
446 fndoc = 'No documentation'
446 fndoc = 'No documentation'
447 else:
447 else:
448 if fn.__doc__:
448 if fn.__doc__:
449 fndoc = fn.__doc__.rstrip()
449 fndoc = fn.__doc__.rstrip()
450 else:
450 else:
451 fndoc = 'No documentation'
451 fndoc = 'No documentation'
452
452
453
453
454 if mode == 'rest':
454 if mode == 'rest':
455 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
455 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
456 fname,fndoc))
456 fname,fndoc))
457
457
458 else:
458 else:
459 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
459 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
460 fname,fndoc))
460 fname,fndoc))
461
461
462 magic_docs = ''.join(magic_docs)
462 magic_docs = ''.join(magic_docs)
463
463
464 if mode == 'rest':
464 if mode == 'rest':
465 return "".join(rest_docs)
465 return "".join(rest_docs)
466
466
467 if mode == 'latex':
467 if mode == 'latex':
468 print self.format_latex(magic_docs)
468 print self.format_latex(magic_docs)
469 return
469 return
470 else:
470 else:
471 magic_docs = self.format_screen(magic_docs)
471 magic_docs = self.format_screen(magic_docs)
472 if mode == 'brief':
472 if mode == 'brief':
473 return magic_docs
473 return magic_docs
474
474
475 outmsg = """
475 outmsg = """
476 IPython's 'magic' functions
476 IPython's 'magic' functions
477 ===========================
477 ===========================
478
478
479 The magic function system provides a series of functions which allow you to
479 The magic function system provides a series of functions which allow you to
480 control the behavior of IPython itself, plus a lot of system-type
480 control the behavior of IPython itself, plus a lot of system-type
481 features. All these functions are prefixed with a % character, but parameters
481 features. All these functions are prefixed with a % character, but parameters
482 are given without parentheses or quotes.
482 are given without parentheses or quotes.
483
483
484 NOTE: If you have 'automagic' enabled (via the command line option or with the
484 NOTE: If you have 'automagic' enabled (via the command line option or with the
485 %automagic function), you don't need to type in the % explicitly. By default,
485 %automagic function), you don't need to type in the % explicitly. By default,
486 IPython ships with automagic on, so you should only rarely need the % escape.
486 IPython ships with automagic on, so you should only rarely need the % escape.
487
487
488 Example: typing '%cd mydir' (without the quotes) changes you working directory
488 Example: typing '%cd mydir' (without the quotes) changes you working directory
489 to 'mydir', if it exists.
489 to 'mydir', if it exists.
490
490
491 You can define your own magic functions to extend the system. See the supplied
491 You can define your own magic functions to extend the system. See the supplied
492 ipythonrc and example-magic.py files for details (in your ipython
492 ipythonrc and example-magic.py files for details (in your ipython
493 configuration directory, typically $HOME/.ipython/).
493 configuration directory, typically $HOME/.ipython/).
494
494
495 You can also define your own aliased names for magic functions. In your
495 You can also define your own aliased names for magic functions. In your
496 ipythonrc file, placing a line like:
496 ipythonrc file, placing a line like:
497
497
498 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
498 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
499
499
500 will define %pf as a new name for %profile.
500 will define %pf as a new name for %profile.
501
501
502 You can also call magics in code using the magic() function, which IPython
502 You can also call magics in code using the magic() function, which IPython
503 automatically adds to the builtin namespace. Type 'magic?' for details.
503 automatically adds to the builtin namespace. Type 'magic?' for details.
504
504
505 For a list of the available magic functions, use %lsmagic. For a description
505 For a list of the available magic functions, use %lsmagic. For a description
506 of any of them, type %magic_name?, e.g. '%cd?'.
506 of any of them, type %magic_name?, e.g. '%cd?'.
507
507
508 Currently the magic system has the following functions:\n"""
508 Currently the magic system has the following functions:\n"""
509
509
510 mesc = ESC_MAGIC
510 mesc = ESC_MAGIC
511 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
511 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
512 "\n\n%s%s\n\n%s" % (outmsg,
512 "\n\n%s%s\n\n%s" % (outmsg,
513 magic_docs,mesc,mesc,
513 magic_docs,mesc,mesc,
514 (' '+mesc).join(self.lsmagic()),
514 (' '+mesc).join(self.lsmagic()),
515 Magic.auto_status[self.shell.automagic] ) )
515 Magic.auto_status[self.shell.automagic] ) )
516 page.page(outmsg)
516 page.page(outmsg)
517
517
518 def magic_autoindent(self, parameter_s = ''):
518 def magic_autoindent(self, parameter_s = ''):
519 """Toggle autoindent on/off (if available)."""
519 """Toggle autoindent on/off (if available)."""
520
520
521 self.shell.set_autoindent()
521 self.shell.set_autoindent()
522 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
522 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
523
523
524 def magic_automagic(self, parameter_s = ''):
524 def magic_automagic(self, parameter_s = ''):
525 """Make magic functions callable without having to type the initial %.
525 """Make magic functions callable without having to type the initial %.
526
526
527 Without argumentsl toggles on/off (when off, you must call it as
527 Without argumentsl toggles on/off (when off, you must call it as
528 %automagic, of course). With arguments it sets the value, and you can
528 %automagic, of course). With arguments it sets the value, and you can
529 use any of (case insensitive):
529 use any of (case insensitive):
530
530
531 - on,1,True: to activate
531 - on,1,True: to activate
532
532
533 - off,0,False: to deactivate.
533 - off,0,False: to deactivate.
534
534
535 Note that magic functions have lowest priority, so if there's a
535 Note that magic functions have lowest priority, so if there's a
536 variable whose name collides with that of a magic fn, automagic won't
536 variable whose name collides with that of a magic fn, automagic won't
537 work for that function (you get the variable instead). However, if you
537 work for that function (you get the variable instead). However, if you
538 delete the variable (del var), the previously shadowed magic function
538 delete the variable (del var), the previously shadowed magic function
539 becomes visible to automagic again."""
539 becomes visible to automagic again."""
540
540
541 arg = parameter_s.lower()
541 arg = parameter_s.lower()
542 if parameter_s in ('on','1','true'):
542 if parameter_s in ('on','1','true'):
543 self.shell.automagic = True
543 self.shell.automagic = True
544 elif parameter_s in ('off','0','false'):
544 elif parameter_s in ('off','0','false'):
545 self.shell.automagic = False
545 self.shell.automagic = False
546 else:
546 else:
547 self.shell.automagic = not self.shell.automagic
547 self.shell.automagic = not self.shell.automagic
548 print '\n' + Magic.auto_status[self.shell.automagic]
548 print '\n' + Magic.auto_status[self.shell.automagic]
549
549
550 @testdec.skip_doctest
550 @testdec.skip_doctest
551 def magic_autocall(self, parameter_s = ''):
551 def magic_autocall(self, parameter_s = ''):
552 """Make functions callable without having to type parentheses.
552 """Make functions callable without having to type parentheses.
553
553
554 Usage:
554 Usage:
555
555
556 %autocall [mode]
556 %autocall [mode]
557
557
558 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
558 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
559 value is toggled on and off (remembering the previous state).
559 value is toggled on and off (remembering the previous state).
560
560
561 In more detail, these values mean:
561 In more detail, these values mean:
562
562
563 0 -> fully disabled
563 0 -> fully disabled
564
564
565 1 -> active, but do not apply if there are no arguments on the line.
565 1 -> active, but do not apply if there are no arguments on the line.
566
566
567 In this mode, you get:
567 In this mode, you get:
568
568
569 In [1]: callable
569 In [1]: callable
570 Out[1]: <built-in function callable>
570 Out[1]: <built-in function callable>
571
571
572 In [2]: callable 'hello'
572 In [2]: callable 'hello'
573 ------> callable('hello')
573 ------> callable('hello')
574 Out[2]: False
574 Out[2]: False
575
575
576 2 -> Active always. Even if no arguments are present, the callable
576 2 -> Active always. Even if no arguments are present, the callable
577 object is called:
577 object is called:
578
578
579 In [2]: float
579 In [2]: float
580 ------> float()
580 ------> float()
581 Out[2]: 0.0
581 Out[2]: 0.0
582
582
583 Note that even with autocall off, you can still use '/' at the start of
583 Note that even with autocall off, you can still use '/' at the start of
584 a line to treat the first argument on the command line as a function
584 a line to treat the first argument on the command line as a function
585 and add parentheses to it:
585 and add parentheses to it:
586
586
587 In [8]: /str 43
587 In [8]: /str 43
588 ------> str(43)
588 ------> str(43)
589 Out[8]: '43'
589 Out[8]: '43'
590
590
591 # all-random (note for auto-testing)
591 # all-random (note for auto-testing)
592 """
592 """
593
593
594 if parameter_s:
594 if parameter_s:
595 arg = int(parameter_s)
595 arg = int(parameter_s)
596 else:
596 else:
597 arg = 'toggle'
597 arg = 'toggle'
598
598
599 if not arg in (0,1,2,'toggle'):
599 if not arg in (0,1,2,'toggle'):
600 error('Valid modes: (0->Off, 1->Smart, 2->Full')
600 error('Valid modes: (0->Off, 1->Smart, 2->Full')
601 return
601 return
602
602
603 if arg in (0,1,2):
603 if arg in (0,1,2):
604 self.shell.autocall = arg
604 self.shell.autocall = arg
605 else: # toggle
605 else: # toggle
606 if self.shell.autocall:
606 if self.shell.autocall:
607 self._magic_state.autocall_save = self.shell.autocall
607 self._magic_state.autocall_save = self.shell.autocall
608 self.shell.autocall = 0
608 self.shell.autocall = 0
609 else:
609 else:
610 try:
610 try:
611 self.shell.autocall = self._magic_state.autocall_save
611 self.shell.autocall = self._magic_state.autocall_save
612 except AttributeError:
612 except AttributeError:
613 self.shell.autocall = self._magic_state.autocall_save = 1
613 self.shell.autocall = self._magic_state.autocall_save = 1
614
614
615 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
615 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
616
616
617
617
618 def magic_page(self, parameter_s=''):
618 def magic_page(self, parameter_s=''):
619 """Pretty print the object and display it through a pager.
619 """Pretty print the object and display it through a pager.
620
620
621 %page [options] OBJECT
621 %page [options] OBJECT
622
622
623 If no object is given, use _ (last output).
623 If no object is given, use _ (last output).
624
624
625 Options:
625 Options:
626
626
627 -r: page str(object), don't pretty-print it."""
627 -r: page str(object), don't pretty-print it."""
628
628
629 # After a function contributed by Olivier Aubert, slightly modified.
629 # After a function contributed by Olivier Aubert, slightly modified.
630
630
631 # Process options/args
631 # Process options/args
632 opts,args = self.parse_options(parameter_s,'r')
632 opts,args = self.parse_options(parameter_s,'r')
633 raw = 'r' in opts
633 raw = 'r' in opts
634
634
635 oname = args and args or '_'
635 oname = args and args or '_'
636 info = self._ofind(oname)
636 info = self._ofind(oname)
637 if info['found']:
637 if info['found']:
638 txt = (raw and str or pformat)( info['obj'] )
638 txt = (raw and str or pformat)( info['obj'] )
639 page.page(txt)
639 page.page(txt)
640 else:
640 else:
641 print 'Object `%s` not found' % oname
641 print 'Object `%s` not found' % oname
642
642
643 def magic_profile(self, parameter_s=''):
643 def magic_profile(self, parameter_s=''):
644 """Print your currently active IPython profile."""
644 """Print your currently active IPython profile."""
645 if self.shell.profile:
645 if self.shell.profile:
646 printpl('Current IPython profile: $self.shell.profile.')
646 printpl('Current IPython profile: $self.shell.profile.')
647 else:
647 else:
648 print 'No profile active.'
648 print 'No profile active.'
649
649
650 def magic_pinfo(self, parameter_s='', namespaces=None):
650 def magic_pinfo(self, parameter_s='', namespaces=None):
651 """Provide detailed information about an object.
651 """Provide detailed information about an object.
652
652
653 '%pinfo object' is just a synonym for object? or ?object."""
653 '%pinfo object' is just a synonym for object? or ?object."""
654
654
655 #print 'pinfo par: <%s>' % parameter_s # dbg
655 #print 'pinfo par: <%s>' % parameter_s # dbg
656
656
657
657
658 # detail_level: 0 -> obj? , 1 -> obj??
658 # detail_level: 0 -> obj? , 1 -> obj??
659 detail_level = 0
659 detail_level = 0
660 # We need to detect if we got called as 'pinfo pinfo foo', which can
660 # We need to detect if we got called as 'pinfo pinfo foo', which can
661 # happen if the user types 'pinfo foo?' at the cmd line.
661 # happen if the user types 'pinfo foo?' at the cmd line.
662 pinfo,qmark1,oname,qmark2 = \
662 pinfo,qmark1,oname,qmark2 = \
663 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
663 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
664 if pinfo or qmark1 or qmark2:
664 if pinfo or qmark1 or qmark2:
665 detail_level = 1
665 detail_level = 1
666 if "*" in oname:
666 if "*" in oname:
667 self.magic_psearch(oname)
667 self.magic_psearch(oname)
668 else:
668 else:
669 self._inspect('pinfo', oname, detail_level=detail_level,
669 self._inspect('pinfo', oname, detail_level=detail_level,
670 namespaces=namespaces)
670 namespaces=namespaces)
671
671
672 def magic_pdef(self, parameter_s='', namespaces=None):
672 def magic_pdef(self, parameter_s='', namespaces=None):
673 """Print the definition header for any callable object.
673 """Print the definition header for any callable object.
674
674
675 If the object is a class, print the constructor information."""
675 If the object is a class, print the constructor information."""
676 self._inspect('pdef',parameter_s, namespaces)
676 self._inspect('pdef',parameter_s, namespaces)
677
677
678 def magic_pdoc(self, parameter_s='', namespaces=None):
678 def magic_pdoc(self, parameter_s='', namespaces=None):
679 """Print the docstring for an object.
679 """Print the docstring for an object.
680
680
681 If the given object is a class, it will print both the class and the
681 If the given object is a class, it will print both the class and the
682 constructor docstrings."""
682 constructor docstrings."""
683 self._inspect('pdoc',parameter_s, namespaces)
683 self._inspect('pdoc',parameter_s, namespaces)
684
684
685 def magic_psource(self, parameter_s='', namespaces=None):
685 def magic_psource(self, parameter_s='', namespaces=None):
686 """Print (or run through pager) the source code for an object."""
686 """Print (or run through pager) the source code for an object."""
687 self._inspect('psource',parameter_s, namespaces)
687 self._inspect('psource',parameter_s, namespaces)
688
688
689 def magic_pfile(self, parameter_s=''):
689 def magic_pfile(self, parameter_s=''):
690 """Print (or run through pager) the file where an object is defined.
690 """Print (or run through pager) the file where an object is defined.
691
691
692 The file opens at the line where the object definition begins. IPython
692 The file opens at the line where the object definition begins. IPython
693 will honor the environment variable PAGER if set, and otherwise will
693 will honor the environment variable PAGER if set, and otherwise will
694 do its best to print the file in a convenient form.
694 do its best to print the file in a convenient form.
695
695
696 If the given argument is not an object currently defined, IPython will
696 If the given argument is not an object currently defined, IPython will
697 try to interpret it as a filename (automatically adding a .py extension
697 try to interpret it as a filename (automatically adding a .py extension
698 if needed). You can thus use %pfile as a syntax highlighting code
698 if needed). You can thus use %pfile as a syntax highlighting code
699 viewer."""
699 viewer."""
700
700
701 # first interpret argument as an object name
701 # first interpret argument as an object name
702 out = self._inspect('pfile',parameter_s)
702 out = self._inspect('pfile',parameter_s)
703 # if not, try the input as a filename
703 # if not, try the input as a filename
704 if out == 'not found':
704 if out == 'not found':
705 try:
705 try:
706 filename = get_py_filename(parameter_s)
706 filename = get_py_filename(parameter_s)
707 except IOError,msg:
707 except IOError,msg:
708 print msg
708 print msg
709 return
709 return
710 page.page(self.shell.inspector.format(file(filename).read()))
710 page.page(self.shell.inspector.format(file(filename).read()))
711
711
712 def _inspect(self,meth,oname,namespaces=None,**kw):
712 def _inspect(self,meth,oname,namespaces=None,**kw):
713 """Generic interface to the inspector system.
713 """Generic interface to the inspector system.
714
714
715 This function is meant to be called by pdef, pdoc & friends."""
715 This function is meant to be called by pdef, pdoc & friends."""
716
716
717 #oname = oname.strip()
717 #oname = oname.strip()
718 #print '1- oname: <%r>' % oname # dbg
718 #print '1- oname: <%r>' % oname # dbg
719 try:
719 try:
720 oname = oname.strip().encode('ascii')
720 oname = oname.strip().encode('ascii')
721 #print '2- oname: <%r>' % oname # dbg
721 #print '2- oname: <%r>' % oname # dbg
722 except UnicodeEncodeError:
722 except UnicodeEncodeError:
723 print 'Python identifiers can only contain ascii characters.'
723 print 'Python identifiers can only contain ascii characters.'
724 return 'not found'
724 return 'not found'
725
725
726 info = Struct(self._ofind(oname, namespaces))
726 info = Struct(self._ofind(oname, namespaces))
727
727
728 if info.found:
728 if info.found:
729 try:
729 try:
730 IPython.utils.generics.inspect_object(info.obj)
730 IPython.utils.generics.inspect_object(info.obj)
731 return
731 return
732 except TryNext:
732 except TryNext:
733 pass
733 pass
734 # Get the docstring of the class property if it exists.
734 # Get the docstring of the class property if it exists.
735 path = oname.split('.')
735 path = oname.split('.')
736 root = '.'.join(path[:-1])
736 root = '.'.join(path[:-1])
737 if info.parent is not None:
737 if info.parent is not None:
738 try:
738 try:
739 target = getattr(info.parent, '__class__')
739 target = getattr(info.parent, '__class__')
740 # The object belongs to a class instance.
740 # The object belongs to a class instance.
741 try:
741 try:
742 target = getattr(target, path[-1])
742 target = getattr(target, path[-1])
743 # The class defines the object.
743 # The class defines the object.
744 if isinstance(target, property):
744 if isinstance(target, property):
745 oname = root + '.__class__.' + path[-1]
745 oname = root + '.__class__.' + path[-1]
746 info = Struct(self._ofind(oname))
746 info = Struct(self._ofind(oname))
747 except AttributeError: pass
747 except AttributeError: pass
748 except AttributeError: pass
748 except AttributeError: pass
749
749
750 pmethod = getattr(self.shell.inspector,meth)
750 pmethod = getattr(self.shell.inspector,meth)
751 formatter = info.ismagic and self.format_screen or None
751 formatter = info.ismagic and self.format_screen or None
752 if meth == 'pdoc':
752 if meth == 'pdoc':
753 pmethod(info.obj,oname,formatter)
753 pmethod(info.obj,oname,formatter)
754 elif meth == 'pinfo':
754 elif meth == 'pinfo':
755 pmethod(info.obj,oname,formatter,info,**kw)
755 pmethod(info.obj,oname,formatter,info,**kw)
756 else:
756 else:
757 pmethod(info.obj,oname)
757 pmethod(info.obj,oname)
758 else:
758 else:
759 print 'Object `%s` not found.' % oname
759 print 'Object `%s` not found.' % oname
760 return 'not found' # so callers can take other action
760 return 'not found' # so callers can take other action
761
761
762 def magic_psearch(self, parameter_s=''):
762 def magic_psearch(self, parameter_s=''):
763 """Search for object in namespaces by wildcard.
763 """Search for object in namespaces by wildcard.
764
764
765 %psearch [options] PATTERN [OBJECT TYPE]
765 %psearch [options] PATTERN [OBJECT TYPE]
766
766
767 Note: ? can be used as a synonym for %psearch, at the beginning or at
767 Note: ? can be used as a synonym for %psearch, at the beginning or at
768 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
768 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
769 rest of the command line must be unchanged (options come first), so
769 rest of the command line must be unchanged (options come first), so
770 for example the following forms are equivalent
770 for example the following forms are equivalent
771
771
772 %psearch -i a* function
772 %psearch -i a* function
773 -i a* function?
773 -i a* function?
774 ?-i a* function
774 ?-i a* function
775
775
776 Arguments:
776 Arguments:
777
777
778 PATTERN
778 PATTERN
779
779
780 where PATTERN is a string containing * as a wildcard similar to its
780 where PATTERN is a string containing * as a wildcard similar to its
781 use in a shell. The pattern is matched in all namespaces on the
781 use in a shell. The pattern is matched in all namespaces on the
782 search path. By default objects starting with a single _ are not
782 search path. By default objects starting with a single _ are not
783 matched, many IPython generated objects have a single
783 matched, many IPython generated objects have a single
784 underscore. The default is case insensitive matching. Matching is
784 underscore. The default is case insensitive matching. Matching is
785 also done on the attributes of objects and not only on the objects
785 also done on the attributes of objects and not only on the objects
786 in a module.
786 in a module.
787
787
788 [OBJECT TYPE]
788 [OBJECT TYPE]
789
789
790 Is the name of a python type from the types module. The name is
790 Is the name of a python type from the types module. The name is
791 given in lowercase without the ending type, ex. StringType is
791 given in lowercase without the ending type, ex. StringType is
792 written string. By adding a type here only objects matching the
792 written string. By adding a type here only objects matching the
793 given type are matched. Using all here makes the pattern match all
793 given type are matched. Using all here makes the pattern match all
794 types (this is the default).
794 types (this is the default).
795
795
796 Options:
796 Options:
797
797
798 -a: makes the pattern match even objects whose names start with a
798 -a: makes the pattern match even objects whose names start with a
799 single underscore. These names are normally ommitted from the
799 single underscore. These names are normally ommitted from the
800 search.
800 search.
801
801
802 -i/-c: make the pattern case insensitive/sensitive. If neither of
802 -i/-c: make the pattern case insensitive/sensitive. If neither of
803 these options is given, the default is read from your ipythonrc
803 these options is given, the default is read from your ipythonrc
804 file. The option name which sets this value is
804 file. The option name which sets this value is
805 'wildcards_case_sensitive'. If this option is not specified in your
805 'wildcards_case_sensitive'. If this option is not specified in your
806 ipythonrc file, IPython's internal default is to do a case sensitive
806 ipythonrc file, IPython's internal default is to do a case sensitive
807 search.
807 search.
808
808
809 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
809 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
810 specifiy can be searched in any of the following namespaces:
810 specifiy can be searched in any of the following namespaces:
811 'builtin', 'user', 'user_global','internal', 'alias', where
811 'builtin', 'user', 'user_global','internal', 'alias', where
812 'builtin' and 'user' are the search defaults. Note that you should
812 'builtin' and 'user' are the search defaults. Note that you should
813 not use quotes when specifying namespaces.
813 not use quotes when specifying namespaces.
814
814
815 'Builtin' contains the python module builtin, 'user' contains all
815 'Builtin' contains the python module builtin, 'user' contains all
816 user data, 'alias' only contain the shell aliases and no python
816 user data, 'alias' only contain the shell aliases and no python
817 objects, 'internal' contains objects used by IPython. The
817 objects, 'internal' contains objects used by IPython. The
818 'user_global' namespace is only used by embedded IPython instances,
818 'user_global' namespace is only used by embedded IPython instances,
819 and it contains module-level globals. You can add namespaces to the
819 and it contains module-level globals. You can add namespaces to the
820 search with -s or exclude them with -e (these options can be given
820 search with -s or exclude them with -e (these options can be given
821 more than once).
821 more than once).
822
822
823 Examples:
823 Examples:
824
824
825 %psearch a* -> objects beginning with an a
825 %psearch a* -> objects beginning with an a
826 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
826 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
827 %psearch a* function -> all functions beginning with an a
827 %psearch a* function -> all functions beginning with an a
828 %psearch re.e* -> objects beginning with an e in module re
828 %psearch re.e* -> objects beginning with an e in module re
829 %psearch r*.e* -> objects that start with e in modules starting in r
829 %psearch r*.e* -> objects that start with e in modules starting in r
830 %psearch r*.* string -> all strings in modules beginning with r
830 %psearch r*.* string -> all strings in modules beginning with r
831
831
832 Case sensitve search:
832 Case sensitve search:
833
833
834 %psearch -c a* list all object beginning with lower case a
834 %psearch -c a* list all object beginning with lower case a
835
835
836 Show objects beginning with a single _:
836 Show objects beginning with a single _:
837
837
838 %psearch -a _* list objects beginning with a single underscore"""
838 %psearch -a _* list objects beginning with a single underscore"""
839 try:
839 try:
840 parameter_s = parameter_s.encode('ascii')
840 parameter_s = parameter_s.encode('ascii')
841 except UnicodeEncodeError:
841 except UnicodeEncodeError:
842 print 'Python identifiers can only contain ascii characters.'
842 print 'Python identifiers can only contain ascii characters.'
843 return
843 return
844
844
845 # default namespaces to be searched
845 # default namespaces to be searched
846 def_search = ['user','builtin']
846 def_search = ['user','builtin']
847
847
848 # Process options/args
848 # Process options/args
849 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
849 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
850 opt = opts.get
850 opt = opts.get
851 shell = self.shell
851 shell = self.shell
852 psearch = shell.inspector.psearch
852 psearch = shell.inspector.psearch
853
853
854 # select case options
854 # select case options
855 if opts.has_key('i'):
855 if opts.has_key('i'):
856 ignore_case = True
856 ignore_case = True
857 elif opts.has_key('c'):
857 elif opts.has_key('c'):
858 ignore_case = False
858 ignore_case = False
859 else:
859 else:
860 ignore_case = not shell.wildcards_case_sensitive
860 ignore_case = not shell.wildcards_case_sensitive
861
861
862 # Build list of namespaces to search from user options
862 # Build list of namespaces to search from user options
863 def_search.extend(opt('s',[]))
863 def_search.extend(opt('s',[]))
864 ns_exclude = ns_exclude=opt('e',[])
864 ns_exclude = ns_exclude=opt('e',[])
865 ns_search = [nm for nm in def_search if nm not in ns_exclude]
865 ns_search = [nm for nm in def_search if nm not in ns_exclude]
866
866
867 # Call the actual search
867 # Call the actual search
868 try:
868 try:
869 psearch(args,shell.ns_table,ns_search,
869 psearch(args,shell.ns_table,ns_search,
870 show_all=opt('a'),ignore_case=ignore_case)
870 show_all=opt('a'),ignore_case=ignore_case)
871 except:
871 except:
872 shell.showtraceback()
872 shell.showtraceback()
873
873
874 def magic_who_ls(self, parameter_s=''):
874 def magic_who_ls(self, parameter_s=''):
875 """Return a sorted list of all interactive variables.
875 """Return a sorted list of all interactive variables.
876
876
877 If arguments are given, only variables of types matching these
877 If arguments are given, only variables of types matching these
878 arguments are returned."""
878 arguments are returned."""
879
879
880 user_ns = self.shell.user_ns
880 user_ns = self.shell.user_ns
881 internal_ns = self.shell.internal_ns
881 internal_ns = self.shell.internal_ns
882 user_ns_hidden = self.shell.user_ns_hidden
882 user_ns_hidden = self.shell.user_ns_hidden
883 out = [ i for i in user_ns
883 out = [ i for i in user_ns
884 if not i.startswith('_') \
884 if not i.startswith('_') \
885 and not (i in internal_ns or i in user_ns_hidden) ]
885 and not (i in internal_ns or i in user_ns_hidden) ]
886
886
887 typelist = parameter_s.split()
887 typelist = parameter_s.split()
888 if typelist:
888 if typelist:
889 typeset = set(typelist)
889 typeset = set(typelist)
890 out = [i for i in out if type(i).__name__ in typeset]
890 out = [i for i in out if type(i).__name__ in typeset]
891
891
892 out.sort()
892 out.sort()
893 return out
893 return out
894
894
895 def magic_who(self, parameter_s=''):
895 def magic_who(self, parameter_s=''):
896 """Print all interactive variables, with some minimal formatting.
896 """Print all interactive variables, with some minimal formatting.
897
897
898 If any arguments are given, only variables whose type matches one of
898 If any arguments are given, only variables whose type matches one of
899 these are printed. For example:
899 these are printed. For example:
900
900
901 %who function str
901 %who function str
902
902
903 will only list functions and strings, excluding all other types of
903 will only list functions and strings, excluding all other types of
904 variables. To find the proper type names, simply use type(var) at a
904 variables. To find the proper type names, simply use type(var) at a
905 command line to see how python prints type names. For example:
905 command line to see how python prints type names. For example:
906
906
907 In [1]: type('hello')\\
907 In [1]: type('hello')\\
908 Out[1]: <type 'str'>
908 Out[1]: <type 'str'>
909
909
910 indicates that the type name for strings is 'str'.
910 indicates that the type name for strings is 'str'.
911
911
912 %who always excludes executed names loaded through your configuration
912 %who always excludes executed names loaded through your configuration
913 file and things which are internal to IPython.
913 file and things which are internal to IPython.
914
914
915 This is deliberate, as typically you may load many modules and the
915 This is deliberate, as typically you may load many modules and the
916 purpose of %who is to show you only what you've manually defined."""
916 purpose of %who is to show you only what you've manually defined."""
917
917
918 varlist = self.magic_who_ls(parameter_s)
918 varlist = self.magic_who_ls(parameter_s)
919 if not varlist:
919 if not varlist:
920 if parameter_s:
920 if parameter_s:
921 print 'No variables match your requested type.'
921 print 'No variables match your requested type.'
922 else:
922 else:
923 print 'Interactive namespace is empty.'
923 print 'Interactive namespace is empty.'
924 return
924 return
925
925
926 # if we have variables, move on...
926 # if we have variables, move on...
927 count = 0
927 count = 0
928 for i in varlist:
928 for i in varlist:
929 print i+'\t',
929 print i+'\t',
930 count += 1
930 count += 1
931 if count > 8:
931 if count > 8:
932 count = 0
932 count = 0
933 print
933 print
934 print
934 print
935
935
936 def magic_whos(self, parameter_s=''):
936 def magic_whos(self, parameter_s=''):
937 """Like %who, but gives some extra information about each variable.
937 """Like %who, but gives some extra information about each variable.
938
938
939 The same type filtering of %who can be applied here.
939 The same type filtering of %who can be applied here.
940
940
941 For all variables, the type is printed. Additionally it prints:
941 For all variables, the type is printed. Additionally it prints:
942
942
943 - For {},[],(): their length.
943 - For {},[],(): their length.
944
944
945 - For numpy and Numeric arrays, a summary with shape, number of
945 - For numpy and Numeric arrays, a summary with shape, number of
946 elements, typecode and size in memory.
946 elements, typecode and size in memory.
947
947
948 - Everything else: a string representation, snipping their middle if
948 - Everything else: a string representation, snipping their middle if
949 too long."""
949 too long."""
950
950
951 varnames = self.magic_who_ls(parameter_s)
951 varnames = self.magic_who_ls(parameter_s)
952 if not varnames:
952 if not varnames:
953 if parameter_s:
953 if parameter_s:
954 print 'No variables match your requested type.'
954 print 'No variables match your requested type.'
955 else:
955 else:
956 print 'Interactive namespace is empty.'
956 print 'Interactive namespace is empty.'
957 return
957 return
958
958
959 # if we have variables, move on...
959 # if we have variables, move on...
960
960
961 # for these types, show len() instead of data:
961 # for these types, show len() instead of data:
962 seq_types = [types.DictType,types.ListType,types.TupleType]
962 seq_types = [types.DictType,types.ListType,types.TupleType]
963
963
964 # for numpy/Numeric arrays, display summary info
964 # for numpy/Numeric arrays, display summary info
965 try:
965 try:
966 import numpy
966 import numpy
967 except ImportError:
967 except ImportError:
968 ndarray_type = None
968 ndarray_type = None
969 else:
969 else:
970 ndarray_type = numpy.ndarray.__name__
970 ndarray_type = numpy.ndarray.__name__
971 try:
971 try:
972 import Numeric
972 import Numeric
973 except ImportError:
973 except ImportError:
974 array_type = None
974 array_type = None
975 else:
975 else:
976 array_type = Numeric.ArrayType.__name__
976 array_type = Numeric.ArrayType.__name__
977
977
978 # Find all variable names and types so we can figure out column sizes
978 # Find all variable names and types so we can figure out column sizes
979 def get_vars(i):
979 def get_vars(i):
980 return self.shell.user_ns[i]
980 return self.shell.user_ns[i]
981
981
982 # some types are well known and can be shorter
982 # some types are well known and can be shorter
983 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
983 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
984 def type_name(v):
984 def type_name(v):
985 tn = type(v).__name__
985 tn = type(v).__name__
986 return abbrevs.get(tn,tn)
986 return abbrevs.get(tn,tn)
987
987
988 varlist = map(get_vars,varnames)
988 varlist = map(get_vars,varnames)
989
989
990 typelist = []
990 typelist = []
991 for vv in varlist:
991 for vv in varlist:
992 tt = type_name(vv)
992 tt = type_name(vv)
993
993
994 if tt=='instance':
994 if tt=='instance':
995 typelist.append( abbrevs.get(str(vv.__class__),
995 typelist.append( abbrevs.get(str(vv.__class__),
996 str(vv.__class__)))
996 str(vv.__class__)))
997 else:
997 else:
998 typelist.append(tt)
998 typelist.append(tt)
999
999
1000 # column labels and # of spaces as separator
1000 # column labels and # of spaces as separator
1001 varlabel = 'Variable'
1001 varlabel = 'Variable'
1002 typelabel = 'Type'
1002 typelabel = 'Type'
1003 datalabel = 'Data/Info'
1003 datalabel = 'Data/Info'
1004 colsep = 3
1004 colsep = 3
1005 # variable format strings
1005 # variable format strings
1006 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1006 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
1007 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1007 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
1008 aformat = "%s: %s elems, type `%s`, %s bytes"
1008 aformat = "%s: %s elems, type `%s`, %s bytes"
1009 # find the size of the columns to format the output nicely
1009 # find the size of the columns to format the output nicely
1010 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1010 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1011 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1011 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1012 # table header
1012 # table header
1013 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1013 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1014 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1014 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1015 # and the table itself
1015 # and the table itself
1016 kb = 1024
1016 kb = 1024
1017 Mb = 1048576 # kb**2
1017 Mb = 1048576 # kb**2
1018 for vname,var,vtype in zip(varnames,varlist,typelist):
1018 for vname,var,vtype in zip(varnames,varlist,typelist):
1019 print itpl(vformat),
1019 print itpl(vformat),
1020 if vtype in seq_types:
1020 if vtype in seq_types:
1021 print len(var)
1021 print len(var)
1022 elif vtype in [array_type,ndarray_type]:
1022 elif vtype in [array_type,ndarray_type]:
1023 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1023 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1024 if vtype==ndarray_type:
1024 if vtype==ndarray_type:
1025 # numpy
1025 # numpy
1026 vsize = var.size
1026 vsize = var.size
1027 vbytes = vsize*var.itemsize
1027 vbytes = vsize*var.itemsize
1028 vdtype = var.dtype
1028 vdtype = var.dtype
1029 else:
1029 else:
1030 # Numeric
1030 # Numeric
1031 vsize = Numeric.size(var)
1031 vsize = Numeric.size(var)
1032 vbytes = vsize*var.itemsize()
1032 vbytes = vsize*var.itemsize()
1033 vdtype = var.typecode()
1033 vdtype = var.typecode()
1034
1034
1035 if vbytes < 100000:
1035 if vbytes < 100000:
1036 print aformat % (vshape,vsize,vdtype,vbytes)
1036 print aformat % (vshape,vsize,vdtype,vbytes)
1037 else:
1037 else:
1038 print aformat % (vshape,vsize,vdtype,vbytes),
1038 print aformat % (vshape,vsize,vdtype,vbytes),
1039 if vbytes < Mb:
1039 if vbytes < Mb:
1040 print '(%s kb)' % (vbytes/kb,)
1040 print '(%s kb)' % (vbytes/kb,)
1041 else:
1041 else:
1042 print '(%s Mb)' % (vbytes/Mb,)
1042 print '(%s Mb)' % (vbytes/Mb,)
1043 else:
1043 else:
1044 try:
1044 try:
1045 vstr = str(var)
1045 vstr = str(var)
1046 except UnicodeEncodeError:
1046 except UnicodeEncodeError:
1047 vstr = unicode(var).encode(sys.getdefaultencoding(),
1047 vstr = unicode(var).encode(sys.getdefaultencoding(),
1048 'backslashreplace')
1048 'backslashreplace')
1049 vstr = vstr.replace('\n','\\n')
1049 vstr = vstr.replace('\n','\\n')
1050 if len(vstr) < 50:
1050 if len(vstr) < 50:
1051 print vstr
1051 print vstr
1052 else:
1052 else:
1053 printpl(vfmt_short)
1053 printpl(vfmt_short)
1054
1054
1055 def magic_reset(self, parameter_s=''):
1055 def magic_reset(self, parameter_s=''):
1056 """Resets the namespace by removing all names defined by the user.
1056 """Resets the namespace by removing all names defined by the user.
1057
1057
1058 Input/Output history are left around in case you need them.
1058 Input/Output history are left around in case you need them.
1059
1059
1060 Parameters
1060 Parameters
1061 ----------
1061 ----------
1062 -y : force reset without asking for confirmation.
1062 -y : force reset without asking for confirmation.
1063
1063
1064 Examples
1064 Examples
1065 --------
1065 --------
1066 In [6]: a = 1
1066 In [6]: a = 1
1067
1067
1068 In [7]: a
1068 In [7]: a
1069 Out[7]: 1
1069 Out[7]: 1
1070
1070
1071 In [8]: 'a' in _ip.user_ns
1071 In [8]: 'a' in _ip.user_ns
1072 Out[8]: True
1072 Out[8]: True
1073
1073
1074 In [9]: %reset -f
1074 In [9]: %reset -f
1075
1075
1076 In [10]: 'a' in _ip.user_ns
1076 In [10]: 'a' in _ip.user_ns
1077 Out[10]: False
1077 Out[10]: False
1078 """
1078 """
1079
1079
1080 if parameter_s == '-f':
1080 if parameter_s == '-f':
1081 ans = True
1081 ans = True
1082 else:
1082 else:
1083 ans = self.shell.ask_yes_no(
1083 ans = self.shell.ask_yes_no(
1084 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1084 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1085 if not ans:
1085 if not ans:
1086 print 'Nothing done.'
1086 print 'Nothing done.'
1087 return
1087 return
1088 user_ns = self.shell.user_ns
1088 user_ns = self.shell.user_ns
1089 for i in self.magic_who_ls():
1089 for i in self.magic_who_ls():
1090 del(user_ns[i])
1090 del(user_ns[i])
1091
1091
1092 # Also flush the private list of module references kept for script
1092 # Also flush the private list of module references kept for script
1093 # execution protection
1093 # execution protection
1094 self.shell.clear_main_mod_cache()
1094 self.shell.clear_main_mod_cache()
1095
1095
1096 def magic_reset_selective(self, parameter_s=''):
1096 def magic_reset_selective(self, parameter_s=''):
1097 """Resets the namespace by removing names defined by the user.
1097 """Resets the namespace by removing names defined by the user.
1098
1098
1099 Input/Output history are left around in case you need them.
1099 Input/Output history are left around in case you need them.
1100
1100
1101 %reset_selective [-f] regex
1101 %reset_selective [-f] regex
1102
1102
1103 No action is taken if regex is not included
1103 No action is taken if regex is not included
1104
1104
1105 Options
1105 Options
1106 -f : force reset without asking for confirmation.
1106 -f : force reset without asking for confirmation.
1107
1107
1108 Examples
1108 Examples
1109 --------
1109 --------
1110
1110
1111 We first fully reset the namespace so your output looks identical to
1111 We first fully reset the namespace so your output looks identical to
1112 this example for pedagogical reasons; in practice you do not need a
1112 this example for pedagogical reasons; in practice you do not need a
1113 full reset.
1113 full reset.
1114
1114
1115 In [1]: %reset -f
1115 In [1]: %reset -f
1116
1116
1117 Now, with a clean namespace we can make a few variables and use
1117 Now, with a clean namespace we can make a few variables and use
1118 %reset_selective to only delete names that match our regexp:
1118 %reset_selective to only delete names that match our regexp:
1119
1119
1120 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1120 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1121
1121
1122 In [3]: who_ls
1122 In [3]: who_ls
1123 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1123 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1124
1124
1125 In [4]: %reset_selective -f b[2-3]m
1125 In [4]: %reset_selective -f b[2-3]m
1126
1126
1127 In [5]: who_ls
1127 In [5]: who_ls
1128 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1128 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1129
1129
1130 In [6]: %reset_selective -f d
1130 In [6]: %reset_selective -f d
1131
1131
1132 In [7]: who_ls
1132 In [7]: who_ls
1133 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1133 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1134
1134
1135 In [8]: %reset_selective -f c
1135 In [8]: %reset_selective -f c
1136
1136
1137 In [9]: who_ls
1137 In [9]: who_ls
1138 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1138 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1139
1139
1140 In [10]: %reset_selective -f b
1140 In [10]: %reset_selective -f b
1141
1141
1142 In [11]: who_ls
1142 In [11]: who_ls
1143 Out[11]: ['a']
1143 Out[11]: ['a']
1144 """
1144 """
1145
1145
1146 opts, regex = self.parse_options(parameter_s,'f')
1146 opts, regex = self.parse_options(parameter_s,'f')
1147
1147
1148 if opts.has_key('f'):
1148 if opts.has_key('f'):
1149 ans = True
1149 ans = True
1150 else:
1150 else:
1151 ans = self.shell.ask_yes_no(
1151 ans = self.shell.ask_yes_no(
1152 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1152 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1153 if not ans:
1153 if not ans:
1154 print 'Nothing done.'
1154 print 'Nothing done.'
1155 return
1155 return
1156 user_ns = self.shell.user_ns
1156 user_ns = self.shell.user_ns
1157 if not regex:
1157 if not regex:
1158 print 'No regex pattern specified. Nothing done.'
1158 print 'No regex pattern specified. Nothing done.'
1159 return
1159 return
1160 else:
1160 else:
1161 try:
1161 try:
1162 m = re.compile(regex)
1162 m = re.compile(regex)
1163 except TypeError:
1163 except TypeError:
1164 raise TypeError('regex must be a string or compiled pattern')
1164 raise TypeError('regex must be a string or compiled pattern')
1165 for i in self.magic_who_ls():
1165 for i in self.magic_who_ls():
1166 if m.search(i):
1166 if m.search(i):
1167 del(user_ns[i])
1167 del(user_ns[i])
1168
1168
1169 def magic_logstart(self,parameter_s=''):
1169 def magic_logstart(self,parameter_s=''):
1170 """Start logging anywhere in a session.
1170 """Start logging anywhere in a session.
1171
1171
1172 %logstart [-o|-r|-t] [log_name [log_mode]]
1172 %logstart [-o|-r|-t] [log_name [log_mode]]
1173
1173
1174 If no name is given, it defaults to a file named 'ipython_log.py' in your
1174 If no name is given, it defaults to a file named 'ipython_log.py' in your
1175 current directory, in 'rotate' mode (see below).
1175 current directory, in 'rotate' mode (see below).
1176
1176
1177 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1177 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1178 history up to that point and then continues logging.
1178 history up to that point and then continues logging.
1179
1179
1180 %logstart takes a second optional parameter: logging mode. This can be one
1180 %logstart takes a second optional parameter: logging mode. This can be one
1181 of (note that the modes are given unquoted):\\
1181 of (note that the modes are given unquoted):\\
1182 append: well, that says it.\\
1182 append: well, that says it.\\
1183 backup: rename (if exists) to name~ and start name.\\
1183 backup: rename (if exists) to name~ and start name.\\
1184 global: single logfile in your home dir, appended to.\\
1184 global: single logfile in your home dir, appended to.\\
1185 over : overwrite existing log.\\
1185 over : overwrite existing log.\\
1186 rotate: create rotating logs name.1~, name.2~, etc.
1186 rotate: create rotating logs name.1~, name.2~, etc.
1187
1187
1188 Options:
1188 Options:
1189
1189
1190 -o: log also IPython's output. In this mode, all commands which
1190 -o: log also IPython's output. In this mode, all commands which
1191 generate an Out[NN] prompt are recorded to the logfile, right after
1191 generate an Out[NN] prompt are recorded to the logfile, right after
1192 their corresponding input line. The output lines are always
1192 their corresponding input line. The output lines are always
1193 prepended with a '#[Out]# ' marker, so that the log remains valid
1193 prepended with a '#[Out]# ' marker, so that the log remains valid
1194 Python code.
1194 Python code.
1195
1195
1196 Since this marker is always the same, filtering only the output from
1196 Since this marker is always the same, filtering only the output from
1197 a log is very easy, using for example a simple awk call:
1197 a log is very easy, using for example a simple awk call:
1198
1198
1199 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1199 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1200
1200
1201 -r: log 'raw' input. Normally, IPython's logs contain the processed
1201 -r: log 'raw' input. Normally, IPython's logs contain the processed
1202 input, so that user lines are logged in their final form, converted
1202 input, so that user lines are logged in their final form, converted
1203 into valid Python. For example, %Exit is logged as
1203 into valid Python. For example, %Exit is logged as
1204 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1204 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1205 exactly as typed, with no transformations applied.
1205 exactly as typed, with no transformations applied.
1206
1206
1207 -t: put timestamps before each input line logged (these are put in
1207 -t: put timestamps before each input line logged (these are put in
1208 comments)."""
1208 comments)."""
1209
1209
1210 opts,par = self.parse_options(parameter_s,'ort')
1210 opts,par = self.parse_options(parameter_s,'ort')
1211 log_output = 'o' in opts
1211 log_output = 'o' in opts
1212 log_raw_input = 'r' in opts
1212 log_raw_input = 'r' in opts
1213 timestamp = 't' in opts
1213 timestamp = 't' in opts
1214
1214
1215 logger = self.shell.logger
1215 logger = self.shell.logger
1216
1216
1217 # if no args are given, the defaults set in the logger constructor by
1217 # if no args are given, the defaults set in the logger constructor by
1218 # ipytohn remain valid
1218 # ipytohn remain valid
1219 if par:
1219 if par:
1220 try:
1220 try:
1221 logfname,logmode = par.split()
1221 logfname,logmode = par.split()
1222 except:
1222 except:
1223 logfname = par
1223 logfname = par
1224 logmode = 'backup'
1224 logmode = 'backup'
1225 else:
1225 else:
1226 logfname = logger.logfname
1226 logfname = logger.logfname
1227 logmode = logger.logmode
1227 logmode = logger.logmode
1228 # put logfname into rc struct as if it had been called on the command
1228 # put logfname into rc struct as if it had been called on the command
1229 # line, so it ends up saved in the log header Save it in case we need
1229 # line, so it ends up saved in the log header Save it in case we need
1230 # to restore it...
1230 # to restore it...
1231 old_logfile = self.shell.logfile
1231 old_logfile = self.shell.logfile
1232 if logfname:
1232 if logfname:
1233 logfname = os.path.expanduser(logfname)
1233 logfname = os.path.expanduser(logfname)
1234 self.shell.logfile = logfname
1234 self.shell.logfile = logfname
1235
1235
1236 loghead = '# IPython log file\n\n'
1236 loghead = '# IPython log file\n\n'
1237 try:
1237 try:
1238 started = logger.logstart(logfname,loghead,logmode,
1238 started = logger.logstart(logfname,loghead,logmode,
1239 log_output,timestamp,log_raw_input)
1239 log_output,timestamp,log_raw_input)
1240 except:
1240 except:
1241 self.shell.logfile = old_logfile
1241 self.shell.logfile = old_logfile
1242 warn("Couldn't start log: %s" % sys.exc_info()[1])
1242 warn("Couldn't start log: %s" % sys.exc_info()[1])
1243 else:
1243 else:
1244 # log input history up to this point, optionally interleaving
1244 # log input history up to this point, optionally interleaving
1245 # output if requested
1245 # output if requested
1246
1246
1247 if timestamp:
1247 if timestamp:
1248 # disable timestamping for the previous history, since we've
1248 # disable timestamping for the previous history, since we've
1249 # lost those already (no time machine here).
1249 # lost those already (no time machine here).
1250 logger.timestamp = False
1250 logger.timestamp = False
1251
1251
1252 if log_raw_input:
1252 if log_raw_input:
1253 input_hist = self.shell.input_hist_raw
1253 input_hist = self.shell.input_hist_raw
1254 else:
1254 else:
1255 input_hist = self.shell.input_hist
1255 input_hist = self.shell.input_hist
1256
1256
1257 if log_output:
1257 if log_output:
1258 log_write = logger.log_write
1258 log_write = logger.log_write
1259 output_hist = self.shell.output_hist
1259 output_hist = self.shell.output_hist
1260 for n in range(1,len(input_hist)-1):
1260 for n in range(1,len(input_hist)-1):
1261 log_write(input_hist[n].rstrip())
1261 log_write(input_hist[n].rstrip())
1262 if n in output_hist:
1262 if n in output_hist:
1263 log_write(repr(output_hist[n]),'output')
1263 log_write(repr(output_hist[n]),'output')
1264 else:
1264 else:
1265 logger.log_write(input_hist[1:])
1265 logger.log_write(input_hist[1:])
1266 if timestamp:
1266 if timestamp:
1267 # re-enable timestamping
1267 # re-enable timestamping
1268 logger.timestamp = True
1268 logger.timestamp = True
1269
1269
1270 print ('Activating auto-logging. '
1270 print ('Activating auto-logging. '
1271 'Current session state plus future input saved.')
1271 'Current session state plus future input saved.')
1272 logger.logstate()
1272 logger.logstate()
1273
1273
1274 def magic_logstop(self,parameter_s=''):
1274 def magic_logstop(self,parameter_s=''):
1275 """Fully stop logging and close log file.
1275 """Fully stop logging and close log file.
1276
1276
1277 In order to start logging again, a new %logstart call needs to be made,
1277 In order to start logging again, a new %logstart call needs to be made,
1278 possibly (though not necessarily) with a new filename, mode and other
1278 possibly (though not necessarily) with a new filename, mode and other
1279 options."""
1279 options."""
1280 self.logger.logstop()
1280 self.logger.logstop()
1281
1281
1282 def magic_logoff(self,parameter_s=''):
1282 def magic_logoff(self,parameter_s=''):
1283 """Temporarily stop logging.
1283 """Temporarily stop logging.
1284
1284
1285 You must have previously started logging."""
1285 You must have previously started logging."""
1286 self.shell.logger.switch_log(0)
1286 self.shell.logger.switch_log(0)
1287
1287
1288 def magic_logon(self,parameter_s=''):
1288 def magic_logon(self,parameter_s=''):
1289 """Restart logging.
1289 """Restart logging.
1290
1290
1291 This function is for restarting logging which you've temporarily
1291 This function is for restarting logging which you've temporarily
1292 stopped with %logoff. For starting logging for the first time, you
1292 stopped with %logoff. For starting logging for the first time, you
1293 must use the %logstart function, which allows you to specify an
1293 must use the %logstart function, which allows you to specify an
1294 optional log filename."""
1294 optional log filename."""
1295
1295
1296 self.shell.logger.switch_log(1)
1296 self.shell.logger.switch_log(1)
1297
1297
1298 def magic_logstate(self,parameter_s=''):
1298 def magic_logstate(self,parameter_s=''):
1299 """Print the status of the logging system."""
1299 """Print the status of the logging system."""
1300
1300
1301 self.shell.logger.logstate()
1301 self.shell.logger.logstate()
1302
1302
1303 def magic_pdb(self, parameter_s=''):
1303 def magic_pdb(self, parameter_s=''):
1304 """Control the automatic calling of the pdb interactive debugger.
1304 """Control the automatic calling of the pdb interactive debugger.
1305
1305
1306 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1306 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1307 argument it works as a toggle.
1307 argument it works as a toggle.
1308
1308
1309 When an exception is triggered, IPython can optionally call the
1309 When an exception is triggered, IPython can optionally call the
1310 interactive pdb debugger after the traceback printout. %pdb toggles
1310 interactive pdb debugger after the traceback printout. %pdb toggles
1311 this feature on and off.
1311 this feature on and off.
1312
1312
1313 The initial state of this feature is set in your ipythonrc
1313 The initial state of this feature is set in your ipythonrc
1314 configuration file (the variable is called 'pdb').
1314 configuration file (the variable is called 'pdb').
1315
1315
1316 If you want to just activate the debugger AFTER an exception has fired,
1316 If you want to just activate the debugger AFTER an exception has fired,
1317 without having to type '%pdb on' and rerunning your code, you can use
1317 without having to type '%pdb on' and rerunning your code, you can use
1318 the %debug magic."""
1318 the %debug magic."""
1319
1319
1320 par = parameter_s.strip().lower()
1320 par = parameter_s.strip().lower()
1321
1321
1322 if par:
1322 if par:
1323 try:
1323 try:
1324 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1324 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1325 except KeyError:
1325 except KeyError:
1326 print ('Incorrect argument. Use on/1, off/0, '
1326 print ('Incorrect argument. Use on/1, off/0, '
1327 'or nothing for a toggle.')
1327 'or nothing for a toggle.')
1328 return
1328 return
1329 else:
1329 else:
1330 # toggle
1330 # toggle
1331 new_pdb = not self.shell.call_pdb
1331 new_pdb = not self.shell.call_pdb
1332
1332
1333 # set on the shell
1333 # set on the shell
1334 self.shell.call_pdb = new_pdb
1334 self.shell.call_pdb = new_pdb
1335 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1335 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1336
1336
1337 def magic_debug(self, parameter_s=''):
1337 def magic_debug(self, parameter_s=''):
1338 """Activate the interactive debugger in post-mortem mode.
1338 """Activate the interactive debugger in post-mortem mode.
1339
1339
1340 If an exception has just occurred, this lets you inspect its stack
1340 If an exception has just occurred, this lets you inspect its stack
1341 frames interactively. Note that this will always work only on the last
1341 frames interactively. Note that this will always work only on the last
1342 traceback that occurred, so you must call this quickly after an
1342 traceback that occurred, so you must call this quickly after an
1343 exception that you wish to inspect has fired, because if another one
1343 exception that you wish to inspect has fired, because if another one
1344 occurs, it clobbers the previous one.
1344 occurs, it clobbers the previous one.
1345
1345
1346 If you want IPython to automatically do this on every exception, see
1346 If you want IPython to automatically do this on every exception, see
1347 the %pdb magic for more details.
1347 the %pdb magic for more details.
1348 """
1348 """
1349 self.shell.debugger(force=True)
1349 self.shell.debugger(force=True)
1350
1350
1351 @testdec.skip_doctest
1351 @testdec.skip_doctest
1352 def magic_prun(self, parameter_s ='',user_mode=1,
1352 def magic_prun(self, parameter_s ='',user_mode=1,
1353 opts=None,arg_lst=None,prog_ns=None):
1353 opts=None,arg_lst=None,prog_ns=None):
1354
1354
1355 """Run a statement through the python code profiler.
1355 """Run a statement through the python code profiler.
1356
1356
1357 Usage:
1357 Usage:
1358 %prun [options] statement
1358 %prun [options] statement
1359
1359
1360 The given statement (which doesn't require quote marks) is run via the
1360 The given statement (which doesn't require quote marks) is run via the
1361 python profiler in a manner similar to the profile.run() function.
1361 python profiler in a manner similar to the profile.run() function.
1362 Namespaces are internally managed to work correctly; profile.run
1362 Namespaces are internally managed to work correctly; profile.run
1363 cannot be used in IPython because it makes certain assumptions about
1363 cannot be used in IPython because it makes certain assumptions about
1364 namespaces which do not hold under IPython.
1364 namespaces which do not hold under IPython.
1365
1365
1366 Options:
1366 Options:
1367
1367
1368 -l <limit>: you can place restrictions on what or how much of the
1368 -l <limit>: you can place restrictions on what or how much of the
1369 profile gets printed. The limit value can be:
1369 profile gets printed. The limit value can be:
1370
1370
1371 * A string: only information for function names containing this string
1371 * A string: only information for function names containing this string
1372 is printed.
1372 is printed.
1373
1373
1374 * An integer: only these many lines are printed.
1374 * An integer: only these many lines are printed.
1375
1375
1376 * A float (between 0 and 1): this fraction of the report is printed
1376 * A float (between 0 and 1): this fraction of the report is printed
1377 (for example, use a limit of 0.4 to see the topmost 40% only).
1377 (for example, use a limit of 0.4 to see the topmost 40% only).
1378
1378
1379 You can combine several limits with repeated use of the option. For
1379 You can combine several limits with repeated use of the option. For
1380 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1380 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1381 information about class constructors.
1381 information about class constructors.
1382
1382
1383 -r: return the pstats.Stats object generated by the profiling. This
1383 -r: return the pstats.Stats object generated by the profiling. This
1384 object has all the information about the profile in it, and you can
1384 object has all the information about the profile in it, and you can
1385 later use it for further analysis or in other functions.
1385 later use it for further analysis or in other functions.
1386
1386
1387 -s <key>: sort profile by given key. You can provide more than one key
1387 -s <key>: sort profile by given key. You can provide more than one key
1388 by using the option several times: '-s key1 -s key2 -s key3...'. The
1388 by using the option several times: '-s key1 -s key2 -s key3...'. The
1389 default sorting key is 'time'.
1389 default sorting key is 'time'.
1390
1390
1391 The following is copied verbatim from the profile documentation
1391 The following is copied verbatim from the profile documentation
1392 referenced below:
1392 referenced below:
1393
1393
1394 When more than one key is provided, additional keys are used as
1394 When more than one key is provided, additional keys are used as
1395 secondary criteria when the there is equality in all keys selected
1395 secondary criteria when the there is equality in all keys selected
1396 before them.
1396 before them.
1397
1397
1398 Abbreviations can be used for any key names, as long as the
1398 Abbreviations can be used for any key names, as long as the
1399 abbreviation is unambiguous. The following are the keys currently
1399 abbreviation is unambiguous. The following are the keys currently
1400 defined:
1400 defined:
1401
1401
1402 Valid Arg Meaning
1402 Valid Arg Meaning
1403 "calls" call count
1403 "calls" call count
1404 "cumulative" cumulative time
1404 "cumulative" cumulative time
1405 "file" file name
1405 "file" file name
1406 "module" file name
1406 "module" file name
1407 "pcalls" primitive call count
1407 "pcalls" primitive call count
1408 "line" line number
1408 "line" line number
1409 "name" function name
1409 "name" function name
1410 "nfl" name/file/line
1410 "nfl" name/file/line
1411 "stdname" standard name
1411 "stdname" standard name
1412 "time" internal time
1412 "time" internal time
1413
1413
1414 Note that all sorts on statistics are in descending order (placing
1414 Note that all sorts on statistics are in descending order (placing
1415 most time consuming items first), where as name, file, and line number
1415 most time consuming items first), where as name, file, and line number
1416 searches are in ascending order (i.e., alphabetical). The subtle
1416 searches are in ascending order (i.e., alphabetical). The subtle
1417 distinction between "nfl" and "stdname" is that the standard name is a
1417 distinction between "nfl" and "stdname" is that the standard name is a
1418 sort of the name as printed, which means that the embedded line
1418 sort of the name as printed, which means that the embedded line
1419 numbers get compared in an odd way. For example, lines 3, 20, and 40
1419 numbers get compared in an odd way. For example, lines 3, 20, and 40
1420 would (if the file names were the same) appear in the string order
1420 would (if the file names were the same) appear in the string order
1421 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1421 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1422 line numbers. In fact, sort_stats("nfl") is the same as
1422 line numbers. In fact, sort_stats("nfl") is the same as
1423 sort_stats("name", "file", "line").
1423 sort_stats("name", "file", "line").
1424
1424
1425 -T <filename>: save profile results as shown on screen to a text
1425 -T <filename>: save profile results as shown on screen to a text
1426 file. The profile is still shown on screen.
1426 file. The profile is still shown on screen.
1427
1427
1428 -D <filename>: save (via dump_stats) profile statistics to given
1428 -D <filename>: save (via dump_stats) profile statistics to given
1429 filename. This data is in a format understod by the pstats module, and
1429 filename. This data is in a format understod by the pstats module, and
1430 is generated by a call to the dump_stats() method of profile
1430 is generated by a call to the dump_stats() method of profile
1431 objects. The profile is still shown on screen.
1431 objects. The profile is still shown on screen.
1432
1432
1433 If you want to run complete programs under the profiler's control, use
1433 If you want to run complete programs under the profiler's control, use
1434 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1434 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1435 contains profiler specific options as described here.
1435 contains profiler specific options as described here.
1436
1436
1437 You can read the complete documentation for the profile module with::
1437 You can read the complete documentation for the profile module with::
1438
1438
1439 In [1]: import profile; profile.help()
1439 In [1]: import profile; profile.help()
1440 """
1440 """
1441
1441
1442 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1442 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1443 # protect user quote marks
1443 # protect user quote marks
1444 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1444 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1445
1445
1446 if user_mode: # regular user call
1446 if user_mode: # regular user call
1447 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1447 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1448 list_all=1)
1448 list_all=1)
1449 namespace = self.shell.user_ns
1449 namespace = self.shell.user_ns
1450 else: # called to run a program by %run -p
1450 else: # called to run a program by %run -p
1451 try:
1451 try:
1452 filename = get_py_filename(arg_lst[0])
1452 filename = get_py_filename(arg_lst[0])
1453 except IOError,msg:
1453 except IOError,msg:
1454 error(msg)
1454 error(msg)
1455 return
1455 return
1456
1456
1457 arg_str = 'execfile(filename,prog_ns)'
1457 arg_str = 'execfile(filename,prog_ns)'
1458 namespace = locals()
1458 namespace = locals()
1459
1459
1460 opts.merge(opts_def)
1460 opts.merge(opts_def)
1461
1461
1462 prof = profile.Profile()
1462 prof = profile.Profile()
1463 try:
1463 try:
1464 prof = prof.runctx(arg_str,namespace,namespace)
1464 prof = prof.runctx(arg_str,namespace,namespace)
1465 sys_exit = ''
1465 sys_exit = ''
1466 except SystemExit:
1466 except SystemExit:
1467 sys_exit = """*** SystemExit exception caught in code being profiled."""
1467 sys_exit = """*** SystemExit exception caught in code being profiled."""
1468
1468
1469 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1469 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1470
1470
1471 lims = opts.l
1471 lims = opts.l
1472 if lims:
1472 if lims:
1473 lims = [] # rebuild lims with ints/floats/strings
1473 lims = [] # rebuild lims with ints/floats/strings
1474 for lim in opts.l:
1474 for lim in opts.l:
1475 try:
1475 try:
1476 lims.append(int(lim))
1476 lims.append(int(lim))
1477 except ValueError:
1477 except ValueError:
1478 try:
1478 try:
1479 lims.append(float(lim))
1479 lims.append(float(lim))
1480 except ValueError:
1480 except ValueError:
1481 lims.append(lim)
1481 lims.append(lim)
1482
1482
1483 # Trap output.
1483 # Trap output.
1484 stdout_trap = StringIO()
1484 stdout_trap = StringIO()
1485
1485
1486 if hasattr(stats,'stream'):
1486 if hasattr(stats,'stream'):
1487 # In newer versions of python, the stats object has a 'stream'
1487 # In newer versions of python, the stats object has a 'stream'
1488 # attribute to write into.
1488 # attribute to write into.
1489 stats.stream = stdout_trap
1489 stats.stream = stdout_trap
1490 stats.print_stats(*lims)
1490 stats.print_stats(*lims)
1491 else:
1491 else:
1492 # For older versions, we manually redirect stdout during printing
1492 # For older versions, we manually redirect stdout during printing
1493 sys_stdout = sys.stdout
1493 sys_stdout = sys.stdout
1494 try:
1494 try:
1495 sys.stdout = stdout_trap
1495 sys.stdout = stdout_trap
1496 stats.print_stats(*lims)
1496 stats.print_stats(*lims)
1497 finally:
1497 finally:
1498 sys.stdout = sys_stdout
1498 sys.stdout = sys_stdout
1499
1499
1500 output = stdout_trap.getvalue()
1500 output = stdout_trap.getvalue()
1501 output = output.rstrip()
1501 output = output.rstrip()
1502
1502
1503 page.page(output)
1503 page.page(output)
1504 print sys_exit,
1504 print sys_exit,
1505
1505
1506 dump_file = opts.D[0]
1506 dump_file = opts.D[0]
1507 text_file = opts.T[0]
1507 text_file = opts.T[0]
1508 if dump_file:
1508 if dump_file:
1509 prof.dump_stats(dump_file)
1509 prof.dump_stats(dump_file)
1510 print '\n*** Profile stats marshalled to file',\
1510 print '\n*** Profile stats marshalled to file',\
1511 `dump_file`+'.',sys_exit
1511 `dump_file`+'.',sys_exit
1512 if text_file:
1512 if text_file:
1513 pfile = file(text_file,'w')
1513 pfile = file(text_file,'w')
1514 pfile.write(output)
1514 pfile.write(output)
1515 pfile.close()
1515 pfile.close()
1516 print '\n*** Profile printout saved to text file',\
1516 print '\n*** Profile printout saved to text file',\
1517 `text_file`+'.',sys_exit
1517 `text_file`+'.',sys_exit
1518
1518
1519 if opts.has_key('r'):
1519 if opts.has_key('r'):
1520 return stats
1520 return stats
1521 else:
1521 else:
1522 return None
1522 return None
1523
1523
1524 @testdec.skip_doctest
1524 @testdec.skip_doctest
1525 def magic_run(self, parameter_s ='',runner=None,
1525 def magic_run(self, parameter_s ='',runner=None,
1526 file_finder=get_py_filename):
1526 file_finder=get_py_filename):
1527 """Run the named file inside IPython as a program.
1527 """Run the named file inside IPython as a program.
1528
1528
1529 Usage:\\
1529 Usage:\\
1530 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1530 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1531
1531
1532 Parameters after the filename are passed as command-line arguments to
1532 Parameters after the filename are passed as command-line arguments to
1533 the program (put in sys.argv). Then, control returns to IPython's
1533 the program (put in sys.argv). Then, control returns to IPython's
1534 prompt.
1534 prompt.
1535
1535
1536 This is similar to running at a system prompt:\\
1536 This is similar to running at a system prompt:\\
1537 $ python file args\\
1537 $ python file args\\
1538 but with the advantage of giving you IPython's tracebacks, and of
1538 but with the advantage of giving you IPython's tracebacks, and of
1539 loading all variables into your interactive namespace for further use
1539 loading all variables into your interactive namespace for further use
1540 (unless -p is used, see below).
1540 (unless -p is used, see below).
1541
1541
1542 The file is executed in a namespace initially consisting only of
1542 The file is executed in a namespace initially consisting only of
1543 __name__=='__main__' and sys.argv constructed as indicated. It thus
1543 __name__=='__main__' and sys.argv constructed as indicated. It thus
1544 sees its environment as if it were being run as a stand-alone program
1544 sees its environment as if it were being run as a stand-alone program
1545 (except for sharing global objects such as previously imported
1545 (except for sharing global objects such as previously imported
1546 modules). But after execution, the IPython interactive namespace gets
1546 modules). But after execution, the IPython interactive namespace gets
1547 updated with all variables defined in the program (except for __name__
1547 updated with all variables defined in the program (except for __name__
1548 and sys.argv). This allows for very convenient loading of code for
1548 and sys.argv). This allows for very convenient loading of code for
1549 interactive work, while giving each program a 'clean sheet' to run in.
1549 interactive work, while giving each program a 'clean sheet' to run in.
1550
1550
1551 Options:
1551 Options:
1552
1552
1553 -n: __name__ is NOT set to '__main__', but to the running file's name
1553 -n: __name__ is NOT set to '__main__', but to the running file's name
1554 without extension (as python does under import). This allows running
1554 without extension (as python does under import). This allows running
1555 scripts and reloading the definitions in them without calling code
1555 scripts and reloading the definitions in them without calling code
1556 protected by an ' if __name__ == "__main__" ' clause.
1556 protected by an ' if __name__ == "__main__" ' clause.
1557
1557
1558 -i: run the file in IPython's namespace instead of an empty one. This
1558 -i: run the file in IPython's namespace instead of an empty one. This
1559 is useful if you are experimenting with code written in a text editor
1559 is useful if you are experimenting with code written in a text editor
1560 which depends on variables defined interactively.
1560 which depends on variables defined interactively.
1561
1561
1562 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1562 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1563 being run. This is particularly useful if IPython is being used to
1563 being run. This is particularly useful if IPython is being used to
1564 run unittests, which always exit with a sys.exit() call. In such
1564 run unittests, which always exit with a sys.exit() call. In such
1565 cases you are interested in the output of the test results, not in
1565 cases you are interested in the output of the test results, not in
1566 seeing a traceback of the unittest module.
1566 seeing a traceback of the unittest module.
1567
1567
1568 -t: print timing information at the end of the run. IPython will give
1568 -t: print timing information at the end of the run. IPython will give
1569 you an estimated CPU time consumption for your script, which under
1569 you an estimated CPU time consumption for your script, which under
1570 Unix uses the resource module to avoid the wraparound problems of
1570 Unix uses the resource module to avoid the wraparound problems of
1571 time.clock(). Under Unix, an estimate of time spent on system tasks
1571 time.clock(). Under Unix, an estimate of time spent on system tasks
1572 is also given (for Windows platforms this is reported as 0.0).
1572 is also given (for Windows platforms this is reported as 0.0).
1573
1573
1574 If -t is given, an additional -N<N> option can be given, where <N>
1574 If -t is given, an additional -N<N> option can be given, where <N>
1575 must be an integer indicating how many times you want the script to
1575 must be an integer indicating how many times you want the script to
1576 run. The final timing report will include total and per run results.
1576 run. The final timing report will include total and per run results.
1577
1577
1578 For example (testing the script uniq_stable.py):
1578 For example (testing the script uniq_stable.py):
1579
1579
1580 In [1]: run -t uniq_stable
1580 In [1]: run -t uniq_stable
1581
1581
1582 IPython CPU timings (estimated):\\
1582 IPython CPU timings (estimated):\\
1583 User : 0.19597 s.\\
1583 User : 0.19597 s.\\
1584 System: 0.0 s.\\
1584 System: 0.0 s.\\
1585
1585
1586 In [2]: run -t -N5 uniq_stable
1586 In [2]: run -t -N5 uniq_stable
1587
1587
1588 IPython CPU timings (estimated):\\
1588 IPython CPU timings (estimated):\\
1589 Total runs performed: 5\\
1589 Total runs performed: 5\\
1590 Times : Total Per run\\
1590 Times : Total Per run\\
1591 User : 0.910862 s, 0.1821724 s.\\
1591 User : 0.910862 s, 0.1821724 s.\\
1592 System: 0.0 s, 0.0 s.
1592 System: 0.0 s, 0.0 s.
1593
1593
1594 -d: run your program under the control of pdb, the Python debugger.
1594 -d: run your program under the control of pdb, the Python debugger.
1595 This allows you to execute your program step by step, watch variables,
1595 This allows you to execute your program step by step, watch variables,
1596 etc. Internally, what IPython does is similar to calling:
1596 etc. Internally, what IPython does is similar to calling:
1597
1597
1598 pdb.run('execfile("YOURFILENAME")')
1598 pdb.run('execfile("YOURFILENAME")')
1599
1599
1600 with a breakpoint set on line 1 of your file. You can change the line
1600 with a breakpoint set on line 1 of your file. You can change the line
1601 number for this automatic breakpoint to be <N> by using the -bN option
1601 number for this automatic breakpoint to be <N> by using the -bN option
1602 (where N must be an integer). For example:
1602 (where N must be an integer). For example:
1603
1603
1604 %run -d -b40 myscript
1604 %run -d -b40 myscript
1605
1605
1606 will set the first breakpoint at line 40 in myscript.py. Note that
1606 will set the first breakpoint at line 40 in myscript.py. Note that
1607 the first breakpoint must be set on a line which actually does
1607 the first breakpoint must be set on a line which actually does
1608 something (not a comment or docstring) for it to stop execution.
1608 something (not a comment or docstring) for it to stop execution.
1609
1609
1610 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1610 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1611 first enter 'c' (without qoutes) to start execution up to the first
1611 first enter 'c' (without qoutes) to start execution up to the first
1612 breakpoint.
1612 breakpoint.
1613
1613
1614 Entering 'help' gives information about the use of the debugger. You
1614 Entering 'help' gives information about the use of the debugger. You
1615 can easily see pdb's full documentation with "import pdb;pdb.help()"
1615 can easily see pdb's full documentation with "import pdb;pdb.help()"
1616 at a prompt.
1616 at a prompt.
1617
1617
1618 -p: run program under the control of the Python profiler module (which
1618 -p: run program under the control of the Python profiler module (which
1619 prints a detailed report of execution times, function calls, etc).
1619 prints a detailed report of execution times, function calls, etc).
1620
1620
1621 You can pass other options after -p which affect the behavior of the
1621 You can pass other options after -p which affect the behavior of the
1622 profiler itself. See the docs for %prun for details.
1622 profiler itself. See the docs for %prun for details.
1623
1623
1624 In this mode, the program's variables do NOT propagate back to the
1624 In this mode, the program's variables do NOT propagate back to the
1625 IPython interactive namespace (because they remain in the namespace
1625 IPython interactive namespace (because they remain in the namespace
1626 where the profiler executes them).
1626 where the profiler executes them).
1627
1627
1628 Internally this triggers a call to %prun, see its documentation for
1628 Internally this triggers a call to %prun, see its documentation for
1629 details on the options available specifically for profiling.
1629 details on the options available specifically for profiling.
1630
1630
1631 There is one special usage for which the text above doesn't apply:
1631 There is one special usage for which the text above doesn't apply:
1632 if the filename ends with .ipy, the file is run as ipython script,
1632 if the filename ends with .ipy, the file is run as ipython script,
1633 just as if the commands were written on IPython prompt.
1633 just as if the commands were written on IPython prompt.
1634 """
1634 """
1635
1635
1636 # get arguments and set sys.argv for program to be run.
1636 # get arguments and set sys.argv for program to be run.
1637 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1637 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1638 mode='list',list_all=1)
1638 mode='list',list_all=1)
1639
1639
1640 try:
1640 try:
1641 filename = file_finder(arg_lst[0])
1641 filename = file_finder(arg_lst[0])
1642 except IndexError:
1642 except IndexError:
1643 warn('you must provide at least a filename.')
1643 warn('you must provide at least a filename.')
1644 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1644 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1645 return
1645 return
1646 except IOError,msg:
1646 except IOError,msg:
1647 error(msg)
1647 error(msg)
1648 return
1648 return
1649
1649
1650 if filename.lower().endswith('.ipy'):
1650 if filename.lower().endswith('.ipy'):
1651 self.shell.safe_execfile_ipy(filename)
1651 self.shell.safe_execfile_ipy(filename)
1652 return
1652 return
1653
1653
1654 # Control the response to exit() calls made by the script being run
1654 # Control the response to exit() calls made by the script being run
1655 exit_ignore = opts.has_key('e')
1655 exit_ignore = opts.has_key('e')
1656
1656
1657 # Make sure that the running script gets a proper sys.argv as if it
1657 # Make sure that the running script gets a proper sys.argv as if it
1658 # were run from a system shell.
1658 # were run from a system shell.
1659 save_argv = sys.argv # save it for later restoring
1659 save_argv = sys.argv # save it for later restoring
1660 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1660 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1661
1661
1662 if opts.has_key('i'):
1662 if opts.has_key('i'):
1663 # Run in user's interactive namespace
1663 # Run in user's interactive namespace
1664 prog_ns = self.shell.user_ns
1664 prog_ns = self.shell.user_ns
1665 __name__save = self.shell.user_ns['__name__']
1665 __name__save = self.shell.user_ns['__name__']
1666 prog_ns['__name__'] = '__main__'
1666 prog_ns['__name__'] = '__main__'
1667 main_mod = self.shell.new_main_mod(prog_ns)
1667 main_mod = self.shell.new_main_mod(prog_ns)
1668 else:
1668 else:
1669 # Run in a fresh, empty namespace
1669 # Run in a fresh, empty namespace
1670 if opts.has_key('n'):
1670 if opts.has_key('n'):
1671 name = os.path.splitext(os.path.basename(filename))[0]
1671 name = os.path.splitext(os.path.basename(filename))[0]
1672 else:
1672 else:
1673 name = '__main__'
1673 name = '__main__'
1674
1674
1675 main_mod = self.shell.new_main_mod()
1675 main_mod = self.shell.new_main_mod()
1676 prog_ns = main_mod.__dict__
1676 prog_ns = main_mod.__dict__
1677 prog_ns['__name__'] = name
1677 prog_ns['__name__'] = name
1678
1678
1679 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1679 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1680 # set the __file__ global in the script's namespace
1680 # set the __file__ global in the script's namespace
1681 prog_ns['__file__'] = filename
1681 prog_ns['__file__'] = filename
1682
1682
1683 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1683 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1684 # that, if we overwrite __main__, we replace it at the end
1684 # that, if we overwrite __main__, we replace it at the end
1685 main_mod_name = prog_ns['__name__']
1685 main_mod_name = prog_ns['__name__']
1686
1686
1687 if main_mod_name == '__main__':
1687 if main_mod_name == '__main__':
1688 restore_main = sys.modules['__main__']
1688 restore_main = sys.modules['__main__']
1689 else:
1689 else:
1690 restore_main = False
1690 restore_main = False
1691
1691
1692 # This needs to be undone at the end to prevent holding references to
1692 # This needs to be undone at the end to prevent holding references to
1693 # every single object ever created.
1693 # every single object ever created.
1694 sys.modules[main_mod_name] = main_mod
1694 sys.modules[main_mod_name] = main_mod
1695
1695
1696 stats = None
1696 stats = None
1697 try:
1697 try:
1698 self.shell.savehist()
1698 self.shell.savehist()
1699
1699
1700 if opts.has_key('p'):
1700 if opts.has_key('p'):
1701 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1701 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1702 else:
1702 else:
1703 if opts.has_key('d'):
1703 if opts.has_key('d'):
1704 deb = debugger.Pdb(self.shell.colors)
1704 deb = debugger.Pdb(self.shell.colors)
1705 # reset Breakpoint state, which is moronically kept
1705 # reset Breakpoint state, which is moronically kept
1706 # in a class
1706 # in a class
1707 bdb.Breakpoint.next = 1
1707 bdb.Breakpoint.next = 1
1708 bdb.Breakpoint.bplist = {}
1708 bdb.Breakpoint.bplist = {}
1709 bdb.Breakpoint.bpbynumber = [None]
1709 bdb.Breakpoint.bpbynumber = [None]
1710 # Set an initial breakpoint to stop execution
1710 # Set an initial breakpoint to stop execution
1711 maxtries = 10
1711 maxtries = 10
1712 bp = int(opts.get('b',[1])[0])
1712 bp = int(opts.get('b',[1])[0])
1713 checkline = deb.checkline(filename,bp)
1713 checkline = deb.checkline(filename,bp)
1714 if not checkline:
1714 if not checkline:
1715 for bp in range(bp+1,bp+maxtries+1):
1715 for bp in range(bp+1,bp+maxtries+1):
1716 if deb.checkline(filename,bp):
1716 if deb.checkline(filename,bp):
1717 break
1717 break
1718 else:
1718 else:
1719 msg = ("\nI failed to find a valid line to set "
1719 msg = ("\nI failed to find a valid line to set "
1720 "a breakpoint\n"
1720 "a breakpoint\n"
1721 "after trying up to line: %s.\n"
1721 "after trying up to line: %s.\n"
1722 "Please set a valid breakpoint manually "
1722 "Please set a valid breakpoint manually "
1723 "with the -b option." % bp)
1723 "with the -b option." % bp)
1724 error(msg)
1724 error(msg)
1725 return
1725 return
1726 # if we find a good linenumber, set the breakpoint
1726 # if we find a good linenumber, set the breakpoint
1727 deb.do_break('%s:%s' % (filename,bp))
1727 deb.do_break('%s:%s' % (filename,bp))
1728 # Start file run
1728 # Start file run
1729 print "NOTE: Enter 'c' at the",
1729 print "NOTE: Enter 'c' at the",
1730 print "%s prompt to start your script." % deb.prompt
1730 print "%s prompt to start your script." % deb.prompt
1731 try:
1731 try:
1732 deb.run('execfile("%s")' % filename,prog_ns)
1732 deb.run('execfile("%s")' % filename,prog_ns)
1733
1733
1734 except:
1734 except:
1735 etype, value, tb = sys.exc_info()
1735 etype, value, tb = sys.exc_info()
1736 # Skip three frames in the traceback: the %run one,
1736 # Skip three frames in the traceback: the %run one,
1737 # one inside bdb.py, and the command-line typed by the
1737 # one inside bdb.py, and the command-line typed by the
1738 # user (run by exec in pdb itself).
1738 # user (run by exec in pdb itself).
1739 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1739 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1740 else:
1740 else:
1741 if runner is None:
1741 if runner is None:
1742 runner = self.shell.safe_execfile
1742 runner = self.shell.safe_execfile
1743 if opts.has_key('t'):
1743 if opts.has_key('t'):
1744 # timed execution
1744 # timed execution
1745 try:
1745 try:
1746 nruns = int(opts['N'][0])
1746 nruns = int(opts['N'][0])
1747 if nruns < 1:
1747 if nruns < 1:
1748 error('Number of runs must be >=1')
1748 error('Number of runs must be >=1')
1749 return
1749 return
1750 except (KeyError):
1750 except (KeyError):
1751 nruns = 1
1751 nruns = 1
1752 if nruns == 1:
1752 if nruns == 1:
1753 t0 = clock2()
1753 t0 = clock2()
1754 runner(filename,prog_ns,prog_ns,
1754 runner(filename,prog_ns,prog_ns,
1755 exit_ignore=exit_ignore)
1755 exit_ignore=exit_ignore)
1756 t1 = clock2()
1756 t1 = clock2()
1757 t_usr = t1[0]-t0[0]
1757 t_usr = t1[0]-t0[0]
1758 t_sys = t1[1]-t0[1]
1758 t_sys = t1[1]-t0[1]
1759 print "\nIPython CPU timings (estimated):"
1759 print "\nIPython CPU timings (estimated):"
1760 print " User : %10s s." % t_usr
1760 print " User : %10s s." % t_usr
1761 print " System: %10s s." % t_sys
1761 print " System: %10s s." % t_sys
1762 else:
1762 else:
1763 runs = range(nruns)
1763 runs = range(nruns)
1764 t0 = clock2()
1764 t0 = clock2()
1765 for nr in runs:
1765 for nr in runs:
1766 runner(filename,prog_ns,prog_ns,
1766 runner(filename,prog_ns,prog_ns,
1767 exit_ignore=exit_ignore)
1767 exit_ignore=exit_ignore)
1768 t1 = clock2()
1768 t1 = clock2()
1769 t_usr = t1[0]-t0[0]
1769 t_usr = t1[0]-t0[0]
1770 t_sys = t1[1]-t0[1]
1770 t_sys = t1[1]-t0[1]
1771 print "\nIPython CPU timings (estimated):"
1771 print "\nIPython CPU timings (estimated):"
1772 print "Total runs performed:",nruns
1772 print "Total runs performed:",nruns
1773 print " Times : %10s %10s" % ('Total','Per run')
1773 print " Times : %10s %10s" % ('Total','Per run')
1774 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1774 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1775 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1775 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1776
1776
1777 else:
1777 else:
1778 # regular execution
1778 # regular execution
1779 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1779 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1780
1780
1781 if opts.has_key('i'):
1781 if opts.has_key('i'):
1782 self.shell.user_ns['__name__'] = __name__save
1782 self.shell.user_ns['__name__'] = __name__save
1783 else:
1783 else:
1784 # The shell MUST hold a reference to prog_ns so after %run
1784 # The shell MUST hold a reference to prog_ns so after %run
1785 # exits, the python deletion mechanism doesn't zero it out
1785 # exits, the python deletion mechanism doesn't zero it out
1786 # (leaving dangling references).
1786 # (leaving dangling references).
1787 self.shell.cache_main_mod(prog_ns,filename)
1787 self.shell.cache_main_mod(prog_ns,filename)
1788 # update IPython interactive namespace
1788 # update IPython interactive namespace
1789
1789
1790 # Some forms of read errors on the file may mean the
1790 # Some forms of read errors on the file may mean the
1791 # __name__ key was never set; using pop we don't have to
1791 # __name__ key was never set; using pop we don't have to
1792 # worry about a possible KeyError.
1792 # worry about a possible KeyError.
1793 prog_ns.pop('__name__', None)
1793 prog_ns.pop('__name__', None)
1794
1794
1795 self.shell.user_ns.update(prog_ns)
1795 self.shell.user_ns.update(prog_ns)
1796 finally:
1796 finally:
1797 # It's a bit of a mystery why, but __builtins__ can change from
1797 # It's a bit of a mystery why, but __builtins__ can change from
1798 # being a module to becoming a dict missing some key data after
1798 # being a module to becoming a dict missing some key data after
1799 # %run. As best I can see, this is NOT something IPython is doing
1799 # %run. As best I can see, this is NOT something IPython is doing
1800 # at all, and similar problems have been reported before:
1800 # at all, and similar problems have been reported before:
1801 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1801 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1802 # Since this seems to be done by the interpreter itself, the best
1802 # Since this seems to be done by the interpreter itself, the best
1803 # we can do is to at least restore __builtins__ for the user on
1803 # we can do is to at least restore __builtins__ for the user on
1804 # exit.
1804 # exit.
1805 self.shell.user_ns['__builtins__'] = __builtin__
1805 self.shell.user_ns['__builtins__'] = __builtin__
1806
1806
1807 # Ensure key global structures are restored
1807 # Ensure key global structures are restored
1808 sys.argv = save_argv
1808 sys.argv = save_argv
1809 if restore_main:
1809 if restore_main:
1810 sys.modules['__main__'] = restore_main
1810 sys.modules['__main__'] = restore_main
1811 else:
1811 else:
1812 # Remove from sys.modules the reference to main_mod we'd
1812 # Remove from sys.modules the reference to main_mod we'd
1813 # added. Otherwise it will trap references to objects
1813 # added. Otherwise it will trap references to objects
1814 # contained therein.
1814 # contained therein.
1815 del sys.modules[main_mod_name]
1815 del sys.modules[main_mod_name]
1816
1816
1817 self.shell.reloadhist()
1817 self.shell.reloadhist()
1818
1818
1819 return stats
1819 return stats
1820
1820
1821 @testdec.skip_doctest
1821 @testdec.skip_doctest
1822 def magic_timeit(self, parameter_s =''):
1822 def magic_timeit(self, parameter_s =''):
1823 """Time execution of a Python statement or expression
1823 """Time execution of a Python statement or expression
1824
1824
1825 Usage:\\
1825 Usage:\\
1826 %timeit [-n<N> -r<R> [-t|-c]] statement
1826 %timeit [-n<N> -r<R> [-t|-c]] statement
1827
1827
1828 Time execution of a Python statement or expression using the timeit
1828 Time execution of a Python statement or expression using the timeit
1829 module.
1829 module.
1830
1830
1831 Options:
1831 Options:
1832 -n<N>: execute the given statement <N> times in a loop. If this value
1832 -n<N>: execute the given statement <N> times in a loop. If this value
1833 is not given, a fitting value is chosen.
1833 is not given, a fitting value is chosen.
1834
1834
1835 -r<R>: repeat the loop iteration <R> times and take the best result.
1835 -r<R>: repeat the loop iteration <R> times and take the best result.
1836 Default: 3
1836 Default: 3
1837
1837
1838 -t: use time.time to measure the time, which is the default on Unix.
1838 -t: use time.time to measure the time, which is the default on Unix.
1839 This function measures wall time.
1839 This function measures wall time.
1840
1840
1841 -c: use time.clock to measure the time, which is the default on
1841 -c: use time.clock to measure the time, which is the default on
1842 Windows and measures wall time. On Unix, resource.getrusage is used
1842 Windows and measures wall time. On Unix, resource.getrusage is used
1843 instead and returns the CPU user time.
1843 instead and returns the CPU user time.
1844
1844
1845 -p<P>: use a precision of <P> digits to display the timing result.
1845 -p<P>: use a precision of <P> digits to display the timing result.
1846 Default: 3
1846 Default: 3
1847
1847
1848
1848
1849 Examples:
1849 Examples:
1850
1850
1851 In [1]: %timeit pass
1851 In [1]: %timeit pass
1852 10000000 loops, best of 3: 53.3 ns per loop
1852 10000000 loops, best of 3: 53.3 ns per loop
1853
1853
1854 In [2]: u = None
1854 In [2]: u = None
1855
1855
1856 In [3]: %timeit u is None
1856 In [3]: %timeit u is None
1857 10000000 loops, best of 3: 184 ns per loop
1857 10000000 loops, best of 3: 184 ns per loop
1858
1858
1859 In [4]: %timeit -r 4 u == None
1859 In [4]: %timeit -r 4 u == None
1860 1000000 loops, best of 4: 242 ns per loop
1860 1000000 loops, best of 4: 242 ns per loop
1861
1861
1862 In [5]: import time
1862 In [5]: import time
1863
1863
1864 In [6]: %timeit -n1 time.sleep(2)
1864 In [6]: %timeit -n1 time.sleep(2)
1865 1 loops, best of 3: 2 s per loop
1865 1 loops, best of 3: 2 s per loop
1866
1866
1867
1867
1868 The times reported by %timeit will be slightly higher than those
1868 The times reported by %timeit will be slightly higher than those
1869 reported by the timeit.py script when variables are accessed. This is
1869 reported by the timeit.py script when variables are accessed. This is
1870 due to the fact that %timeit executes the statement in the namespace
1870 due to the fact that %timeit executes the statement in the namespace
1871 of the shell, compared with timeit.py, which uses a single setup
1871 of the shell, compared with timeit.py, which uses a single setup
1872 statement to import function or create variables. Generally, the bias
1872 statement to import function or create variables. Generally, the bias
1873 does not matter as long as results from timeit.py are not mixed with
1873 does not matter as long as results from timeit.py are not mixed with
1874 those from %timeit."""
1874 those from %timeit."""
1875
1875
1876 import timeit
1876 import timeit
1877 import math
1877 import math
1878
1878
1879 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1879 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1880 # certain terminals. Until we figure out a robust way of
1880 # certain terminals. Until we figure out a robust way of
1881 # auto-detecting if the terminal can deal with it, use plain 'us' for
1881 # auto-detecting if the terminal can deal with it, use plain 'us' for
1882 # microseconds. I am really NOT happy about disabling the proper
1882 # microseconds. I am really NOT happy about disabling the proper
1883 # 'micro' prefix, but crashing is worse... If anyone knows what the
1883 # 'micro' prefix, but crashing is worse... If anyone knows what the
1884 # right solution for this is, I'm all ears...
1884 # right solution for this is, I'm all ears...
1885 #
1885 #
1886 # Note: using
1886 # Note: using
1887 #
1887 #
1888 # s = u'\xb5'
1888 # s = u'\xb5'
1889 # s.encode(sys.getdefaultencoding())
1889 # s.encode(sys.getdefaultencoding())
1890 #
1890 #
1891 # is not sufficient, as I've seen terminals where that fails but
1891 # is not sufficient, as I've seen terminals where that fails but
1892 # print s
1892 # print s
1893 #
1893 #
1894 # succeeds
1894 # succeeds
1895 #
1895 #
1896 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1896 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1897
1897
1898 #units = [u"s", u"ms",u'\xb5',"ns"]
1898 #units = [u"s", u"ms",u'\xb5',"ns"]
1899 units = [u"s", u"ms",u'us',"ns"]
1899 units = [u"s", u"ms",u'us',"ns"]
1900
1900
1901 scaling = [1, 1e3, 1e6, 1e9]
1901 scaling = [1, 1e3, 1e6, 1e9]
1902
1902
1903 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1903 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1904 posix=False)
1904 posix=False)
1905 if stmt == "":
1905 if stmt == "":
1906 return
1906 return
1907 timefunc = timeit.default_timer
1907 timefunc = timeit.default_timer
1908 number = int(getattr(opts, "n", 0))
1908 number = int(getattr(opts, "n", 0))
1909 repeat = int(getattr(opts, "r", timeit.default_repeat))
1909 repeat = int(getattr(opts, "r", timeit.default_repeat))
1910 precision = int(getattr(opts, "p", 3))
1910 precision = int(getattr(opts, "p", 3))
1911 if hasattr(opts, "t"):
1911 if hasattr(opts, "t"):
1912 timefunc = time.time
1912 timefunc = time.time
1913 if hasattr(opts, "c"):
1913 if hasattr(opts, "c"):
1914 timefunc = clock
1914 timefunc = clock
1915
1915
1916 timer = timeit.Timer(timer=timefunc)
1916 timer = timeit.Timer(timer=timefunc)
1917 # this code has tight coupling to the inner workings of timeit.Timer,
1917 # this code has tight coupling to the inner workings of timeit.Timer,
1918 # but is there a better way to achieve that the code stmt has access
1918 # but is there a better way to achieve that the code stmt has access
1919 # to the shell namespace?
1919 # to the shell namespace?
1920
1920
1921 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1921 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1922 'setup': "pass"}
1922 'setup': "pass"}
1923 # Track compilation time so it can be reported if too long
1923 # Track compilation time so it can be reported if too long
1924 # Minimum time above which compilation time will be reported
1924 # Minimum time above which compilation time will be reported
1925 tc_min = 0.1
1925 tc_min = 0.1
1926
1926
1927 t0 = clock()
1927 t0 = clock()
1928 code = compile(src, "<magic-timeit>", "exec")
1928 code = compile(src, "<magic-timeit>", "exec")
1929 tc = clock()-t0
1929 tc = clock()-t0
1930
1930
1931 ns = {}
1931 ns = {}
1932 exec code in self.shell.user_ns, ns
1932 exec code in self.shell.user_ns, ns
1933 timer.inner = ns["inner"]
1933 timer.inner = ns["inner"]
1934
1934
1935 if number == 0:
1935 if number == 0:
1936 # determine number so that 0.2 <= total time < 2.0
1936 # determine number so that 0.2 <= total time < 2.0
1937 number = 1
1937 number = 1
1938 for i in range(1, 10):
1938 for i in range(1, 10):
1939 if timer.timeit(number) >= 0.2:
1939 if timer.timeit(number) >= 0.2:
1940 break
1940 break
1941 number *= 10
1941 number *= 10
1942
1942
1943 best = min(timer.repeat(repeat, number)) / number
1943 best = min(timer.repeat(repeat, number)) / number
1944
1944
1945 if best > 0.0 and best < 1000.0:
1945 if best > 0.0 and best < 1000.0:
1946 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1946 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1947 elif best >= 1000.0:
1947 elif best >= 1000.0:
1948 order = 0
1948 order = 0
1949 else:
1949 else:
1950 order = 3
1950 order = 3
1951 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1951 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1952 precision,
1952 precision,
1953 best * scaling[order],
1953 best * scaling[order],
1954 units[order])
1954 units[order])
1955 if tc > tc_min:
1955 if tc > tc_min:
1956 print "Compiler time: %.2f s" % tc
1956 print "Compiler time: %.2f s" % tc
1957
1957
1958 @testdec.skip_doctest
1958 @testdec.skip_doctest
1959 def magic_time(self,parameter_s = ''):
1959 def magic_time(self,parameter_s = ''):
1960 """Time execution of a Python statement or expression.
1960 """Time execution of a Python statement or expression.
1961
1961
1962 The CPU and wall clock times are printed, and the value of the
1962 The CPU and wall clock times are printed, and the value of the
1963 expression (if any) is returned. Note that under Win32, system time
1963 expression (if any) is returned. Note that under Win32, system time
1964 is always reported as 0, since it can not be measured.
1964 is always reported as 0, since it can not be measured.
1965
1965
1966 This function provides very basic timing functionality. In Python
1966 This function provides very basic timing functionality. In Python
1967 2.3, the timeit module offers more control and sophistication, so this
1967 2.3, the timeit module offers more control and sophistication, so this
1968 could be rewritten to use it (patches welcome).
1968 could be rewritten to use it (patches welcome).
1969
1969
1970 Some examples:
1970 Some examples:
1971
1971
1972 In [1]: time 2**128
1972 In [1]: time 2**128
1973 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1973 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1974 Wall time: 0.00
1974 Wall time: 0.00
1975 Out[1]: 340282366920938463463374607431768211456L
1975 Out[1]: 340282366920938463463374607431768211456L
1976
1976
1977 In [2]: n = 1000000
1977 In [2]: n = 1000000
1978
1978
1979 In [3]: time sum(range(n))
1979 In [3]: time sum(range(n))
1980 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1980 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1981 Wall time: 1.37
1981 Wall time: 1.37
1982 Out[3]: 499999500000L
1982 Out[3]: 499999500000L
1983
1983
1984 In [4]: time print 'hello world'
1984 In [4]: time print 'hello world'
1985 hello world
1985 hello world
1986 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1986 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1987 Wall time: 0.00
1987 Wall time: 0.00
1988
1988
1989 Note that the time needed by Python to compile the given expression
1989 Note that the time needed by Python to compile the given expression
1990 will be reported if it is more than 0.1s. In this example, the
1990 will be reported if it is more than 0.1s. In this example, the
1991 actual exponentiation is done by Python at compilation time, so while
1991 actual exponentiation is done by Python at compilation time, so while
1992 the expression can take a noticeable amount of time to compute, that
1992 the expression can take a noticeable amount of time to compute, that
1993 time is purely due to the compilation:
1993 time is purely due to the compilation:
1994
1994
1995 In [5]: time 3**9999;
1995 In [5]: time 3**9999;
1996 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1996 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1997 Wall time: 0.00 s
1997 Wall time: 0.00 s
1998
1998
1999 In [6]: time 3**999999;
1999 In [6]: time 3**999999;
2000 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2000 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2001 Wall time: 0.00 s
2001 Wall time: 0.00 s
2002 Compiler : 0.78 s
2002 Compiler : 0.78 s
2003 """
2003 """
2004
2004
2005 # fail immediately if the given expression can't be compiled
2005 # fail immediately if the given expression can't be compiled
2006
2006
2007 expr = self.shell.prefilter(parameter_s,False)
2007 expr = self.shell.prefilter(parameter_s,False)
2008
2008
2009 # Minimum time above which compilation time will be reported
2009 # Minimum time above which compilation time will be reported
2010 tc_min = 0.1
2010 tc_min = 0.1
2011
2011
2012 try:
2012 try:
2013 mode = 'eval'
2013 mode = 'eval'
2014 t0 = clock()
2014 t0 = clock()
2015 code = compile(expr,'<timed eval>',mode)
2015 code = compile(expr,'<timed eval>',mode)
2016 tc = clock()-t0
2016 tc = clock()-t0
2017 except SyntaxError:
2017 except SyntaxError:
2018 mode = 'exec'
2018 mode = 'exec'
2019 t0 = clock()
2019 t0 = clock()
2020 code = compile(expr,'<timed exec>',mode)
2020 code = compile(expr,'<timed exec>',mode)
2021 tc = clock()-t0
2021 tc = clock()-t0
2022 # skew measurement as little as possible
2022 # skew measurement as little as possible
2023 glob = self.shell.user_ns
2023 glob = self.shell.user_ns
2024 clk = clock2
2024 clk = clock2
2025 wtime = time.time
2025 wtime = time.time
2026 # time execution
2026 # time execution
2027 wall_st = wtime()
2027 wall_st = wtime()
2028 if mode=='eval':
2028 if mode=='eval':
2029 st = clk()
2029 st = clk()
2030 out = eval(code,glob)
2030 out = eval(code,glob)
2031 end = clk()
2031 end = clk()
2032 else:
2032 else:
2033 st = clk()
2033 st = clk()
2034 exec code in glob
2034 exec code in glob
2035 end = clk()
2035 end = clk()
2036 out = None
2036 out = None
2037 wall_end = wtime()
2037 wall_end = wtime()
2038 # Compute actual times and report
2038 # Compute actual times and report
2039 wall_time = wall_end-wall_st
2039 wall_time = wall_end-wall_st
2040 cpu_user = end[0]-st[0]
2040 cpu_user = end[0]-st[0]
2041 cpu_sys = end[1]-st[1]
2041 cpu_sys = end[1]-st[1]
2042 cpu_tot = cpu_user+cpu_sys
2042 cpu_tot = cpu_user+cpu_sys
2043 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2043 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2044 (cpu_user,cpu_sys,cpu_tot)
2044 (cpu_user,cpu_sys,cpu_tot)
2045 print "Wall time: %.2f s" % wall_time
2045 print "Wall time: %.2f s" % wall_time
2046 if tc > tc_min:
2046 if tc > tc_min:
2047 print "Compiler : %.2f s" % tc
2047 print "Compiler : %.2f s" % tc
2048 return out
2048 return out
2049
2049
2050 @testdec.skip_doctest
2050 @testdec.skip_doctest
2051 def magic_macro(self,parameter_s = ''):
2051 def magic_macro(self,parameter_s = ''):
2052 """Define a set of input lines as a macro for future re-execution.
2052 """Define a set of input lines as a macro for future re-execution.
2053
2053
2054 Usage:\\
2054 Usage:\\
2055 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2055 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2056
2056
2057 Options:
2057 Options:
2058
2058
2059 -r: use 'raw' input. By default, the 'processed' history is used,
2059 -r: use 'raw' input. By default, the 'processed' history is used,
2060 so that magics are loaded in their transformed version to valid
2060 so that magics are loaded in their transformed version to valid
2061 Python. If this option is given, the raw input as typed as the
2061 Python. If this option is given, the raw input as typed as the
2062 command line is used instead.
2062 command line is used instead.
2063
2063
2064 This will define a global variable called `name` which is a string
2064 This will define a global variable called `name` which is a string
2065 made of joining the slices and lines you specify (n1,n2,... numbers
2065 made of joining the slices and lines you specify (n1,n2,... numbers
2066 above) from your input history into a single string. This variable
2066 above) from your input history into a single string. This variable
2067 acts like an automatic function which re-executes those lines as if
2067 acts like an automatic function which re-executes those lines as if
2068 you had typed them. You just type 'name' at the prompt and the code
2068 you had typed them. You just type 'name' at the prompt and the code
2069 executes.
2069 executes.
2070
2070
2071 The notation for indicating number ranges is: n1-n2 means 'use line
2071 The notation for indicating number ranges is: n1-n2 means 'use line
2072 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2072 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
2073 using the lines numbered 5,6 and 7.
2073 using the lines numbered 5,6 and 7.
2074
2074
2075 Note: as a 'hidden' feature, you can also use traditional python slice
2075 Note: as a 'hidden' feature, you can also use traditional python slice
2076 notation, where N:M means numbers N through M-1.
2076 notation, where N:M means numbers N through M-1.
2077
2077
2078 For example, if your history contains (%hist prints it):
2078 For example, if your history contains (%hist prints it):
2079
2079
2080 44: x=1
2080 44: x=1
2081 45: y=3
2081 45: y=3
2082 46: z=x+y
2082 46: z=x+y
2083 47: print x
2083 47: print x
2084 48: a=5
2084 48: a=5
2085 49: print 'x',x,'y',y
2085 49: print 'x',x,'y',y
2086
2086
2087 you can create a macro with lines 44 through 47 (included) and line 49
2087 you can create a macro with lines 44 through 47 (included) and line 49
2088 called my_macro with:
2088 called my_macro with:
2089
2089
2090 In [55]: %macro my_macro 44-47 49
2090 In [55]: %macro my_macro 44-47 49
2091
2091
2092 Now, typing `my_macro` (without quotes) will re-execute all this code
2092 Now, typing `my_macro` (without quotes) will re-execute all this code
2093 in one pass.
2093 in one pass.
2094
2094
2095 You don't need to give the line-numbers in order, and any given line
2095 You don't need to give the line-numbers in order, and any given line
2096 number can appear multiple times. You can assemble macros with any
2096 number can appear multiple times. You can assemble macros with any
2097 lines from your input history in any order.
2097 lines from your input history in any order.
2098
2098
2099 The macro is a simple object which holds its value in an attribute,
2099 The macro is a simple object which holds its value in an attribute,
2100 but IPython's display system checks for macros and executes them as
2100 but IPython's display system checks for macros and executes them as
2101 code instead of printing them when you type their name.
2101 code instead of printing them when you type their name.
2102
2102
2103 You can view a macro's contents by explicitly printing it with:
2103 You can view a macro's contents by explicitly printing it with:
2104
2104
2105 'print macro_name'.
2105 'print macro_name'.
2106
2106
2107 For one-off cases which DON'T contain magic function calls in them you
2107 For one-off cases which DON'T contain magic function calls in them you
2108 can obtain similar results by explicitly executing slices from your
2108 can obtain similar results by explicitly executing slices from your
2109 input history with:
2109 input history with:
2110
2110
2111 In [60]: exec In[44:48]+In[49]"""
2111 In [60]: exec In[44:48]+In[49]"""
2112
2112
2113 opts,args = self.parse_options(parameter_s,'r',mode='list')
2113 opts,args = self.parse_options(parameter_s,'r',mode='list')
2114 if not args:
2114 if not args:
2115 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2115 macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)]
2116 macs.sort()
2116 macs.sort()
2117 return macs
2117 return macs
2118 if len(args) == 1:
2118 if len(args) == 1:
2119 raise UsageError(
2119 raise UsageError(
2120 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2120 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2121 name,ranges = args[0], args[1:]
2121 name,ranges = args[0], args[1:]
2122
2122
2123 #print 'rng',ranges # dbg
2123 #print 'rng',ranges # dbg
2124 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2124 lines = self.extract_input_slices(ranges,opts.has_key('r'))
2125 macro = Macro(lines)
2125 macro = Macro(lines)
2126 self.shell.define_macro(name, macro)
2126 self.shell.define_macro(name, macro)
2127 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2127 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2128 print 'Macro contents:'
2128 print 'Macro contents:'
2129 print macro,
2129 print macro,
2130
2130
2131 def magic_save(self,parameter_s = ''):
2131 def magic_save(self,parameter_s = ''):
2132 """Save a set of lines to a given filename.
2132 """Save a set of lines to a given filename.
2133
2133
2134 Usage:\\
2134 Usage:\\
2135 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2135 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2136
2136
2137 Options:
2137 Options:
2138
2138
2139 -r: use 'raw' input. By default, the 'processed' history is used,
2139 -r: use 'raw' input. By default, the 'processed' history is used,
2140 so that magics are loaded in their transformed version to valid
2140 so that magics are loaded in their transformed version to valid
2141 Python. If this option is given, the raw input as typed as the
2141 Python. If this option is given, the raw input as typed as the
2142 command line is used instead.
2142 command line is used instead.
2143
2143
2144 This function uses the same syntax as %macro for line extraction, but
2144 This function uses the same syntax as %macro for line extraction, but
2145 instead of creating a macro it saves the resulting string to the
2145 instead of creating a macro it saves the resulting string to the
2146 filename you specify.
2146 filename you specify.
2147
2147
2148 It adds a '.py' extension to the file if you don't do so yourself, and
2148 It adds a '.py' extension to the file if you don't do so yourself, and
2149 it asks for confirmation before overwriting existing files."""
2149 it asks for confirmation before overwriting existing files."""
2150
2150
2151 opts,args = self.parse_options(parameter_s,'r',mode='list')
2151 opts,args = self.parse_options(parameter_s,'r',mode='list')
2152 fname,ranges = args[0], args[1:]
2152 fname,ranges = args[0], args[1:]
2153 if not fname.endswith('.py'):
2153 if not fname.endswith('.py'):
2154 fname += '.py'
2154 fname += '.py'
2155 if os.path.isfile(fname):
2155 if os.path.isfile(fname):
2156 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2156 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2157 if ans.lower() not in ['y','yes']:
2157 if ans.lower() not in ['y','yes']:
2158 print 'Operation cancelled.'
2158 print 'Operation cancelled.'
2159 return
2159 return
2160 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2160 cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r')))
2161 f = file(fname,'w')
2161 f = file(fname,'w')
2162 f.write(cmds)
2162 f.write(cmds)
2163 f.close()
2163 f.close()
2164 print 'The following commands were written to file `%s`:' % fname
2164 print 'The following commands were written to file `%s`:' % fname
2165 print cmds
2165 print cmds
2166
2166
2167 def _edit_macro(self,mname,macro):
2167 def _edit_macro(self,mname,macro):
2168 """open an editor with the macro data in a file"""
2168 """open an editor with the macro data in a file"""
2169 filename = self.shell.mktempfile(macro.value)
2169 filename = self.shell.mktempfile(macro.value)
2170 self.shell.hooks.editor(filename)
2170 self.shell.hooks.editor(filename)
2171
2171
2172 # and make a new macro object, to replace the old one
2172 # and make a new macro object, to replace the old one
2173 mfile = open(filename)
2173 mfile = open(filename)
2174 mvalue = mfile.read()
2174 mvalue = mfile.read()
2175 mfile.close()
2175 mfile.close()
2176 self.shell.user_ns[mname] = Macro(mvalue)
2176 self.shell.user_ns[mname] = Macro(mvalue)
2177
2177
2178 def magic_ed(self,parameter_s=''):
2178 def magic_ed(self,parameter_s=''):
2179 """Alias to %edit."""
2179 """Alias to %edit."""
2180 return self.magic_edit(parameter_s)
2180 return self.magic_edit(parameter_s)
2181
2181
2182 @testdec.skip_doctest
2182 @testdec.skip_doctest
2183 def magic_edit(self,parameter_s='',last_call=['','']):
2183 def magic_edit(self,parameter_s='',last_call=['','']):
2184 """Bring up an editor and execute the resulting code.
2184 """Bring up an editor and execute the resulting code.
2185
2185
2186 Usage:
2186 Usage:
2187 %edit [options] [args]
2187 %edit [options] [args]
2188
2188
2189 %edit runs IPython's editor hook. The default version of this hook is
2189 %edit runs IPython's editor hook. The default version of this hook is
2190 set to call the __IPYTHON__.rc.editor command. This is read from your
2190 set to call the __IPYTHON__.rc.editor command. This is read from your
2191 environment variable $EDITOR. If this isn't found, it will default to
2191 environment variable $EDITOR. If this isn't found, it will default to
2192 vi under Linux/Unix and to notepad under Windows. See the end of this
2192 vi under Linux/Unix and to notepad under Windows. See the end of this
2193 docstring for how to change the editor hook.
2193 docstring for how to change the editor hook.
2194
2194
2195 You can also set the value of this editor via the command line option
2195 You can also set the value of this editor via the command line option
2196 '-editor' or in your ipythonrc file. This is useful if you wish to use
2196 '-editor' or in your ipythonrc file. This is useful if you wish to use
2197 specifically for IPython an editor different from your typical default
2197 specifically for IPython an editor different from your typical default
2198 (and for Windows users who typically don't set environment variables).
2198 (and for Windows users who typically don't set environment variables).
2199
2199
2200 This command allows you to conveniently edit multi-line code right in
2200 This command allows you to conveniently edit multi-line code right in
2201 your IPython session.
2201 your IPython session.
2202
2202
2203 If called without arguments, %edit opens up an empty editor with a
2203 If called without arguments, %edit opens up an empty editor with a
2204 temporary file and will execute the contents of this file when you
2204 temporary file and will execute the contents of this file when you
2205 close it (don't forget to save it!).
2205 close it (don't forget to save it!).
2206
2206
2207
2207
2208 Options:
2208 Options:
2209
2209
2210 -n <number>: open the editor at a specified line number. By default,
2210 -n <number>: open the editor at a specified line number. By default,
2211 the IPython editor hook uses the unix syntax 'editor +N filename', but
2211 the IPython editor hook uses the unix syntax 'editor +N filename', but
2212 you can configure this by providing your own modified hook if your
2212 you can configure this by providing your own modified hook if your
2213 favorite editor supports line-number specifications with a different
2213 favorite editor supports line-number specifications with a different
2214 syntax.
2214 syntax.
2215
2215
2216 -p: this will call the editor with the same data as the previous time
2216 -p: this will call the editor with the same data as the previous time
2217 it was used, regardless of how long ago (in your current session) it
2217 it was used, regardless of how long ago (in your current session) it
2218 was.
2218 was.
2219
2219
2220 -r: use 'raw' input. This option only applies to input taken from the
2220 -r: use 'raw' input. This option only applies to input taken from the
2221 user's history. By default, the 'processed' history is used, so that
2221 user's history. By default, the 'processed' history is used, so that
2222 magics are loaded in their transformed version to valid Python. If
2222 magics are loaded in their transformed version to valid Python. If
2223 this option is given, the raw input as typed as the command line is
2223 this option is given, the raw input as typed as the command line is
2224 used instead. When you exit the editor, it will be executed by
2224 used instead. When you exit the editor, it will be executed by
2225 IPython's own processor.
2225 IPython's own processor.
2226
2226
2227 -x: do not execute the edited code immediately upon exit. This is
2227 -x: do not execute the edited code immediately upon exit. This is
2228 mainly useful if you are editing programs which need to be called with
2228 mainly useful if you are editing programs which need to be called with
2229 command line arguments, which you can then do using %run.
2229 command line arguments, which you can then do using %run.
2230
2230
2231
2231
2232 Arguments:
2232 Arguments:
2233
2233
2234 If arguments are given, the following possibilites exist:
2234 If arguments are given, the following possibilites exist:
2235
2235
2236 - The arguments are numbers or pairs of colon-separated numbers (like
2236 - The arguments are numbers or pairs of colon-separated numbers (like
2237 1 4:8 9). These are interpreted as lines of previous input to be
2237 1 4:8 9). These are interpreted as lines of previous input to be
2238 loaded into the editor. The syntax is the same of the %macro command.
2238 loaded into the editor. The syntax is the same of the %macro command.
2239
2239
2240 - If the argument doesn't start with a number, it is evaluated as a
2240 - If the argument doesn't start with a number, it is evaluated as a
2241 variable and its contents loaded into the editor. You can thus edit
2241 variable and its contents loaded into the editor. You can thus edit
2242 any string which contains python code (including the result of
2242 any string which contains python code (including the result of
2243 previous edits).
2243 previous edits).
2244
2244
2245 - If the argument is the name of an object (other than a string),
2245 - If the argument is the name of an object (other than a string),
2246 IPython will try to locate the file where it was defined and open the
2246 IPython will try to locate the file where it was defined and open the
2247 editor at the point where it is defined. You can use `%edit function`
2247 editor at the point where it is defined. You can use `%edit function`
2248 to load an editor exactly at the point where 'function' is defined,
2248 to load an editor exactly at the point where 'function' is defined,
2249 edit it and have the file be executed automatically.
2249 edit it and have the file be executed automatically.
2250
2250
2251 If the object is a macro (see %macro for details), this opens up your
2251 If the object is a macro (see %macro for details), this opens up your
2252 specified editor with a temporary file containing the macro's data.
2252 specified editor with a temporary file containing the macro's data.
2253 Upon exit, the macro is reloaded with the contents of the file.
2253 Upon exit, the macro is reloaded with the contents of the file.
2254
2254
2255 Note: opening at an exact line is only supported under Unix, and some
2255 Note: opening at an exact line is only supported under Unix, and some
2256 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2256 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2257 '+NUMBER' parameter necessary for this feature. Good editors like
2257 '+NUMBER' parameter necessary for this feature. Good editors like
2258 (X)Emacs, vi, jed, pico and joe all do.
2258 (X)Emacs, vi, jed, pico and joe all do.
2259
2259
2260 - If the argument is not found as a variable, IPython will look for a
2260 - If the argument is not found as a variable, IPython will look for a
2261 file with that name (adding .py if necessary) and load it into the
2261 file with that name (adding .py if necessary) and load it into the
2262 editor. It will execute its contents with execfile() when you exit,
2262 editor. It will execute its contents with execfile() when you exit,
2263 loading any code in the file into your interactive namespace.
2263 loading any code in the file into your interactive namespace.
2264
2264
2265 After executing your code, %edit will return as output the code you
2265 After executing your code, %edit will return as output the code you
2266 typed in the editor (except when it was an existing file). This way
2266 typed in the editor (except when it was an existing file). This way
2267 you can reload the code in further invocations of %edit as a variable,
2267 you can reload the code in further invocations of %edit as a variable,
2268 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2268 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2269 the output.
2269 the output.
2270
2270
2271 Note that %edit is also available through the alias %ed.
2271 Note that %edit is also available through the alias %ed.
2272
2272
2273 This is an example of creating a simple function inside the editor and
2273 This is an example of creating a simple function inside the editor and
2274 then modifying it. First, start up the editor:
2274 then modifying it. First, start up the editor:
2275
2275
2276 In [1]: ed
2276 In [1]: ed
2277 Editing... done. Executing edited code...
2277 Editing... done. Executing edited code...
2278 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2278 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2279
2279
2280 We can then call the function foo():
2280 We can then call the function foo():
2281
2281
2282 In [2]: foo()
2282 In [2]: foo()
2283 foo() was defined in an editing session
2283 foo() was defined in an editing session
2284
2284
2285 Now we edit foo. IPython automatically loads the editor with the
2285 Now we edit foo. IPython automatically loads the editor with the
2286 (temporary) file where foo() was previously defined:
2286 (temporary) file where foo() was previously defined:
2287
2287
2288 In [3]: ed foo
2288 In [3]: ed foo
2289 Editing... done. Executing edited code...
2289 Editing... done. Executing edited code...
2290
2290
2291 And if we call foo() again we get the modified version:
2291 And if we call foo() again we get the modified version:
2292
2292
2293 In [4]: foo()
2293 In [4]: foo()
2294 foo() has now been changed!
2294 foo() has now been changed!
2295
2295
2296 Here is an example of how to edit a code snippet successive
2296 Here is an example of how to edit a code snippet successive
2297 times. First we call the editor:
2297 times. First we call the editor:
2298
2298
2299 In [5]: ed
2299 In [5]: ed
2300 Editing... done. Executing edited code...
2300 Editing... done. Executing edited code...
2301 hello
2301 hello
2302 Out[5]: "print 'hello'n"
2302 Out[5]: "print 'hello'n"
2303
2303
2304 Now we call it again with the previous output (stored in _):
2304 Now we call it again with the previous output (stored in _):
2305
2305
2306 In [6]: ed _
2306 In [6]: ed _
2307 Editing... done. Executing edited code...
2307 Editing... done. Executing edited code...
2308 hello world
2308 hello world
2309 Out[6]: "print 'hello world'n"
2309 Out[6]: "print 'hello world'n"
2310
2310
2311 Now we call it with the output #8 (stored in _8, also as Out[8]):
2311 Now we call it with the output #8 (stored in _8, also as Out[8]):
2312
2312
2313 In [7]: ed _8
2313 In [7]: ed _8
2314 Editing... done. Executing edited code...
2314 Editing... done. Executing edited code...
2315 hello again
2315 hello again
2316 Out[7]: "print 'hello again'n"
2316 Out[7]: "print 'hello again'n"
2317
2317
2318
2318
2319 Changing the default editor hook:
2319 Changing the default editor hook:
2320
2320
2321 If you wish to write your own editor hook, you can put it in a
2321 If you wish to write your own editor hook, you can put it in a
2322 configuration file which you load at startup time. The default hook
2322 configuration file which you load at startup time. The default hook
2323 is defined in the IPython.core.hooks module, and you can use that as a
2323 is defined in the IPython.core.hooks module, and you can use that as a
2324 starting example for further modifications. That file also has
2324 starting example for further modifications. That file also has
2325 general instructions on how to set a new hook for use once you've
2325 general instructions on how to set a new hook for use once you've
2326 defined it."""
2326 defined it."""
2327
2327
2328 # FIXME: This function has become a convoluted mess. It needs a
2328 # FIXME: This function has become a convoluted mess. It needs a
2329 # ground-up rewrite with clean, simple logic.
2329 # ground-up rewrite with clean, simple logic.
2330
2330
2331 def make_filename(arg):
2331 def make_filename(arg):
2332 "Make a filename from the given args"
2332 "Make a filename from the given args"
2333 try:
2333 try:
2334 filename = get_py_filename(arg)
2334 filename = get_py_filename(arg)
2335 except IOError:
2335 except IOError:
2336 if args.endswith('.py'):
2336 if args.endswith('.py'):
2337 filename = arg
2337 filename = arg
2338 else:
2338 else:
2339 filename = None
2339 filename = None
2340 return filename
2340 return filename
2341
2341
2342 # custom exceptions
2342 # custom exceptions
2343 class DataIsObject(Exception): pass
2343 class DataIsObject(Exception): pass
2344
2344
2345 opts,args = self.parse_options(parameter_s,'prxn:')
2345 opts,args = self.parse_options(parameter_s,'prxn:')
2346 # Set a few locals from the options for convenience:
2346 # Set a few locals from the options for convenience:
2347 opts_p = opts.has_key('p')
2347 opts_p = opts.has_key('p')
2348 opts_r = opts.has_key('r')
2348 opts_r = opts.has_key('r')
2349
2349
2350 # Default line number value
2350 # Default line number value
2351 lineno = opts.get('n',None)
2351 lineno = opts.get('n',None)
2352
2352
2353 if opts_p:
2353 if opts_p:
2354 args = '_%s' % last_call[0]
2354 args = '_%s' % last_call[0]
2355 if not self.shell.user_ns.has_key(args):
2355 if not self.shell.user_ns.has_key(args):
2356 args = last_call[1]
2356 args = last_call[1]
2357
2357
2358 # use last_call to remember the state of the previous call, but don't
2358 # use last_call to remember the state of the previous call, but don't
2359 # let it be clobbered by successive '-p' calls.
2359 # let it be clobbered by successive '-p' calls.
2360 try:
2360 try:
2361 last_call[0] = self.shell.displayhook.prompt_count
2361 last_call[0] = self.shell.displayhook.prompt_count
2362 if not opts_p:
2362 if not opts_p:
2363 last_call[1] = parameter_s
2363 last_call[1] = parameter_s
2364 except:
2364 except:
2365 pass
2365 pass
2366
2366
2367 # by default this is done with temp files, except when the given
2367 # by default this is done with temp files, except when the given
2368 # arg is a filename
2368 # arg is a filename
2369 use_temp = 1
2369 use_temp = 1
2370
2370
2371 if re.match(r'\d',args):
2371 if re.match(r'\d',args):
2372 # Mode where user specifies ranges of lines, like in %macro.
2372 # Mode where user specifies ranges of lines, like in %macro.
2373 # This means that you can't edit files whose names begin with
2373 # This means that you can't edit files whose names begin with
2374 # numbers this way. Tough.
2374 # numbers this way. Tough.
2375 ranges = args.split()
2375 ranges = args.split()
2376 data = ''.join(self.extract_input_slices(ranges,opts_r))
2376 data = ''.join(self.extract_input_slices(ranges,opts_r))
2377 elif args.endswith('.py'):
2377 elif args.endswith('.py'):
2378 filename = make_filename(args)
2378 filename = make_filename(args)
2379 data = ''
2379 data = ''
2380 use_temp = 0
2380 use_temp = 0
2381 elif args:
2381 elif args:
2382 try:
2382 try:
2383 # Load the parameter given as a variable. If not a string,
2383 # Load the parameter given as a variable. If not a string,
2384 # process it as an object instead (below)
2384 # process it as an object instead (below)
2385
2385
2386 #print '*** args',args,'type',type(args) # dbg
2386 #print '*** args',args,'type',type(args) # dbg
2387 data = eval(args,self.shell.user_ns)
2387 data = eval(args,self.shell.user_ns)
2388 if not type(data) in StringTypes:
2388 if not type(data) in StringTypes:
2389 raise DataIsObject
2389 raise DataIsObject
2390
2390
2391 except (NameError,SyntaxError):
2391 except (NameError,SyntaxError):
2392 # given argument is not a variable, try as a filename
2392 # given argument is not a variable, try as a filename
2393 filename = make_filename(args)
2393 filename = make_filename(args)
2394 if filename is None:
2394 if filename is None:
2395 warn("Argument given (%s) can't be found as a variable "
2395 warn("Argument given (%s) can't be found as a variable "
2396 "or as a filename." % args)
2396 "or as a filename." % args)
2397 return
2397 return
2398
2398
2399 data = ''
2399 data = ''
2400 use_temp = 0
2400 use_temp = 0
2401 except DataIsObject:
2401 except DataIsObject:
2402
2402
2403 # macros have a special edit function
2403 # macros have a special edit function
2404 if isinstance(data,Macro):
2404 if isinstance(data,Macro):
2405 self._edit_macro(args,data)
2405 self._edit_macro(args,data)
2406 return
2406 return
2407
2407
2408 # For objects, try to edit the file where they are defined
2408 # For objects, try to edit the file where they are defined
2409 try:
2409 try:
2410 filename = inspect.getabsfile(data)
2410 filename = inspect.getabsfile(data)
2411 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2411 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2412 # class created by %edit? Try to find source
2412 # class created by %edit? Try to find source
2413 # by looking for method definitions instead, the
2413 # by looking for method definitions instead, the
2414 # __module__ in those classes is FakeModule.
2414 # __module__ in those classes is FakeModule.
2415 attrs = [getattr(data, aname) for aname in dir(data)]
2415 attrs = [getattr(data, aname) for aname in dir(data)]
2416 for attr in attrs:
2416 for attr in attrs:
2417 if not inspect.ismethod(attr):
2417 if not inspect.ismethod(attr):
2418 continue
2418 continue
2419 filename = inspect.getabsfile(attr)
2419 filename = inspect.getabsfile(attr)
2420 if filename and 'fakemodule' not in filename.lower():
2420 if filename and 'fakemodule' not in filename.lower():
2421 # change the attribute to be the edit target instead
2421 # change the attribute to be the edit target instead
2422 data = attr
2422 data = attr
2423 break
2423 break
2424
2424
2425 datafile = 1
2425 datafile = 1
2426 except TypeError:
2426 except TypeError:
2427 filename = make_filename(args)
2427 filename = make_filename(args)
2428 datafile = 1
2428 datafile = 1
2429 warn('Could not find file where `%s` is defined.\n'
2429 warn('Could not find file where `%s` is defined.\n'
2430 'Opening a file named `%s`' % (args,filename))
2430 'Opening a file named `%s`' % (args,filename))
2431 # Now, make sure we can actually read the source (if it was in
2431 # Now, make sure we can actually read the source (if it was in
2432 # a temp file it's gone by now).
2432 # a temp file it's gone by now).
2433 if datafile:
2433 if datafile:
2434 try:
2434 try:
2435 if lineno is None:
2435 if lineno is None:
2436 lineno = inspect.getsourcelines(data)[1]
2436 lineno = inspect.getsourcelines(data)[1]
2437 except IOError:
2437 except IOError:
2438 filename = make_filename(args)
2438 filename = make_filename(args)
2439 if filename is None:
2439 if filename is None:
2440 warn('The file `%s` where `%s` was defined cannot '
2440 warn('The file `%s` where `%s` was defined cannot '
2441 'be read.' % (filename,data))
2441 'be read.' % (filename,data))
2442 return
2442 return
2443 use_temp = 0
2443 use_temp = 0
2444 else:
2444 else:
2445 data = ''
2445 data = ''
2446
2446
2447 if use_temp:
2447 if use_temp:
2448 filename = self.shell.mktempfile(data)
2448 filename = self.shell.mktempfile(data)
2449 print 'IPython will make a temporary file named:',filename
2449 print 'IPython will make a temporary file named:',filename
2450
2450
2451 # do actual editing here
2451 # do actual editing here
2452 print 'Editing...',
2452 print 'Editing...',
2453 sys.stdout.flush()
2453 sys.stdout.flush()
2454 try:
2454 try:
2455 # Quote filenames that may have spaces in them
2455 # Quote filenames that may have spaces in them
2456 if ' ' in filename:
2456 if ' ' in filename:
2457 filename = "%s" % filename
2457 filename = "%s" % filename
2458 self.shell.hooks.editor(filename,lineno)
2458 self.shell.hooks.editor(filename,lineno)
2459 except TryNext:
2459 except TryNext:
2460 warn('Could not open editor')
2460 warn('Could not open editor')
2461 return
2461 return
2462
2462
2463 # XXX TODO: should this be generalized for all string vars?
2463 # XXX TODO: should this be generalized for all string vars?
2464 # For now, this is special-cased to blocks created by cpaste
2464 # For now, this is special-cased to blocks created by cpaste
2465 if args.strip() == 'pasted_block':
2465 if args.strip() == 'pasted_block':
2466 self.shell.user_ns['pasted_block'] = file_read(filename)
2466 self.shell.user_ns['pasted_block'] = file_read(filename)
2467
2467
2468 if opts.has_key('x'): # -x prevents actual execution
2468 if opts.has_key('x'): # -x prevents actual execution
2469 print
2469 print
2470 else:
2470 else:
2471 print 'done. Executing edited code...'
2471 print 'done. Executing edited code...'
2472 if opts_r:
2472 if opts_r:
2473 self.shell.runlines(file_read(filename))
2473 self.shell.runlines(file_read(filename))
2474 else:
2474 else:
2475 self.shell.safe_execfile(filename,self.shell.user_ns,
2475 self.shell.safe_execfile(filename,self.shell.user_ns,
2476 self.shell.user_ns)
2476 self.shell.user_ns)
2477
2477
2478
2478
2479 if use_temp:
2479 if use_temp:
2480 try:
2480 try:
2481 return open(filename).read()
2481 return open(filename).read()
2482 except IOError,msg:
2482 except IOError,msg:
2483 if msg.filename == filename:
2483 if msg.filename == filename:
2484 warn('File not found. Did you forget to save?')
2484 warn('File not found. Did you forget to save?')
2485 return
2485 return
2486 else:
2486 else:
2487 self.shell.showtraceback()
2487 self.shell.showtraceback()
2488
2488
2489 def magic_xmode(self,parameter_s = ''):
2489 def magic_xmode(self,parameter_s = ''):
2490 """Switch modes for the exception handlers.
2490 """Switch modes for the exception handlers.
2491
2491
2492 Valid modes: Plain, Context and Verbose.
2492 Valid modes: Plain, Context and Verbose.
2493
2493
2494 If called without arguments, acts as a toggle."""
2494 If called without arguments, acts as a toggle."""
2495
2495
2496 def xmode_switch_err(name):
2496 def xmode_switch_err(name):
2497 warn('Error changing %s exception modes.\n%s' %
2497 warn('Error changing %s exception modes.\n%s' %
2498 (name,sys.exc_info()[1]))
2498 (name,sys.exc_info()[1]))
2499
2499
2500 shell = self.shell
2500 shell = self.shell
2501 new_mode = parameter_s.strip().capitalize()
2501 new_mode = parameter_s.strip().capitalize()
2502 try:
2502 try:
2503 shell.InteractiveTB.set_mode(mode=new_mode)
2503 shell.InteractiveTB.set_mode(mode=new_mode)
2504 print 'Exception reporting mode:',shell.InteractiveTB.mode
2504 print 'Exception reporting mode:',shell.InteractiveTB.mode
2505 except:
2505 except:
2506 xmode_switch_err('user')
2506 xmode_switch_err('user')
2507
2507
2508 def magic_colors(self,parameter_s = ''):
2508 def magic_colors(self,parameter_s = ''):
2509 """Switch color scheme for prompts, info system and exception handlers.
2509 """Switch color scheme for prompts, info system and exception handlers.
2510
2510
2511 Currently implemented schemes: NoColor, Linux, LightBG.
2511 Currently implemented schemes: NoColor, Linux, LightBG.
2512
2512
2513 Color scheme names are not case-sensitive."""
2513 Color scheme names are not case-sensitive."""
2514
2514
2515 def color_switch_err(name):
2515 def color_switch_err(name):
2516 warn('Error changing %s color schemes.\n%s' %
2516 warn('Error changing %s color schemes.\n%s' %
2517 (name,sys.exc_info()[1]))
2517 (name,sys.exc_info()[1]))
2518
2518
2519
2519
2520 new_scheme = parameter_s.strip()
2520 new_scheme = parameter_s.strip()
2521 if not new_scheme:
2521 if not new_scheme:
2522 raise UsageError(
2522 raise UsageError(
2523 "%colors: you must specify a color scheme. See '%colors?'")
2523 "%colors: you must specify a color scheme. See '%colors?'")
2524 return
2524 return
2525 # local shortcut
2525 # local shortcut
2526 shell = self.shell
2526 shell = self.shell
2527
2527
2528 import IPython.utils.rlineimpl as readline
2528 import IPython.utils.rlineimpl as readline
2529
2529
2530 if not readline.have_readline and sys.platform == "win32":
2530 if not readline.have_readline and sys.platform == "win32":
2531 msg = """\
2531 msg = """\
2532 Proper color support under MS Windows requires the pyreadline library.
2532 Proper color support under MS Windows requires the pyreadline library.
2533 You can find it at:
2533 You can find it at:
2534 http://ipython.scipy.org/moin/PyReadline/Intro
2534 http://ipython.scipy.org/moin/PyReadline/Intro
2535 Gary's readline needs the ctypes module, from:
2535 Gary's readline needs the ctypes module, from:
2536 http://starship.python.net/crew/theller/ctypes
2536 http://starship.python.net/crew/theller/ctypes
2537 (Note that ctypes is already part of Python versions 2.5 and newer).
2537 (Note that ctypes is already part of Python versions 2.5 and newer).
2538
2538
2539 Defaulting color scheme to 'NoColor'"""
2539 Defaulting color scheme to 'NoColor'"""
2540 new_scheme = 'NoColor'
2540 new_scheme = 'NoColor'
2541 warn(msg)
2541 warn(msg)
2542
2542
2543 # readline option is 0
2543 # readline option is 0
2544 if not shell.has_readline:
2544 if not shell.has_readline:
2545 new_scheme = 'NoColor'
2545 new_scheme = 'NoColor'
2546
2546
2547 # Set prompt colors
2547 # Set prompt colors
2548 try:
2548 try:
2549 shell.displayhook.set_colors(new_scheme)
2549 shell.displayhook.set_colors(new_scheme)
2550 except:
2550 except:
2551 color_switch_err('prompt')
2551 color_switch_err('prompt')
2552 else:
2552 else:
2553 shell.colors = \
2553 shell.colors = \
2554 shell.displayhook.color_table.active_scheme_name
2554 shell.displayhook.color_table.active_scheme_name
2555 # Set exception colors
2555 # Set exception colors
2556 try:
2556 try:
2557 shell.InteractiveTB.set_colors(scheme = new_scheme)
2557 shell.InteractiveTB.set_colors(scheme = new_scheme)
2558 shell.SyntaxTB.set_colors(scheme = new_scheme)
2558 shell.SyntaxTB.set_colors(scheme = new_scheme)
2559 except:
2559 except:
2560 color_switch_err('exception')
2560 color_switch_err('exception')
2561
2561
2562 # Set info (for 'object?') colors
2562 # Set info (for 'object?') colors
2563 if shell.color_info:
2563 if shell.color_info:
2564 try:
2564 try:
2565 shell.inspector.set_active_scheme(new_scheme)
2565 shell.inspector.set_active_scheme(new_scheme)
2566 except:
2566 except:
2567 color_switch_err('object inspector')
2567 color_switch_err('object inspector')
2568 else:
2568 else:
2569 shell.inspector.set_active_scheme('NoColor')
2569 shell.inspector.set_active_scheme('NoColor')
2570
2570
2571 def magic_color_info(self,parameter_s = ''):
2571 def magic_color_info(self,parameter_s = ''):
2572 """Toggle color_info.
2572 """Toggle color_info.
2573
2573
2574 The color_info configuration parameter controls whether colors are
2574 The color_info configuration parameter controls whether colors are
2575 used for displaying object details (by things like %psource, %pfile or
2575 used for displaying object details (by things like %psource, %pfile or
2576 the '?' system). This function toggles this value with each call.
2576 the '?' system). This function toggles this value with each call.
2577
2577
2578 Note that unless you have a fairly recent pager (less works better
2578 Note that unless you have a fairly recent pager (less works better
2579 than more) in your system, using colored object information displays
2579 than more) in your system, using colored object information displays
2580 will not work properly. Test it and see."""
2580 will not work properly. Test it and see."""
2581
2581
2582 self.shell.color_info = not self.shell.color_info
2582 self.shell.color_info = not self.shell.color_info
2583 self.magic_colors(self.shell.colors)
2583 self.magic_colors(self.shell.colors)
2584 print 'Object introspection functions have now coloring:',
2584 print 'Object introspection functions have now coloring:',
2585 print ['OFF','ON'][int(self.shell.color_info)]
2585 print ['OFF','ON'][int(self.shell.color_info)]
2586
2586
2587 def magic_Pprint(self, parameter_s=''):
2587 def magic_Pprint(self, parameter_s=''):
2588 """Toggle pretty printing on/off."""
2588 """Toggle pretty printing on/off."""
2589
2589
2590 self.shell.pprint = 1 - self.shell.pprint
2590 self.shell.pprint = 1 - self.shell.pprint
2591 print 'Pretty printing has been turned', \
2591 print 'Pretty printing has been turned', \
2592 ['OFF','ON'][self.shell.pprint]
2592 ['OFF','ON'][self.shell.pprint]
2593
2593
2594 def magic_Exit(self, parameter_s=''):
2594 def magic_Exit(self, parameter_s=''):
2595 """Exit IPython without confirmation."""
2595 """Exit IPython without confirmation."""
2596
2596
2597 self.shell.ask_exit()
2597 self.shell.ask_exit()
2598
2598
2599 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2599 # Add aliases as magics so all common forms work: exit, quit, Exit, Quit.
2600 magic_exit = magic_quit = magic_Quit = magic_Exit
2600 magic_exit = magic_quit = magic_Quit = magic_Exit
2601
2601
2602 #......................................................................
2602 #......................................................................
2603 # Functions to implement unix shell-type things
2603 # Functions to implement unix shell-type things
2604
2604
2605 @testdec.skip_doctest
2605 @testdec.skip_doctest
2606 def magic_alias(self, parameter_s = ''):
2606 def magic_alias(self, parameter_s = ''):
2607 """Define an alias for a system command.
2607 """Define an alias for a system command.
2608
2608
2609 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2609 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2610
2610
2611 Then, typing 'alias_name params' will execute the system command 'cmd
2611 Then, typing 'alias_name params' will execute the system command 'cmd
2612 params' (from your underlying operating system).
2612 params' (from your underlying operating system).
2613
2613
2614 Aliases have lower precedence than magic functions and Python normal
2614 Aliases have lower precedence than magic functions and Python normal
2615 variables, so if 'foo' is both a Python variable and an alias, the
2615 variables, so if 'foo' is both a Python variable and an alias, the
2616 alias can not be executed until 'del foo' removes the Python variable.
2616 alias can not be executed until 'del foo' removes the Python variable.
2617
2617
2618 You can use the %l specifier in an alias definition to represent the
2618 You can use the %l specifier in an alias definition to represent the
2619 whole line when the alias is called. For example:
2619 whole line when the alias is called. For example:
2620
2620
2621 In [2]: alias bracket echo "Input in brackets: <%l>"
2621 In [2]: alias bracket echo "Input in brackets: <%l>"
2622 In [3]: bracket hello world
2622 In [3]: bracket hello world
2623 Input in brackets: <hello world>
2623 Input in brackets: <hello world>
2624
2624
2625 You can also define aliases with parameters using %s specifiers (one
2625 You can also define aliases with parameters using %s specifiers (one
2626 per parameter):
2626 per parameter):
2627
2627
2628 In [1]: alias parts echo first %s second %s
2628 In [1]: alias parts echo first %s second %s
2629 In [2]: %parts A B
2629 In [2]: %parts A B
2630 first A second B
2630 first A second B
2631 In [3]: %parts A
2631 In [3]: %parts A
2632 Incorrect number of arguments: 2 expected.
2632 Incorrect number of arguments: 2 expected.
2633 parts is an alias to: 'echo first %s second %s'
2633 parts is an alias to: 'echo first %s second %s'
2634
2634
2635 Note that %l and %s are mutually exclusive. You can only use one or
2635 Note that %l and %s are mutually exclusive. You can only use one or
2636 the other in your aliases.
2636 the other in your aliases.
2637
2637
2638 Aliases expand Python variables just like system calls using ! or !!
2638 Aliases expand Python variables just like system calls using ! or !!
2639 do: all expressions prefixed with '$' get expanded. For details of
2639 do: all expressions prefixed with '$' get expanded. For details of
2640 the semantic rules, see PEP-215:
2640 the semantic rules, see PEP-215:
2641 http://www.python.org/peps/pep-0215.html. This is the library used by
2641 http://www.python.org/peps/pep-0215.html. This is the library used by
2642 IPython for variable expansion. If you want to access a true shell
2642 IPython for variable expansion. If you want to access a true shell
2643 variable, an extra $ is necessary to prevent its expansion by IPython:
2643 variable, an extra $ is necessary to prevent its expansion by IPython:
2644
2644
2645 In [6]: alias show echo
2645 In [6]: alias show echo
2646 In [7]: PATH='A Python string'
2646 In [7]: PATH='A Python string'
2647 In [8]: show $PATH
2647 In [8]: show $PATH
2648 A Python string
2648 A Python string
2649 In [9]: show $$PATH
2649 In [9]: show $$PATH
2650 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2650 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2651
2651
2652 You can use the alias facility to acess all of $PATH. See the %rehash
2652 You can use the alias facility to acess all of $PATH. See the %rehash
2653 and %rehashx functions, which automatically create aliases for the
2653 and %rehashx functions, which automatically create aliases for the
2654 contents of your $PATH.
2654 contents of your $PATH.
2655
2655
2656 If called with no parameters, %alias prints the current alias table."""
2656 If called with no parameters, %alias prints the current alias table."""
2657
2657
2658 par = parameter_s.strip()
2658 par = parameter_s.strip()
2659 if not par:
2659 if not par:
2660 stored = self.db.get('stored_aliases', {} )
2660 stored = self.db.get('stored_aliases', {} )
2661 aliases = sorted(self.shell.alias_manager.aliases)
2661 aliases = sorted(self.shell.alias_manager.aliases)
2662 # for k, v in stored:
2662 # for k, v in stored:
2663 # atab.append(k, v[0])
2663 # atab.append(k, v[0])
2664
2664
2665 print "Total number of aliases:", len(aliases)
2665 print "Total number of aliases:", len(aliases)
2666 return aliases
2666 return aliases
2667
2667
2668 # Now try to define a new one
2668 # Now try to define a new one
2669 try:
2669 try:
2670 alias,cmd = par.split(None, 1)
2670 alias,cmd = par.split(None, 1)
2671 except:
2671 except:
2672 print oinspect.getdoc(self.magic_alias)
2672 print oinspect.getdoc(self.magic_alias)
2673 else:
2673 else:
2674 self.shell.alias_manager.soft_define_alias(alias, cmd)
2674 self.shell.alias_manager.soft_define_alias(alias, cmd)
2675 # end magic_alias
2675 # end magic_alias
2676
2676
2677 def magic_unalias(self, parameter_s = ''):
2677 def magic_unalias(self, parameter_s = ''):
2678 """Remove an alias"""
2678 """Remove an alias"""
2679
2679
2680 aname = parameter_s.strip()
2680 aname = parameter_s.strip()
2681 self.shell.alias_manager.undefine_alias(aname)
2681 self.shell.alias_manager.undefine_alias(aname)
2682 stored = self.db.get('stored_aliases', {} )
2682 stored = self.db.get('stored_aliases', {} )
2683 if aname in stored:
2683 if aname in stored:
2684 print "Removing %stored alias",aname
2684 print "Removing %stored alias",aname
2685 del stored[aname]
2685 del stored[aname]
2686 self.db['stored_aliases'] = stored
2686 self.db['stored_aliases'] = stored
2687
2687
2688
2688
2689 def magic_rehashx(self, parameter_s = ''):
2689 def magic_rehashx(self, parameter_s = ''):
2690 """Update the alias table with all executable files in $PATH.
2690 """Update the alias table with all executable files in $PATH.
2691
2691
2692 This version explicitly checks that every entry in $PATH is a file
2692 This version explicitly checks that every entry in $PATH is a file
2693 with execute access (os.X_OK), so it is much slower than %rehash.
2693 with execute access (os.X_OK), so it is much slower than %rehash.
2694
2694
2695 Under Windows, it checks executability as a match agains a
2695 Under Windows, it checks executability as a match agains a
2696 '|'-separated string of extensions, stored in the IPython config
2696 '|'-separated string of extensions, stored in the IPython config
2697 variable win_exec_ext. This defaults to 'exe|com|bat'.
2697 variable win_exec_ext. This defaults to 'exe|com|bat'.
2698
2698
2699 This function also resets the root module cache of module completer,
2699 This function also resets the root module cache of module completer,
2700 used on slow filesystems.
2700 used on slow filesystems.
2701 """
2701 """
2702 from IPython.core.alias import InvalidAliasError
2702 from IPython.core.alias import InvalidAliasError
2703
2703
2704 # for the benefit of module completer in ipy_completers.py
2704 # for the benefit of module completer in ipy_completers.py
2705 del self.db['rootmodules']
2705 del self.db['rootmodules']
2706
2706
2707 path = [os.path.abspath(os.path.expanduser(p)) for p in
2707 path = [os.path.abspath(os.path.expanduser(p)) for p in
2708 os.environ.get('PATH','').split(os.pathsep)]
2708 os.environ.get('PATH','').split(os.pathsep)]
2709 path = filter(os.path.isdir,path)
2709 path = filter(os.path.isdir,path)
2710
2710
2711 syscmdlist = []
2711 syscmdlist = []
2712 # Now define isexec in a cross platform manner.
2712 # Now define isexec in a cross platform manner.
2713 if os.name == 'posix':
2713 if os.name == 'posix':
2714 isexec = lambda fname:os.path.isfile(fname) and \
2714 isexec = lambda fname:os.path.isfile(fname) and \
2715 os.access(fname,os.X_OK)
2715 os.access(fname,os.X_OK)
2716 else:
2716 else:
2717 try:
2717 try:
2718 winext = os.environ['pathext'].replace(';','|').replace('.','')
2718 winext = os.environ['pathext'].replace(';','|').replace('.','')
2719 except KeyError:
2719 except KeyError:
2720 winext = 'exe|com|bat|py'
2720 winext = 'exe|com|bat|py'
2721 if 'py' not in winext:
2721 if 'py' not in winext:
2722 winext += '|py'
2722 winext += '|py'
2723 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2723 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2724 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2724 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2725 savedir = os.getcwd()
2725 savedir = os.getcwd()
2726
2726
2727 # Now walk the paths looking for executables to alias.
2727 # Now walk the paths looking for executables to alias.
2728 try:
2728 try:
2729 # write the whole loop for posix/Windows so we don't have an if in
2729 # write the whole loop for posix/Windows so we don't have an if in
2730 # the innermost part
2730 # the innermost part
2731 if os.name == 'posix':
2731 if os.name == 'posix':
2732 for pdir in path:
2732 for pdir in path:
2733 os.chdir(pdir)
2733 os.chdir(pdir)
2734 for ff in os.listdir(pdir):
2734 for ff in os.listdir(pdir):
2735 if isexec(ff):
2735 if isexec(ff):
2736 try:
2736 try:
2737 # Removes dots from the name since ipython
2737 # Removes dots from the name since ipython
2738 # will assume names with dots to be python.
2738 # will assume names with dots to be python.
2739 self.shell.alias_manager.define_alias(
2739 self.shell.alias_manager.define_alias(
2740 ff.replace('.',''), ff)
2740 ff.replace('.',''), ff)
2741 except InvalidAliasError:
2741 except InvalidAliasError:
2742 pass
2742 pass
2743 else:
2743 else:
2744 syscmdlist.append(ff)
2744 syscmdlist.append(ff)
2745 else:
2745 else:
2746 no_alias = self.shell.alias_manager.no_alias
2746 no_alias = self.shell.alias_manager.no_alias
2747 for pdir in path:
2747 for pdir in path:
2748 os.chdir(pdir)
2748 os.chdir(pdir)
2749 for ff in os.listdir(pdir):
2749 for ff in os.listdir(pdir):
2750 base, ext = os.path.splitext(ff)
2750 base, ext = os.path.splitext(ff)
2751 if isexec(ff) and base.lower() not in no_alias:
2751 if isexec(ff) and base.lower() not in no_alias:
2752 if ext.lower() == '.exe':
2752 if ext.lower() == '.exe':
2753 ff = base
2753 ff = base
2754 try:
2754 try:
2755 # Removes dots from the name since ipython
2755 # Removes dots from the name since ipython
2756 # will assume names with dots to be python.
2756 # will assume names with dots to be python.
2757 self.shell.alias_manager.define_alias(
2757 self.shell.alias_manager.define_alias(
2758 base.lower().replace('.',''), ff)
2758 base.lower().replace('.',''), ff)
2759 except InvalidAliasError:
2759 except InvalidAliasError:
2760 pass
2760 pass
2761 syscmdlist.append(ff)
2761 syscmdlist.append(ff)
2762 db = self.db
2762 db = self.db
2763 db['syscmdlist'] = syscmdlist
2763 db['syscmdlist'] = syscmdlist
2764 finally:
2764 finally:
2765 os.chdir(savedir)
2765 os.chdir(savedir)
2766
2766
2767 def magic_pwd(self, parameter_s = ''):
2767 def magic_pwd(self, parameter_s = ''):
2768 """Return the current working directory path."""
2768 """Return the current working directory path."""
2769 return os.getcwd()
2769 return os.getcwd()
2770
2770
2771 def magic_cd(self, parameter_s=''):
2771 def magic_cd(self, parameter_s=''):
2772 """Change the current working directory.
2772 """Change the current working directory.
2773
2773
2774 This command automatically maintains an internal list of directories
2774 This command automatically maintains an internal list of directories
2775 you visit during your IPython session, in the variable _dh. The
2775 you visit during your IPython session, in the variable _dh. The
2776 command %dhist shows this history nicely formatted. You can also
2776 command %dhist shows this history nicely formatted. You can also
2777 do 'cd -<tab>' to see directory history conveniently.
2777 do 'cd -<tab>' to see directory history conveniently.
2778
2778
2779 Usage:
2779 Usage:
2780
2780
2781 cd 'dir': changes to directory 'dir'.
2781 cd 'dir': changes to directory 'dir'.
2782
2782
2783 cd -: changes to the last visited directory.
2783 cd -: changes to the last visited directory.
2784
2784
2785 cd -<n>: changes to the n-th directory in the directory history.
2785 cd -<n>: changes to the n-th directory in the directory history.
2786
2786
2787 cd --foo: change to directory that matches 'foo' in history
2787 cd --foo: change to directory that matches 'foo' in history
2788
2788
2789 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2789 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2790 (note: cd <bookmark_name> is enough if there is no
2790 (note: cd <bookmark_name> is enough if there is no
2791 directory <bookmark_name>, but a bookmark with the name exists.)
2791 directory <bookmark_name>, but a bookmark with the name exists.)
2792 'cd -b <tab>' allows you to tab-complete bookmark names.
2792 'cd -b <tab>' allows you to tab-complete bookmark names.
2793
2793
2794 Options:
2794 Options:
2795
2795
2796 -q: quiet. Do not print the working directory after the cd command is
2796 -q: quiet. Do not print the working directory after the cd command is
2797 executed. By default IPython's cd command does print this directory,
2797 executed. By default IPython's cd command does print this directory,
2798 since the default prompts do not display path information.
2798 since the default prompts do not display path information.
2799
2799
2800 Note that !cd doesn't work for this purpose because the shell where
2800 Note that !cd doesn't work for this purpose because the shell where
2801 !command runs is immediately discarded after executing 'command'."""
2801 !command runs is immediately discarded after executing 'command'."""
2802
2802
2803 parameter_s = parameter_s.strip()
2803 parameter_s = parameter_s.strip()
2804 #bkms = self.shell.persist.get("bookmarks",{})
2804 #bkms = self.shell.persist.get("bookmarks",{})
2805
2805
2806 oldcwd = os.getcwd()
2806 oldcwd = os.getcwd()
2807 numcd = re.match(r'(-)(\d+)$',parameter_s)
2807 numcd = re.match(r'(-)(\d+)$',parameter_s)
2808 # jump in directory history by number
2808 # jump in directory history by number
2809 if numcd:
2809 if numcd:
2810 nn = int(numcd.group(2))
2810 nn = int(numcd.group(2))
2811 try:
2811 try:
2812 ps = self.shell.user_ns['_dh'][nn]
2812 ps = self.shell.user_ns['_dh'][nn]
2813 except IndexError:
2813 except IndexError:
2814 print 'The requested directory does not exist in history.'
2814 print 'The requested directory does not exist in history.'
2815 return
2815 return
2816 else:
2816 else:
2817 opts = {}
2817 opts = {}
2818 elif parameter_s.startswith('--'):
2818 elif parameter_s.startswith('--'):
2819 ps = None
2819 ps = None
2820 fallback = None
2820 fallback = None
2821 pat = parameter_s[2:]
2821 pat = parameter_s[2:]
2822 dh = self.shell.user_ns['_dh']
2822 dh = self.shell.user_ns['_dh']
2823 # first search only by basename (last component)
2823 # first search only by basename (last component)
2824 for ent in reversed(dh):
2824 for ent in reversed(dh):
2825 if pat in os.path.basename(ent) and os.path.isdir(ent):
2825 if pat in os.path.basename(ent) and os.path.isdir(ent):
2826 ps = ent
2826 ps = ent
2827 break
2827 break
2828
2828
2829 if fallback is None and pat in ent and os.path.isdir(ent):
2829 if fallback is None and pat in ent and os.path.isdir(ent):
2830 fallback = ent
2830 fallback = ent
2831
2831
2832 # if we have no last part match, pick the first full path match
2832 # if we have no last part match, pick the first full path match
2833 if ps is None:
2833 if ps is None:
2834 ps = fallback
2834 ps = fallback
2835
2835
2836 if ps is None:
2836 if ps is None:
2837 print "No matching entry in directory history"
2837 print "No matching entry in directory history"
2838 return
2838 return
2839 else:
2839 else:
2840 opts = {}
2840 opts = {}
2841
2841
2842
2842
2843 else:
2843 else:
2844 #turn all non-space-escaping backslashes to slashes,
2844 #turn all non-space-escaping backslashes to slashes,
2845 # for c:\windows\directory\names\
2845 # for c:\windows\directory\names\
2846 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2846 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2847 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2847 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2848 # jump to previous
2848 # jump to previous
2849 if ps == '-':
2849 if ps == '-':
2850 try:
2850 try:
2851 ps = self.shell.user_ns['_dh'][-2]
2851 ps = self.shell.user_ns['_dh'][-2]
2852 except IndexError:
2852 except IndexError:
2853 raise UsageError('%cd -: No previous directory to change to.')
2853 raise UsageError('%cd -: No previous directory to change to.')
2854 # jump to bookmark if needed
2854 # jump to bookmark if needed
2855 else:
2855 else:
2856 if not os.path.isdir(ps) or opts.has_key('b'):
2856 if not os.path.isdir(ps) or opts.has_key('b'):
2857 bkms = self.db.get('bookmarks', {})
2857 bkms = self.db.get('bookmarks', {})
2858
2858
2859 if bkms.has_key(ps):
2859 if bkms.has_key(ps):
2860 target = bkms[ps]
2860 target = bkms[ps]
2861 print '(bookmark:%s) -> %s' % (ps,target)
2861 print '(bookmark:%s) -> %s' % (ps,target)
2862 ps = target
2862 ps = target
2863 else:
2863 else:
2864 if opts.has_key('b'):
2864 if opts.has_key('b'):
2865 raise UsageError("Bookmark '%s' not found. "
2865 raise UsageError("Bookmark '%s' not found. "
2866 "Use '%%bookmark -l' to see your bookmarks." % ps)
2866 "Use '%%bookmark -l' to see your bookmarks." % ps)
2867
2867
2868 # at this point ps should point to the target dir
2868 # at this point ps should point to the target dir
2869 if ps:
2869 if ps:
2870 try:
2870 try:
2871 os.chdir(os.path.expanduser(ps))
2871 os.chdir(os.path.expanduser(ps))
2872 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2872 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2873 set_term_title('IPython: ' + abbrev_cwd())
2873 set_term_title('IPython: ' + abbrev_cwd())
2874 except OSError:
2874 except OSError:
2875 print sys.exc_info()[1]
2875 print sys.exc_info()[1]
2876 else:
2876 else:
2877 cwd = os.getcwd()
2877 cwd = os.getcwd()
2878 dhist = self.shell.user_ns['_dh']
2878 dhist = self.shell.user_ns['_dh']
2879 if oldcwd != cwd:
2879 if oldcwd != cwd:
2880 dhist.append(cwd)
2880 dhist.append(cwd)
2881 self.db['dhist'] = compress_dhist(dhist)[-100:]
2881 self.db['dhist'] = compress_dhist(dhist)[-100:]
2882
2882
2883 else:
2883 else:
2884 os.chdir(self.shell.home_dir)
2884 os.chdir(self.shell.home_dir)
2885 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2885 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2886 set_term_title('IPython: ' + '~')
2886 set_term_title('IPython: ' + '~')
2887 cwd = os.getcwd()
2887 cwd = os.getcwd()
2888 dhist = self.shell.user_ns['_dh']
2888 dhist = self.shell.user_ns['_dh']
2889
2889
2890 if oldcwd != cwd:
2890 if oldcwd != cwd:
2891 dhist.append(cwd)
2891 dhist.append(cwd)
2892 self.db['dhist'] = compress_dhist(dhist)[-100:]
2892 self.db['dhist'] = compress_dhist(dhist)[-100:]
2893 if not 'q' in opts and self.shell.user_ns['_dh']:
2893 if not 'q' in opts and self.shell.user_ns['_dh']:
2894 print self.shell.user_ns['_dh'][-1]
2894 print self.shell.user_ns['_dh'][-1]
2895
2895
2896
2896
2897 def magic_env(self, parameter_s=''):
2897 def magic_env(self, parameter_s=''):
2898 """List environment variables."""
2898 """List environment variables."""
2899
2899
2900 return os.environ.data
2900 return os.environ.data
2901
2901
2902 def magic_pushd(self, parameter_s=''):
2902 def magic_pushd(self, parameter_s=''):
2903 """Place the current dir on stack and change directory.
2903 """Place the current dir on stack and change directory.
2904
2904
2905 Usage:\\
2905 Usage:\\
2906 %pushd ['dirname']
2906 %pushd ['dirname']
2907 """
2907 """
2908
2908
2909 dir_s = self.shell.dir_stack
2909 dir_s = self.shell.dir_stack
2910 tgt = os.path.expanduser(parameter_s)
2910 tgt = os.path.expanduser(parameter_s)
2911 cwd = os.getcwd().replace(self.home_dir,'~')
2911 cwd = os.getcwd().replace(self.home_dir,'~')
2912 if tgt:
2912 if tgt:
2913 self.magic_cd(parameter_s)
2913 self.magic_cd(parameter_s)
2914 dir_s.insert(0,cwd)
2914 dir_s.insert(0,cwd)
2915 return self.magic_dirs()
2915 return self.magic_dirs()
2916
2916
2917 def magic_popd(self, parameter_s=''):
2917 def magic_popd(self, parameter_s=''):
2918 """Change to directory popped off the top of the stack.
2918 """Change to directory popped off the top of the stack.
2919 """
2919 """
2920 if not self.shell.dir_stack:
2920 if not self.shell.dir_stack:
2921 raise UsageError("%popd on empty stack")
2921 raise UsageError("%popd on empty stack")
2922 top = self.shell.dir_stack.pop(0)
2922 top = self.shell.dir_stack.pop(0)
2923 self.magic_cd(top)
2923 self.magic_cd(top)
2924 print "popd ->",top
2924 print "popd ->",top
2925
2925
2926 def magic_dirs(self, parameter_s=''):
2926 def magic_dirs(self, parameter_s=''):
2927 """Return the current directory stack."""
2927 """Return the current directory stack."""
2928
2928
2929 return self.shell.dir_stack
2929 return self.shell.dir_stack
2930
2930
2931 def magic_dhist(self, parameter_s=''):
2931 def magic_dhist(self, parameter_s=''):
2932 """Print your history of visited directories.
2932 """Print your history of visited directories.
2933
2933
2934 %dhist -> print full history\\
2934 %dhist -> print full history\\
2935 %dhist n -> print last n entries only\\
2935 %dhist n -> print last n entries only\\
2936 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2936 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2937
2937
2938 This history is automatically maintained by the %cd command, and
2938 This history is automatically maintained by the %cd command, and
2939 always available as the global list variable _dh. You can use %cd -<n>
2939 always available as the global list variable _dh. You can use %cd -<n>
2940 to go to directory number <n>.
2940 to go to directory number <n>.
2941
2941
2942 Note that most of time, you should view directory history by entering
2942 Note that most of time, you should view directory history by entering
2943 cd -<TAB>.
2943 cd -<TAB>.
2944
2944
2945 """
2945 """
2946
2946
2947 dh = self.shell.user_ns['_dh']
2947 dh = self.shell.user_ns['_dh']
2948 if parameter_s:
2948 if parameter_s:
2949 try:
2949 try:
2950 args = map(int,parameter_s.split())
2950 args = map(int,parameter_s.split())
2951 except:
2951 except:
2952 self.arg_err(Magic.magic_dhist)
2952 self.arg_err(Magic.magic_dhist)
2953 return
2953 return
2954 if len(args) == 1:
2954 if len(args) == 1:
2955 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2955 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2956 elif len(args) == 2:
2956 elif len(args) == 2:
2957 ini,fin = args
2957 ini,fin = args
2958 else:
2958 else:
2959 self.arg_err(Magic.magic_dhist)
2959 self.arg_err(Magic.magic_dhist)
2960 return
2960 return
2961 else:
2961 else:
2962 ini,fin = 0,len(dh)
2962 ini,fin = 0,len(dh)
2963 nlprint(dh,
2963 nlprint(dh,
2964 header = 'Directory history (kept in _dh)',
2964 header = 'Directory history (kept in _dh)',
2965 start=ini,stop=fin)
2965 start=ini,stop=fin)
2966
2966
2967 @testdec.skip_doctest
2967 @testdec.skip_doctest
2968 def magic_sc(self, parameter_s=''):
2968 def magic_sc(self, parameter_s=''):
2969 """Shell capture - execute a shell command and capture its output.
2969 """Shell capture - execute a shell command and capture its output.
2970
2970
2971 DEPRECATED. Suboptimal, retained for backwards compatibility.
2971 DEPRECATED. Suboptimal, retained for backwards compatibility.
2972
2972
2973 You should use the form 'var = !command' instead. Example:
2973 You should use the form 'var = !command' instead. Example:
2974
2974
2975 "%sc -l myfiles = ls ~" should now be written as
2975 "%sc -l myfiles = ls ~" should now be written as
2976
2976
2977 "myfiles = !ls ~"
2977 "myfiles = !ls ~"
2978
2978
2979 myfiles.s, myfiles.l and myfiles.n still apply as documented
2979 myfiles.s, myfiles.l and myfiles.n still apply as documented
2980 below.
2980 below.
2981
2981
2982 --
2982 --
2983 %sc [options] varname=command
2983 %sc [options] varname=command
2984
2984
2985 IPython will run the given command using commands.getoutput(), and
2985 IPython will run the given command using commands.getoutput(), and
2986 will then update the user's interactive namespace with a variable
2986 will then update the user's interactive namespace with a variable
2987 called varname, containing the value of the call. Your command can
2987 called varname, containing the value of the call. Your command can
2988 contain shell wildcards, pipes, etc.
2988 contain shell wildcards, pipes, etc.
2989
2989
2990 The '=' sign in the syntax is mandatory, and the variable name you
2990 The '=' sign in the syntax is mandatory, and the variable name you
2991 supply must follow Python's standard conventions for valid names.
2991 supply must follow Python's standard conventions for valid names.
2992
2992
2993 (A special format without variable name exists for internal use)
2993 (A special format without variable name exists for internal use)
2994
2994
2995 Options:
2995 Options:
2996
2996
2997 -l: list output. Split the output on newlines into a list before
2997 -l: list output. Split the output on newlines into a list before
2998 assigning it to the given variable. By default the output is stored
2998 assigning it to the given variable. By default the output is stored
2999 as a single string.
2999 as a single string.
3000
3000
3001 -v: verbose. Print the contents of the variable.
3001 -v: verbose. Print the contents of the variable.
3002
3002
3003 In most cases you should not need to split as a list, because the
3003 In most cases you should not need to split as a list, because the
3004 returned value is a special type of string which can automatically
3004 returned value is a special type of string which can automatically
3005 provide its contents either as a list (split on newlines) or as a
3005 provide its contents either as a list (split on newlines) or as a
3006 space-separated string. These are convenient, respectively, either
3006 space-separated string. These are convenient, respectively, either
3007 for sequential processing or to be passed to a shell command.
3007 for sequential processing or to be passed to a shell command.
3008
3008
3009 For example:
3009 For example:
3010
3010
3011 # all-random
3011 # all-random
3012
3012
3013 # Capture into variable a
3013 # Capture into variable a
3014 In [1]: sc a=ls *py
3014 In [1]: sc a=ls *py
3015
3015
3016 # a is a string with embedded newlines
3016 # a is a string with embedded newlines
3017 In [2]: a
3017 In [2]: a
3018 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3018 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3019
3019
3020 # which can be seen as a list:
3020 # which can be seen as a list:
3021 In [3]: a.l
3021 In [3]: a.l
3022 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3022 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3023
3023
3024 # or as a whitespace-separated string:
3024 # or as a whitespace-separated string:
3025 In [4]: a.s
3025 In [4]: a.s
3026 Out[4]: 'setup.py win32_manual_post_install.py'
3026 Out[4]: 'setup.py win32_manual_post_install.py'
3027
3027
3028 # a.s is useful to pass as a single command line:
3028 # a.s is useful to pass as a single command line:
3029 In [5]: !wc -l $a.s
3029 In [5]: !wc -l $a.s
3030 146 setup.py
3030 146 setup.py
3031 130 win32_manual_post_install.py
3031 130 win32_manual_post_install.py
3032 276 total
3032 276 total
3033
3033
3034 # while the list form is useful to loop over:
3034 # while the list form is useful to loop over:
3035 In [6]: for f in a.l:
3035 In [6]: for f in a.l:
3036 ...: !wc -l $f
3036 ...: !wc -l $f
3037 ...:
3037 ...:
3038 146 setup.py
3038 146 setup.py
3039 130 win32_manual_post_install.py
3039 130 win32_manual_post_install.py
3040
3040
3041 Similiarly, the lists returned by the -l option are also special, in
3041 Similiarly, the lists returned by the -l option are also special, in
3042 the sense that you can equally invoke the .s attribute on them to
3042 the sense that you can equally invoke the .s attribute on them to
3043 automatically get a whitespace-separated string from their contents:
3043 automatically get a whitespace-separated string from their contents:
3044
3044
3045 In [7]: sc -l b=ls *py
3045 In [7]: sc -l b=ls *py
3046
3046
3047 In [8]: b
3047 In [8]: b
3048 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3048 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3049
3049
3050 In [9]: b.s
3050 In [9]: b.s
3051 Out[9]: 'setup.py win32_manual_post_install.py'
3051 Out[9]: 'setup.py win32_manual_post_install.py'
3052
3052
3053 In summary, both the lists and strings used for ouptut capture have
3053 In summary, both the lists and strings used for ouptut capture have
3054 the following special attributes:
3054 the following special attributes:
3055
3055
3056 .l (or .list) : value as list.
3056 .l (or .list) : value as list.
3057 .n (or .nlstr): value as newline-separated string.
3057 .n (or .nlstr): value as newline-separated string.
3058 .s (or .spstr): value as space-separated string.
3058 .s (or .spstr): value as space-separated string.
3059 """
3059 """
3060
3060
3061 opts,args = self.parse_options(parameter_s,'lv')
3061 opts,args = self.parse_options(parameter_s,'lv')
3062 # Try to get a variable name and command to run
3062 # Try to get a variable name and command to run
3063 try:
3063 try:
3064 # the variable name must be obtained from the parse_options
3064 # the variable name must be obtained from the parse_options
3065 # output, which uses shlex.split to strip options out.
3065 # output, which uses shlex.split to strip options out.
3066 var,_ = args.split('=',1)
3066 var,_ = args.split('=',1)
3067 var = var.strip()
3067 var = var.strip()
3068 # But the the command has to be extracted from the original input
3068 # But the the command has to be extracted from the original input
3069 # parameter_s, not on what parse_options returns, to avoid the
3069 # parameter_s, not on what parse_options returns, to avoid the
3070 # quote stripping which shlex.split performs on it.
3070 # quote stripping which shlex.split performs on it.
3071 _,cmd = parameter_s.split('=',1)
3071 _,cmd = parameter_s.split('=',1)
3072 except ValueError:
3072 except ValueError:
3073 var,cmd = '',''
3073 var,cmd = '',''
3074 # If all looks ok, proceed
3074 # If all looks ok, proceed
3075 out,err = self.shell.getoutputerror(cmd)
3075 out = self.shell.getoutput(cmd)
3076 if err:
3077 print >> IPython.utils.io.Term.cerr, err
3078 if opts.has_key('l'):
3076 if opts.has_key('l'):
3079 out = SList(out.split('\n'))
3077 out = SList(out.split('\n'))
3080 else:
3078 else:
3081 out = LSString(out)
3079 out = LSString(out)
3082 if opts.has_key('v'):
3080 if opts.has_key('v'):
3083 print '%s ==\n%s' % (var,pformat(out))
3081 print '%s ==\n%s' % (var,pformat(out))
3084 if var:
3082 if var:
3085 self.shell.user_ns.update({var:out})
3083 self.shell.user_ns.update({var:out})
3086 else:
3084 else:
3087 return out
3085 return out
3088
3086
3089 def magic_sx(self, parameter_s=''):
3087 def magic_sx(self, parameter_s=''):
3090 """Shell execute - run a shell command and capture its output.
3088 """Shell execute - run a shell command and capture its output.
3091
3089
3092 %sx command
3090 %sx command
3093
3091
3094 IPython will run the given command using commands.getoutput(), and
3092 IPython will run the given command using commands.getoutput(), and
3095 return the result formatted as a list (split on '\\n'). Since the
3093 return the result formatted as a list (split on '\\n'). Since the
3096 output is _returned_, it will be stored in ipython's regular output
3094 output is _returned_, it will be stored in ipython's regular output
3097 cache Out[N] and in the '_N' automatic variables.
3095 cache Out[N] and in the '_N' automatic variables.
3098
3096
3099 Notes:
3097 Notes:
3100
3098
3101 1) If an input line begins with '!!', then %sx is automatically
3099 1) If an input line begins with '!!', then %sx is automatically
3102 invoked. That is, while:
3100 invoked. That is, while:
3103 !ls
3101 !ls
3104 causes ipython to simply issue system('ls'), typing
3102 causes ipython to simply issue system('ls'), typing
3105 !!ls
3103 !!ls
3106 is a shorthand equivalent to:
3104 is a shorthand equivalent to:
3107 %sx ls
3105 %sx ls
3108
3106
3109 2) %sx differs from %sc in that %sx automatically splits into a list,
3107 2) %sx differs from %sc in that %sx automatically splits into a list,
3110 like '%sc -l'. The reason for this is to make it as easy as possible
3108 like '%sc -l'. The reason for this is to make it as easy as possible
3111 to process line-oriented shell output via further python commands.
3109 to process line-oriented shell output via further python commands.
3112 %sc is meant to provide much finer control, but requires more
3110 %sc is meant to provide much finer control, but requires more
3113 typing.
3111 typing.
3114
3112
3115 3) Just like %sc -l, this is a list with special attributes:
3113 3) Just like %sc -l, this is a list with special attributes:
3116
3114
3117 .l (or .list) : value as list.
3115 .l (or .list) : value as list.
3118 .n (or .nlstr): value as newline-separated string.
3116 .n (or .nlstr): value as newline-separated string.
3119 .s (or .spstr): value as whitespace-separated string.
3117 .s (or .spstr): value as whitespace-separated string.
3120
3118
3121 This is very useful when trying to use such lists as arguments to
3119 This is very useful when trying to use such lists as arguments to
3122 system commands."""
3120 system commands."""
3123
3121
3124 if parameter_s:
3122 if parameter_s:
3125 out,err = self.shell.getoutputerror(parameter_s)
3123 out = self.shell.getoutput(parameter_s)
3126 if err:
3124 if out is not None:
3127 print >> IPython.utils.io.Term.cerr, err
3125 return SList(out.splitlines())
3128 return SList(out.split('\n'))
3129
3126
3130 def magic_r(self, parameter_s=''):
3127 def magic_r(self, parameter_s=''):
3131 """Repeat previous input.
3128 """Repeat previous input.
3132
3129
3133 Note: Consider using the more powerfull %rep instead!
3130 Note: Consider using the more powerfull %rep instead!
3134
3131
3135 If given an argument, repeats the previous command which starts with
3132 If given an argument, repeats the previous command which starts with
3136 the same string, otherwise it just repeats the previous input.
3133 the same string, otherwise it just repeats the previous input.
3137
3134
3138 Shell escaped commands (with ! as first character) are not recognized
3135 Shell escaped commands (with ! as first character) are not recognized
3139 by this system, only pure python code and magic commands.
3136 by this system, only pure python code and magic commands.
3140 """
3137 """
3141
3138
3142 start = parameter_s.strip()
3139 start = parameter_s.strip()
3143 esc_magic = ESC_MAGIC
3140 esc_magic = ESC_MAGIC
3144 # Identify magic commands even if automagic is on (which means
3141 # Identify magic commands even if automagic is on (which means
3145 # the in-memory version is different from that typed by the user).
3142 # the in-memory version is different from that typed by the user).
3146 if self.shell.automagic:
3143 if self.shell.automagic:
3147 start_magic = esc_magic+start
3144 start_magic = esc_magic+start
3148 else:
3145 else:
3149 start_magic = start
3146 start_magic = start
3150 # Look through the input history in reverse
3147 # Look through the input history in reverse
3151 for n in range(len(self.shell.input_hist)-2,0,-1):
3148 for n in range(len(self.shell.input_hist)-2,0,-1):
3152 input = self.shell.input_hist[n]
3149 input = self.shell.input_hist[n]
3153 # skip plain 'r' lines so we don't recurse to infinity
3150 # skip plain 'r' lines so we don't recurse to infinity
3154 if input != '_ip.magic("r")\n' and \
3151 if input != '_ip.magic("r")\n' and \
3155 (input.startswith(start) or input.startswith(start_magic)):
3152 (input.startswith(start) or input.startswith(start_magic)):
3156 #print 'match',`input` # dbg
3153 #print 'match',`input` # dbg
3157 print 'Executing:',input,
3154 print 'Executing:',input,
3158 self.shell.runlines(input)
3155 self.shell.runlines(input)
3159 return
3156 return
3160 print 'No previous input matching `%s` found.' % start
3157 print 'No previous input matching `%s` found.' % start
3161
3158
3162
3159
3163 def magic_bookmark(self, parameter_s=''):
3160 def magic_bookmark(self, parameter_s=''):
3164 """Manage IPython's bookmark system.
3161 """Manage IPython's bookmark system.
3165
3162
3166 %bookmark <name> - set bookmark to current dir
3163 %bookmark <name> - set bookmark to current dir
3167 %bookmark <name> <dir> - set bookmark to <dir>
3164 %bookmark <name> <dir> - set bookmark to <dir>
3168 %bookmark -l - list all bookmarks
3165 %bookmark -l - list all bookmarks
3169 %bookmark -d <name> - remove bookmark
3166 %bookmark -d <name> - remove bookmark
3170 %bookmark -r - remove all bookmarks
3167 %bookmark -r - remove all bookmarks
3171
3168
3172 You can later on access a bookmarked folder with:
3169 You can later on access a bookmarked folder with:
3173 %cd -b <name>
3170 %cd -b <name>
3174 or simply '%cd <name>' if there is no directory called <name> AND
3171 or simply '%cd <name>' if there is no directory called <name> AND
3175 there is such a bookmark defined.
3172 there is such a bookmark defined.
3176
3173
3177 Your bookmarks persist through IPython sessions, but they are
3174 Your bookmarks persist through IPython sessions, but they are
3178 associated with each profile."""
3175 associated with each profile."""
3179
3176
3180 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3177 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3181 if len(args) > 2:
3178 if len(args) > 2:
3182 raise UsageError("%bookmark: too many arguments")
3179 raise UsageError("%bookmark: too many arguments")
3183
3180
3184 bkms = self.db.get('bookmarks',{})
3181 bkms = self.db.get('bookmarks',{})
3185
3182
3186 if opts.has_key('d'):
3183 if opts.has_key('d'):
3187 try:
3184 try:
3188 todel = args[0]
3185 todel = args[0]
3189 except IndexError:
3186 except IndexError:
3190 raise UsageError(
3187 raise UsageError(
3191 "%bookmark -d: must provide a bookmark to delete")
3188 "%bookmark -d: must provide a bookmark to delete")
3192 else:
3189 else:
3193 try:
3190 try:
3194 del bkms[todel]
3191 del bkms[todel]
3195 except KeyError:
3192 except KeyError:
3196 raise UsageError(
3193 raise UsageError(
3197 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3194 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3198
3195
3199 elif opts.has_key('r'):
3196 elif opts.has_key('r'):
3200 bkms = {}
3197 bkms = {}
3201 elif opts.has_key('l'):
3198 elif opts.has_key('l'):
3202 bks = bkms.keys()
3199 bks = bkms.keys()
3203 bks.sort()
3200 bks.sort()
3204 if bks:
3201 if bks:
3205 size = max(map(len,bks))
3202 size = max(map(len,bks))
3206 else:
3203 else:
3207 size = 0
3204 size = 0
3208 fmt = '%-'+str(size)+'s -> %s'
3205 fmt = '%-'+str(size)+'s -> %s'
3209 print 'Current bookmarks:'
3206 print 'Current bookmarks:'
3210 for bk in bks:
3207 for bk in bks:
3211 print fmt % (bk,bkms[bk])
3208 print fmt % (bk,bkms[bk])
3212 else:
3209 else:
3213 if not args:
3210 if not args:
3214 raise UsageError("%bookmark: You must specify the bookmark name")
3211 raise UsageError("%bookmark: You must specify the bookmark name")
3215 elif len(args)==1:
3212 elif len(args)==1:
3216 bkms[args[0]] = os.getcwd()
3213 bkms[args[0]] = os.getcwd()
3217 elif len(args)==2:
3214 elif len(args)==2:
3218 bkms[args[0]] = args[1]
3215 bkms[args[0]] = args[1]
3219 self.db['bookmarks'] = bkms
3216 self.db['bookmarks'] = bkms
3220
3217
3221 def magic_pycat(self, parameter_s=''):
3218 def magic_pycat(self, parameter_s=''):
3222 """Show a syntax-highlighted file through a pager.
3219 """Show a syntax-highlighted file through a pager.
3223
3220
3224 This magic is similar to the cat utility, but it will assume the file
3221 This magic is similar to the cat utility, but it will assume the file
3225 to be Python source and will show it with syntax highlighting. """
3222 to be Python source and will show it with syntax highlighting. """
3226
3223
3227 try:
3224 try:
3228 filename = get_py_filename(parameter_s)
3225 filename = get_py_filename(parameter_s)
3229 cont = file_read(filename)
3226 cont = file_read(filename)
3230 except IOError:
3227 except IOError:
3231 try:
3228 try:
3232 cont = eval(parameter_s,self.user_ns)
3229 cont = eval(parameter_s,self.user_ns)
3233 except NameError:
3230 except NameError:
3234 cont = None
3231 cont = None
3235 if cont is None:
3232 if cont is None:
3236 print "Error: no such file or variable"
3233 print "Error: no such file or variable"
3237 return
3234 return
3238
3235
3239 page.page(self.shell.pycolorize(cont))
3236 page.page(self.shell.pycolorize(cont))
3240
3237
3241 def _rerun_pasted(self):
3238 def _rerun_pasted(self):
3242 """ Rerun a previously pasted command.
3239 """ Rerun a previously pasted command.
3243 """
3240 """
3244 b = self.user_ns.get('pasted_block', None)
3241 b = self.user_ns.get('pasted_block', None)
3245 if b is None:
3242 if b is None:
3246 raise UsageError('No previous pasted block available')
3243 raise UsageError('No previous pasted block available')
3247 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3244 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3248 exec b in self.user_ns
3245 exec b in self.user_ns
3249
3246
3250 def _get_pasted_lines(self, sentinel):
3247 def _get_pasted_lines(self, sentinel):
3251 """ Yield pasted lines until the user enters the given sentinel value.
3248 """ Yield pasted lines until the user enters the given sentinel value.
3252 """
3249 """
3253 from IPython.core import interactiveshell
3250 from IPython.core import interactiveshell
3254 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3251 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3255 while True:
3252 while True:
3256 l = interactiveshell.raw_input_original(':')
3253 l = interactiveshell.raw_input_original(':')
3257 if l == sentinel:
3254 if l == sentinel:
3258 return
3255 return
3259 else:
3256 else:
3260 yield l
3257 yield l
3261
3258
3262 def _strip_pasted_lines_for_code(self, raw_lines):
3259 def _strip_pasted_lines_for_code(self, raw_lines):
3263 """ Strip non-code parts of a sequence of lines to return a block of
3260 """ Strip non-code parts of a sequence of lines to return a block of
3264 code.
3261 code.
3265 """
3262 """
3266 # Regular expressions that declare text we strip from the input:
3263 # Regular expressions that declare text we strip from the input:
3267 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3264 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3268 r'^\s*(\s?>)+', # Python input prompt
3265 r'^\s*(\s?>)+', # Python input prompt
3269 r'^\s*\.{3,}', # Continuation prompts
3266 r'^\s*\.{3,}', # Continuation prompts
3270 r'^\++',
3267 r'^\++',
3271 ]
3268 ]
3272
3269
3273 strip_from_start = map(re.compile,strip_re)
3270 strip_from_start = map(re.compile,strip_re)
3274
3271
3275 lines = []
3272 lines = []
3276 for l in raw_lines:
3273 for l in raw_lines:
3277 for pat in strip_from_start:
3274 for pat in strip_from_start:
3278 l = pat.sub('',l)
3275 l = pat.sub('',l)
3279 lines.append(l)
3276 lines.append(l)
3280
3277
3281 block = "\n".join(lines) + '\n'
3278 block = "\n".join(lines) + '\n'
3282 #print "block:\n",block
3279 #print "block:\n",block
3283 return block
3280 return block
3284
3281
3285 def _execute_block(self, block, par):
3282 def _execute_block(self, block, par):
3286 """ Execute a block, or store it in a variable, per the user's request.
3283 """ Execute a block, or store it in a variable, per the user's request.
3287 """
3284 """
3288 if not par:
3285 if not par:
3289 b = textwrap.dedent(block)
3286 b = textwrap.dedent(block)
3290 self.user_ns['pasted_block'] = b
3287 self.user_ns['pasted_block'] = b
3291 exec b in self.user_ns
3288 exec b in self.user_ns
3292 else:
3289 else:
3293 self.user_ns[par] = SList(block.splitlines())
3290 self.user_ns[par] = SList(block.splitlines())
3294 print "Block assigned to '%s'" % par
3291 print "Block assigned to '%s'" % par
3295
3292
3296 def magic_cpaste(self, parameter_s=''):
3293 def magic_cpaste(self, parameter_s=''):
3297 """Allows you to paste & execute a pre-formatted code block from clipboard.
3294 """Allows you to paste & execute a pre-formatted code block from clipboard.
3298
3295
3299 You must terminate the block with '--' (two minus-signs) alone on the
3296 You must terminate the block with '--' (two minus-signs) alone on the
3300 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3297 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
3301 is the new sentinel for this operation)
3298 is the new sentinel for this operation)
3302
3299
3303 The block is dedented prior to execution to enable execution of method
3300 The block is dedented prior to execution to enable execution of method
3304 definitions. '>' and '+' characters at the beginning of a line are
3301 definitions. '>' and '+' characters at the beginning of a line are
3305 ignored, to allow pasting directly from e-mails, diff files and
3302 ignored, to allow pasting directly from e-mails, diff files and
3306 doctests (the '...' continuation prompt is also stripped). The
3303 doctests (the '...' continuation prompt is also stripped). The
3307 executed block is also assigned to variable named 'pasted_block' for
3304 executed block is also assigned to variable named 'pasted_block' for
3308 later editing with '%edit pasted_block'.
3305 later editing with '%edit pasted_block'.
3309
3306
3310 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3307 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
3311 This assigns the pasted block to variable 'foo' as string, without
3308 This assigns the pasted block to variable 'foo' as string, without
3312 dedenting or executing it (preceding >>> and + is still stripped)
3309 dedenting or executing it (preceding >>> and + is still stripped)
3313
3310
3314 '%cpaste -r' re-executes the block previously entered by cpaste.
3311 '%cpaste -r' re-executes the block previously entered by cpaste.
3315
3312
3316 Do not be alarmed by garbled output on Windows (it's a readline bug).
3313 Do not be alarmed by garbled output on Windows (it's a readline bug).
3317 Just press enter and type -- (and press enter again) and the block
3314 Just press enter and type -- (and press enter again) and the block
3318 will be what was just pasted.
3315 will be what was just pasted.
3319
3316
3320 IPython statements (magics, shell escapes) are not supported (yet).
3317 IPython statements (magics, shell escapes) are not supported (yet).
3321
3318
3322 See also
3319 See also
3323 --------
3320 --------
3324 paste: automatically pull code from clipboard.
3321 paste: automatically pull code from clipboard.
3325 """
3322 """
3326
3323
3327 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3324 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
3328 par = args.strip()
3325 par = args.strip()
3329 if opts.has_key('r'):
3326 if opts.has_key('r'):
3330 self._rerun_pasted()
3327 self._rerun_pasted()
3331 return
3328 return
3332
3329
3333 sentinel = opts.get('s','--')
3330 sentinel = opts.get('s','--')
3334
3331
3335 block = self._strip_pasted_lines_for_code(
3332 block = self._strip_pasted_lines_for_code(
3336 self._get_pasted_lines(sentinel))
3333 self._get_pasted_lines(sentinel))
3337
3334
3338 self._execute_block(block, par)
3335 self._execute_block(block, par)
3339
3336
3340 def magic_paste(self, parameter_s=''):
3337 def magic_paste(self, parameter_s=''):
3341 """Allows you to paste & execute a pre-formatted code block from clipboard.
3338 """Allows you to paste & execute a pre-formatted code block from clipboard.
3342
3339
3343 The text is pulled directly from the clipboard without user
3340 The text is pulled directly from the clipboard without user
3344 intervention and printed back on the screen before execution (unless
3341 intervention and printed back on the screen before execution (unless
3345 the -q flag is given to force quiet mode).
3342 the -q flag is given to force quiet mode).
3346
3343
3347 The block is dedented prior to execution to enable execution of method
3344 The block is dedented prior to execution to enable execution of method
3348 definitions. '>' and '+' characters at the beginning of a line are
3345 definitions. '>' and '+' characters at the beginning of a line are
3349 ignored, to allow pasting directly from e-mails, diff files and
3346 ignored, to allow pasting directly from e-mails, diff files and
3350 doctests (the '...' continuation prompt is also stripped). The
3347 doctests (the '...' continuation prompt is also stripped). The
3351 executed block is also assigned to variable named 'pasted_block' for
3348 executed block is also assigned to variable named 'pasted_block' for
3352 later editing with '%edit pasted_block'.
3349 later editing with '%edit pasted_block'.
3353
3350
3354 You can also pass a variable name as an argument, e.g. '%paste foo'.
3351 You can also pass a variable name as an argument, e.g. '%paste foo'.
3355 This assigns the pasted block to variable 'foo' as string, without
3352 This assigns the pasted block to variable 'foo' as string, without
3356 dedenting or executing it (preceding >>> and + is still stripped)
3353 dedenting or executing it (preceding >>> and + is still stripped)
3357
3354
3358 Options
3355 Options
3359 -------
3356 -------
3360
3357
3361 -r: re-executes the block previously entered by cpaste.
3358 -r: re-executes the block previously entered by cpaste.
3362
3359
3363 -q: quiet mode: do not echo the pasted text back to the terminal.
3360 -q: quiet mode: do not echo the pasted text back to the terminal.
3364
3361
3365 IPython statements (magics, shell escapes) are not supported (yet).
3362 IPython statements (magics, shell escapes) are not supported (yet).
3366
3363
3367 See also
3364 See also
3368 --------
3365 --------
3369 cpaste: manually paste code into terminal until you mark its end.
3366 cpaste: manually paste code into terminal until you mark its end.
3370 """
3367 """
3371 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3368 opts,args = self.parse_options(parameter_s,'rq',mode='string')
3372 par = args.strip()
3369 par = args.strip()
3373 if opts.has_key('r'):
3370 if opts.has_key('r'):
3374 self._rerun_pasted()
3371 self._rerun_pasted()
3375 return
3372 return
3376
3373
3377 text = self.shell.hooks.clipboard_get()
3374 text = self.shell.hooks.clipboard_get()
3378 block = self._strip_pasted_lines_for_code(text.splitlines())
3375 block = self._strip_pasted_lines_for_code(text.splitlines())
3379
3376
3380 # By default, echo back to terminal unless quiet mode is requested
3377 # By default, echo back to terminal unless quiet mode is requested
3381 if not opts.has_key('q'):
3378 if not opts.has_key('q'):
3382 write = self.shell.write
3379 write = self.shell.write
3383 write(self.shell.pycolorize(block))
3380 write(self.shell.pycolorize(block))
3384 if not block.endswith('\n'):
3381 if not block.endswith('\n'):
3385 write('\n')
3382 write('\n')
3386 write("## -- End pasted text --\n")
3383 write("## -- End pasted text --\n")
3387
3384
3388 self._execute_block(block, par)
3385 self._execute_block(block, par)
3389
3386
3390 def magic_quickref(self,arg):
3387 def magic_quickref(self,arg):
3391 """ Show a quick reference sheet """
3388 """ Show a quick reference sheet """
3392 import IPython.core.usage
3389 import IPython.core.usage
3393 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3390 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3394
3391
3395 page.page(qr)
3392 page.page(qr)
3396
3393
3397 def magic_doctest_mode(self,parameter_s=''):
3394 def magic_doctest_mode(self,parameter_s=''):
3398 """Toggle doctest mode on and off.
3395 """Toggle doctest mode on and off.
3399
3396
3400 This mode allows you to toggle the prompt behavior between normal
3397 This mode allows you to toggle the prompt behavior between normal
3401 IPython prompts and ones that are as similar to the default IPython
3398 IPython prompts and ones that are as similar to the default IPython
3402 interpreter as possible.
3399 interpreter as possible.
3403
3400
3404 It also supports the pasting of code snippets that have leading '>>>'
3401 It also supports the pasting of code snippets that have leading '>>>'
3405 and '...' prompts in them. This means that you can paste doctests from
3402 and '...' prompts in them. This means that you can paste doctests from
3406 files or docstrings (even if they have leading whitespace), and the
3403 files or docstrings (even if they have leading whitespace), and the
3407 code will execute correctly. You can then use '%history -tn' to see
3404 code will execute correctly. You can then use '%history -tn' to see
3408 the translated history without line numbers; this will give you the
3405 the translated history without line numbers; this will give you the
3409 input after removal of all the leading prompts and whitespace, which
3406 input after removal of all the leading prompts and whitespace, which
3410 can be pasted back into an editor.
3407 can be pasted back into an editor.
3411
3408
3412 With these features, you can switch into this mode easily whenever you
3409 With these features, you can switch into this mode easily whenever you
3413 need to do testing and changes to doctests, without having to leave
3410 need to do testing and changes to doctests, without having to leave
3414 your existing IPython session.
3411 your existing IPython session.
3415 """
3412 """
3416
3413
3417 from IPython.utils.ipstruct import Struct
3414 from IPython.utils.ipstruct import Struct
3418
3415
3419 # Shorthands
3416 # Shorthands
3420 shell = self.shell
3417 shell = self.shell
3421 oc = shell.displayhook
3418 oc = shell.displayhook
3422 meta = shell.meta
3419 meta = shell.meta
3423 # dstore is a data store kept in the instance metadata bag to track any
3420 # dstore is a data store kept in the instance metadata bag to track any
3424 # changes we make, so we can undo them later.
3421 # changes we make, so we can undo them later.
3425 dstore = meta.setdefault('doctest_mode',Struct())
3422 dstore = meta.setdefault('doctest_mode',Struct())
3426 save_dstore = dstore.setdefault
3423 save_dstore = dstore.setdefault
3427
3424
3428 # save a few values we'll need to recover later
3425 # save a few values we'll need to recover later
3429 mode = save_dstore('mode',False)
3426 mode = save_dstore('mode',False)
3430 save_dstore('rc_pprint',shell.pprint)
3427 save_dstore('rc_pprint',shell.pprint)
3431 save_dstore('xmode',shell.InteractiveTB.mode)
3428 save_dstore('xmode',shell.InteractiveTB.mode)
3432 save_dstore('rc_separate_out',shell.separate_out)
3429 save_dstore('rc_separate_out',shell.separate_out)
3433 save_dstore('rc_separate_out2',shell.separate_out2)
3430 save_dstore('rc_separate_out2',shell.separate_out2)
3434 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3431 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3435 save_dstore('rc_separate_in',shell.separate_in)
3432 save_dstore('rc_separate_in',shell.separate_in)
3436
3433
3437 if mode == False:
3434 if mode == False:
3438 # turn on
3435 # turn on
3439 oc.prompt1.p_template = '>>> '
3436 oc.prompt1.p_template = '>>> '
3440 oc.prompt2.p_template = '... '
3437 oc.prompt2.p_template = '... '
3441 oc.prompt_out.p_template = ''
3438 oc.prompt_out.p_template = ''
3442
3439
3443 # Prompt separators like plain python
3440 # Prompt separators like plain python
3444 oc.input_sep = oc.prompt1.sep = ''
3441 oc.input_sep = oc.prompt1.sep = ''
3445 oc.output_sep = ''
3442 oc.output_sep = ''
3446 oc.output_sep2 = ''
3443 oc.output_sep2 = ''
3447
3444
3448 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3445 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3449 oc.prompt_out.pad_left = False
3446 oc.prompt_out.pad_left = False
3450
3447
3451 shell.pprint = False
3448 shell.pprint = False
3452
3449
3453 shell.magic_xmode('Plain')
3450 shell.magic_xmode('Plain')
3454
3451
3455 else:
3452 else:
3456 # turn off
3453 # turn off
3457 oc.prompt1.p_template = shell.prompt_in1
3454 oc.prompt1.p_template = shell.prompt_in1
3458 oc.prompt2.p_template = shell.prompt_in2
3455 oc.prompt2.p_template = shell.prompt_in2
3459 oc.prompt_out.p_template = shell.prompt_out
3456 oc.prompt_out.p_template = shell.prompt_out
3460
3457
3461 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3458 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3462
3459
3463 oc.output_sep = dstore.rc_separate_out
3460 oc.output_sep = dstore.rc_separate_out
3464 oc.output_sep2 = dstore.rc_separate_out2
3461 oc.output_sep2 = dstore.rc_separate_out2
3465
3462
3466 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3463 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3467 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3464 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3468
3465
3469 shell.pprint = dstore.rc_pprint
3466 shell.pprint = dstore.rc_pprint
3470
3467
3471 shell.magic_xmode(dstore.xmode)
3468 shell.magic_xmode(dstore.xmode)
3472
3469
3473 # Store new mode and inform
3470 # Store new mode and inform
3474 dstore.mode = bool(1-int(mode))
3471 dstore.mode = bool(1-int(mode))
3475 print 'Doctest mode is:',
3472 print 'Doctest mode is:',
3476 print ['OFF','ON'][dstore.mode]
3473 print ['OFF','ON'][dstore.mode]
3477
3474
3478 def magic_gui(self, parameter_s=''):
3475 def magic_gui(self, parameter_s=''):
3479 """Enable or disable IPython GUI event loop integration.
3476 """Enable or disable IPython GUI event loop integration.
3480
3477
3481 %gui [-a] [GUINAME]
3478 %gui [-a] [GUINAME]
3482
3479
3483 This magic replaces IPython's threaded shells that were activated
3480 This magic replaces IPython's threaded shells that were activated
3484 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3481 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3485 can now be enabled, disabled and swtiched at runtime and keyboard
3482 can now be enabled, disabled and swtiched at runtime and keyboard
3486 interrupts should work without any problems. The following toolkits
3483 interrupts should work without any problems. The following toolkits
3487 are supported: wxPython, PyQt4, PyGTK, and Tk::
3484 are supported: wxPython, PyQt4, PyGTK, and Tk::
3488
3485
3489 %gui wx # enable wxPython event loop integration
3486 %gui wx # enable wxPython event loop integration
3490 %gui qt4|qt # enable PyQt4 event loop integration
3487 %gui qt4|qt # enable PyQt4 event loop integration
3491 %gui gtk # enable PyGTK event loop integration
3488 %gui gtk # enable PyGTK event loop integration
3492 %gui tk # enable Tk event loop integration
3489 %gui tk # enable Tk event loop integration
3493 %gui # disable all event loop integration
3490 %gui # disable all event loop integration
3494
3491
3495 WARNING: after any of these has been called you can simply create
3492 WARNING: after any of these has been called you can simply create
3496 an application object, but DO NOT start the event loop yourself, as
3493 an application object, but DO NOT start the event loop yourself, as
3497 we have already handled that.
3494 we have already handled that.
3498
3495
3499 If you want us to create an appropriate application object add the
3496 If you want us to create an appropriate application object add the
3500 "-a" flag to your command::
3497 "-a" flag to your command::
3501
3498
3502 %gui -a wx
3499 %gui -a wx
3503
3500
3504 This is highly recommended for most users.
3501 This is highly recommended for most users.
3505 """
3502 """
3506 opts, arg = self.parse_options(parameter_s,'a')
3503 opts, arg = self.parse_options(parameter_s,'a')
3507 if arg=='': arg = None
3504 if arg=='': arg = None
3508 return enable_gui(arg, 'a' in opts)
3505 return enable_gui(arg, 'a' in opts)
3509
3506
3510 def magic_load_ext(self, module_str):
3507 def magic_load_ext(self, module_str):
3511 """Load an IPython extension by its module name."""
3508 """Load an IPython extension by its module name."""
3512 return self.extension_manager.load_extension(module_str)
3509 return self.extension_manager.load_extension(module_str)
3513
3510
3514 def magic_unload_ext(self, module_str):
3511 def magic_unload_ext(self, module_str):
3515 """Unload an IPython extension by its module name."""
3512 """Unload an IPython extension by its module name."""
3516 self.extension_manager.unload_extension(module_str)
3513 self.extension_manager.unload_extension(module_str)
3517
3514
3518 def magic_reload_ext(self, module_str):
3515 def magic_reload_ext(self, module_str):
3519 """Reload an IPython extension by its module name."""
3516 """Reload an IPython extension by its module name."""
3520 self.extension_manager.reload_extension(module_str)
3517 self.extension_manager.reload_extension(module_str)
3521
3518
3522 @testdec.skip_doctest
3519 @testdec.skip_doctest
3523 def magic_install_profiles(self, s):
3520 def magic_install_profiles(self, s):
3524 """Install the default IPython profiles into the .ipython dir.
3521 """Install the default IPython profiles into the .ipython dir.
3525
3522
3526 If the default profiles have already been installed, they will not
3523 If the default profiles have already been installed, they will not
3527 be overwritten. You can force overwriting them by using the ``-o``
3524 be overwritten. You can force overwriting them by using the ``-o``
3528 option::
3525 option::
3529
3526
3530 In [1]: %install_profiles -o
3527 In [1]: %install_profiles -o
3531 """
3528 """
3532 if '-o' in s:
3529 if '-o' in s:
3533 overwrite = True
3530 overwrite = True
3534 else:
3531 else:
3535 overwrite = False
3532 overwrite = False
3536 from IPython.config import profile
3533 from IPython.config import profile
3537 profile_dir = os.path.split(profile.__file__)[0]
3534 profile_dir = os.path.split(profile.__file__)[0]
3538 ipython_dir = self.ipython_dir
3535 ipython_dir = self.ipython_dir
3539 files = os.listdir(profile_dir)
3536 files = os.listdir(profile_dir)
3540
3537
3541 to_install = []
3538 to_install = []
3542 for f in files:
3539 for f in files:
3543 if f.startswith('ipython_config'):
3540 if f.startswith('ipython_config'):
3544 src = os.path.join(profile_dir, f)
3541 src = os.path.join(profile_dir, f)
3545 dst = os.path.join(ipython_dir, f)
3542 dst = os.path.join(ipython_dir, f)
3546 if (not os.path.isfile(dst)) or overwrite:
3543 if (not os.path.isfile(dst)) or overwrite:
3547 to_install.append((f, src, dst))
3544 to_install.append((f, src, dst))
3548 if len(to_install)>0:
3545 if len(to_install)>0:
3549 print "Installing profiles to: ", ipython_dir
3546 print "Installing profiles to: ", ipython_dir
3550 for (f, src, dst) in to_install:
3547 for (f, src, dst) in to_install:
3551 shutil.copy(src, dst)
3548 shutil.copy(src, dst)
3552 print " %s" % f
3549 print " %s" % f
3553
3550
3554 def magic_install_default_config(self, s):
3551 def magic_install_default_config(self, s):
3555 """Install IPython's default config file into the .ipython dir.
3552 """Install IPython's default config file into the .ipython dir.
3556
3553
3557 If the default config file (:file:`ipython_config.py`) is already
3554 If the default config file (:file:`ipython_config.py`) is already
3558 installed, it will not be overwritten. You can force overwriting
3555 installed, it will not be overwritten. You can force overwriting
3559 by using the ``-o`` option::
3556 by using the ``-o`` option::
3560
3557
3561 In [1]: %install_default_config
3558 In [1]: %install_default_config
3562 """
3559 """
3563 if '-o' in s:
3560 if '-o' in s:
3564 overwrite = True
3561 overwrite = True
3565 else:
3562 else:
3566 overwrite = False
3563 overwrite = False
3567 from IPython.config import default
3564 from IPython.config import default
3568 config_dir = os.path.split(default.__file__)[0]
3565 config_dir = os.path.split(default.__file__)[0]
3569 ipython_dir = self.ipython_dir
3566 ipython_dir = self.ipython_dir
3570 default_config_file_name = 'ipython_config.py'
3567 default_config_file_name = 'ipython_config.py'
3571 src = os.path.join(config_dir, default_config_file_name)
3568 src = os.path.join(config_dir, default_config_file_name)
3572 dst = os.path.join(ipython_dir, default_config_file_name)
3569 dst = os.path.join(ipython_dir, default_config_file_name)
3573 if (not os.path.isfile(dst)) or overwrite:
3570 if (not os.path.isfile(dst)) or overwrite:
3574 shutil.copy(src, dst)
3571 shutil.copy(src, dst)
3575 print "Installing default config file: %s" % dst
3572 print "Installing default config file: %s" % dst
3576
3573
3577 # Pylab support: simple wrappers that activate pylab, load gui input
3574 # Pylab support: simple wrappers that activate pylab, load gui input
3578 # handling and modify slightly %run
3575 # handling and modify slightly %run
3579
3576
3580 @testdec.skip_doctest
3577 @testdec.skip_doctest
3581 def _pylab_magic_run(self, parameter_s=''):
3578 def _pylab_magic_run(self, parameter_s=''):
3582 Magic.magic_run(self, parameter_s,
3579 Magic.magic_run(self, parameter_s,
3583 runner=mpl_runner(self.shell.safe_execfile))
3580 runner=mpl_runner(self.shell.safe_execfile))
3584
3581
3585 _pylab_magic_run.__doc__ = magic_run.__doc__
3582 _pylab_magic_run.__doc__ = magic_run.__doc__
3586
3583
3587 @testdec.skip_doctest
3584 @testdec.skip_doctest
3588 def magic_pylab(self, s):
3585 def magic_pylab(self, s):
3589 """Load numpy and matplotlib to work interactively.
3586 """Load numpy and matplotlib to work interactively.
3590
3587
3591 %pylab [GUINAME]
3588 %pylab [GUINAME]
3592
3589
3593 This function lets you activate pylab (matplotlib, numpy and
3590 This function lets you activate pylab (matplotlib, numpy and
3594 interactive support) at any point during an IPython session.
3591 interactive support) at any point during an IPython session.
3595
3592
3596 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3593 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3597 pylab and mlab, as well as all names from numpy and pylab.
3594 pylab and mlab, as well as all names from numpy and pylab.
3598
3595
3599 Parameters
3596 Parameters
3600 ----------
3597 ----------
3601 guiname : optional
3598 guiname : optional
3602 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3599 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or
3603 'tk'). If given, the corresponding Matplotlib backend is used,
3600 'tk'). If given, the corresponding Matplotlib backend is used,
3604 otherwise matplotlib's default (which you can override in your
3601 otherwise matplotlib's default (which you can override in your
3605 matplotlib config file) is used.
3602 matplotlib config file) is used.
3606
3603
3607 Examples
3604 Examples
3608 --------
3605 --------
3609 In this case, where the MPL default is TkAgg:
3606 In this case, where the MPL default is TkAgg:
3610 In [2]: %pylab
3607 In [2]: %pylab
3611
3608
3612 Welcome to pylab, a matplotlib-based Python environment.
3609 Welcome to pylab, a matplotlib-based Python environment.
3613 Backend in use: TkAgg
3610 Backend in use: TkAgg
3614 For more information, type 'help(pylab)'.
3611 For more information, type 'help(pylab)'.
3615
3612
3616 But you can explicitly request a different backend:
3613 But you can explicitly request a different backend:
3617 In [3]: %pylab qt
3614 In [3]: %pylab qt
3618
3615
3619 Welcome to pylab, a matplotlib-based Python environment.
3616 Welcome to pylab, a matplotlib-based Python environment.
3620 Backend in use: Qt4Agg
3617 Backend in use: Qt4Agg
3621 For more information, type 'help(pylab)'.
3618 For more information, type 'help(pylab)'.
3622 """
3619 """
3623 self.shell.enable_pylab(s)
3620 self.shell.enable_pylab(s)
3624
3621
3625 def magic_tb(self, s):
3622 def magic_tb(self, s):
3626 """Print the last traceback with the currently active exception mode.
3623 """Print the last traceback with the currently active exception mode.
3627
3624
3628 See %xmode for changing exception reporting modes."""
3625 See %xmode for changing exception reporting modes."""
3629 self.shell.showtraceback()
3626 self.shell.showtraceback()
3630
3627
3631 # end Magic
3628 # end Magic
@@ -1,307 +1,307 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 Paging capabilities for IPython.core
4 Paging capabilities for IPython.core
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10
10
11 Notes
11 Notes
12 -----
12 -----
13
13
14 For now this uses ipapi, so it can't be in IPython.utils. If we can get
14 For now this uses ipapi, so it can't be in IPython.utils. If we can get
15 rid of that dependency, we could move it there.
15 rid of that dependency, we could move it there.
16 -----
16 -----
17 """
17 """
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Copyright (C) 2008-2009 The IPython Development Team
20 # Copyright (C) 2008-2009 The IPython Development Team
21 #
21 #
22 # Distributed under the terms of the BSD License. The full license is in
22 # Distributed under the terms of the BSD License. The full license is in
23 # the file COPYING, distributed as part of this software.
23 # the file COPYING, distributed as part of this software.
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Imports
27 # Imports
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 import os
30 import os
31 import re
31 import re
32 import sys
32 import sys
33 import tempfile
33 import tempfile
34
34
35 from IPython.core import ipapi
35 from IPython.core import ipapi
36 from IPython.core.error import TryNext
36 from IPython.core.error import TryNext
37 from IPython.utils.cursesimport import use_curses
37 from IPython.utils.cursesimport import use_curses
38 from IPython.utils.data import chop
38 from IPython.utils.data import chop
39 import IPython.utils.io
39 import IPython.utils.io
40 from IPython.utils.process import xsys
40 from IPython.utils.process import system
41 from IPython.utils.terminal import get_terminal_size
41 from IPython.utils.terminal import get_terminal_size
42
42
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # Classes and functions
45 # Classes and functions
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48 esc_re = re.compile(r"(\x1b[^m]+m)")
48 esc_re = re.compile(r"(\x1b[^m]+m)")
49
49
50 def page_dumb(strng, start=0, screen_lines=25):
50 def page_dumb(strng, start=0, screen_lines=25):
51 """Very dumb 'pager' in Python, for when nothing else works.
51 """Very dumb 'pager' in Python, for when nothing else works.
52
52
53 Only moves forward, same interface as page(), except for pager_cmd and
53 Only moves forward, same interface as page(), except for pager_cmd and
54 mode."""
54 mode."""
55
55
56 out_ln = strng.splitlines()[start:]
56 out_ln = strng.splitlines()[start:]
57 screens = chop(out_ln,screen_lines-1)
57 screens = chop(out_ln,screen_lines-1)
58 if len(screens) == 1:
58 if len(screens) == 1:
59 print >>IPython.utils.io.Term.cout, os.linesep.join(screens[0])
59 print >>IPython.utils.io.Term.cout, os.linesep.join(screens[0])
60 else:
60 else:
61 last_escape = ""
61 last_escape = ""
62 for scr in screens[0:-1]:
62 for scr in screens[0:-1]:
63 hunk = os.linesep.join(scr)
63 hunk = os.linesep.join(scr)
64 print >>IPython.utils.io.Term.cout, last_escape + hunk
64 print >>IPython.utils.io.Term.cout, last_escape + hunk
65 if not page_more():
65 if not page_more():
66 return
66 return
67 esc_list = esc_re.findall(hunk)
67 esc_list = esc_re.findall(hunk)
68 if len(esc_list) > 0:
68 if len(esc_list) > 0:
69 last_escape = esc_list[-1]
69 last_escape = esc_list[-1]
70 print >>IPython.utils.io.Term.cout, last_escape + os.linesep.join(screens[-1])
70 print >>IPython.utils.io.Term.cout, last_escape + os.linesep.join(screens[-1])
71
71
72
72
73 def page(strng, start=0, screen_lines=0, pager_cmd=None):
73 def page(strng, start=0, screen_lines=0, pager_cmd=None):
74 """Print a string, piping through a pager after a certain length.
74 """Print a string, piping through a pager after a certain length.
75
75
76 The screen_lines parameter specifies the number of *usable* lines of your
76 The screen_lines parameter specifies the number of *usable* lines of your
77 terminal screen (total lines minus lines you need to reserve to show other
77 terminal screen (total lines minus lines you need to reserve to show other
78 information).
78 information).
79
79
80 If you set screen_lines to a number <=0, page() will try to auto-determine
80 If you set screen_lines to a number <=0, page() will try to auto-determine
81 your screen size and will only use up to (screen_size+screen_lines) for
81 your screen size and will only use up to (screen_size+screen_lines) for
82 printing, paging after that. That is, if you want auto-detection but need
82 printing, paging after that. That is, if you want auto-detection but need
83 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
83 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
84 auto-detection without any lines reserved simply use screen_lines = 0.
84 auto-detection without any lines reserved simply use screen_lines = 0.
85
85
86 If a string won't fit in the allowed lines, it is sent through the
86 If a string won't fit in the allowed lines, it is sent through the
87 specified pager command. If none given, look for PAGER in the environment,
87 specified pager command. If none given, look for PAGER in the environment,
88 and ultimately default to less.
88 and ultimately default to less.
89
89
90 If no system pager works, the string is sent through a 'dumb pager'
90 If no system pager works, the string is sent through a 'dumb pager'
91 written in python, very simplistic.
91 written in python, very simplistic.
92 """
92 """
93
93
94 # Some routines may auto-compute start offsets incorrectly and pass a
94 # Some routines may auto-compute start offsets incorrectly and pass a
95 # negative value. Offset to 0 for robustness.
95 # negative value. Offset to 0 for robustness.
96 start = max(0, start)
96 start = max(0, start)
97
97
98 # first, try the hook
98 # first, try the hook
99 ip = ipapi.get()
99 ip = ipapi.get()
100 if ip:
100 if ip:
101 try:
101 try:
102 ip.hooks.show_in_pager(strng)
102 ip.hooks.show_in_pager(strng)
103 return
103 return
104 except TryNext:
104 except TryNext:
105 pass
105 pass
106
106
107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
108 TERM = os.environ.get('TERM','dumb')
108 TERM = os.environ.get('TERM','dumb')
109 if TERM in ['dumb','emacs'] and os.name != 'nt':
109 if TERM in ['dumb','emacs'] and os.name != 'nt':
110 print strng
110 print strng
111 return
111 return
112 # chop off the topmost part of the string we don't want to see
112 # chop off the topmost part of the string we don't want to see
113 str_lines = strng.split(os.linesep)[start:]
113 str_lines = strng.split(os.linesep)[start:]
114 str_toprint = os.linesep.join(str_lines)
114 str_toprint = os.linesep.join(str_lines)
115 num_newlines = len(str_lines)
115 num_newlines = len(str_lines)
116 len_str = len(str_toprint)
116 len_str = len(str_toprint)
117
117
118 # Dumb heuristics to guesstimate number of on-screen lines the string
118 # Dumb heuristics to guesstimate number of on-screen lines the string
119 # takes. Very basic, but good enough for docstrings in reasonable
119 # takes. Very basic, but good enough for docstrings in reasonable
120 # terminals. If someone later feels like refining it, it's not hard.
120 # terminals. If someone later feels like refining it, it's not hard.
121 numlines = max(num_newlines,int(len_str/80)+1)
121 numlines = max(num_newlines,int(len_str/80)+1)
122
122
123 screen_lines_def = get_terminal_size()[1]
123 screen_lines_def = get_terminal_size()[1]
124
124
125 # auto-determine screen size
125 # auto-determine screen size
126 if screen_lines <= 0:
126 if screen_lines <= 0:
127 if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5':
127 if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5':
128 local_use_curses = use_curses
128 local_use_curses = use_curses
129 else:
129 else:
130 # curses causes problems on many terminals other than xterm, and
130 # curses causes problems on many terminals other than xterm, and
131 # some termios calls lock up on Sun OS5.
131 # some termios calls lock up on Sun OS5.
132 local_use_curses = False
132 local_use_curses = False
133 if local_use_curses:
133 if local_use_curses:
134 import termios
134 import termios
135 import curses
135 import curses
136 # There is a bug in curses, where *sometimes* it fails to properly
136 # There is a bug in curses, where *sometimes* it fails to properly
137 # initialize, and then after the endwin() call is made, the
137 # initialize, and then after the endwin() call is made, the
138 # terminal is left in an unusable state. Rather than trying to
138 # terminal is left in an unusable state. Rather than trying to
139 # check everytime for this (by requesting and comparing termios
139 # check everytime for this (by requesting and comparing termios
140 # flags each time), we just save the initial terminal state and
140 # flags each time), we just save the initial terminal state and
141 # unconditionally reset it every time. It's cheaper than making
141 # unconditionally reset it every time. It's cheaper than making
142 # the checks.
142 # the checks.
143 term_flags = termios.tcgetattr(sys.stdout)
143 term_flags = termios.tcgetattr(sys.stdout)
144 scr = curses.initscr()
144 scr = curses.initscr()
145 screen_lines_real,screen_cols = scr.getmaxyx()
145 screen_lines_real,screen_cols = scr.getmaxyx()
146 curses.endwin()
146 curses.endwin()
147 # Restore terminal state in case endwin() didn't.
147 # Restore terminal state in case endwin() didn't.
148 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
148 termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags)
149 # Now we have what we needed: the screen size in rows/columns
149 # Now we have what we needed: the screen size in rows/columns
150 screen_lines += screen_lines_real
150 screen_lines += screen_lines_real
151 #print '***Screen size:',screen_lines_real,'lines x',\
151 #print '***Screen size:',screen_lines_real,'lines x',\
152 #screen_cols,'columns.' # dbg
152 #screen_cols,'columns.' # dbg
153 else:
153 else:
154 screen_lines += screen_lines_def
154 screen_lines += screen_lines_def
155
155
156 #print 'numlines',numlines,'screenlines',screen_lines # dbg
156 #print 'numlines',numlines,'screenlines',screen_lines # dbg
157 if numlines <= screen_lines :
157 if numlines <= screen_lines :
158 #print '*** normal print' # dbg
158 #print '*** normal print' # dbg
159 print >>IPython.utils.io.Term.cout, str_toprint
159 print >>IPython.utils.io.Term.cout, str_toprint
160 else:
160 else:
161 # Try to open pager and default to internal one if that fails.
161 # Try to open pager and default to internal one if that fails.
162 # All failure modes are tagged as 'retval=1', to match the return
162 # All failure modes are tagged as 'retval=1', to match the return
163 # value of a failed system command. If any intermediate attempt
163 # value of a failed system command. If any intermediate attempt
164 # sets retval to 1, at the end we resort to our own page_dumb() pager.
164 # sets retval to 1, at the end we resort to our own page_dumb() pager.
165 pager_cmd = get_pager_cmd(pager_cmd)
165 pager_cmd = get_pager_cmd(pager_cmd)
166 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
166 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
167 if os.name == 'nt':
167 if os.name == 'nt':
168 if pager_cmd.startswith('type'):
168 if pager_cmd.startswith('type'):
169 # The default WinXP 'type' command is failing on complex strings.
169 # The default WinXP 'type' command is failing on complex strings.
170 retval = 1
170 retval = 1
171 else:
171 else:
172 tmpname = tempfile.mktemp('.txt')
172 tmpname = tempfile.mktemp('.txt')
173 tmpfile = file(tmpname,'wt')
173 tmpfile = file(tmpname,'wt')
174 tmpfile.write(strng)
174 tmpfile.write(strng)
175 tmpfile.close()
175 tmpfile.close()
176 cmd = "%s < %s" % (pager_cmd,tmpname)
176 cmd = "%s < %s" % (pager_cmd,tmpname)
177 if os.system(cmd):
177 if os.system(cmd):
178 retval = 1
178 retval = 1
179 else:
179 else:
180 retval = None
180 retval = None
181 os.remove(tmpname)
181 os.remove(tmpname)
182 else:
182 else:
183 try:
183 try:
184 retval = None
184 retval = None
185 # if I use popen4, things hang. No idea why.
185 # if I use popen4, things hang. No idea why.
186 #pager,shell_out = os.popen4(pager_cmd)
186 #pager,shell_out = os.popen4(pager_cmd)
187 pager = os.popen(pager_cmd,'w')
187 pager = os.popen(pager_cmd,'w')
188 pager.write(strng)
188 pager.write(strng)
189 pager.close()
189 pager.close()
190 retval = pager.close() # success returns None
190 retval = pager.close() # success returns None
191 except IOError,msg: # broken pipe when user quits
191 except IOError,msg: # broken pipe when user quits
192 if msg.args == (32,'Broken pipe'):
192 if msg.args == (32,'Broken pipe'):
193 retval = None
193 retval = None
194 else:
194 else:
195 retval = 1
195 retval = 1
196 except OSError:
196 except OSError:
197 # Other strange problems, sometimes seen in Win2k/cygwin
197 # Other strange problems, sometimes seen in Win2k/cygwin
198 retval = 1
198 retval = 1
199 if retval is not None:
199 if retval is not None:
200 page_dumb(strng,screen_lines=screen_lines)
200 page_dumb(strng,screen_lines=screen_lines)
201
201
202
202
203 def page_file(fname, start=0, pager_cmd=None):
203 def page_file(fname, start=0, pager_cmd=None):
204 """Page a file, using an optional pager command and starting line.
204 """Page a file, using an optional pager command and starting line.
205 """
205 """
206
206
207 pager_cmd = get_pager_cmd(pager_cmd)
207 pager_cmd = get_pager_cmd(pager_cmd)
208 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
208 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
209
209
210 try:
210 try:
211 if os.environ['TERM'] in ['emacs','dumb']:
211 if os.environ['TERM'] in ['emacs','dumb']:
212 raise EnvironmentError
212 raise EnvironmentError
213 xsys(pager_cmd + ' ' + fname)
213 system(pager_cmd + ' ' + fname)
214 except:
214 except:
215 try:
215 try:
216 if start > 0:
216 if start > 0:
217 start -= 1
217 start -= 1
218 page(open(fname).read(),start)
218 page(open(fname).read(),start)
219 except:
219 except:
220 print 'Unable to show file',`fname`
220 print 'Unable to show file',`fname`
221
221
222
222
223 def get_pager_cmd(pager_cmd=None):
223 def get_pager_cmd(pager_cmd=None):
224 """Return a pager command.
224 """Return a pager command.
225
225
226 Makes some attempts at finding an OS-correct one.
226 Makes some attempts at finding an OS-correct one.
227 """
227 """
228 if os.name == 'posix':
228 if os.name == 'posix':
229 default_pager_cmd = 'less -r' # -r for color control sequences
229 default_pager_cmd = 'less -r' # -r for color control sequences
230 elif os.name in ['nt','dos']:
230 elif os.name in ['nt','dos']:
231 default_pager_cmd = 'type'
231 default_pager_cmd = 'type'
232
232
233 if pager_cmd is None:
233 if pager_cmd is None:
234 try:
234 try:
235 pager_cmd = os.environ['PAGER']
235 pager_cmd = os.environ['PAGER']
236 except:
236 except:
237 pager_cmd = default_pager_cmd
237 pager_cmd = default_pager_cmd
238 return pager_cmd
238 return pager_cmd
239
239
240
240
241 def get_pager_start(pager, start):
241 def get_pager_start(pager, start):
242 """Return the string for paging files with an offset.
242 """Return the string for paging files with an offset.
243
243
244 This is the '+N' argument which less and more (under Unix) accept.
244 This is the '+N' argument which less and more (under Unix) accept.
245 """
245 """
246
246
247 if pager in ['less','more']:
247 if pager in ['less','more']:
248 if start:
248 if start:
249 start_string = '+' + str(start)
249 start_string = '+' + str(start)
250 else:
250 else:
251 start_string = ''
251 start_string = ''
252 else:
252 else:
253 start_string = ''
253 start_string = ''
254 return start_string
254 return start_string
255
255
256
256
257 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
257 # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch()
258 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
258 if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
259 import msvcrt
259 import msvcrt
260 def page_more():
260 def page_more():
261 """ Smart pausing between pages
261 """ Smart pausing between pages
262
262
263 @return: True if need print more lines, False if quit
263 @return: True if need print more lines, False if quit
264 """
264 """
265 IPython.utils.io.Term.cout.write('---Return to continue, q to quit--- ')
265 IPython.utils.io.Term.cout.write('---Return to continue, q to quit--- ')
266 ans = msvcrt.getch()
266 ans = msvcrt.getch()
267 if ans in ("q", "Q"):
267 if ans in ("q", "Q"):
268 result = False
268 result = False
269 else:
269 else:
270 result = True
270 result = True
271 IPython.utils.io.Term.cout.write("\b"*37 + " "*37 + "\b"*37)
271 IPython.utils.io.Term.cout.write("\b"*37 + " "*37 + "\b"*37)
272 return result
272 return result
273 else:
273 else:
274 def page_more():
274 def page_more():
275 ans = raw_input('---Return to continue, q to quit--- ')
275 ans = raw_input('---Return to continue, q to quit--- ')
276 if ans.lower().startswith('q'):
276 if ans.lower().startswith('q'):
277 return False
277 return False
278 else:
278 else:
279 return True
279 return True
280
280
281
281
282 def snip_print(str,width = 75,print_full = 0,header = ''):
282 def snip_print(str,width = 75,print_full = 0,header = ''):
283 """Print a string snipping the midsection to fit in width.
283 """Print a string snipping the midsection to fit in width.
284
284
285 print_full: mode control:
285 print_full: mode control:
286 - 0: only snip long strings
286 - 0: only snip long strings
287 - 1: send to page() directly.
287 - 1: send to page() directly.
288 - 2: snip long strings and ask for full length viewing with page()
288 - 2: snip long strings and ask for full length viewing with page()
289 Return 1 if snipping was necessary, 0 otherwise."""
289 Return 1 if snipping was necessary, 0 otherwise."""
290
290
291 if print_full == 1:
291 if print_full == 1:
292 page(header+str)
292 page(header+str)
293 return 0
293 return 0
294
294
295 print header,
295 print header,
296 if len(str) < width:
296 if len(str) < width:
297 print str
297 print str
298 snip = 0
298 snip = 0
299 else:
299 else:
300 whalf = int((width -5)/2)
300 whalf = int((width -5)/2)
301 print str[:whalf] + ' <...> ' + str[-whalf:]
301 print str[:whalf] + ' <...> ' + str[-whalf:]
302 snip = 1
302 snip = 1
303 if snip and print_full == 2:
303 if snip and print_full == 2:
304 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
304 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
305 page(str)
305 page(str)
306 return snip
306 return snip
307
307
@@ -1,162 +1,164 b''
1 #!/usr/bin/env python
1 """Descriptor utilities.
2 # encoding: utf-8
3 """Descriptor support for NIPY.
4
2
5 Utilities to support special Python descriptors [1,2], in particular the use of
3 Utilities to support special Python descriptors [1,2], in particular the use of
6 a useful pattern for properties we call 'one time properties'. These are
4 a useful pattern for properties we call 'one time properties'. These are
7 object attributes which are declared as properties, but become regular
5 object attributes which are declared as properties, but become regular
8 attributes once they've been read the first time. They can thus be evaluated
6 attributes once they've been read the first time. They can thus be evaluated
9 later in the object's life cycle, but once evaluated they become normal, static
7 later in the object's life cycle, but once evaluated they become normal, static
10 attributes with no function call overhead on access or any other constraints.
8 attributes with no function call overhead on access or any other constraints.
11
9
12 A special ResetMixin class is provided to add a .reset() method to users who
10 A special ResetMixin class is provided to add a .reset() method to users who
13 may want to have their objects capable of resetting these computed properties
11 may want to have their objects capable of resetting these computed properties
14 to their 'untriggered' state.
12 to their 'untriggered' state.
15
13
16 References
14 References
17 ----------
15 ----------
18 [1] How-To Guide for Descriptors, Raymond
16 [1] How-To Guide for Descriptors, Raymond
19 Hettinger. http://users.rcn.com/python/download/Descriptor.htm
17 Hettinger. http://users.rcn.com/python/download/Descriptor.htm
20
18
21 [2] Python data model, http://docs.python.org/reference/datamodel.html
19 [2] Python data model, http://docs.python.org/reference/datamodel.html
22
20
23 Notes
21 Notes
24 -----
22 -----
25 This module is taken from the NiPy project
23 This module is taken from the NiPy project
26 (http://neuroimaging.scipy.org/site/index.html), and is BSD licensed.
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 # Classes and Functions
32 # Classes and Functions
31 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
32
34
33 class ResetMixin(object):
35 class ResetMixin(object):
34 """A Mixin class to add a .reset() method to users of OneTimeProperty.
36 """A Mixin class to add a .reset() method to users of OneTimeProperty.
35
37
36 By default, auto attributes once computed, become static. If they happen to
38 By default, auto attributes once computed, become static. If they happen to
37 depend on other parts of an object and those parts change, their values may
39 depend on other parts of an object and those parts change, their values may
38 now be invalid.
40 now be invalid.
39
41
40 This class offers a .reset() method that users can call *explicitly* when
42 This class offers a .reset() method that users can call *explicitly* when
41 they know the state of their objects may have changed and they want to
43 they know the state of their objects may have changed and they want to
42 ensure that *all* their special attributes should be invalidated. Once
44 ensure that *all* their special attributes should be invalidated. Once
43 reset() is called, all their auto attributes are reset to their
45 reset() is called, all their auto attributes are reset to their
44 OneTimeProperty descriptors, and their accessor functions will be triggered
46 OneTimeProperty descriptors, and their accessor functions will be triggered
45 again.
47 again.
46
48
47 Example
49 Example
48 -------
50 -------
49
51
50 >>> class A(ResetMixin):
52 >>> class A(ResetMixin):
51 ... def __init__(self,x=1.0):
53 ... def __init__(self,x=1.0):
52 ... self.x = x
54 ... self.x = x
53 ...
55 ...
54 ... @auto_attr
56 ... @auto_attr
55 ... def y(self):
57 ... def y(self):
56 ... print '*** y computation executed ***'
58 ... print '*** y computation executed ***'
57 ... return self.x / 2.0
59 ... return self.x / 2.0
58 ...
60 ...
59
61
60 >>> a = A(10)
62 >>> a = A(10)
61
63
62 About to access y twice, the second time no computation is done:
64 About to access y twice, the second time no computation is done:
63 >>> a.y
65 >>> a.y
64 *** y computation executed ***
66 *** y computation executed ***
65 5.0
67 5.0
66 >>> a.y
68 >>> a.y
67 5.0
69 5.0
68
70
69 Changing x
71 Changing x
70 >>> a.x = 20
72 >>> a.x = 20
71
73
72 a.y doesn't change to 10, since it is a static attribute:
74 a.y doesn't change to 10, since it is a static attribute:
73 >>> a.y
75 >>> a.y
74 5.0
76 5.0
75
77
76 We now reset a, and this will then force all auto attributes to recompute
78 We now reset a, and this will then force all auto attributes to recompute
77 the next time we access them:
79 the next time we access them:
78 >>> a.reset()
80 >>> a.reset()
79
81
80 About to access y twice again after reset():
82 About to access y twice again after reset():
81 >>> a.y
83 >>> a.y
82 *** y computation executed ***
84 *** y computation executed ***
83 10.0
85 10.0
84 >>> a.y
86 >>> a.y
85 10.0
87 10.0
86 """
88 """
87
89
88 def reset(self):
90 def reset(self):
89 """Reset all OneTimeProperty attributes that may have fired already."""
91 """Reset all OneTimeProperty attributes that may have fired already."""
90 instdict = self.__dict__
92 instdict = self.__dict__
91 classdict = self.__class__.__dict__
93 classdict = self.__class__.__dict__
92 # To reset them, we simply remove them from the instance dict. At that
94 # To reset them, we simply remove them from the instance dict. At that
93 # point, it's as if they had never been computed. On the next access,
95 # point, it's as if they had never been computed. On the next access,
94 # the accessor function from the parent class will be called, simply
96 # the accessor function from the parent class will be called, simply
95 # because that's how the python descriptor protocol works.
97 # because that's how the python descriptor protocol works.
96 for mname, mval in classdict.items():
98 for mname, mval in classdict.items():
97 if mname in instdict and isinstance(mval, OneTimeProperty):
99 if mname in instdict and isinstance(mval, OneTimeProperty):
98 delattr(self, mname)
100 delattr(self, mname)
99
101
100
102
101 class OneTimeProperty(object):
103 class OneTimeProperty(object):
102 """A descriptor to make special properties that become normal attributes.
104 """A descriptor to make special properties that become normal attributes.
103
105
104 This is meant to be used mostly by the auto_attr decorator in this module.
106 This is meant to be used mostly by the auto_attr decorator in this module.
105 """
107 """
106 def __init__(self,func):
108 def __init__(self,func):
107 """Create a OneTimeProperty instance.
109 """Create a OneTimeProperty instance.
108
110
109 Parameters
111 Parameters
110 ----------
112 ----------
111 func : method
113 func : method
112
114
113 The method that will be called the first time to compute a value.
115 The method that will be called the first time to compute a value.
114 Afterwards, the method's name will be a standard attribute holding
116 Afterwards, the method's name will be a standard attribute holding
115 the value of this computation.
117 the value of this computation.
116 """
118 """
117 self.getter = func
119 self.getter = func
118 self.name = func.func_name
120 self.name = func.func_name
119
121
120 def __get__(self,obj,type=None):
122 def __get__(self,obj,type=None):
121 """This will be called on attribute access on the class or instance. """
123 """This will be called on attribute access on the class or instance. """
122
124
123 if obj is None:
125 if obj is None:
124 # Being called on the class, return the original function. This way,
126 # Being called on the class, return the original function. This way,
125 # introspection works on the class.
127 # introspection works on the class.
126 #return func
128 #return func
127 return self.getter
129 return self.getter
128
130
129 val = self.getter(obj)
131 val = self.getter(obj)
130 #print "** auto_attr - loading '%s'" % self.name # dbg
132 #print "** auto_attr - loading '%s'" % self.name # dbg
131 setattr(obj, self.name, val)
133 setattr(obj, self.name, val)
132 return val
134 return val
133
135
134
136
135 def auto_attr(func):
137 def auto_attr(func):
136 """Decorator to create OneTimeProperty attributes.
138 """Decorator to create OneTimeProperty attributes.
137
139
138 Parameters
140 Parameters
139 ----------
141 ----------
140 func : method
142 func : method
141 The method that will be called the first time to compute a value.
143 The method that will be called the first time to compute a value.
142 Afterwards, the method's name will be a standard attribute holding the
144 Afterwards, the method's name will be a standard attribute holding the
143 value of this computation.
145 value of this computation.
144
146
145 Examples
147 Examples
146 --------
148 --------
147 >>> class MagicProp(object):
149 >>> class MagicProp(object):
148 ... @auto_attr
150 ... @auto_attr
149 ... def a(self):
151 ... def a(self):
150 ... return 99
152 ... return 99
151 ...
153 ...
152 >>> x = MagicProp()
154 >>> x = MagicProp()
153 >>> 'a' in x.__dict__
155 >>> 'a' in x.__dict__
154 False
156 False
155 >>> x.a
157 >>> x.a
156 99
158 99
157 >>> 'a' in x.__dict__
159 >>> 'a' in x.__dict__
158 True
160 True
159 """
161 """
160 return OneTimeProperty(func)
162 return OneTimeProperty(func)
161
163
162
164
@@ -1,345 +1,345 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for path handling.
3 Utilities for path handling.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import os
17 import os
18 import sys
18 import sys
19
19
20 import IPython
20 import IPython
21 from IPython.utils.process import xsys
21 from IPython.utils.process import system
22 from IPython.utils.importstring import import_item
22 from IPython.utils.importstring import import_item
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Code
25 # Code
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28
28
29 def _get_long_path_name(path):
29 def _get_long_path_name(path):
30 """Dummy no-op."""
30 """Dummy no-op."""
31 return path
31 return path
32
32
33
33
34 if sys.platform == 'win32':
34 if sys.platform == 'win32':
35 def _get_long_path_name(path):
35 def _get_long_path_name(path):
36 """Get a long path name (expand ~) on Windows using ctypes.
36 """Get a long path name (expand ~) on Windows using ctypes.
37
37
38 Examples
38 Examples
39 --------
39 --------
40
40
41 >>> get_long_path_name('c:\\docume~1')
41 >>> get_long_path_name('c:\\docume~1')
42 u'c:\\\\Documents and Settings'
42 u'c:\\\\Documents and Settings'
43
43
44 """
44 """
45 try:
45 try:
46 import ctypes
46 import ctypes
47 except ImportError:
47 except ImportError:
48 raise ImportError('you need to have ctypes installed for this to work')
48 raise ImportError('you need to have ctypes installed for this to work')
49 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
49 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
50 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
50 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
51 ctypes.c_uint ]
51 ctypes.c_uint ]
52
52
53 buf = ctypes.create_unicode_buffer(260)
53 buf = ctypes.create_unicode_buffer(260)
54 rv = _GetLongPathName(path, buf, 260)
54 rv = _GetLongPathName(path, buf, 260)
55 if rv == 0 or rv > 260:
55 if rv == 0 or rv > 260:
56 return path
56 return path
57 else:
57 else:
58 return buf.value
58 return buf.value
59
59
60
60
61 def get_long_path_name(path):
61 def get_long_path_name(path):
62 """Expand a path into its long form.
62 """Expand a path into its long form.
63
63
64 On Windows this expands any ~ in the paths. On other platforms, it is
64 On Windows this expands any ~ in the paths. On other platforms, it is
65 a null operation.
65 a null operation.
66 """
66 """
67 return _get_long_path_name(path)
67 return _get_long_path_name(path)
68
68
69
69
70 def get_py_filename(name):
70 def get_py_filename(name):
71 """Return a valid python filename in the current directory.
71 """Return a valid python filename in the current directory.
72
72
73 If the given name is not a file, it adds '.py' and searches again.
73 If the given name is not a file, it adds '.py' and searches again.
74 Raises IOError with an informative message if the file isn't found."""
74 Raises IOError with an informative message if the file isn't found."""
75
75
76 name = os.path.expanduser(name)
76 name = os.path.expanduser(name)
77 if not os.path.isfile(name) and not name.endswith('.py'):
77 if not os.path.isfile(name) and not name.endswith('.py'):
78 name += '.py'
78 name += '.py'
79 if os.path.isfile(name):
79 if os.path.isfile(name):
80 return name
80 return name
81 else:
81 else:
82 raise IOError,'File `%s` not found.' % name
82 raise IOError,'File `%s` not found.' % name
83
83
84
84
85 def filefind(filename, path_dirs=None):
85 def filefind(filename, path_dirs=None):
86 """Find a file by looking through a sequence of paths.
86 """Find a file by looking through a sequence of paths.
87
87
88 This iterates through a sequence of paths looking for a file and returns
88 This iterates through a sequence of paths looking for a file and returns
89 the full, absolute path of the first occurence of the file. If no set of
89 the full, absolute path of the first occurence of the file. If no set of
90 path dirs is given, the filename is tested as is, after running through
90 path dirs is given, the filename is tested as is, after running through
91 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
91 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
92
92
93 filefind('myfile.txt')
93 filefind('myfile.txt')
94
94
95 will find the file in the current working dir, but::
95 will find the file in the current working dir, but::
96
96
97 filefind('~/myfile.txt')
97 filefind('~/myfile.txt')
98
98
99 Will find the file in the users home directory. This function does not
99 Will find the file in the users home directory. This function does not
100 automatically try any paths, such as the cwd or the user's home directory.
100 automatically try any paths, such as the cwd or the user's home directory.
101
101
102 Parameters
102 Parameters
103 ----------
103 ----------
104 filename : str
104 filename : str
105 The filename to look for.
105 The filename to look for.
106 path_dirs : str, None or sequence of str
106 path_dirs : str, None or sequence of str
107 The sequence of paths to look for the file in. If None, the filename
107 The sequence of paths to look for the file in. If None, the filename
108 need to be absolute or be in the cwd. If a string, the string is
108 need to be absolute or be in the cwd. If a string, the string is
109 put into a sequence and the searched. If a sequence, walk through
109 put into a sequence and the searched. If a sequence, walk through
110 each element and join with ``filename``, calling :func:`expandvars`
110 each element and join with ``filename``, calling :func:`expandvars`
111 and :func:`expanduser` before testing for existence.
111 and :func:`expanduser` before testing for existence.
112
112
113 Returns
113 Returns
114 -------
114 -------
115 Raises :exc:`IOError` or returns absolute path to file.
115 Raises :exc:`IOError` or returns absolute path to file.
116 """
116 """
117
117
118 # If paths are quoted, abspath gets confused, strip them...
118 # If paths are quoted, abspath gets confused, strip them...
119 filename = filename.strip('"').strip("'")
119 filename = filename.strip('"').strip("'")
120 # If the input is an absolute path, just check it exists
120 # If the input is an absolute path, just check it exists
121 if os.path.isabs(filename) and os.path.isfile(filename):
121 if os.path.isabs(filename) and os.path.isfile(filename):
122 return filename
122 return filename
123
123
124 if path_dirs is None:
124 if path_dirs is None:
125 path_dirs = ("",)
125 path_dirs = ("",)
126 elif isinstance(path_dirs, basestring):
126 elif isinstance(path_dirs, basestring):
127 path_dirs = (path_dirs,)
127 path_dirs = (path_dirs,)
128
128
129 for path in path_dirs:
129 for path in path_dirs:
130 if path == '.': path = os.getcwd()
130 if path == '.': path = os.getcwd()
131 testname = expand_path(os.path.join(path, filename))
131 testname = expand_path(os.path.join(path, filename))
132 if os.path.isfile(testname):
132 if os.path.isfile(testname):
133 return os.path.abspath(testname)
133 return os.path.abspath(testname)
134
134
135 raise IOError("File %r does not exist in any of the search paths: %r" %
135 raise IOError("File %r does not exist in any of the search paths: %r" %
136 (filename, path_dirs) )
136 (filename, path_dirs) )
137
137
138
138
139 class HomeDirError(Exception):
139 class HomeDirError(Exception):
140 pass
140 pass
141
141
142
142
143 def get_home_dir():
143 def get_home_dir():
144 """Return the closest possible equivalent to a 'home' directory.
144 """Return the closest possible equivalent to a 'home' directory.
145
145
146 * On POSIX, we try $HOME.
146 * On POSIX, we try $HOME.
147 * On Windows we try:
147 * On Windows we try:
148 - %HOMESHARE%
148 - %HOMESHARE%
149 - %HOMEDRIVE\%HOMEPATH%
149 - %HOMEDRIVE\%HOMEPATH%
150 - %USERPROFILE%
150 - %USERPROFILE%
151 - Registry hack for My Documents
151 - Registry hack for My Documents
152 - %HOME%: rare, but some people with unix-like setups may have defined it
152 - %HOME%: rare, but some people with unix-like setups may have defined it
153 * On Dos C:\
153 * On Dos C:\
154
154
155 Currently only Posix and NT are implemented, a HomeDirError exception is
155 Currently only Posix and NT are implemented, a HomeDirError exception is
156 raised for all other OSes.
156 raised for all other OSes.
157 """
157 """
158
158
159 isdir = os.path.isdir
159 isdir = os.path.isdir
160 env = os.environ
160 env = os.environ
161
161
162 # first, check py2exe distribution root directory for _ipython.
162 # first, check py2exe distribution root directory for _ipython.
163 # This overrides all. Normally does not exist.
163 # This overrides all. Normally does not exist.
164
164
165 if hasattr(sys, "frozen"): #Is frozen by py2exe
165 if hasattr(sys, "frozen"): #Is frozen by py2exe
166 if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
166 if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
167 root, rest = IPython.__file__.lower().split('library.zip')
167 root, rest = IPython.__file__.lower().split('library.zip')
168 else:
168 else:
169 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
169 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
170 root=os.path.abspath(root).rstrip('\\')
170 root=os.path.abspath(root).rstrip('\\')
171 if isdir(os.path.join(root, '_ipython')):
171 if isdir(os.path.join(root, '_ipython')):
172 os.environ["IPYKITROOT"] = root
172 os.environ["IPYKITROOT"] = root
173 return root.decode(sys.getfilesystemencoding())
173 return root.decode(sys.getfilesystemencoding())
174
174
175 if os.name == 'posix':
175 if os.name == 'posix':
176 # Linux, Unix, AIX, OS X
176 # Linux, Unix, AIX, OS X
177 try:
177 try:
178 homedir = env['HOME']
178 homedir = env['HOME']
179 except KeyError:
179 except KeyError:
180 raise HomeDirError('Undefined $HOME, IPython cannot proceed.')
180 raise HomeDirError('Undefined $HOME, IPython cannot proceed.')
181 else:
181 else:
182 return homedir.decode(sys.getfilesystemencoding())
182 return homedir.decode(sys.getfilesystemencoding())
183 elif os.name == 'nt':
183 elif os.name == 'nt':
184 # Now for win9x, XP, Vista, 7?
184 # Now for win9x, XP, Vista, 7?
185 # For some strange reason all of these return 'nt' for os.name.
185 # For some strange reason all of these return 'nt' for os.name.
186 # First look for a network home directory. This will return the UNC
186 # First look for a network home directory. This will return the UNC
187 # path (\\server\\Users\%username%) not the mapped path (Z:\). This
187 # path (\\server\\Users\%username%) not the mapped path (Z:\). This
188 # is needed when running IPython on cluster where all paths have to
188 # is needed when running IPython on cluster where all paths have to
189 # be UNC.
189 # be UNC.
190 try:
190 try:
191 homedir = env['HOMESHARE']
191 homedir = env['HOMESHARE']
192 except KeyError:
192 except KeyError:
193 pass
193 pass
194 else:
194 else:
195 if isdir(homedir):
195 if isdir(homedir):
196 return homedir.decode(sys.getfilesystemencoding())
196 return homedir.decode(sys.getfilesystemencoding())
197
197
198 # Now look for a local home directory
198 # Now look for a local home directory
199 try:
199 try:
200 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
200 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
201 except KeyError:
201 except KeyError:
202 pass
202 pass
203 else:
203 else:
204 if isdir(homedir):
204 if isdir(homedir):
205 return homedir.decode(sys.getfilesystemencoding())
205 return homedir.decode(sys.getfilesystemencoding())
206
206
207 # Now the users profile directory
207 # Now the users profile directory
208 try:
208 try:
209 homedir = os.path.join(env['USERPROFILE'])
209 homedir = os.path.join(env['USERPROFILE'])
210 except KeyError:
210 except KeyError:
211 pass
211 pass
212 else:
212 else:
213 if isdir(homedir):
213 if isdir(homedir):
214 return homedir.decode(sys.getfilesystemencoding())
214 return homedir.decode(sys.getfilesystemencoding())
215
215
216 # Use the registry to get the 'My Documents' folder.
216 # Use the registry to get the 'My Documents' folder.
217 try:
217 try:
218 import _winreg as wreg
218 import _winreg as wreg
219 key = wreg.OpenKey(
219 key = wreg.OpenKey(
220 wreg.HKEY_CURRENT_USER,
220 wreg.HKEY_CURRENT_USER,
221 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
221 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
222 )
222 )
223 homedir = wreg.QueryValueEx(key,'Personal')[0]
223 homedir = wreg.QueryValueEx(key,'Personal')[0]
224 key.Close()
224 key.Close()
225 except:
225 except:
226 pass
226 pass
227 else:
227 else:
228 if isdir(homedir):
228 if isdir(homedir):
229 return homedir.decode(sys.getfilesystemencoding())
229 return homedir.decode(sys.getfilesystemencoding())
230
230
231 # A user with a lot of unix tools in win32 may have defined $HOME.
231 # A user with a lot of unix tools in win32 may have defined $HOME.
232 # Try this as a last ditch option.
232 # Try this as a last ditch option.
233 try:
233 try:
234 homedir = env['HOME']
234 homedir = env['HOME']
235 except KeyError:
235 except KeyError:
236 pass
236 pass
237 else:
237 else:
238 if isdir(homedir):
238 if isdir(homedir):
239 return homedir.decode(sys.getfilesystemencoding())
239 return homedir.decode(sys.getfilesystemencoding())
240
240
241 # If all else fails, raise HomeDirError
241 # If all else fails, raise HomeDirError
242 raise HomeDirError('No valid home directory could be found')
242 raise HomeDirError('No valid home directory could be found')
243 elif os.name == 'dos':
243 elif os.name == 'dos':
244 # Desperate, may do absurd things in classic MacOS. May work under DOS.
244 # Desperate, may do absurd things in classic MacOS. May work under DOS.
245 return 'C:\\'.decode(sys.getfilesystemencoding())
245 return 'C:\\'.decode(sys.getfilesystemencoding())
246 else:
246 else:
247 raise HomeDirError('No valid home directory could be found for your OS')
247 raise HomeDirError('No valid home directory could be found for your OS')
248
248
249
249
250 def get_ipython_dir():
250 def get_ipython_dir():
251 """Get the IPython directory for this platform and user.
251 """Get the IPython directory for this platform and user.
252
252
253 This uses the logic in `get_home_dir` to find the home directory
253 This uses the logic in `get_home_dir` to find the home directory
254 and the adds .ipython to the end of the path.
254 and the adds .ipython to the end of the path.
255 """
255 """
256 ipdir_def = '.ipython'
256 ipdir_def = '.ipython'
257 home_dir = get_home_dir()
257 home_dir = get_home_dir()
258 # import pdb; pdb.set_trace() # dbg
258 # import pdb; pdb.set_trace() # dbg
259 ipdir = os.environ.get(
259 ipdir = os.environ.get(
260 'IPYTHON_DIR', os.environ.get(
260 'IPYTHON_DIR', os.environ.get(
261 'IPYTHONDIR', os.path.join(home_dir, ipdir_def)
261 'IPYTHONDIR', os.path.join(home_dir, ipdir_def)
262 )
262 )
263 )
263 )
264 return ipdir.decode(sys.getfilesystemencoding())
264 return ipdir.decode(sys.getfilesystemencoding())
265
265
266
266
267 def get_ipython_package_dir():
267 def get_ipython_package_dir():
268 """Get the base directory where IPython itself is installed."""
268 """Get the base directory where IPython itself is installed."""
269 ipdir = os.path.dirname(IPython.__file__)
269 ipdir = os.path.dirname(IPython.__file__)
270 return ipdir.decode(sys.getfilesystemencoding())
270 return ipdir.decode(sys.getfilesystemencoding())
271
271
272
272
273 def get_ipython_module_path(module_str):
273 def get_ipython_module_path(module_str):
274 """Find the path to an IPython module in this version of IPython.
274 """Find the path to an IPython module in this version of IPython.
275
275
276 This will always find the version of the module that is in this importable
276 This will always find the version of the module that is in this importable
277 IPython package. This will always return the path to the ``.py``
277 IPython package. This will always return the path to the ``.py``
278 version of the module.
278 version of the module.
279 """
279 """
280 if module_str == 'IPython':
280 if module_str == 'IPython':
281 return os.path.join(get_ipython_package_dir(), '__init__.py')
281 return os.path.join(get_ipython_package_dir(), '__init__.py')
282 mod = import_item(module_str)
282 mod = import_item(module_str)
283 the_path = mod.__file__.replace('.pyc', '.py')
283 the_path = mod.__file__.replace('.pyc', '.py')
284 the_path = the_path.replace('.pyo', '.py')
284 the_path = the_path.replace('.pyo', '.py')
285 return the_path.decode(sys.getfilesystemencoding())
285 return the_path.decode(sys.getfilesystemencoding())
286
286
287
287
288 def expand_path(s):
288 def expand_path(s):
289 """Expand $VARS and ~names in a string, like a shell
289 """Expand $VARS and ~names in a string, like a shell
290
290
291 :Examples:
291 :Examples:
292
292
293 In [2]: os.environ['FOO']='test'
293 In [2]: os.environ['FOO']='test'
294
294
295 In [3]: expand_path('variable FOO is $FOO')
295 In [3]: expand_path('variable FOO is $FOO')
296 Out[3]: 'variable FOO is test'
296 Out[3]: 'variable FOO is test'
297 """
297 """
298 # This is a pretty subtle hack. When expand user is given a UNC path
298 # This is a pretty subtle hack. When expand user is given a UNC path
299 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
299 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
300 # the $ to get (\\server\share\%username%). I think it considered $
300 # the $ to get (\\server\share\%username%). I think it considered $
301 # alone an empty var. But, we need the $ to remains there (it indicates
301 # alone an empty var. But, we need the $ to remains there (it indicates
302 # a hidden share).
302 # a hidden share).
303 if os.name=='nt':
303 if os.name=='nt':
304 s = s.replace('$\\', 'IPYTHON_TEMP')
304 s = s.replace('$\\', 'IPYTHON_TEMP')
305 s = os.path.expandvars(os.path.expanduser(s))
305 s = os.path.expandvars(os.path.expanduser(s))
306 if os.name=='nt':
306 if os.name=='nt':
307 s = s.replace('IPYTHON_TEMP', '$\\')
307 s = s.replace('IPYTHON_TEMP', '$\\')
308 return s
308 return s
309
309
310
310
311 def target_outdated(target,deps):
311 def target_outdated(target,deps):
312 """Determine whether a target is out of date.
312 """Determine whether a target is out of date.
313
313
314 target_outdated(target,deps) -> 1/0
314 target_outdated(target,deps) -> 1/0
315
315
316 deps: list of filenames which MUST exist.
316 deps: list of filenames which MUST exist.
317 target: single filename which may or may not exist.
317 target: single filename which may or may not exist.
318
318
319 If target doesn't exist or is older than any file listed in deps, return
319 If target doesn't exist or is older than any file listed in deps, return
320 true, otherwise return false.
320 true, otherwise return false.
321 """
321 """
322 try:
322 try:
323 target_time = os.path.getmtime(target)
323 target_time = os.path.getmtime(target)
324 except os.error:
324 except os.error:
325 return 1
325 return 1
326 for dep in deps:
326 for dep in deps:
327 dep_time = os.path.getmtime(dep)
327 dep_time = os.path.getmtime(dep)
328 if dep_time > target_time:
328 if dep_time > target_time:
329 #print "For target",target,"Dep failed:",dep # dbg
329 #print "For target",target,"Dep failed:",dep # dbg
330 #print "times (dep,tar):",dep_time,target_time # dbg
330 #print "times (dep,tar):",dep_time,target_time # dbg
331 return 1
331 return 1
332 return 0
332 return 0
333
333
334
334
335 def target_update(target,deps,cmd):
335 def target_update(target,deps,cmd):
336 """Update a target with a given command given a list of dependencies.
336 """Update a target with a given command given a list of dependencies.
337
337
338 target_update(target,deps,cmd) -> runs cmd if target is outdated.
338 target_update(target,deps,cmd) -> runs cmd if target is outdated.
339
339
340 This is just a wrapper around target_outdated() which calls the given
340 This is just a wrapper around target_outdated() which calls the given
341 command if target is outdated."""
341 command if target is outdated."""
342
342
343 if target_outdated(target,deps):
343 if target_outdated(target,deps):
344 xsys(cmd)
344 system(cmd)
345
345
@@ -1,367 +1,140 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for working with external processes.
3 Utilities for working with external processes.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16
17
18 # Stdlib
17 import os
19 import os
18 import sys
20 import sys
19 import shlex
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 # Code
32 # Code
26 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
27
34
28
35
29 class FindCmdError(Exception):
36 class FindCmdError(Exception):
30 pass
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 def find_cmd(cmd):
40 def find_cmd(cmd):
67 """Find absolute path to executable cmd in a cross platform manner.
41 """Find absolute path to executable cmd in a cross platform manner.
68
42
69 This function tries to determine the full path to a command line program
43 This function tries to determine the full path to a command line program
70 using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
44 using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
71 time it will use the version that is first on the users `PATH`. If
45 time it will use the version that is first on the users `PATH`. If
72 cmd is `python` return `sys.executable`.
46 cmd is `python` return `sys.executable`.
73
47
74 Warning, don't use this to find IPython command line programs as there
48 Warning, don't use this to find IPython command line programs as there
75 is a risk you will find the wrong one. Instead find those using the
49 is a risk you will find the wrong one. Instead find those using the
76 following code and looking for the application itself::
50 following code and looking for the application itself::
77
51
78 from IPython.utils.path import get_ipython_module_path
52 from IPython.utils.path import get_ipython_module_path
79 from IPython.utils.process import pycmd2argv
53 from IPython.utils.process import pycmd2argv
80 argv = pycmd2argv(get_ipython_module_path('IPython.frontend.terminal.ipapp'))
54 argv = pycmd2argv(get_ipython_module_path('IPython.frontend.terminal.ipapp'))
81
55
82 Parameters
56 Parameters
83 ----------
57 ----------
84 cmd : str
58 cmd : str
85 The command line program to look for.
59 The command line program to look for.
86 """
60 """
87 if cmd == 'python':
61 if cmd == 'python':
88 return os.path.abspath(sys.executable)
62 return os.path.abspath(sys.executable)
89 try:
63 try:
90 path = _find_cmd(cmd)
64 path = _find_cmd(cmd).rstrip()
91 except OSError:
65 except OSError:
92 raise FindCmdError('command could not be found: %s' % cmd)
66 raise FindCmdError('command could not be found: %s' % cmd)
93 # which returns empty if not found
67 # which returns empty if not found
94 if path == '':
68 if path == '':
95 raise FindCmdError('command could not be found: %s' % cmd)
69 raise FindCmdError('command could not be found: %s' % cmd)
96 return os.path.abspath(path)
70 return os.path.abspath(path)
97
71
98
72
99 def pycmd2argv(cmd):
73 def pycmd2argv(cmd):
100 r"""Take the path of a python command and return a list (argv-style).
74 r"""Take the path of a python command and return a list (argv-style).
101
75
102 This only works on Python based command line programs and will find the
76 This only works on Python based command line programs and will find the
103 location of the ``python`` executable using ``sys.executable`` to make
77 location of the ``python`` executable using ``sys.executable`` to make
104 sure the right version is used.
78 sure the right version is used.
105
79
106 For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe,
80 For a given path ``cmd``, this returns [cmd] if cmd's extension is .exe,
107 .com or .bat, and [, cmd] otherwise.
81 .com or .bat, and [, cmd] otherwise.
108
82
109 Parameters
83 Parameters
110 ----------
84 ----------
111 cmd : string
85 cmd : string
112 The path of the command.
86 The path of the command.
113
87
114 Returns
88 Returns
115 -------
89 -------
116 argv-style list.
90 argv-style list.
117 """
91 """
118 ext = os.path.splitext(cmd)[1]
92 ext = os.path.splitext(cmd)[1]
119 if ext in ['.exe', '.com', '.bat']:
93 if ext in ['.exe', '.com', '.bat']:
120 return [cmd]
94 return [cmd]
121 else:
95 else:
122 if sys.platform == 'win32':
96 if sys.platform == 'win32':
123 # The -u option here turns on unbuffered output, which is required
97 # The -u option here turns on unbuffered output, which is required
124 # on Win32 to prevent wierd conflict and problems with Twisted.
98 # on Win32 to prevent wierd conflict and problems with Twisted.
125 # Also, use sys.executable to make sure we are picking up the
99 # Also, use sys.executable to make sure we are picking up the
126 # right python exe.
100 # right python exe.
127 return [sys.executable, '-u', cmd]
101 return [sys.executable, '-u', cmd]
128 else:
102 else:
129 return [sys.executable, cmd]
103 return [sys.executable, cmd]
130
104
131
105
132 def arg_split(s, posix=False):
106 def arg_split(s, posix=False):
133 """Split a command line's arguments in a shell-like manner.
107 """Split a command line's arguments in a shell-like manner.
134
108
135 This is a modified version of the standard library's shlex.split()
109 This is a modified version of the standard library's shlex.split()
136 function, but with a default of posix=False for splitting, so that quotes
110 function, but with a default of posix=False for splitting, so that quotes
137 in inputs are respected."""
111 in inputs are respected."""
138
112
139 # Unfortunately, python's shlex module is buggy with unicode input:
113 # Unfortunately, python's shlex module is buggy with unicode input:
140 # http://bugs.python.org/issue1170
114 # http://bugs.python.org/issue1170
141 # At least encoding the input when it's unicode seems to help, but there
115 # At least encoding the input when it's unicode seems to help, but there
142 # may be more problems lurking. Apparently this is fixed in python3.
116 # may be more problems lurking. Apparently this is fixed in python3.
143 if isinstance(s, unicode):
117 if isinstance(s, unicode):
144 s = s.encode(sys.stdin.encoding)
118 s = s.encode(sys.stdin.encoding)
145 lex = shlex.shlex(s, posix=posix)
119 lex = shlex.shlex(s, posix=posix)
146 lex.whitespace_split = True
120 lex.whitespace_split = True
147 return list(lex)
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 def abbrev_cwd():
124 def abbrev_cwd():
173 """ Return abbreviated version of cwd, e.g. d:mydir """
125 """ Return abbreviated version of cwd, e.g. d:mydir """
174 cwd = os.getcwd().replace('\\','/')
126 cwd = os.getcwd().replace('\\','/')
175 drivepart = ''
127 drivepart = ''
176 tail = cwd
128 tail = cwd
177 if sys.platform == 'win32':
129 if sys.platform == 'win32':
178 if len(cwd) < 4:
130 if len(cwd) < 4:
179 return cwd
131 return cwd
180 drivepart,tail = os.path.splitdrive(cwd)
132 drivepart,tail = os.path.splitdrive(cwd)
181
133
182
134
183 parts = tail.split('/')
135 parts = tail.split('/')
184 if len(parts) > 2:
136 if len(parts) > 2:
185 tail = '/'.join(parts[-2:])
137 tail = '/'.join(parts[-2:])
186
138
187 return (drivepart + (
139 return (drivepart + (
188 cwd == '/' and '/' or tail))
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 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Tests for platutils.py
3 Tests for platutils.py
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2009 The IPython Development Team
7 # Copyright (C) 2008-2009 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import sys
17 import sys
18 from unittest import TestCase
18
19
19 import nose.tools as nt
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 from IPython.testing import decorators as dec
24 from IPython.testing import decorators as dec
25 from IPython.testing import tools as tt
23
26
24 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
25 # Tests
28 # Tests
26 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
27
30
28 def test_find_cmd_python():
31 def test_find_cmd_python():
29 """Make sure we find sys.exectable for python."""
32 """Make sure we find sys.exectable for python."""
30 nt.assert_equals(find_cmd('python'), sys.executable)
33 nt.assert_equals(find_cmd('python'), sys.executable)
31
34
32
35
33 @dec.skip_win32
36 @dec.skip_win32
34 def test_find_cmd_ls():
37 def test_find_cmd_ls():
35 """Make sure we can find the full path to ls."""
38 """Make sure we can find the full path to ls."""
36 path = find_cmd('ls')
39 path = find_cmd('ls')
37 nt.assert_true(path.endswith('ls'))
40 nt.assert_true(path.endswith('ls'))
38
41
39
42
40 def has_pywin32():
43 def has_pywin32():
41 try:
44 try:
42 import win32api
45 import win32api
43 except ImportError:
46 except ImportError:
44 return False
47 return False
45 return True
48 return True
46
49
47
50
48 @dec.onlyif(has_pywin32, "This test requires win32api to run")
51 @dec.onlyif(has_pywin32, "This test requires win32api to run")
49 def test_find_cmd_pythonw():
52 def test_find_cmd_pythonw():
50 """Try to find pythonw on Windows."""
53 """Try to find pythonw on Windows."""
51 path = find_cmd('pythonw')
54 path = find_cmd('pythonw')
52 nt.assert_true(path.endswith('pythonw.exe'))
55 nt.assert_true(path.endswith('pythonw.exe'))
53
56
54
57
55 @dec.onlyif(lambda : sys.platform != 'win32' or has_pywin32(),
58 @dec.onlyif(lambda : sys.platform != 'win32' or has_pywin32(),
56 "This test runs on posix or in win32 with win32api installed")
59 "This test runs on posix or in win32 with win32api installed")
57 def test_find_cmd_fail():
60 def test_find_cmd_fail():
58 """Make sure that FindCmdError is raised if we can't find the cmd."""
61 """Make sure that FindCmdError is raised if we can't find the cmd."""
59 nt.assert_raises(FindCmdError,find_cmd,'asdfasdf')
62 nt.assert_raises(FindCmdError,find_cmd,'asdfasdf')
60
63
61
64
62 def test_arg_split():
65 def test_arg_split():
63 """Ensure that argument lines are correctly split like in a shell."""
66 """Ensure that argument lines are correctly split like in a shell."""
64 tests = [['hi', ['hi']],
67 tests = [['hi', ['hi']],
65 [u'hi', [u'hi']],
68 [u'hi', [u'hi']],
66 ]
69 ]
67 for argstr, argv in tests:
70 for argstr, argv in tests:
68 nt.assert_equal(arg_split(argstr), argv)
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 """A ZMQ-based subclass of InteractiveShell.
1 """A ZMQ-based subclass of InteractiveShell.
2
2
3 This code is meant to ease the refactoring of the base InteractiveShell into
3 This code is meant to ease the refactoring of the base InteractiveShell into
4 something with a cleaner architecture for 2-process use, without actually
4 something with a cleaner architecture for 2-process use, without actually
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 we subclass and override what we want to fix. Once this is working well, we
6 we subclass and override what we want to fix. Once this is working well, we
7 can go back to the base class and refactor the code for a cleaner inheritance
7 can go back to the base class and refactor the code for a cleaner inheritance
8 implementation that doesn't rely on so much monkeypatching.
8 implementation that doesn't rely on so much monkeypatching.
9
9
10 But this lets us maintain a fully working IPython as we develop the new
10 But this lets us maintain a fully working IPython as we develop the new
11 machinery. This should thus be thought of as scaffolding.
11 machinery. This should thus be thought of as scaffolding.
12 """
12 """
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Stdlib
18 # Stdlib
19 import inspect
19 import inspect
20 import os
20 import os
21 import re
21 import re
22 import sys
23
24 from subprocess import Popen, PIPE
25
22
26 # Our own
23 # Our own
27 from IPython.core.interactiveshell import (
24 from IPython.core.interactiveshell import (
28 InteractiveShell, InteractiveShellABC
25 InteractiveShell, InteractiveShellABC
29 )
26 )
30 from IPython.core.displayhook import DisplayHook
27 from IPython.core.displayhook import DisplayHook
31 from IPython.core.macro import Macro
28 from IPython.core.macro import Macro
32 from IPython.utils.path import get_py_filename
29 from IPython.utils.path import get_py_filename
33 from IPython.utils.text import StringTypes
30 from IPython.utils.text import StringTypes
34 from IPython.utils.traitlets import Instance, Type, Dict
31 from IPython.utils.traitlets import Instance, Type, Dict
35 from IPython.utils.warn import warn
32 from IPython.utils.warn import warn
36 from IPython.zmq.session import extract_header
33 from IPython.zmq.session import extract_header
37 from IPython.core.payloadpage import install_payload_page
34 from IPython.core.payloadpage import install_payload_page
38 from session import Session
35 from session import Session
39
36
40 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
41 # Globals and side-effects
38 # Globals and side-effects
42 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
43
40
44 # Install the payload version of page.
41 # Install the payload version of page.
45 install_payload_page()
42 install_payload_page()
46
43
47 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
48 # Functions and classes
45 # Functions and classes
49 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
50
47
51 class ZMQDisplayHook(DisplayHook):
48 class ZMQDisplayHook(DisplayHook):
52
49
53 session = Instance(Session)
50 session = Instance(Session)
54 pub_socket = Instance('zmq.Socket')
51 pub_socket = Instance('zmq.Socket')
55 parent_header = Dict({})
52 parent_header = Dict({})
56
53
57 def set_parent(self, parent):
54 def set_parent(self, parent):
58 """Set the parent for outbound messages."""
55 """Set the parent for outbound messages."""
59 self.parent_header = extract_header(parent)
56 self.parent_header = extract_header(parent)
60
57
61 def start_displayhook(self):
58 def start_displayhook(self):
62 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
59 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
63
60
64 def write_output_prompt(self):
61 def write_output_prompt(self):
65 """Write the output prompt."""
62 """Write the output prompt."""
66 if self.do_full_cache:
63 if self.do_full_cache:
67 self.msg['content']['output_sep'] = self.output_sep
64 self.msg['content']['output_sep'] = self.output_sep
68 self.msg['content']['prompt_string'] = str(self.prompt_out)
65 self.msg['content']['prompt_string'] = str(self.prompt_out)
69 self.msg['content']['prompt_number'] = self.prompt_count
66 self.msg['content']['prompt_number'] = self.prompt_count
70 self.msg['content']['output_sep2'] = self.output_sep2
67 self.msg['content']['output_sep2'] = self.output_sep2
71
68
72 def write_result_repr(self, result_repr):
69 def write_result_repr(self, result_repr):
73 self.msg['content']['data'] = result_repr
70 self.msg['content']['data'] = result_repr
74
71
75 def finish_displayhook(self):
72 def finish_displayhook(self):
76 """Finish up all displayhook activities."""
73 """Finish up all displayhook activities."""
77 self.pub_socket.send_json(self.msg)
74 self.pub_socket.send_json(self.msg)
78 self.msg = None
75 self.msg = None
79
76
80
77
81 class ZMQInteractiveShell(InteractiveShell):
78 class ZMQInteractiveShell(InteractiveShell):
82 """A subclass of InteractiveShell for ZMQ."""
79 """A subclass of InteractiveShell for ZMQ."""
83
80
84 displayhook_class = Type(ZMQDisplayHook)
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 def init_io(self):
83 def init_io(self):
107 # This will just use sys.stdout and sys.stderr. If you want to
84 # This will just use sys.stdout and sys.stderr. If you want to
108 # override sys.stdout and sys.stderr themselves, you need to do that
85 # override sys.stdout and sys.stderr themselves, you need to do that
109 # *before* instantiating this class, because Term holds onto
86 # *before* instantiating this class, because Term holds onto
110 # references to the underlying streams.
87 # references to the underlying streams.
111 import IPython.utils.io
88 import IPython.utils.io
112 Term = IPython.utils.io.IOTerm()
89 Term = IPython.utils.io.IOTerm()
113 IPython.utils.io.Term = Term
90 IPython.utils.io.Term = Term
114
91
115 def magic_edit(self,parameter_s='',last_call=['','']):
92 def magic_edit(self,parameter_s='',last_call=['','']):
116 """Bring up an editor and execute the resulting code.
93 """Bring up an editor and execute the resulting code.
117
94
118 Usage:
95 Usage:
119 %edit [options] [args]
96 %edit [options] [args]
120
97
121 %edit runs IPython's editor hook. The default version of this hook is
98 %edit runs IPython's editor hook. The default version of this hook is
122 set to call the __IPYTHON__.rc.editor command. This is read from your
99 set to call the __IPYTHON__.rc.editor command. This is read from your
123 environment variable $EDITOR. If this isn't found, it will default to
100 environment variable $EDITOR. If this isn't found, it will default to
124 vi under Linux/Unix and to notepad under Windows. See the end of this
101 vi under Linux/Unix and to notepad under Windows. See the end of this
125 docstring for how to change the editor hook.
102 docstring for how to change the editor hook.
126
103
127 You can also set the value of this editor via the command line option
104 You can also set the value of this editor via the command line option
128 '-editor' or in your ipythonrc file. This is useful if you wish to use
105 '-editor' or in your ipythonrc file. This is useful if you wish to use
129 specifically for IPython an editor different from your typical default
106 specifically for IPython an editor different from your typical default
130 (and for Windows users who typically don't set environment variables).
107 (and for Windows users who typically don't set environment variables).
131
108
132 This command allows you to conveniently edit multi-line code right in
109 This command allows you to conveniently edit multi-line code right in
133 your IPython session.
110 your IPython session.
134
111
135 If called without arguments, %edit opens up an empty editor with a
112 If called without arguments, %edit opens up an empty editor with a
136 temporary file and will execute the contents of this file when you
113 temporary file and will execute the contents of this file when you
137 close it (don't forget to save it!).
114 close it (don't forget to save it!).
138
115
139
116
140 Options:
117 Options:
141
118
142 -n <number>: open the editor at a specified line number. By default,
119 -n <number>: open the editor at a specified line number. By default,
143 the IPython editor hook uses the unix syntax 'editor +N filename', but
120 the IPython editor hook uses the unix syntax 'editor +N filename', but
144 you can configure this by providing your own modified hook if your
121 you can configure this by providing your own modified hook if your
145 favorite editor supports line-number specifications with a different
122 favorite editor supports line-number specifications with a different
146 syntax.
123 syntax.
147
124
148 -p: this will call the editor with the same data as the previous time
125 -p: this will call the editor with the same data as the previous time
149 it was used, regardless of how long ago (in your current session) it
126 it was used, regardless of how long ago (in your current session) it
150 was.
127 was.
151
128
152 -r: use 'raw' input. This option only applies to input taken from the
129 -r: use 'raw' input. This option only applies to input taken from the
153 user's history. By default, the 'processed' history is used, so that
130 user's history. By default, the 'processed' history is used, so that
154 magics are loaded in their transformed version to valid Python. If
131 magics are loaded in their transformed version to valid Python. If
155 this option is given, the raw input as typed as the command line is
132 this option is given, the raw input as typed as the command line is
156 used instead. When you exit the editor, it will be executed by
133 used instead. When you exit the editor, it will be executed by
157 IPython's own processor.
134 IPython's own processor.
158
135
159 -x: do not execute the edited code immediately upon exit. This is
136 -x: do not execute the edited code immediately upon exit. This is
160 mainly useful if you are editing programs which need to be called with
137 mainly useful if you are editing programs which need to be called with
161 command line arguments, which you can then do using %run.
138 command line arguments, which you can then do using %run.
162
139
163
140
164 Arguments:
141 Arguments:
165
142
166 If arguments are given, the following possibilites exist:
143 If arguments are given, the following possibilites exist:
167
144
168 - The arguments are numbers or pairs of colon-separated numbers (like
145 - The arguments are numbers or pairs of colon-separated numbers (like
169 1 4:8 9). These are interpreted as lines of previous input to be
146 1 4:8 9). These are interpreted as lines of previous input to be
170 loaded into the editor. The syntax is the same of the %macro command.
147 loaded into the editor. The syntax is the same of the %macro command.
171
148
172 - If the argument doesn't start with a number, it is evaluated as a
149 - If the argument doesn't start with a number, it is evaluated as a
173 variable and its contents loaded into the editor. You can thus edit
150 variable and its contents loaded into the editor. You can thus edit
174 any string which contains python code (including the result of
151 any string which contains python code (including the result of
175 previous edits).
152 previous edits).
176
153
177 - If the argument is the name of an object (other than a string),
154 - If the argument is the name of an object (other than a string),
178 IPython will try to locate the file where it was defined and open the
155 IPython will try to locate the file where it was defined and open the
179 editor at the point where it is defined. You can use `%edit function`
156 editor at the point where it is defined. You can use `%edit function`
180 to load an editor exactly at the point where 'function' is defined,
157 to load an editor exactly at the point where 'function' is defined,
181 edit it and have the file be executed automatically.
158 edit it and have the file be executed automatically.
182
159
183 If the object is a macro (see %macro for details), this opens up your
160 If the object is a macro (see %macro for details), this opens up your
184 specified editor with a temporary file containing the macro's data.
161 specified editor with a temporary file containing the macro's data.
185 Upon exit, the macro is reloaded with the contents of the file.
162 Upon exit, the macro is reloaded with the contents of the file.
186
163
187 Note: opening at an exact line is only supported under Unix, and some
164 Note: opening at an exact line is only supported under Unix, and some
188 editors (like kedit and gedit up to Gnome 2.8) do not understand the
165 editors (like kedit and gedit up to Gnome 2.8) do not understand the
189 '+NUMBER' parameter necessary for this feature. Good editors like
166 '+NUMBER' parameter necessary for this feature. Good editors like
190 (X)Emacs, vi, jed, pico and joe all do.
167 (X)Emacs, vi, jed, pico and joe all do.
191
168
192 - If the argument is not found as a variable, IPython will look for a
169 - If the argument is not found as a variable, IPython will look for a
193 file with that name (adding .py if necessary) and load it into the
170 file with that name (adding .py if necessary) and load it into the
194 editor. It will execute its contents with execfile() when you exit,
171 editor. It will execute its contents with execfile() when you exit,
195 loading any code in the file into your interactive namespace.
172 loading any code in the file into your interactive namespace.
196
173
197 After executing your code, %edit will return as output the code you
174 After executing your code, %edit will return as output the code you
198 typed in the editor (except when it was an existing file). This way
175 typed in the editor (except when it was an existing file). This way
199 you can reload the code in further invocations of %edit as a variable,
176 you can reload the code in further invocations of %edit as a variable,
200 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
177 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
201 the output.
178 the output.
202
179
203 Note that %edit is also available through the alias %ed.
180 Note that %edit is also available through the alias %ed.
204
181
205 This is an example of creating a simple function inside the editor and
182 This is an example of creating a simple function inside the editor and
206 then modifying it. First, start up the editor:
183 then modifying it. First, start up the editor:
207
184
208 In [1]: ed
185 In [1]: ed
209 Editing... done. Executing edited code...
186 Editing... done. Executing edited code...
210 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
187 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
211
188
212 We can then call the function foo():
189 We can then call the function foo():
213
190
214 In [2]: foo()
191 In [2]: foo()
215 foo() was defined in an editing session
192 foo() was defined in an editing session
216
193
217 Now we edit foo. IPython automatically loads the editor with the
194 Now we edit foo. IPython automatically loads the editor with the
218 (temporary) file where foo() was previously defined:
195 (temporary) file where foo() was previously defined:
219
196
220 In [3]: ed foo
197 In [3]: ed foo
221 Editing... done. Executing edited code...
198 Editing... done. Executing edited code...
222
199
223 And if we call foo() again we get the modified version:
200 And if we call foo() again we get the modified version:
224
201
225 In [4]: foo()
202 In [4]: foo()
226 foo() has now been changed!
203 foo() has now been changed!
227
204
228 Here is an example of how to edit a code snippet successive
205 Here is an example of how to edit a code snippet successive
229 times. First we call the editor:
206 times. First we call the editor:
230
207
231 In [5]: ed
208 In [5]: ed
232 Editing... done. Executing edited code...
209 Editing... done. Executing edited code...
233 hello
210 hello
234 Out[5]: "print 'hello'n"
211 Out[5]: "print 'hello'n"
235
212
236 Now we call it again with the previous output (stored in _):
213 Now we call it again with the previous output (stored in _):
237
214
238 In [6]: ed _
215 In [6]: ed _
239 Editing... done. Executing edited code...
216 Editing... done. Executing edited code...
240 hello world
217 hello world
241 Out[6]: "print 'hello world'n"
218 Out[6]: "print 'hello world'n"
242
219
243 Now we call it with the output #8 (stored in _8, also as Out[8]):
220 Now we call it with the output #8 (stored in _8, also as Out[8]):
244
221
245 In [7]: ed _8
222 In [7]: ed _8
246 Editing... done. Executing edited code...
223 Editing... done. Executing edited code...
247 hello again
224 hello again
248 Out[7]: "print 'hello again'n"
225 Out[7]: "print 'hello again'n"
249
226
250
227
251 Changing the default editor hook:
228 Changing the default editor hook:
252
229
253 If you wish to write your own editor hook, you can put it in a
230 If you wish to write your own editor hook, you can put it in a
254 configuration file which you load at startup time. The default hook
231 configuration file which you load at startup time. The default hook
255 is defined in the IPython.core.hooks module, and you can use that as a
232 is defined in the IPython.core.hooks module, and you can use that as a
256 starting example for further modifications. That file also has
233 starting example for further modifications. That file also has
257 general instructions on how to set a new hook for use once you've
234 general instructions on how to set a new hook for use once you've
258 defined it."""
235 defined it."""
259
236
260 # FIXME: This function has become a convoluted mess. It needs a
237 # FIXME: This function has become a convoluted mess. It needs a
261 # ground-up rewrite with clean, simple logic.
238 # ground-up rewrite with clean, simple logic.
262
239
263 def make_filename(arg):
240 def make_filename(arg):
264 "Make a filename from the given args"
241 "Make a filename from the given args"
265 try:
242 try:
266 filename = get_py_filename(arg)
243 filename = get_py_filename(arg)
267 except IOError:
244 except IOError:
268 if args.endswith('.py'):
245 if args.endswith('.py'):
269 filename = arg
246 filename = arg
270 else:
247 else:
271 filename = None
248 filename = None
272 return filename
249 return filename
273
250
274 # custom exceptions
251 # custom exceptions
275 class DataIsObject(Exception): pass
252 class DataIsObject(Exception): pass
276
253
277 opts,args = self.parse_options(parameter_s,'prn:')
254 opts,args = self.parse_options(parameter_s,'prn:')
278 # Set a few locals from the options for convenience:
255 # Set a few locals from the options for convenience:
279 opts_p = opts.has_key('p')
256 opts_p = opts.has_key('p')
280 opts_r = opts.has_key('r')
257 opts_r = opts.has_key('r')
281
258
282 # Default line number value
259 # Default line number value
283 lineno = opts.get('n',None)
260 lineno = opts.get('n',None)
284 if lineno is not None:
261 if lineno is not None:
285 try:
262 try:
286 lineno = int(lineno)
263 lineno = int(lineno)
287 except:
264 except:
288 warn("The -n argument must be an integer.")
265 warn("The -n argument must be an integer.")
289 return
266 return
290
267
291 if opts_p:
268 if opts_p:
292 args = '_%s' % last_call[0]
269 args = '_%s' % last_call[0]
293 if not self.shell.user_ns.has_key(args):
270 if not self.shell.user_ns.has_key(args):
294 args = last_call[1]
271 args = last_call[1]
295
272
296 # use last_call to remember the state of the previous call, but don't
273 # use last_call to remember the state of the previous call, but don't
297 # let it be clobbered by successive '-p' calls.
274 # let it be clobbered by successive '-p' calls.
298 try:
275 try:
299 last_call[0] = self.shell.displayhook.prompt_count
276 last_call[0] = self.shell.displayhook.prompt_count
300 if not opts_p:
277 if not opts_p:
301 last_call[1] = parameter_s
278 last_call[1] = parameter_s
302 except:
279 except:
303 pass
280 pass
304
281
305 # by default this is done with temp files, except when the given
282 # by default this is done with temp files, except when the given
306 # arg is a filename
283 # arg is a filename
307 use_temp = 1
284 use_temp = 1
308
285
309 if re.match(r'\d',args):
286 if re.match(r'\d',args):
310 # Mode where user specifies ranges of lines, like in %macro.
287 # Mode where user specifies ranges of lines, like in %macro.
311 # This means that you can't edit files whose names begin with
288 # This means that you can't edit files whose names begin with
312 # numbers this way. Tough.
289 # numbers this way. Tough.
313 ranges = args.split()
290 ranges = args.split()
314 data = ''.join(self.extract_input_slices(ranges,opts_r))
291 data = ''.join(self.extract_input_slices(ranges,opts_r))
315 elif args.endswith('.py'):
292 elif args.endswith('.py'):
316 filename = make_filename(args)
293 filename = make_filename(args)
317 data = ''
294 data = ''
318 use_temp = 0
295 use_temp = 0
319 elif args:
296 elif args:
320 try:
297 try:
321 # Load the parameter given as a variable. If not a string,
298 # Load the parameter given as a variable. If not a string,
322 # process it as an object instead (below)
299 # process it as an object instead (below)
323
300
324 #print '*** args',args,'type',type(args) # dbg
301 #print '*** args',args,'type',type(args) # dbg
325 data = eval(args,self.shell.user_ns)
302 data = eval(args,self.shell.user_ns)
326 if not type(data) in StringTypes:
303 if not type(data) in StringTypes:
327 raise DataIsObject
304 raise DataIsObject
328
305
329 except (NameError,SyntaxError):
306 except (NameError,SyntaxError):
330 # given argument is not a variable, try as a filename
307 # given argument is not a variable, try as a filename
331 filename = make_filename(args)
308 filename = make_filename(args)
332 if filename is None:
309 if filename is None:
333 warn("Argument given (%s) can't be found as a variable "
310 warn("Argument given (%s) can't be found as a variable "
334 "or as a filename." % args)
311 "or as a filename." % args)
335 return
312 return
336
313
337 data = ''
314 data = ''
338 use_temp = 0
315 use_temp = 0
339 except DataIsObject:
316 except DataIsObject:
340
317
341 # macros have a special edit function
318 # macros have a special edit function
342 if isinstance(data,Macro):
319 if isinstance(data,Macro):
343 self._edit_macro(args,data)
320 self._edit_macro(args,data)
344 return
321 return
345
322
346 # For objects, try to edit the file where they are defined
323 # For objects, try to edit the file where they are defined
347 try:
324 try:
348 filename = inspect.getabsfile(data)
325 filename = inspect.getabsfile(data)
349 if 'fakemodule' in filename.lower() and inspect.isclass(data):
326 if 'fakemodule' in filename.lower() and inspect.isclass(data):
350 # class created by %edit? Try to find source
327 # class created by %edit? Try to find source
351 # by looking for method definitions instead, the
328 # by looking for method definitions instead, the
352 # __module__ in those classes is FakeModule.
329 # __module__ in those classes is FakeModule.
353 attrs = [getattr(data, aname) for aname in dir(data)]
330 attrs = [getattr(data, aname) for aname in dir(data)]
354 for attr in attrs:
331 for attr in attrs:
355 if not inspect.ismethod(attr):
332 if not inspect.ismethod(attr):
356 continue
333 continue
357 filename = inspect.getabsfile(attr)
334 filename = inspect.getabsfile(attr)
358 if filename and 'fakemodule' not in filename.lower():
335 if filename and 'fakemodule' not in filename.lower():
359 # change the attribute to be the edit target instead
336 # change the attribute to be the edit target instead
360 data = attr
337 data = attr
361 break
338 break
362
339
363 datafile = 1
340 datafile = 1
364 except TypeError:
341 except TypeError:
365 filename = make_filename(args)
342 filename = make_filename(args)
366 datafile = 1
343 datafile = 1
367 warn('Could not find file where `%s` is defined.\n'
344 warn('Could not find file where `%s` is defined.\n'
368 'Opening a file named `%s`' % (args,filename))
345 'Opening a file named `%s`' % (args,filename))
369 # Now, make sure we can actually read the source (if it was in
346 # Now, make sure we can actually read the source (if it was in
370 # a temp file it's gone by now).
347 # a temp file it's gone by now).
371 if datafile:
348 if datafile:
372 try:
349 try:
373 if lineno is None:
350 if lineno is None:
374 lineno = inspect.getsourcelines(data)[1]
351 lineno = inspect.getsourcelines(data)[1]
375 except IOError:
352 except IOError:
376 filename = make_filename(args)
353 filename = make_filename(args)
377 if filename is None:
354 if filename is None:
378 warn('The file `%s` where `%s` was defined cannot '
355 warn('The file `%s` where `%s` was defined cannot '
379 'be read.' % (filename,data))
356 'be read.' % (filename,data))
380 return
357 return
381 use_temp = 0
358 use_temp = 0
382 else:
359 else:
383 data = ''
360 data = ''
384
361
385 if use_temp:
362 if use_temp:
386 filename = self.shell.mktempfile(data)
363 filename = self.shell.mktempfile(data)
387 print('IPython will make a temporary file named:', filename)
364 print('IPython will make a temporary file named:', filename)
388
365
389 # Make sure we send to the client an absolute path, in case the working
366 # Make sure we send to the client an absolute path, in case the working
390 # directory of client and kernel don't match
367 # directory of client and kernel don't match
391 filename = os.path.abspath(filename)
368 filename = os.path.abspath(filename)
392
369
393 payload = {
370 payload = {
394 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
371 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
395 'filename' : filename,
372 'filename' : filename,
396 'line_number' : lineno
373 'line_number' : lineno
397 }
374 }
398 self.payload_manager.write_payload(payload)
375 self.payload_manager.write_payload(payload)
399
376
400
377
401 def _showtraceback(self, etype, evalue, stb):
378 def _showtraceback(self, etype, evalue, stb):
402
379
403 exc_content = {
380 exc_content = {
404 u'status' : u'error',
381 u'status' : u'error',
405 u'traceback' : stb,
382 u'traceback' : stb,
406 u'ename' : unicode(etype.__name__),
383 u'ename' : unicode(etype.__name__),
407 u'evalue' : unicode(evalue)
384 u'evalue' : unicode(evalue)
408 }
385 }
409
386
410 dh = self.displayhook
387 dh = self.displayhook
411 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
388 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
412 # Send exception info over pub socket for other clients than the caller
389 # Send exception info over pub socket for other clients than the caller
413 # to pick up
390 # to pick up
414 dh.pub_socket.send_json(exc_msg)
391 dh.pub_socket.send_json(exc_msg)
415
392
416 # FIXME - Hack: store exception info in shell object. Right now, the
393 # FIXME - Hack: store exception info in shell object. Right now, the
417 # caller is reading this info after the fact, we need to fix this logic
394 # caller is reading this info after the fact, we need to fix this logic
418 # to remove this hack.
395 # to remove this hack.
419 self._reply_content = exc_content
396 self._reply_content = exc_content
420 # /FIXME
397 # /FIXME
421
398
422 return exc_content
399 return exc_content
423
400
424 def runlines(self, lines, clean=False):
401 def runlines(self, lines, clean=False):
425 return InteractiveShell.runlines(self, lines, clean)
402 return InteractiveShell.runlines(self, lines, clean)
426
403
427 InteractiveShellABC.register(ZMQInteractiveShell)
404 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now